Programs & Examples On #Sql function

A function defined in a relational database system. Most RDBS's include numerous built-in functions and also allow for the creation of additional custom functions.

Select Rows with id having even number

Try this:

SELECT DISTINCT city FROM STATION WHERE ID%2=0 ORDER BY CITY;

How to check date of last change in stored procedure or function in SQL server

SELECT name, create_date, modify_date 
FROM sys.objects
WHERE type = 'P'
ORDER BY modify_date DESC

The type for a function is FN rather than P for procedure. Or you can filter on the name column.

How to Replace Multiple Characters in SQL?

I had a one-off data migration issue where the source data could not output correctly some unusual/technical characters plus the ubiquitous extra commas in CSVs.

We decided that for each such character the source extract should replace them with something that was recognisable to both the source system and the SQL Server that was loading them but which would not be in the data otherwise.

It did mean however that in various columns across various tables these replacement characters would appear and I would have to replace them. Nesting multiple REPLACE functions made the import code look scary and prone to errors in misjudging the placement and number of brackets so I wrote the following function. I know it can process a column in a table of 3,000 rows in less than a second though I'm not sure how quickly it will scale up to multi-million row tables.

create function [dbo].[udf_ReplaceMultipleChars]
(
    @OriginalString nvarchar(4000)
  , @ReplaceTheseChars nvarchar(100)
  , @LengthOfReplacement int = 1
)
returns nvarchar(4000)
begin

    declare @RevisedString nvarchar(4000) = N'';
    declare @lengthofinput int =
            (
            select len(@OriginalString)
            );

with AllNumbers
as (select 1 as  Number
    union all
    select Number + 1
    from AllNumbers
    where Number < @lengthofinput)
select @RevisedString += case
                             when (charindex(substring(@OriginalString, Number, 1), @ReplaceTheseChars, 1) - 1) % 2
    = 0 then
                                 substring(
                                              @ReplaceTheseChars
                                            , charindex(
                                                           substring(@OriginalString, Number, 1)
                                                         , @ReplaceTheseChars
                                                         , 1
                                                       ) + 1
                                            , @LengthOfReplacement
                                          )
                             else
                                 substring(@OriginalString, Number, 1)
                         end
    from AllNumbers
    option (maxrecursion 4000);
    return (@RevisedString);
end;

It works by submitting both the string to be evaluated and have characters to be replaced (@OriginalString) along with a string of paired characters where the first character is to be replaced by the second, the third by the fourth, fifth by sixth and so on (@ReplaceTheseChars).

Here is the string of chars that I needed to replace and their replacements... [']"~,{Ø}°$±|¼¦¼ª½¬½^¾#?

i.e. A opening square bracket denotes an apostrophe, a closing one a double quote. You can see that there were vulgar fractions as well as degrees and diameter symbols in there.

There is a default @LengthOfReplacement that is included as a starting point if anyone needed to replace longer strings. I played around with that in my project but the single char replacement was the main function.

The condition of the case statement is important. It ensures that it only replaces the character if it is found in your @ReplaceTheseChars variable and that the character has to be found in an odd numbered position (the minus 1 from charindex result ensures that anything NOT found returns a negative modulo value). i.e if you find a tilde (~) in position 5 it will replace it with a comma but if on a subsequent run it found the comma in position 6 it would not replace it with a curly bracket ({).

This can be best demonstrated with an example...

declare @ProductDescription nvarchar(20) = N'abc~def[¦][123';
select @ProductDescription
= dbo.udf_ReplaceMultipleChars(
                                  @ProductDescription
/* NB the doubling up of the apostrophe is necessary in the string but resolves to a single apostrophe when passed to the function */
                                ,'['']"~,{Ø}°$±|¼¦¼ª½¬½^¾#?' 
                                , default
                              );
select @ProductDescription
 , dbo.udf_ReplaceMultipleChars(
                                   @ProductDescription
                                 ,'['']"~,{Ø}°$±|¼¦¼ª½¬½^¾#?'
/* if you didn't know how to type those peculiar chars in then you can build a string like  this... '[' + nchar(0x0027) + ']"~,{' + nchar(0x00D8) + '}' + nchar(0x00B0) etc */
                                ,
                                 default
                               );

This will return both the value after the first pass through the function and the second time as follows... abc,def'¼"'123 abc,def'¼"'123

A table update would just be

update a
set a.Col1 = udf.ReplaceMultipleChars(a.Col1,'~,]"',1)
from TestTable a

Finally (I hear you say!), although I've not had access to the translate function I believe that this function can process the example shown in the documentation quite easily. The TRANSLATE function demo is

SELECT TRANSLATE('2*[3+4]/{7-2}', '[]{}', '()()');

which returns 2*(3+4)/(7-2) although I understand it might not work on 2*[3+4]/[7-2] !!

My function would approach this as follows listing each char to be replaced followed by its replacement [ --> (, { --> ( etc.

select dbo.udf_ReplaceMultipleChars('2*[3+4]/{7-2}', '[({(])})', 1);

which will also work for

select dbo.udf_ReplaceMultipleChars('2*[3+4]/[7-2]', '[({(])})', 1);

I hope someone finds this useful and if you get to test its performance against larger tables do let us know one way or another!

Function vs. Stored Procedure in SQL Server

Differences between stored procedures and user-defined functions:

  • Stored procedures cannot be used in Select statements.
  • Stored procedures support Deferred Name Resolution.
  • Stored procedures are generally used for performing business logic.
  • Stored procedures can return any datatype.
  • Stored procedures can accept greater numbers of input parameter than user defined functions. Stored procedures can have up to 21,000 input parameters.
  • Stored procedures can execute Dynamic SQL.
  • Stored procedures support error handling.
  • Non-deterministic functions can be used in stored procedures.

  • User-defined functions can be used in Select statements.
  • User-defined functions do not support Deferred Name Resolution.
  • User-defined functions are generally used for computations.
  • User-defined functions should return a value.
  • User-defined functions cannot return Images.
  • User-defined functions accept smaller numbers of input parameters than stored procedures. UDFs can have up to 1,023 input parameters.
  • Temporary tables cannot be used in user-defined functions.
  • User-defined functions cannot execute Dynamic SQL.
  • User-defined functions do not support error handling. RAISEERROR OR @@ERROR are not allowed in UDFs.
  • Non-deterministic functions cannot be used in UDFs. For example, GETDATE() cannot be used in UDFs.

MySQL stored procedure vs function, which would I use when?

You can't mix in stored procedures with ordinary SQL, whilst with stored function you can.

e.g. SELECT get_foo(myColumn) FROM mytable is not valid if get_foo() is a procedure, but you can do that if get_foo() is a function. The price is that functions have more limitations than a procedure.

How to check if a function exists on a SQL database

I've found you can use a very non verbose and straightforward approach to checking for the existence various SQL Server objects this way:

IF OBJECTPROPERTY (object_id('schemaname.scalarfuncname'), 'IsScalarFunction') = 1
IF OBJECTPROPERTY (object_id('schemaname.tablefuncname'), 'IsTableFunction') = 1
IF OBJECTPROPERTY (object_id('schemaname.procname'), 'IsProcedure') = 1

This is based on the OBJECTPROPERTY function which is available in SQL 2005+. The MSDN article can be found here.

The OBJECTPROPERTY function uses the following signature:

OBJECTPROPERTY ( id , property ) 

You pass a literal value into the property parameter, designating the type of object you are looking for. There's a massive list of values you can supply.

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

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

implement in:

df[df.countries.isin(countries)]

implement not in as in of rest countries:

df[df.countries.isin([x for x in np.unique(df.countries) if x not in countries])]

SQL Query - Concatenating Results into One String

@AlexanderMP's answer is correct, but you can also consider handling nulls with coalesce:

declare @CodeNameString  nvarchar(max)
set @CodeNameString = null
SELECT @CodeNameString = Coalesce(@CodeNameString + ', ', '') + cast(CodeName as varchar) from AccountCodes  
select @CodeNameString

MySQL: Selecting multiple fields into multiple variables in a stored procedure

Your syntax isn't quite right: you need to list the fields in order before the INTO, and the corresponding target variables after:

SELECT Id, dateCreated
INTO iId, dCreate
FROM products
WHERE pName = iName

Calling Scalar-valued Functions in SQL

You are using an inline table value function. Therefore you must use Select * From function. If you want to use select function() you must use a scalar function.

https://msdn.microsoft.com/fr-fr/library/ms186755%28v=sql.120%29.aspx

Getting attributes of a class

MyClass().__class__.__dict__

However, the "right" was to do this is via the inspect module.

How to filter object array based on attributes?

You could do this pretty easily - there are probably many implementations you can choose from, but this is my basic idea (and there is probably some format where you can iterate over an object with jQuery, I just cant think of it right now):

function filter(collection, predicate)
{
    var result = new Array();
    var length = collection.length;

    for(var j = 0; j < length; j++)
    {
        if(predicate(collection[j]) == true)
        {
             result.push(collection[j]);
        }
    }

    return result;
}

And then you could invoke this function like so:

filter(json, function(element)
{
    if(element.price <= 1000 && element.sqft >= 500 && element.num_of_beds > 2 && element.num_of_baths > 2.5)
        return true;

    return false;
});

This way, you can invoke the filter based on whatever predicate you define, or even filter multiple times using smaller filters.

How to solve error message: "Failed to map the path '/'."

Changing pool from ASP.NET v4.0 to Framework4 worked for me.

How do I make JavaScript beep?

Using Houshalter's suggestion, I made this simple tone synthesizer demo.

Screenshot

Here is a screenshot. Try the live demo further down in this Answer (click Run code snippet).

screenshot of live demo available further down in this Answer

Demo code

_x000D_
_x000D_
audioCtx = new(window.AudioContext || window.webkitAudioContext)();_x000D_
_x000D_
show();_x000D_
_x000D_
function show() {_x000D_
  frequency = document.getElementById("fIn").value;_x000D_
  document.getElementById("fOut").innerHTML = frequency + ' Hz';_x000D_
_x000D_
  switch (document.getElementById("tIn").value * 1) {_x000D_
    case 0: type = 'sine'; break;_x000D_
    case 1: type = 'square'; break;_x000D_
    case 2: type = 'sawtooth'; break;_x000D_
    case 3: type = 'triangle'; break;_x000D_
  }_x000D_
  document.getElementById("tOut").innerHTML = type;_x000D_
_x000D_
  volume = document.getElementById("vIn").value / 100;_x000D_
  document.getElementById("vOut").innerHTML = volume;_x000D_
_x000D_
  duration = document.getElementById("dIn").value;_x000D_
  document.getElementById("dOut").innerHTML = duration + ' ms';_x000D_
}_x000D_
_x000D_
function beep() {_x000D_
  var oscillator = audioCtx.createOscillator();_x000D_
  var gainNode = audioCtx.createGain();_x000D_
_x000D_
  oscillator.connect(gainNode);_x000D_
  gainNode.connect(audioCtx.destination);_x000D_
_x000D_
  gainNode.gain.value = volume;_x000D_
  oscillator.frequency.value = frequency;_x000D_
  oscillator.type = type;_x000D_
_x000D_
  oscillator.start();_x000D_
_x000D_
  setTimeout(_x000D_
    function() {_x000D_
      oscillator.stop();_x000D_
    },_x000D_
    duration_x000D_
  );_x000D_
};
_x000D_
frequency_x000D_
<input type="range" id="fIn" min="40" max="6000" oninput="show()" />_x000D_
<span id="fOut"></span><br>_x000D_
type_x000D_
<input type="range" id="tIn" min="0" max="3" oninput="show()" />_x000D_
<span id="tOut"></span><br>_x000D_
volume_x000D_
<input type="range" id="vIn" min="0" max="100" oninput="show()" />_x000D_
<span id="vOut"></span><br>_x000D_
duration_x000D_
<input type="range" id="dIn" min="1" max="5000" oninput="show()" />_x000D_
<span id="dOut"></span>_x000D_
<br>_x000D_
<button onclick='beep();'>Play</button>
_x000D_
_x000D_
_x000D_

You can clone and tweak the code here: Tone synthesizer demo on JS Bin

Have fun!

Compatible browsers:

  • Chrome mobile & desktop
  • Firefox mobile & desktop
  • Opera mobile, mini & desktop
  • Android browser
  • Microsoft Edge browser
  • Safari on iPhone or iPad

Not Compatible

  • Internet Explorer version 11 (but does work on the Edge browser)

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

I don't have enough reputation to add comment, so I posted this as an answer. But for original issue with this command:

@echo off
FOR %%p IN (C:\Users\vexe\Pictures\sample) DO FOR %%t IN (*.jpg) DO del /s %%p\%%t

The first For is lacking recursive syntax, it should be:

@echo off
FOR /R %%p IN (C:\Users\vexe\Pictures\sample) DO FOR %%t IN (*.jpg) DO del /s %%p\%%t

You can just do:

FOR %%p IN (C:\Users\0300092544\Downloads\Ces_Sce_600) DO @ECHO %%p

to show the actual output.

How to make URL/Phone-clickable UILabel?

If you want this to be handled by UILabel and not UITextView, you can make UILabel subclass, like this one:

class LinkedLabel: UILabel {

fileprivate let layoutManager = NSLayoutManager()
fileprivate let textContainer = NSTextContainer(size: CGSize.zero)
fileprivate var textStorage: NSTextStorage?


override init(frame aRect:CGRect){
    super.init(frame: aRect)
    self.initialize()
}

required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
    self.initialize()
}

func initialize(){

    let tap = UITapGestureRecognizer(target: self, action: #selector(LinkedLabel.handleTapOnLabel))
    self.isUserInteractionEnabled = true
    self.addGestureRecognizer(tap)
}

override var attributedText: NSAttributedString?{
    didSet{
        if let _attributedText = attributedText{
            self.textStorage = NSTextStorage(attributedString: _attributedText)

            self.layoutManager.addTextContainer(self.textContainer)
            self.textStorage?.addLayoutManager(self.layoutManager)

            self.textContainer.lineFragmentPadding = 0.0;
            self.textContainer.lineBreakMode = self.lineBreakMode;
            self.textContainer.maximumNumberOfLines = self.numberOfLines;
        }

    }
}

func handleTapOnLabel(tapGesture:UITapGestureRecognizer){

    let locationOfTouchInLabel = tapGesture.location(in: tapGesture.view)
    let labelSize = tapGesture.view?.bounds.size
    let textBoundingBox = self.layoutManager.usedRect(for: self.textContainer)
    let textContainerOffset = CGPoint(x: ((labelSize?.width)! - textBoundingBox.size.width) * 0.5 - textBoundingBox.origin.x, y: ((labelSize?.height)! - textBoundingBox.size.height) * 0.5 - textBoundingBox.origin.y)

    let locationOfTouchInTextContainer = CGPoint(x: locationOfTouchInLabel.x - textContainerOffset.x, y: locationOfTouchInLabel.y - textContainerOffset.y)
    let indexOfCharacter = self.layoutManager.characterIndex(for: locationOfTouchInTextContainer, in: self.textContainer, fractionOfDistanceBetweenInsertionPoints: nil)


    self.attributedText?.enumerateAttribute(NSLinkAttributeName, in: NSMakeRange(0, (self.attributedText?.length)!), options: NSAttributedString.EnumerationOptions(rawValue: UInt(0)), using:{
        (attrs: Any?, range: NSRange, stop: UnsafeMutablePointer<ObjCBool>) in

        if NSLocationInRange(indexOfCharacter, range){
            if let _attrs = attrs{

                UIApplication.shared.openURL(URL(string: _attrs as! String)!)
            }
        }
    })

}}

This class was made by reusing code from this answer. In order to make attributed strings check out this answer. And here you can find how to make phone urls.

std::string formatting like sprintf

Modern C++ makes this super simple.

C++20

C++20 introduces std::format, which allows you to do exactly that. It uses replacement fields similar to those in python:

#include <iostream>
#include <format>
 
int main() {
    std::cout << std::format("Hello {}!\n", "world");
}

Code from cppreference.com, CC BY-SA and GFDL

Check out the compiler support page to see if it's available in your standard library implementation. As of 2020-11-06, it's not supported by any, so you'll have to resort to the C++11 solution below.


C++11

With C++11s std::snprintf, this already became a pretty easy and safe task.

#include <memory>
#include <string>
#include <stdexcept>

template<typename ... Args>
std::string string_format( const std::string& format, Args ... args )
{
    int size = snprintf( nullptr, 0, format.c_str(), args ... ) + 1; // Extra space for '\0'
    if( size <= 0 ){ throw std::runtime_error( "Error during formatting." ); }
    std::unique_ptr<char[]> buf( new char[ size ] ); 
    snprintf( buf.get(), size, format.c_str(), args ... );
    return std::string( buf.get(), buf.get() + size - 1 ); // We don't want the '\0' inside
}

The code snippet above is licensed under CC0 1.0.

Line by line explanation:

Aim: Write to a char* by using std::snprintf and then convert that to a std::string.

First, we determine the desired length of the char array using a special condition in snprintf. From cppreference.com:

Return value

[...] If the resulting string gets truncated due to buf_size limit, function returns the total number of characters (not including the terminating null-byte) which would have been written, if the limit was not imposed.

This means that the desired size is the number of characters plus one, so that the null-terminator will sit after all other characters and that it can be cut off by the string constructor again. This issue was explained by @alexk7 in the comments.

int size = snprintf( nullptr, 0, format.c_str(), args ... ) + 1;

snprintf will return a negative number if an error occurred, so we then check whether the formatting worked as desired. Not doing this could lead to silent errors or the allocation of a huge buffer, as pointed out by @ead in the comments.

if( size <= 0 ){ throw std::runtime_error( "Error during formatting." ); }

Next, we allocate a new character array and assign it to a std::unique_ptr. This is generally advised, as you won't have to manually delete it again.

Note that this is not a safe way to allocate a unique_ptr with user-defined types as you can not deallocate the memory if the constructor throws an exception!

std::unique_ptr<char[]> buf( new char[ size ] );

After that, we can of course just use snprintf for its intended use and write the formatted string to the char[].

snprintf( buf.get(), size, format.c_str(), args ... );

Finally, we create and return a new std::string from that, making sure to omit the null-terminator at the end.

return std::string( buf.get(), buf.get() + size - 1 );

You can see an example in action here.


If you also want to use std::string in the argument list, take a look at this gist.


Additional information for Visual Studio users:

As explained in this answer, Microsoft renamed std::snprintf to _snprintf (yes, without std::). MS further set it as deprecated and advises to use _snprintf_s instead, however _snprintf_s won't accept the buffer to be zero or smaller than the formatted output and will not calculate the outputs length if that occurs. So in order to get rid of the deprecation warnings during compilation, you can insert the following line at the top of the file which contains the use of _snprintf:

#pragma warning(disable : 4996)

Final thoughts

A lot of answers to this question were written before the time of C++11 and use fixed buffer lengths or vargs. Unless you're stuck with old versions of C++, I wouldn't recommend using those solutions. Ideally, go the C++20 way.

Because the C++11 solution in this answer uses templates, it can generate quite a bit of code if it is used a lot. However, unless you're developing for an environment with very limited space for binaries, this won't be a problem and is still a vast improvement over the other solutions in both clarity and security.

If space efficiency is super important, these two solution with vargs and vsnprintf can be useful. DO NOT USE any solutions with fixed buffer lengths, that is just asking for trouble.

How to get a key in a JavaScript object by its value?

ES6 methods:

Object.fromEntries(Object.entries(a).map(b => b.reverse()))['value_you_look_for']

How do I compare two Integers?

Compare integer and print its value in value ascending or descending order. All you have to do is implements Comparator interface and override its compare method and compare its value as below:

@Override
public int compare(Integer o1, Integer o2) {
    if (ascending) {
        return o1.intValue() - o2.intValue();
    } else {
        return o2.intValue() - o1.intValue();
    }

}

Install pdo for postgres Ubuntu

Pecl PDO package is now deprecated. By the way the debian package php5-pgsql now includes both the regular and the PDO driver, so just:

apt-get install php-pgsql

Apache also needs to be restarted before sites can use it:

sudo systemctl restart apache2

Using if-else in JSP

You may try this example:

_x000D_
_x000D_
<form>_x000D_
  <h1>Hello! I'm duke! What's you name?</h1>_x000D_
  <input type="text" name="user">_x000D_
  <br>_x000D_
  <br>_x000D_
  <input type="submit" value="submit">&nbsp;&nbsp;&nbsp;&nbsp;_x000D_
  <input type="reset">_x000D_
</form>_x000D_
<h1>Hello ${param.user}</h1> _x000D_
<!-- its Expression Language -->
_x000D_
_x000D_
_x000D_

Array of Matrices in MATLAB

If all of the matrices are going to be the same size (i.e. 500x800), then you can just make a 3D array:

nUnknown;  % The number of unknown arrays
myArray = zeros(500,800,nUnknown);

To access one array, you would use the following syntax:

subMatrix = myArray(:,:,3);  % Gets the third matrix

You can add more matrices to myArray in a couple of ways:

myArray = cat(3,myArray,zeros(500,800));
% OR
myArray(:,:,nUnknown+1) = zeros(500,800);

If each matrix is not going to be the same size, you would need to use cell arrays like Hosam suggested.

EDIT: I missed the part about running out of memory. I'm guessing your nUnknown is fairly large. You may have to switch the data type of the matrices (single or even a uintXX type if you are using integers). You can do this in the call to zeros:

myArray = zeros(500,800,nUnknown,'single');

How to automatically close cmd window after batch file execution?

You could try the somewhat dangerous: taskkill /IM cmd.exe ..dangerous bcz that will kill the cmd that is open and any cmd's opened before it.

Or add a verification to confirm that you had the right cmd.exe and then kill it via PID, such as this:

set loc=%time%%random%
title=%loc%
for /f "tokens=2 delims= " %%A in ('tasklist /v ^| findstr /i "%loc%"') do (taskkill /PID %%A) 

Substitute (pslist &&A) or (tasklist /FI "PID eq %%A") for the (taskkill /PID %%A) if you want to check it first (and maybe have pstools installed).

Equivalent of shell 'cd' command to change the working directory?

If you use spyder and love GUI, you can simply click on the folder button on the upper right corner of your screen and navigate through folders/directories you want as current directory. After doing so you can go to the file explorer tab of the window in spyder IDE and you can see all the files/folders present there. to check your current working directory go to the console of spyder IDE and simply type

pwd

it will print the same path as you have selected before.

how to console.log result of this ajax call?

Ajax call error handler will be triggered if the call itself fails.

You are probably trying to get the error from server in case login credentials do not go through. In that case, you need to inspect the server response json object and display appropriate message.

e.preventDefault();
$.ajax(
{
    type: 'POST',
    url: requestURI,
    data: $(formLogin).serialize(),
    dataType: 'json',
    success: function(result){
        if(result.hasError == true)
        {
            if(result.error_code == 'AUTH_FAILURE')
            {
                //wrong password
                console.log('Recieved authentication error');
                $('#login_errors_auth').fadeIn();
            }
            else
            {
                //generic error here
                $('#login_errors_unknown').fadeIn();
            }
        }
    }
});

Here, "result" is the json object returned form the server which could have a structure like:

$return = array(
        'hasError' => !$validPassword,
        'error_code' => 'AUTH_FAILURE'
);
die(jsonEncode($return));

Return value from a VBScript function

To return a value from a VBScript function, assign the value to the name of the function, like this:

Function getNumber
    getNumber = "423"
End Function

Add inline style using Javascript

var div = document.createElement('div');
div.setAttribute('style', 'width:330px; float:left');
div.setAttribute('class', 'well');
var label = document.createElement('label');
label.innerHTML = 'YOUR TEXT HERE';
div.appendChild(label);

node.js Error: connect ECONNREFUSED; response from server

I had the same problem on my mac, but in my case, the problem was that I did not run the database (sudo mongod) before; the problem was solved when I first ran the mondo sudod on the console and, once it was done, on another console, the connection to the server ...

SQL - How do I get only the numbers after the decimal?

If you want to select only decimal numbers use this WHERE clause:

    (CAST(RIGHT(Myfield, LEN( Myfield)-CHARINDEX('.',Myfield)+1 ) AS FLOAT)) <> 0

If you want a clear list you can sort by decimal/integer:

    CASE WHEN 0 = CAST(RIGHT(Myfield, LEN( Myfield)-CHARINDEX('.',Myfield)+1 ) AS FLOAT) THEN 'Integer' ELSE 'Decimal' END AS Type

Access 2010 VBA query a table and iterate through results

I know some things have changed in AC 2010. However, the old-fashioned ADODB is, as far as I know, the best way to go in VBA. An Example:

Dim cn As ADODB.Connection
Dim cmd As ADODB.Command
Dim prm As ADODB.Parameter
Dim rs As ADODB.Recordset
Dim colReturn As New Collection

Dim SQL As String
SQL = _
    "SELECT c.ClientID, c.LastName, c.FirstName, c.MI, c.DOB, c.SSN, " & _
    "c.RaceID, c.EthnicityID, c.GenderID, c.Deleted, c.RecordDate " & _
    "FROM tblClient AS c " & _
    "WHERE c.ClientID = @ClientID"

Set cn = New ADODB.Connection
Set cmd = New ADODB.Command

With cn
    .Provider = DataConnection.MyADOProvider
    .ConnectionString = DataConnection.MyADOConnectionString
    .Open
End With

With cmd
    .CommandText = SQL
    .ActiveConnection = cn
    Set prm = .CreateParameter("@ClientID", adInteger, adParamInput, , mlngClientID)
    .Parameters.Append prm
End With

Set rs = cmd.Execute

With rs
    If Not .EOF Then
        Do Until .EOF
            mstrLastName = Nz(!LastName, "")
            mstrFirstName = Nz(!FirstName, "")
            mstrMI = Nz(!MI, "")
            mdDOB = !DOB
            mstrSSN = Nz(!SSN, "")
            mlngRaceID = Nz(!RaceID, -1)
            mlngEthnicityID = Nz(!EthnicityID, -1)
            mlngGenderID = Nz(!GenderID, -1)
            mbooDeleted = Deleted
            mdRecordDate = Nz(!RecordDate, "")

            .MoveNext
        Loop
    End If
    .Close
End With

cn.Close

Set rs = Nothing
Set cn = Nothing

How can I rename a field for all documents in MongoDB?

Anyone could potentially use this command to rename a field from the collection (By not using any _id):

dbName.collectionName.update({}, {$rename:{"oldFieldName":"newFieldName"}}, false, true);

see FYI

JavaScript: remove event listener

Try this, it worked for me.

<button id="btn">Click</button>
<script>
 console.log(btn)
 let f;
 btn.addEventListener('click', f=function(event) {
 console.log('Click')
 console.log(f)
 this.removeEventListener('click',f)
 console.log('Event removed')
})  
</script>

How to remove a build from itunes connect?

Choose the build

The answer is that you Mouse over the icon for your build and at the end of the line you'll see a little colored minus in a circle. This removes the build and you can now click on the + sign and choose a new build for submitting.

It is an unbelievably complicated web page with tricks and gizmos to do the thing you want. I'm sure Steve never saw this page or tried to use it.

Surely it's better practice to design the screen so that you can see the options all the time, not to have the screen change depending on whether you have an app in review or not!

newline in <td title="">

Using &#013; didn't work in my fb app. However this did, beautifully (in Chrome FF and IE):

<img src="'../images/foo.gif'" title="line 1&lt;br&gt;line 2">

Javascript: Uncaught TypeError: Cannot call method 'addEventListener' of null

Your code is in the <head> => runs before the elements are rendered, so document.getElementById('compute'); returns null, as MDN promise...

element = document.getElementById(id);
element is a reference to an Element object, or null if an element with the specified ID is not in the document.

MDN

Solutions:

  1. Put the scripts in the bottom of the page.
  2. Call the attach code in the load event.
  3. Use jQuery library and it's DOM ready event.

What is the jQuery ready event and why is it needed?
(why no just JavaScript's load event):

While JavaScript provides the load event for executing code when a page is rendered, this event does not get triggered until all assets such as images have been completely received. In most cases, the script can be run as soon as the DOM hierarchy has been fully constructed. The handler passed to .ready() is guaranteed to be executed after the DOM is ready, so this is usually the best place to attach all other event handlers...
...

ready docs

PowerShell array initialization

Yet another alternative:

for ($i = 0; $i -lt 5; $i++) 
{ 
  $arr += @($false) 
}

This one works if $arr isn't defined yet.

NOTE - there are better (and more performant) ways to do this... see https://stackoverflow.com/a/234060/4570 below as an example.

What port is used by Java RMI connection?

From the javadoc of java.rmi.registry.Registry

Therefore, a registry's remote object implementation is typically exported with a well-known address, such as with a well-known ObjID and TCP port number (default is 1099).

See more in the javadoc of java.rmi.registry.LocateRegistry.

Error: Could not create the Java Virtual Machine Mac OSX Mavericks

if you tried running java with -version argument, and even though the problem could not be solved by any means, then you might have installed many java versions, like JDK 1.8 and JDK 1.7 at the same time.

So try uninstalling all other versions other than the one you need, then set the JAVA_HOMEpath variable for that JDK remaining, and you're done.

How to break out of nested loops?

A different approach is to refactor the code from two for loops into a for loop and one manual loop. That way the break in the manual loop applies to the outer loop. I used this once in a Gauss-Jordan Elimination which required three nested loops to process.

for (int i = 0; i < 1000; i++)
{
    int j = 0;

MANUAL_LOOP:;

    if (j < 1000)
    {
       if (condition)
       {
           break;
       }

       j++;
       goto MANUAL_LOOP;
    }
}

How can you remove all documents from a collection with Mongoose?

MongoDB shell version v4.2.6
Node v14.2.0

Assuming you have a Tour Model: tourModel.js

const mongoose = require('mongoose');

const tourSchema = new mongoose.Schema({
  name: {
    type: String,
    required: [true, 'A tour must have a name'],
    unique: true,
    trim: true,
  },
  createdAt: {
    type: Date,
    default: Date.now(),
  },
});
const Tour = mongoose.model('Tour', tourSchema);

module.exports = Tour;

Now you want to delete all tours at once from your MongoDB, I also providing connection code to connect with the remote cluster. I used deleteMany(), if you do not pass any args to deleteMany(), then it will delete all the documents in Tour collection.

const mongoose = require('mongoose');
const Tour = require('./../../models/tourModel');
const conStr = 'mongodb+srv://lord:<PASSWORD>@cluster0-eeev8.mongodb.net/tour-guide?retryWrites=true&w=majority';
const DB = conStr.replace('<PASSWORD>','ADUSsaZEKESKZX');
mongoose.connect(DB, {
    useNewUrlParser: true,
    useCreateIndex: true,
    useFindAndModify: false,
    useUnifiedTopology: true,
  })
  .then((con) => {
    console.log(`DB connection successful ${con.path}`);
  });

const deleteAllData = async () => {
  try {
    await Tour.deleteMany();
    console.log('All Data successfully deleted');
  } catch (err) {
    console.log(err);
  }
};

If list index exists, do X

Could it be more useful for you to use the length of the list len(n) to inform your decision rather than checking n[i] for each possible length?

convert xml to java object using jaxb (unmarshal)

Tests

On the Tests class we will add an @XmlRootElement annotation. Doing this will let your JAXB implementation know that when a document starts with this element that it should instantiate this class. JAXB is configuration by exception, this means you only need to add annotations where your mapping differs from the default. Since the testData property differs from the default mapping we will use the @XmlElement annotation. You may find the following tutorial helpful: http://wiki.eclipse.org/EclipseLink/Examples/MOXy/GettingStarted

package forum11221136;

import javax.xml.bind.annotation.*;

@XmlRootElement
public class Tests {

    TestData testData;

    @XmlElement(name="test-data")
    public TestData getTestData() {
        return testData;
    }

    public void setTestData(TestData testData) {
        this.testData = testData;
    }

}

TestData

On this class I used the @XmlType annotation to specify the order in which the elements should be ordered in. I added a testData property that appeared to be missing. I also used an @XmlElement annotation for the same reason as in the Tests class.

package forum11221136;

import java.util.List;
import javax.xml.bind.annotation.*;

@XmlType(propOrder={"title", "book", "count", "testData"})
public class TestData {
    String title;
    String book;
    String count;
    List<TestData> testData;

    public String getTitle() {
        return title;
    }
    public void setTitle(String title) {
        this.title = title;
    }
    public String getBook() {
        return book;
    }
    public void setBook(String book) {
        this.book = book;
    }
    public String getCount() {
        return count;
    }
    public void setCount(String count) {
        this.count = count;
    }
    @XmlElement(name="test-data")
    public List<TestData> getTestData() {
        return testData;
    }
    public void setTestData(List<TestData> testData) {
        this.testData = testData;
    }
}

Demo

Below is an example of how to use the JAXB APIs to read (unmarshal) the XML and populate your domain model and then write (marshal) the result back to XML.

package forum11221136;

import java.io.File;
import javax.xml.bind.*;

public class Demo {

    public static void main(String[] args) throws Exception {
        JAXBContext jc = JAXBContext.newInstance(Tests.class);

        Unmarshaller unmarshaller = jc.createUnmarshaller();
        File xml = new File("src/forum11221136/input.xml");
        Tests tests = (Tests) unmarshaller.unmarshal(xml);

        Marshaller marshaller = jc.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.marshal(tests, System.out);
    }

}

Batch file for PuTTY/PSFTP file transfer automation

set DSKTOPDIR="D:\test"
set IPADDRESS="23.23.3.23"

>%DSKTOPDIR%\script.ftp ECHO cd %PAY_REP%
>>%DSKTOPDIR%\script.ftp ECHO mget *.report
>>%DSKTOPDIR%\script.ftp ECHO bye

:: run PSFTP Commands
psftp <domain>@%IPADDRESS% -b %DSKTOPDIR%\script.ftp

Set values using set commands before above lines.

I believe this helps you.

Referre psfpt setup for below link https://www.ssh.com/ssh/putty/putty-manuals/0.68/Chapter6.html

Mail not sending with PHPMailer over SSL using SMTP

$mail->IsSMTP();
$mail->Host = "smtp.gmail.com";
$mail->SMTPAuth = true;
$mail->SMTPSecure = "ssl";
$mail->Username = "[email protected]";
$mail->Password = "**********";
$mail->Port = "465";

That is a working configuration.

try to replace what you have

Export tables to an excel spreadsheet in same directory

For people who find this via search engines, you do not need VBA. You can just:

1.) select the query or table with your mouse
2.) click export data from the ribbon
3.) click excel from the export subgroup
4.) follow the wizard to select the output file and location.

Using putty to scp from windows to Linux

Use scp priv_key.pem source user@host:target if you need to connect using a private key.

or if using pscp then use pscp -i priv_key.ppk source user@host:target

How can I reconcile detached HEAD with master/origin?

Instead of doing git checkout origin/master

just do git checkout master

then git branch will confirm your branch.

R solve:system is exactly singular

Lapack is a Linear Algebra package which is used by R (actually it's used everywhere) underneath solve(), dgesv spits this kind of error when the matrix you passed as a parameter is singular.

As an addendum: dgesv performs LU decomposition, which, when using your matrix, forces a division by 0, since this is ill-defined, it throws this error. This only happens when matrix is singular or when it's singular on your machine (due to approximation you can have a really small number be considered 0)

I'd suggest you check its determinant if the matrix you're using contains mostly integers and is not big. If it's big, then take a look at this link.

Simplest/cleanest way to implement a singleton in JavaScript

Singleton:

Ensure a class has only one instance and provides a global point of access to it.

The singleton pattern limits the number of instances of a particular object to just one. This single instance is called the singleton.

  • defines getInstance() which returns the unique instance.
  • responsible for creating and managing the instance object.

The singleton object is implemented as an immediate anonymous function. The function executes immediately by wrapping it in brackets followed by two additional brackets. It is called anonymous because it doesn't have a name.

Sample Program

_x000D_
_x000D_
var Singleton = (function () {
    var instance;

    function createInstance() {
        var object = new Object("I am the instance");
        return object;
    }

    return {
        getInstance: function () {
            if (!instance) {
                instance = createInstance();
            }
            return instance;
        }
    };
})();

function run() {

    var instance1 = Singleton.getInstance();
    var instance2 = Singleton.getInstance();

    alert("Same instance? " + (instance1 === instance2));
}

run()
_x000D_
_x000D_
_x000D_

Remove the first character of a string

Your problem seems unclear. You say you want to remove "a character from a certain position" then go on to say you want to remove a particular character.

If you only need to remove the first character you would do:

s = ":dfa:sif:e"
fixed = s[1:]

If you want to remove a character at a particular position, you would do:

s = ":dfa:sif:e"
fixed = s[0:pos]+s[pos+1:]

If you need to remove a particular character, say ':', the first time it is encountered in a string then you would do:

s = ":dfa:sif:e"
fixed = ''.join(s.split(':', 1))

How to verify Facebook access token?

Simply request (HTTP GET):

https://graph.facebook.com/USER_ID/access_token=xxxxxxxxxxxxxxxxx

That's it.

How To Accept a File POST

Here is a quick and dirty solution which takes uploaded file contents from the HTTP body and writes it to a file. I included a "bare bones" HTML/JS snippet for the file upload.

Web API Method:

[Route("api/myfileupload")]        
[HttpPost]
public string MyFileUpload()
{
    var request = HttpContext.Current.Request;
    var filePath = "C:\\temp\\" + request.Headers["filename"];
    using (var fs = new System.IO.FileStream(filePath, System.IO.FileMode.Create))
    {
        request.InputStream.CopyTo(fs);
    }
    return "uploaded";
}

HTML File Upload:

<form>
    <input type="file" id="myfile"/>  
    <input type="button" onclick="uploadFile();" value="Upload" />
</form>
<script type="text/javascript">
    function uploadFile() {        
        var xhr = new XMLHttpRequest();                 
        var file = document.getElementById('myfile').files[0];
        xhr.open("POST", "api/myfileupload");
        xhr.setRequestHeader("filename", file.name);
        xhr.send(file);
    }
</script>

div background color, to change onhover

You can just put the anchor around the div.

<a class="big-link"><div>this is a div</div></a>

and then

a.big-link {
background-color: 888;
}
a.big-link:hover {
 background-color: f88;
}

How to write to error log file in PHP

you can simply use :

error_log("your message");

By default, the message will be send to the php system logger.

How can I switch themes in Visual Studio 2012

Slightly off topic, but for those of you that want to modify the built-in colors of the Dark/Light themes you can use this little tool I wrote for Visual Studio 2012.

More info here:

Modify Visual Studio 2012 Dark (and Light) Themes

Source Code

xlsxwriter: is there a way to open an existing worksheet in my workbook?

After searching a bit about the method to open the existing sheet in xlxs, i discovered

existingWorksheet = wb.get_worksheet_by_name('Your Worksheet name goes here...')
existingWorksheet.write_row(0,0,'xyz')

You can now append/write any data to the open worksheet. I hope it helps. Thanks

How to program a fractal?

There is a great book called Chaos and Fractals that has simple example code at the end of each chapter that implements some fractal or other example. A long time ago when I read that book, I converted each sample program (in some Basic dialect) into a Java applet that runs on a web page. The applets are here: http://hewgill.com/chaos-and-fractals/

One of the samples is a simple Mandelbrot implementation.

Get all child elements

Yes, you can use find_elements_by_ to retrieve children elements into a list. See the python bindings here: http://selenium-python.readthedocs.io/locating-elements.html

Example HTML:

<ul class="bar">
    <li>one</li>
    <li>two</li>
    <li>three</li>
</ul>

You can use the find_elements_by_ like so:

parentElement = driver.find_element_by_class_name("bar")
elementList = parentElement.find_elements_by_tag_name("li")

If you want help with a specific case, you can edit your post with the HTML you're looking to get parent and children elements from.

Executing Shell Scripts from the OS X Dock?

I know this is old but in case it is helpful to others:

If you need to run a script and want the terminal to pop up so you can see the results you can do like Abyss Knight said and change the extension to .command. If you double click on it it will open a terminal window and run.

I however needed this to run from automator or appleScript. So to get this to open a new terminal the command I ran from "run shell script" was "open myShellScript.command" and it opened in a new terminal.

'Incomplete final line' warning when trying to read a .csv file into R

Are you really sure that you selected the .csv file and not the .xls file? I can only reproduce the error if I try to read in an .xls file. If I try to read in a .csv file or any other text file, it's impossible to recreate the error you get.

> Data <- read.table("test.csv",header=T,sep=",")
> Data <- read.table("test.xlsx",header=T,sep=",")
Warning message:
In read.table("test.xlsx", header = T, sep = ",") :
  incomplete final line found by readTableHeader on 'test.xlsx'

readTableHead is the c-function that gives the error. It tries to read in the first n lines (standard the first 5 ) to determine the type of the data. The rest of the data is read in using scan(). So the problem is the format of the file.

One way of finding out, is to set the working directory to the directory where the file is. That way you see the extension of the file you read in. I know on Windows it's not shown standard, so you might believe it's csv while it isn't.

The next thing you should do, is open the file in Notepad or Wordpad (or another editor) and check that the format is equivalent to my file test.csv:

Test1,Test2,Test3
1,1,1
2,2,2
3,3,3
4,4,
5,5,
,6,

This file will give you the following dataframe :

> read.table(testfile,header=T,sep=",")
  Test1 Test2 Test3
1     1     1     1
2     2     2     2
3     3     3     3
4     4     4    NA
5     5     5    NA
6    NA     6    NA

The csv format saved by excel seperates all cells with a comma. Empty cells just don't have a value. read.table() can easily deal with this, and recognizes empty cells just fine.

Sass Nesting for :hover does not work

You can easily debug such things when you go through the generated CSS. In this case the pseudo-selector after conversion has to be attached to the class. Which is not the case. Use "&".

http://sass-lang.com/documentation/file.SASS_REFERENCE.html#parent-selector

.class {
    margin:20px;
    &:hover {
        color:yellow;
    }
}

cast class into another class or convert class to another

You could change your class structure to:

public class maincs : sub1
{
   public int d; 
}

public class sub1
{
   public int a;
   public int b;
   public int c;
}

Then you could keep a list of sub1 and cast some of them to mainc.

Sending simple message body + file attachment using Linux Mailx

On RHEL Linux, I had trouble getting my message in the body of the email instead of as an attachment . Using od -cx, I found that the body of my email contained several /r. I used a perl script to strip the /r, and the message was correctly inserted into the body of the email.

mailx -s "subject text" [email protected] < 'body.txt'

The text file body.txt contained the char \r, so I used perl to strip \r.

cat body.txt | perl success.pl > body2.txt
mailx -s "subject text" [email protected] < 'body2.txt'

This is success.pl

    while (<STDIN>) {
        my $currLine = $_;
        s?\r??g;
        print
    }
;

casting Object array to Integer array error

java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.lang.Integer;

you try to cast an Array of Object to cast into Array of Integer. You cant do it. This type of downcast is not permitted.

You can make an array of Integer, and after that copy every value of the first array into second array.

ExecuteReader: Connection property has not been initialized

I like to place all my sql connections in using statements. I think they look cleaner, and they clean up after themselves when your done with them. I also recommend parameterizing every query, not only is it much safer but it is easier to maintain if you need to come back and make changes.

// create/open connection
using (SqlConnection conn = new SqlConnection("Data Source=Si-6\\SQLSERVER2005;Initial Catalog=rags;Integrated Security=SSPI")
{
    try
    {
        conn.Open();

        // initialize command
        using (SqlCommand cmd = conn.CreateCommand())
        {

            // generate query with parameters
            with cmd
            {
                .CommandType = CommandType.Text;
                .CommandText = "insert into time(project,iteration) values(@name, @iteration)";
                .Parameters.Add(new SqlParameter("@name", this.name1.SelectedValue));
                .Parameters.Add(new SqlParameter("@iteration", this.iteration.SelectedValue));
                .ExecuteNonQuery();
            }
        }
    }
    catch (Exception)
    {
        //throw;
    }
    finally
    {
        if (conn != null && conn.State == ConnectionState.Open)
        {
            conn.Close;
        }
    }
}

How to check if an element is off-screen

Well... I've found some issues in every proposed solution here.

  • You should be able to choose if you want entire element to be on screen or just any part of it
  • Proposed solutions fails if element is higher/wider than window and kinda covers browser window.

Here is my solution that include jQuery .fn instance function and expression. I've created more variables inside my function than I could, but for complex logical problem I like to divide it into smaller, clearly named pieces.

I'm using getBoundingClientRect method that returns element position relatively to the viewport so I don't need to care about scroll position

Useage:

$(".some-element").filter(":onscreen").doSomething();
$(".some-element").filter(":entireonscreen").doSomething();
$(".some-element").isOnScreen(); // true / false
$(".some-element").isOnScreen(true); // true / false (partially on screen)
$(".some-element").is(":onscreen"); // true / false (partially on screen)
$(".some-element").is(":entireonscreen"); // true / false 

Source:

$.fn.isOnScreen = function(partial){

    //let's be sure we're checking only one element (in case function is called on set)
    var t = $(this).first();

    //we're using getBoundingClientRect to get position of element relative to viewport
    //so we dont need to care about scroll position
    var box = t[0].getBoundingClientRect();

    //let's save window size
    var win = {
        h : $(window).height(),
        w : $(window).width()
    };

    //now we check against edges of element

    //firstly we check one axis
    //for example we check if left edge of element is between left and right edge of scree (still might be above/below)
    var topEdgeInRange = box.top >= 0 && box.top <= win.h;
    var bottomEdgeInRange = box.bottom >= 0 && box.bottom <= win.h;

    var leftEdgeInRange = box.left >= 0 && box.left <= win.w;
    var rightEdgeInRange = box.right >= 0 && box.right <= win.w;


    //here we check if element is bigger then window and 'covers' the screen in given axis
    var coverScreenHorizontally = box.left <= 0 && box.right >= win.w;
    var coverScreenVertically = box.top <= 0 && box.bottom >= win.h;

    //now we check 2nd axis
    var topEdgeInScreen = topEdgeInRange && ( leftEdgeInRange || rightEdgeInRange || coverScreenHorizontally );
    var bottomEdgeInScreen = bottomEdgeInRange && ( leftEdgeInRange || rightEdgeInRange || coverScreenHorizontally );

    var leftEdgeInScreen = leftEdgeInRange && ( topEdgeInRange || bottomEdgeInRange || coverScreenVertically );
    var rightEdgeInScreen = rightEdgeInRange && ( topEdgeInRange || bottomEdgeInRange || coverScreenVertically );

    //now knowing presence of each edge on screen, we check if element is partially or entirely present on screen
    var isPartiallyOnScreen = topEdgeInScreen || bottomEdgeInScreen || leftEdgeInScreen || rightEdgeInScreen;
    var isEntirelyOnScreen = topEdgeInScreen && bottomEdgeInScreen && leftEdgeInScreen && rightEdgeInScreen;

    return partial ? isPartiallyOnScreen : isEntirelyOnScreen;

};

$.expr.filters.onscreen = function(elem) {
  return $(elem).isOnScreen(true);
};

$.expr.filters.entireonscreen = function(elem) {
  return $(elem).isOnScreen(true);
};

UUID max character length

Section 3 of RFC4122 provides the formal definition of UUID string representations. It's 36 characters (32 hex digits + 4 dashes).

Sounds like you need to figure out where the invalid 60-char IDs are coming from and decide 1) if you want to accept them, and 2) what the max length of those IDs might be based on whatever API is used to generate them.

How can I exclude a directory from Visual Studio Code "Explore" tab?

In version 1.28 of Visual Studio Code "files.exclude" must be placed within a settings node.

Resulting in a workspace file that looks like:

{
    "settings": {
        "files.exclude": {
            "**/node_modules": true
        }
    }
}

How can I check if a Perl module is installed on my system from the command line?

What you're doing there is not recursing into directories. It is only listing the modules in the root directory of the @INC directory.

The module XML::Simple will live in one of the @INC paths under XML/Simple.pm.

What he said above to find specific modules.

CPAN explains how to find all modules here, see How to find installed modules.

commons httpclient - Adding query string parameters to GET/POST request

This approach is ok but will not work for when you get params dynamically , sometimes 1, 2, 3 or more, just like a SOLR search query (for example)

Here is a more flexible solution. Crude but can be refined.

public static void main(String[] args) {

    String host = "localhost";
    String port = "9093";

    String param = "/10-2014.01?description=cars&verbose=true&hl=true&hl.simple.pre=<b>&hl.simple.post=</b>";
    String[] wholeString = param.split("\\?");
    String theQueryString = wholeString.length > 1 ? wholeString[1] : "";

    String SolrUrl = "http://" + host + ":" + port + "/mypublish-services/carclassifications/" + "loc";

    GetMethod method = new GetMethod(SolrUrl );

    if (theQueryString.equalsIgnoreCase("")) {
        method.setQueryString(new NameValuePair[]{
        });
    } else {
        String[] paramKeyValuesArray = theQueryString.split("&");
        List<String> list = Arrays.asList(paramKeyValuesArray);
        List<NameValuePair> nvPairList = new ArrayList<NameValuePair>();
        for (String s : list) {
            String[] nvPair = s.split("=");
            String theKey = nvPair[0];
            String theValue = nvPair[1];
            NameValuePair nameValuePair = new NameValuePair(theKey, theValue);
            nvPairList.add(nameValuePair);
        }
        NameValuePair[] nvPairArray = new NameValuePair[nvPairList.size()];
        nvPairList.toArray(nvPairArray);
        method.setQueryString(nvPairArray);       // Encoding is taken care of here by setQueryString

    }
}

How do I parse an ISO 8601-formatted date?

In these days, Arrow also can be used as a third-party solution:

>>> import arrow
>>> date = arrow.get("2008-09-03T20:56:35.450686Z")
>>> date.datetime
datetime.datetime(2008, 9, 3, 20, 56, 35, 450686, tzinfo=tzutc())

How to convert Excel values into buckets?

The right tool for that is to create a range with your limits and the corresponding names. You can then use the vlookup() function, with the 4th parameter set to Trueto create a range lookup.

enter image description here

Note: my PC uses ; as separator, yours might use ,.
Adjust formula according to your regional settings.

Replace string within file contents

with open('Stud.txt','r') as f:
    newlines = []
    for line in f.readlines():
        newlines.append(line.replace('A', 'Orange'))
with open('Stud.txt', 'w') as f:
    for line in newlines:
        f.write(line)

Spring MVC: how to create a default controller for index page?

It works for me, but some differences:

  • I have no welcome-file-list in web.xml
  • I have no @RequestMapping at class level.
  • And at method level, just @RequestMapping("/")

I know these are no great differences, but I'm pretty sure (I'm not at work now) this is my configuration and it works with Spring MVC 3.0.5.

One more thing. You don't show your dispatcher configuration in web.xml, but maybe you have some preffix. It has to be something like this:

<servlet-mapping>
    <servlet-name>myServletName</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>

If this is not your case, you'll need an url-rewrite filter or try the redirect solution.

EDIT: Answering your question, my view resolver configuration is a little different too:

<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="prefix" value="/WEB-INF/view/" />
    <property name="suffix" value=".jsp" />
</bean>

Disable keyboard on EditText

You can also use setShowSoftInputOnFocus(boolean) directly on API 21+ or through reflection on API 14+:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
    editText.setShowSoftInputOnFocus(false);
} else {
    try {
        final Method method = EditText.class.getMethod(
                "setShowSoftInputOnFocus"
                , new Class[]{boolean.class});
        method.setAccessible(true);
        method.invoke(editText, false);
    } catch (Exception e) {
        // ignore
    }
}

Create Directory When Writing To File In Node.js

With node-fs-extra you can do it easily.

Install it

npm install --save fs-extra

Then use the outputFile method. Its documentation says:

Almost the same as writeFile (i.e. it overwrites), except that if the parent directory does not exist, it's created.

You can use it in three ways:

Callback style

const fse = require('fs-extra');

fse.outputFile('tmp/test.txt', 'Hey there!', err => {
  if(err) {
    console.log(err);
  } else {
    console.log('The file was saved!');
  }
})

Using Promises

If you use promises, and I hope so, this is the code:

fse.outputFile('tmp/test.txt', 'Hey there!')
   .then(() => {
       console.log('The file was saved!');
   })
   .catch(err => {
       console.error(err)
   });

Sync version

If you want a sync version, just use this code:

fse.outputFileSync('tmp/test.txt', 'Hey there!')

For a complete reference, check the outputFile documentation and all node-fs-extra supported methods.

Bring a window to the front in WPF

Well I figured out a work around. I'm making the call from a keyboard hook used to implement a hotkey. The call works as expected if I put it into a BackgroundWorker with a pause. It's a kludge, but I have no idea why it wasn't working originally.

void hotkey_execute()
{
    IntPtr handle = new WindowInteropHelper(Application.Current.MainWindow).Handle;
    BackgroundWorker bg = new BackgroundWorker();
    bg.DoWork += new DoWorkEventHandler(delegate
        {
            Thread.Sleep(10);
            SwitchToThisWindow(handle, true);
        });
    bg.RunWorkerAsync();
}

How to alter a column and change the default value?

ALTER TABLE foobar_data MODIFY COLUMN col VARCHAR(255) NOT NULL DEFAULT '{}';

A second possibility which does the same (thanks to juergen_d):

ALTER TABLE foobar_data CHANGE COLUMN col col VARCHAR(255) NOT NULL DEFAULT '{}';

iterating and filtering two lists using java 8

If you stream the first list and use a filter based on contains within the second...

list1.stream()
    .filter(item -> !list2.contains(item))

The next question is what code you'll add to the end of this streaming operation to further process the results... over to you.

Also, list.contains is quite slow, so you would be better with sets.

But then if you're using sets, you might find some easier operations to handle this, like removeAll

Set list1 = ...;
Set list2 = ...;
Set target = new Set();
target.addAll(list1);
target.removeAll(list2);

Given we don't know how you're going to use this, it's not really possible to advise which approach to take.

Making an svg image object clickable with onclick, avoiding absolute positioning

Perhaps what you're looking for is the SVG element's pointer-events property, which you can read about at the SVG w3C working group docs.

You can use CSS to set what happens to the SVG element when it is clicked, etc.

CSS table-cell equal width

Here is a working fiddle with indeterminate number of cells: http://jsfiddle.net/r9yrM/1/

You can fix a width to each parent div (the table), otherwise it'll be 100% as usual.

The trick is to use table-layout: fixed; and some width on each cell to trigger it, here 2%. That will trigger the other table algorightm, the one where browsers try very hard to respect the dimensions indicated.
Please test with Chrome (and IE8- if needed). It's OK with a recent Safari but I can't remember the compatibility of this trick with them.

CSS (relevant instructions):

div {
    display: table;
    width: 250px;
    table-layout: fixed;
}

div > div {
    display: table-cell;
    width: 2%; /* or 100% according to OP comment. See edit about Safari 6 below */
}

EDIT (2013): Beware of Safari 6 on OS X, it has table-layout: fixed; wrong (or maybe just different, very different from other browsers. I didn't proof-read CSS2.1 REC table layout ;) ). Be prepared to different results.

could not extract ResultSet in hibernate

I faced the same problem after migrating a database from online server to localhost. The schema changed so I had to define the schema manually for each table:

@Entity
@Table(name = "ESBCORE_DOMAIN", schema = "SYS")

Find Item in ObservableCollection without using a loop

I'd suggest storing these in a Hashtable. You can then access an item in the collection using the key, it's a much more efficient lookup.

var myObjects = new Hashtable();
myObjects.Add(yourObject.Title, yourObject);
...
var myRetrievedObject = myObjects["TargetTitle"];

Is there a better alternative than this to 'switch on type'?

For built-in types, you can use the TypeCode enumeration. Please note that GetType() is kind of slow, but probably not relevant in most situations.

switch (Type.GetTypeCode(someObject.GetType()))
{
    case TypeCode.Boolean:
        break;
    case TypeCode.Byte:
        break;
    case TypeCode.Char:
        break;
}

For custom types, you can create your own enumeration, and either an interface or a base class with abstract property or method...

Abstract class implementation of property

public enum FooTypes { FooFighter, AbbreviatedFool, Fubar, Fugu };
public abstract class Foo
{
    public abstract FooTypes FooType { get; }
}
public class FooFighter : Foo
{
    public override FooTypes FooType { get { return FooTypes.FooFighter; } }
}

Abstract class implementation of method

public enum FooTypes { FooFighter, AbbreviatedFool, Fubar, Fugu };
public abstract class Foo
{
    public abstract FooTypes GetFooType();
}
public class FooFighter : Foo
{
    public override FooTypes GetFooType() { return FooTypes.FooFighter; }
}

Interface implementation of property

public enum FooTypes { FooFighter, AbbreviatedFool, Fubar, Fugu };
public interface IFooType
{
    FooTypes FooType { get; }
}
public class FooFighter : IFooType
{
    public FooTypes FooType { get { return FooTypes.FooFighter; } }
}

Interface implementation of method

public enum FooTypes { FooFighter, AbbreviatedFool, Fubar, Fugu };
public interface IFooType
{
    FooTypes GetFooType();
}
public class FooFighter : IFooType
{
    public FooTypes GetFooType() { return FooTypes.FooFighter; }
}

One of my coworkers just told me about this too: This has the advantage that you can use it for literally any type of object, not just ones that you define. It has the disadvantage of being a bit larger and slower.

First define a static class like this:

public static class TypeEnumerator
{
    public class TypeEnumeratorException : Exception
    {
        public Type unknownType { get; private set; }
        public TypeEnumeratorException(Type unknownType) : base()
        {
            this.unknownType = unknownType;
        }
    }
    public enum TypeEnumeratorTypes { _int, _string, _Foo, _TcpClient, };
    private static Dictionary<Type, TypeEnumeratorTypes> typeDict;
    static TypeEnumerator()
    {
        typeDict = new Dictionary<Type, TypeEnumeratorTypes>();
        typeDict[typeof(int)] = TypeEnumeratorTypes._int;
        typeDict[typeof(string)] = TypeEnumeratorTypes._string;
        typeDict[typeof(Foo)] = TypeEnumeratorTypes._Foo;
        typeDict[typeof(System.Net.Sockets.TcpClient)] = TypeEnumeratorTypes._TcpClient;
    }
    /// <summary>
    /// Throws NullReferenceException and TypeEnumeratorException</summary>
    /// <exception cref="System.NullReferenceException">NullReferenceException</exception>
    /// <exception cref="MyProject.TypeEnumerator.TypeEnumeratorException">TypeEnumeratorException</exception>
    public static TypeEnumeratorTypes EnumerateType(object theObject)
    {
        try
        {
            return typeDict[theObject.GetType()];
        }
        catch (KeyNotFoundException)
        {
            throw new TypeEnumeratorException(theObject.GetType());
        }
    }
}

And then you can use it like this:

switch (TypeEnumerator.EnumerateType(someObject))
{
    case TypeEnumerator.TypeEnumeratorTypes._int:
        break;
    case TypeEnumerator.TypeEnumeratorTypes._string:
        break;
}

Web Reference vs. Service Reference

Adding a service reference allows you to create a WCF client, which can be used to talk to a regular web service provided you use the appropriate binding. Adding a web reference will allow you to create only a web service (i.e., SOAP) reference.

If you are absolutely certain you are not ready for WCF (really don't know why) then you should create a regular web service reference.

How do I call a non-static method from a static method in C#?

Static method never allows a non-static method call directly.

Reason: Static method belongs to its class only, and to nay object or any instance.

So, whenever you try to access any non-static method from static method inside the same class: you will receive:

"An object reference is required for the non-static field, method or property".

Solution: Just declare a reference like:

public class <classname>
{
static method()
{
   new <classname>.non-static();
}

non-static method()
{

}


}

How to copy files from 'assets' folder to sdcard?

If anyone else is having the same problem, this is how I did it

private void copyAssets() {
    AssetManager assetManager = getAssets();
    String[] files = null;
    try {
        files = assetManager.list("");
    } catch (IOException e) {
        Log.e("tag", "Failed to get asset file list.", e);
    }
    if (files != null) for (String filename : files) {
        InputStream in = null;
        OutputStream out = null;
        try {
          in = assetManager.open(filename);
          File outFile = new File(getExternalFilesDir(null), filename);
          out = new FileOutputStream(outFile);
          copyFile(in, out);
        } catch(IOException e) {
            Log.e("tag", "Failed to copy asset file: " + filename, e);
        }     
        finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    // NOOP
                }
            }
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    // NOOP
                }
            }
        }  
    }
}
private void copyFile(InputStream in, OutputStream out) throws IOException {
    byte[] buffer = new byte[1024];
    int read;
    while((read = in.read(buffer)) != -1){
      out.write(buffer, 0, read);
    }
}

Reference : Move file using Java

Skipping error in for-loop

Instead of catching the error, wouldn't it be possible to test in or before the myplotfunction() function first if the error will occur (i.e. if the breaks are unique) and only plot it for those cases where it won't appear?!

Forcing Internet Explorer 9 to use standards document mode

There is something very important about this thread that has been touched on but not fully explained. The HTML approach (adding a meta tag in the head) only works consistently on raw HTML or very basic server pages. My site is a very complex server-driven site with master pages, themeing and a lot of third party controls, etc. What I found was that some of these controls were programmatically adding their own tags to the final HTML which were being pushed to the browser at the beginning of the head tag. This effectively rendered the HTML meta tags useless.

Well, if you can't beat them, join them. The only solution that worked for me is to do exactly the same thing in the pre-render event of my master pages as such:

Private Sub Page_PreRender(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.PreRender
    Dim MetaTag As HtmlMeta = New HtmlMeta()
    MetaTag.Attributes("http-equiv") = "Content-Type"
    MetaTag.Attributes("content") = "text/html; charset=utf-8;"
    Page.Header.Controls.AddAt(0, MetaTag)

    MetaTag = New HtmlMeta()
    MetaTag.Attributes("http-equiv") = "X-UA-Compatible"
    MetaTag.Attributes("content") = "IE=9,chrome=1"
    Page.Header.Controls.AddAt(0, MetaTag)
End Sub

This is VB.NET but the same approach would work for any server-side technology. As long as you make sure it's the last thing that gets done right before the page is rendered.

How to declare a inline object with inline variables without a parent class

yes, there is:

object[] x = new object[2];

x[0] = new { firstName = "john", lastName = "walter" };
x[1] = new { brand = "BMW" };

you were practically there, just the declaration of the anonymous types was a little off.

JPA CascadeType.ALL does not delete orphans

For the records, in OpenJPA before JPA2 it was @ElementDependant.

CRON command to run URL address every 5 minutes

To run a url, you need a program to get that url. You can try wget or curl. See manuals for available options.

Merge 2 DataTables and store in a new one

This is what i did for merging two datatables and bind the final result to the gridview

        DataTable dtTemp=new DataTable();
        for (int k = 0; k < GridView2.Rows.Count; k++)
        {
            string roomno = GridView2.Rows[k].Cells[1].Text;
            DataTable dtx = GetRoomDetails(chk, roomno, out msg);
            if (dtx.Rows.Count > 0)
            {
                dtTemp.Merge(dtx);
                dtTemp.AcceptChanges();

            }
        }

Using Java to pull data from a webpage?

Since Java 11 the most convenient way it to use java.net.http.HttpClient from the standard library.

Example:

HttpRequest request = HttpRequest.newBuilder(new URI(
    "https://stackoverflow.com/questions/6159118/using-java-to-pull-data-from-a-webpage"))
  .timeout(Duration.of(10, SECONDS))
  .GET()
  .build();

HttpResponse<String> response = HttpClient.newHttpClient()
  .send(request, BodyHandlers.ofString());

if (response.statusCode() != 200) {
  throw new RuntimeException(
    "Invalid response: " + response.statusCode() + ", request: " + response);
}

System.out.println(response.body());

How to add onload event to a div element

I really like the YUI3 library for this sort of thing.

<div id="mydiv"> ... </div>

<script>
YUI().use('node-base', function(Y) {
  Y.on("available", someFunction, '#mydiv')
})

See: http://developer.yahoo.com/yui/3/event/#onavailable

Python: Continuing to next iteration in outer loop

for i in ...:
    for j in ...:
        for k in ...:
            if something:
                # continue loop i

In a general case, when you have multiple levels of looping and break does not work for you (because you want to continue one of the upper loops, not the one right above the current one), you can do one of the following

Refactor the loops you want to escape from into a function

def inner():
    for j in ...:
        for k in ...:
            if something:
                return


for i in ...:
    inner()

The disadvantage is that you may need to pass to that new function some variables, which were previously in scope. You can either just pass them as parameters, make them instance variables on an object (create a new object just for this function, if it makes sense), or global variables, singletons, whatever (ehm, ehm).

Or you can define inner as a nested function and let it just capture what it needs (may be slower?)

for i in ...:
    def inner():
        for j in ...:
            for k in ...:
                if something:
                    return
    inner()

Use exceptions

Philosophically, this is what exceptions are for, breaking the program flow through the structured programming building blocks (if, for, while) when necessary.

The advantage is that you don't have to break the single piece of code into multiple parts. This is good if it is some kind of computation that you are designing while writing it in Python. Introducing abstractions at this early point may slow you down.

Bad thing with this approach is that interpreter/compiler authors usually assume that exceptions are exceptional and optimize for them accordingly.

class ContinueI(Exception):
    pass


continue_i = ContinueI()

for i in ...:
    try:
        for j in ...:
            for k in ...:
                if something:
                    raise continue_i
    except ContinueI:
        continue

Create a special exception class for this, so that you don't risk accidentally silencing some other exception.

Something else entirely

I am sure there are still other solutions.

Dynamically change color to lighter or darker by percentage CSS (Javascript)

If you need to brute force it for older browser compatibility, you can use Colllor to automatically select similar color variations.

Example (color: #a9dbb4):

enter image description here

How to get row index number in R?

See row in ?base::row. This gives the row indices for any matrix-like object.

What to return if Spring MVC controller method doesn't return value?

You can return "ResponseEntity" object. Using "ResponseEntity" object is very convenient both at the time of constructing the response object (that contains Response Body and HTTP Status Code) and at the time of getting information out of the response object.

Methods like getHeaders(), getBody(), getContentType(), getStatusCode() etc makes the work of reading the ResponseEntity object very easy.

You should be using ResponseEntity object with a http status code of 204(No Content), which is specifically to specify that the request has been processed properly and the response body is intentionally blank. Using appropriate Status Codes to convey the right information is very important, especially if you are making an API that is going to be used by multiple client applications.

What is the purpose of the return statement?

return is part of a function definition, while print outputs text to the standard output (usually the console).

A function is a procedure accepting parameters and returning a value. return is for the latter, while the former is done with def.

Example:

def timestwo(x):
    return x*2

`node-pre-gyp install --fallback-to-build` failed during MeanJS installation on OSX

russfrisch commented 4 days ago:

I was experiencing this same issue. Changing in the version for grunt-node-inspector to prepend a ">=" instead of a "~" got this to work for me.

Link to github page where I found this solution.

Link to my post on StackoverFlow

CAST DECIMAL to INT

A more optimized way in for this purpose*:

SELECT columnName DIV 1 AS columnName, moreColumns, etc
FROM myTable
WHERE ...

Using DIV 1 is a huge speed improvement over FLOOR, not to mention string based functions like FORMAT

mysql> SELECT BENCHMARK(10000000,1234567 DIV 7) ;
+-----------------------------------+
| BENCHMARK(10000000,1234567 DIV 7) |
+-----------------------------------+
|                                 0 |
+-----------------------------------+
1 row in set (0.83 sec)

mysql> SELECT BENCHMARK(10000000,1234567 / 7) ;
+---------------------------------+
| BENCHMARK(10000000,1234567 / 7) |
+---------------------------------+
|                               0 |
+---------------------------------+
1 row in set (7.26 sec)

mysql> SELECT BENCHMARK(10000000,FLOOR(1234567 / 7)) ;
+----------------------------------------+
| BENCHMARK(10000000,FLOOR(1234567 / 7)) |
+----------------------------------------+
|                                      0 |
+----------------------------------------+
1 row in set (8.80 sec)

(*) NOTE: As pointed by Grbts, be aware of the behaviour of DIV 1 when used with non unsigned/positive values.

Calculate age based on date of birth

Reference Link http://www.calculator.net/age-calculator.html

$hours_in_day   = 24;
$minutes_in_hour= 60;
$seconds_in_mins= 60;

$birth_date     = new DateTime("1988-07-31T00:00:00");
$current_date   = new DateTime();

$diff           = $birth_date->diff($current_date);

echo $years     = $diff->y . " years " . $diff->m . " months " . $diff->d . " day(s)"; echo "<br/>";
echo $months    = ($diff->y * 12) + $diff->m . " months " . $diff->d . " day(s)"; echo "<br/>";
echo $weeks     = floor($diff->days/7) . " weeks " . $diff->d%7 . " day(s)"; echo "<br/>";
echo $days      = $diff->days . " days"; echo "<br/>";
echo $hours     = $diff->h + ($diff->days * $hours_in_day) . " hours"; echo "<br/>";
echo $mins      = $diff->h + ($diff->days * $hours_in_day * $minutes_in_hour) . " minutest"; echo "<br/>";
echo $seconds   = $diff->h + ($diff->days * $hours_in_day * $minutes_in_hour * $seconds_in_mins) . " seconds"; echo "<br/>";

What exactly does the Access-Control-Allow-Credentials header do?

By default, CORS does not include cookies on cross-origin requests. This is different from other cross-origin techniques such as JSON-P. JSON-P always includes cookies with the request, and this behavior can lead to a class of vulnerabilities called cross-site request forgery, or CSRF.

In order to reduce the chance of CSRF vulnerabilities in CORS, CORS requires both the server and the client to acknowledge that it is ok to include cookies on requests. Doing this makes cookies an active decision, rather than something that happens passively without any control.

The client code must set the withCredentials property on the XMLHttpRequest to true in order to give permission.

However, this header alone is not enough. The server must respond with the Access-Control-Allow-Credentials header. Responding with this header to true means that the server allows cookies (or other user credentials) to be included on cross-origin requests.

You also need to make sure your browser isn't blocking third-party cookies if you want cross-origin credentialed requests to work.

Note that regardless of whether you are making same-origin or cross-origin requests, you need to protect your site from CSRF (especially if your request includes cookies).

Python Traceback (most recent call last)

You are using Python 2 for which the input() function tries to evaluate the expression entered. Because you enter a string, Python treats it as a name and tries to evaluate it. If there is no variable defined with that name you will get a NameError exception.

To fix the problem, in Python 2, you can use raw_input(). This returns the string entered by the user and does not attempt to evaluate it.

Note that if you were using Python 3, input() behaves the same as raw_input() does in Python 2.

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

Member '<method>' cannot be accessed with an instance reference

This causes the error:

MyClass aCoolObj = new MyClass();
aCoolObj.MyCoolStaticMethod();

This is the fix:

MyClass.MyCoolStaticMethod();

Explanation:

You can't call a static method from an instance of an object. The whole point of static methods is to not be tied to instances of objects, but instead to persist through all instances of that object, and/or to be used without any instances of the object.

How do you format the day of the month to say "11th", "21st" or "23rd" (ordinal indicator)?

String ordinal(int num)
{
    String[] suffix = {"th", "st", "nd", "rd", "th", "th", "th", "th", "th", "th"};
    int m = num % 100;
    return String.valueOf(num) + suffix[(m > 3 && m < 21) ? 0 : (m % 10)];
}

Instagram API - How can I retrieve the list of people a user is following on Instagram

You can use the following Instagram API Endpoint to get a list of people a user is following.

https://api.instagram.com/v1/users/{user-id}/follows?access_token=ACCESS-TOKEN

Here's the complete documentation for that endpoint. GET /users/user-id/follows

And here's a sample response from executing that endpoint. enter image description here

Since this endpoint required a user-id (and not user-name), depending on how you've written your API client, you might have to make a call to the /users/search endpoint with a username, and then get the user-id from the response and pass it on to the above /users/user-id/follows endpoint to get the list of followers.

IANAL, but considering it's documented in their API, and looking at the terms of use, I don't see how this wouldn't be legal to do.

How to run Selenium WebDriver test cases in Chrome

Download the updated version of the Google Chrome driver from Chrome Driver.

Please read the release note as well here.

If the Chrome browser is updated, then you need to download the new Chrome driver from the above link, because it would be compatible with the new browser version.

public class chrome
{

    public static void main(String[] args) {

        System.setProperty("webdriver.chrome.driver", "/path/to/chromedriver");
        WebDriver driver = new ChromeDriver();

        driver.get("http://www.google.com");
    }

}

Setting the default value of a DateTime Property to DateTime.Now inside the System.ComponentModel Default Value Attrbute

I faced the same issue, but the one which works for me best is below:

public DateTime CreatedOn { get; set; } = DateTime.Now;

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.

JQuery window scrolling event?

Try this: http://jsbin.com/axaler/3/edit

$(function(){
  $(window).scroll(function(){
    var aTop = $('.ad').height();
    if($(this).scrollTop()>=aTop){
        alert('header just passed.');
        // instead of alert you can use to show your ad
        // something like $('#footAd').slideup();
    }
  });
});

Adding an item to an associative array

before for loop :

$data = array();

then in your loop:

$data[] = array($catagory => $question);

Simple division in Java - is this a bug or a feature?

You're using integer division.

Try 7.0/10 instead.

How do I add a bullet symbol in TextView?

With Unicode we can do it easily,but if want to change color of bullet, I tried with colored bullet image and set it as drawable left and it worked

<TextView     
    android:text="Hello bullet"
    android:drawableLeft="@drawable/bulleticon" >
</TextView>

How can I find last row that contains data in a specific column?

Public Function GetLastRow(ByVal SheetName As String) As Integer
    Dim sht As Worksheet
    Dim FirstUsedRow As Integer     'the first row of UsedRange
    Dim UsedRows As Integer         ' number of rows used

    Set sht = Sheets(SheetName)
    ''UsedRange.Rows.Count for the empty sheet is 1
    UsedRows = sht.UsedRange.Rows.Count
    FirstUsedRow = sht.UsedRange.Row
    GetLastRow = FirstUsedRow + UsedRows - 1

    Set sht = Nothing
End Function

sheet.UsedRange.Rows.Count: retrurn number of rows used, not include empty row above the first row used

if row 1 is empty, and the last used row is 10, UsedRange.Rows.Count will return 9, not 10.

This function calculate the first row number of UsedRange plus number of UsedRange rows.

Redirect form to different URL based on select option element

you can use this simple way

<select onchange="location = this.value;">
                <option value="/finished">Finished</option>
                <option value="/break">Break</option>
                <option value="/issue">Issues</option>
                <option value="/downtime">Downtime</option>
</select>

will redirect to route url you can direct to .html page or direct to some link just change value in option.

Before and After Suite execution hook in jUnit 4.x

If you don't want to create a suite and have to list all your test classes you can use reflection to find the number of test classes dynamically and count down in a base class @AfterClass to do the tearDown only once:

public class BaseTestClass
{
    private static int testClassToRun = 0;

    // Counting the classes to run so that we can do the tear down only once
    static {
        try {
            Field field = ClassLoader.class.getDeclaredField("classes");
            field.setAccessible(true);

            @SuppressWarnings({ "unchecked", "rawtypes" })
            Vector<Class> classes = (Vector<Class>) field.get(BlockJUnit4ClassRunner.class.getClassLoader());
            for (Class<?> clazz : classes) {
                if (clazz.getName().endsWith("Test")) {
                    testClassToRun++;
                }
            }
        } catch (Exception ignore) {
        }
    }

    // Setup that needs to be done only once
    static {
        // one time set up
    }

    @AfterClass
    public static void baseTearDown() throws Exception
    {
        if (--testClassToRun == 0) {
            // one time clean up
        }
    }
}

If you prefer to use @BeforeClass instead of the static blocks, you can also use a boolean flag to do the reflection count and test setup only once at the first call. Hope this helps someone, it took me an afternoon to figure out a better way than enumerating all classes in a suite.

Now all you need to do is extend this class for all your test classes. We already had a base class to provide some common stuff for all our tests so this was the best solution for us.

Inspiration comes from this SO answer https://stackoverflow.com/a/37488620/5930242

If you don't want to extend this class everywhere, this last SO answer might do what you want.

How to save password when using Subversion from the console

Unfortunately the answers did not solve the problem of asking for password for ssh+svn with a protected private key. After some research I found:

ssh-add

utility if you have a Linux computer. Make sure that you have your keys stored in /home/username/.ssh/ and type this command on Terminal.

Swift_TransportException Connection could not be established with host smtp.gmail.com

In my case, I had trouble with GoDaddy and SSL encryption.

Setting the encryption to Null and Port to 80 (Or any supportive port) did the job.

Create request with POST, which response codes 200 or 201 and content

The idea is that the response body gives you a page that links you to the thing:

201 Created

The 201 (Created) status code indicates that the request has been fulfilled and has resulted in one or more new resources being created. The primary resource created by the request is identified by either a Location header field in the response or, if no Location field is received, by the effective request URI.

This means that you would include a Location in the response header that gives the URL of where you can find the newly created thing:

HTTP/1.1 201 Created
Date: Sat, 02 Apr 2016 12:22:40 GMT
Location: http://stackoverflow.com/a/36373586/12597

Response body

They then go on to mention what you should include in the response body:

The 201 response payload typically describes and links to the resource(s) created.

For the human using the browser, you give them something they can look at, and click, to get to their newly created resource:

HTTP/1.1 201 Created
Date: Sat, 02 Apr 2016 12:22:40 GMT
Location: http://stackoverflow.com/a/36373586/12597
Content-Type: text/html

Your answer has been saved! 
Click <A href="/a/36373586/12597">here</A> to view it.

If the page will only be used by a robot, the it makes sense to have the response be computer readable:

HTTP/1.1 201 Created
Date: Sat, 02 Apr 2016 12:22:40 GMT
Location: http://stackoverflow.com/a/36373586/12597
Content-Type: application/xml

<createdResources>
   <questionID>1860645</questionID>
   <answerID>36373586</answerID>
   <primary>/a/36373586/12597</primary>
   <additional>
      <resource>http://stackoverflow.com/questions/1860645/create-request-with-post-which-response-codes-200-or-201-and-content/36373586#36373586</resource>
      <resource>http://stackoverflow.com/a/1962757/12597</resource>
   </additional>
</createdResource>

Or, if you prefer:

HTTP/1.1 201 Created
Date: Sat, 02 Apr 2016 12:22:40 GMT
Location: http://stackoverflow.com/a/36373586/12597
Content-Type: application/json

{ 
   "questionID": 1860645, 
   "answerID": 36373586,
   "primary": "/a/36373586/12597",
   "additional": [
      "http://stackoverflow.com/questions/1860645/create-request-with-post-which-response-codes-200-or-201-and-content/36373586#36373586",
      "http://stackoverflow.com/a/36373586/12597"
   ]
}

The response is entirely up to you; it's arbitrarily what you'd like.

Cache friendly

Finally there's the optimization that I can pre-cache the created resource (because I already have the content; I just uploaded it). The server can return a date or ETag which I can store with the content I just uploaded:

See Section 7.2 for a discussion of the meaning and purpose of validator header fields, such as ETag and Last-Modified, in a 201 response.

HTTP/1.1 201 Created
Date: Sat, 02 Apr 2016 12:22:40 GMT
Location: http://stackoverflow.com/a/23704283/12597
Content-Type: text/html
ETag: JF2CA53BOMQGU5LTOQQGC3RAMV4GC3LQNRSS4
Last-Modified: Sat, 02 Apr 2016 12:22:39 GMT 

Your answer has been saved! 
Click <A href="/a/36373586/12597">here</A> to view it.

And ETag s are purely arbitrary values. Having them be different when a resource changes (and caches need to be updated) is all that matters. The ETag is usually a hash (e.g. SHA2). But it can be a database rowversion, or an incrementing revision number. Anything that will change when the thing changes.

Difference between setUp() and setUpBeforeClass()

From the Javadoc:

Sometimes several tests need to share computationally expensive setup (like logging into a database). While this can compromise the independence of tests, sometimes it is a necessary optimization. Annotating a public static void no-arg method with @BeforeClass causes it to be run once before any of the test methods in the class. The @BeforeClass methods of superclasses will be run before those the current class.

Open source face recognition for Android

You can try Microsoft's Face API. It can detect and identify people. learn more about face API here.

How to play an android notification sound

Try this:

public void ringtone(){
    try {
        Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        Ringtone r = RingtoneManager.getRingtone(getApplicationContext(), notification);
        r.play();
     } catch (Exception e) {
         e.printStackTrace();
     }
}

Can I add and remove elements of enumeration at runtime in Java

Behind the curtain, enums are POJOs with a private constructor and a bunch of public static final values of the enum's type (see here for an example). In fact, up until Java5, it was considered best-practice to build your own enumeration this way, and Java5 introduced the enum keyword as a shorthand. See the source for Enum<T> to learn more.

So it should be no problem to write your own 'TypeSafeEnum' with a public static final array of constants, that are read by the constructor or passed to it.

Also, do yourself a favor and override equals, hashCode and toString, and if possible create a values method

The question is how to use such a dynamic enumeration... you can't read the value "PI=3.14" from a file to create enum MathConstants and then go ahead and use MathConstants.PI wherever you want...

What is the "__v" field in Mongoose

We can use versionKey: false in Schema definition

'use strict';

const mongoose = require('mongoose');

export class Account extends mongoose.Schema {

    constructor(manager) {

        var trans = {
            tran_date: Date,
            particulars: String,
            debit: Number,
            credit: Number,
            balance: Number
        }

        super({
            account_number: Number,
            account_name: String,
            ifsc_code: String,
            password: String,
            currency: String,
            balance: Number,
            beneficiaries: Array,
            transaction: [trans]
        }, {
            versionKey: false // set to false then it wont create in mongodb
        });

        this.pre('remove', function(next) {
            manager
                .getModel(BENEFICIARY_MODEL)
                .remove({
                    _id: {
                        $in: this.beneficiaries
                    }
                })
                .exec();
            next();
        });
    }

}

Attempted to read or write protected memory

Hi There are two possible reasons.

  1. We have un-managed code and we are calling it from managed code. that is preventing to run this code. try running these commands and restart your pc

    cmd: netsh winsock reset

open cmd.exe and run command "netsh winsock reset catalog"

  1. Anti-virus is considering un-managed code as harmful and restricting to run this code disable anti-virus and then check

How to get ID of clicked element with jQuery

Your id will be passed through as #1, #2 etc. However, # is not valid as an ID (CSS selectors prefix IDs with #).

R: Print list to a text file

Here is another

cat(sapply(mylist, toString), file, sep="\n")

PHP decoding and encoding json with unicode characters

Judging from everything you've said, it seems like the original Odómetro string you're dealing with is encoded with ISO 8859-1, not UTF-8.

Here's why I think so:

  • json_encode produced parseable output after you ran the input string through utf8_encode, which converts from ISO 8859-1 to UTF-8.
  • You did say that you got "mangled" output when using print_r after doing utf8_encode, but the mangled output you got is actually exactly what would happen by trying to parse UTF-8 text as ISO 8859-1 (ó is \x63\xb3 in UTF-8, but that sequence is ó in ISO 8859-1.
  • Your htmlentities hackaround solution worked. htmlentities needs to know what the encoding of the input string to work correctly. If you don't specify one, it assumes ISO 8859-1. (html_entity_decode, confusingly, defaults to UTF-8, so your method had the effect of converting from ISO 8859-1 to UTF-8.)
  • You said you had the same problem in Python, which would seem to exclude PHP from being the issue.

PHP will use the \uXXXX escaping, but as you noted, this is valid JSON.

So, it seems like you need to configure your connection to Postgres so that it will give you UTF-8 strings. The PHP manual indicates you'd do this by appending options='--client_encoding=UTF8' to the connection string. There's also the possibility that the data currently stored in the database is in the wrong encoding. (You could simply use utf8_encode, but this will only support characters that are part of ISO 8859-1).

Finally, as another answer noted, you do need to make sure that you're declaring the proper charset, with an HTTP header or otherwise (of course, this particular issue might have just been an artifact of the environment where you did your print_r testing).

How to center an element in the middle of the browser window?

<div align="center">

or

<div style="margin: 0 auto;">

Timer for Python game

This is the Shortest Way I know of doing it:

def stopWatch():
        import time
        a = 0
        hours = 0
        while a < 1:
            for minutes in range(0, 60):
                for seconds in range(0, 60):
                    time.sleep(1)
                    print(hours,":", minutes,":", seconds)
        hours = hours + 1

awk - concatenate two string variable and assign to a third

Just use var = var1 var2 and it will automatically concatenate the vars var1 and var2:

awk '{new_var=$1$2; print new_var}' file

You can put an space in between with:

awk '{new_var=$1" "$2; print new_var}' file

Which in fact is the same as using FS, because it defaults to the space:

awk '{new_var=$1 FS $2; print new_var}' file

Test

$ cat file
hello how are you
i am fine
$ awk '{new_var=$1$2; print new_var}' file
hellohow
iam
$ awk '{new_var=$1 FS $2; print new_var}' file
hello how
i am

You can play around with it in ideone: http://ideone.com/4u2Aip

How to Logout of an Application Where I Used OAuth2 To Login With Google?

Ouath just makes the Google instance null, hence it you out of Google. Now that's how the architecture is made. Logging out of Google, if you Logout of your app is a dirty work, but can't help if the requirement stipulates the same. Hence add the following to your signOut() function. My project was an Angular 6 app:

document.location.href = "https://www.google.com/accounts/Logout?continue=https://appengine.google.com/_ah/logout?continue=http://localhost:4200";

Here localhost:4200 is the URL of my app. If your login page is xyz.com then input that.

How to download a Nuget package without nuget.exe or Visual Studio extension?

I haven't tried it yet, but it looks like NuGet Package Explorer should be able to do it:

https://github.com/NuGetPackageExplorer/NuGetPackageExplorer

NuGet Package Explorer

(or like Colonel Panic says, 7-zip should probably do it)

Please enter a commit message to explain why this merge is necessary, especially if it merges an updated upstream into a topic branch

Since your local repository is few commits ahead, git tries to merge your remote to your local repo. This can be handled via merge, but in your case, perhaps you are looking for rebase, i.e. add your commit to the top. You can do this with

git rebase or git pull --rebase

Here is a good article explaining the difference between git pull & git pull --rebase.

https://www.derekgourlay.com/blog/git-when-to-merge-vs-when-to-rebase/

ORA-00918: column ambiguously defined in SELECT *

A query's projection can only have one instance of a given name. As your WHERE clause shows, you have several tables with a column called ID. Because you are selecting * your projection will have several columns called ID. Or it would have were it not for the compiler hurling ORA-00918.

The solution is quite simple: you will have to expand the projection to explicitly select named columns. Then you can either leave out the duplicate columns, retaining just (say) COACHES.ID or use column aliases: coaches.id as COACHES_ID.

Perhaps that strikes you as a lot of typing, but it is the only way. If it is any comfort, SELECT * is regarded as bad practice in production code: explicitly named columns are much safer.

gridview data export to excel in asp.net

Instead of doing all these.. cant you use a simpler approach as shown below.

Response.ClearContent();
            Response.AddHeader("content-disposition", "attachment; filename=" + strFileName);
            Response.ContentType = "application/excel";
            System.IO.StringWriter sw = new System.IO.StringWriter();
            HtmlTextWriter htw = new HtmlTextWriter(sw);
            gv.RenderControl(htw);
            Response.Write(sw.ToString());
            Response.End();

You can get the entire walkthrough here

Excel column number from column name

Write and run the following code in the Immediate Window

?cells(,"type the column name here").column

For example ?cells(,"BYL").column will return 2014. The code is case-insensitive, hence you may write ?cells(,"byl").column and the output will still be the same.

Good examples of python-memcache (memcached) being used in Python?

It's fairly simple. You write values using keys and expiry times. You get values using keys. You can expire keys from the system.

Most clients follow the same rules. You can read the generic instructions and best practices on the memcached homepage.

If you really want to dig into it, I'd look at the source. Here's the header comment:

"""
client module for memcached (memory cache daemon)

Overview
========

See U{the MemCached homepage<http://www.danga.com/memcached>} for more about memcached.

Usage summary
=============

This should give you a feel for how this module operates::

    import memcache
    mc = memcache.Client(['127.0.0.1:11211'], debug=0)

    mc.set("some_key", "Some value")
    value = mc.get("some_key")

    mc.set("another_key", 3)
    mc.delete("another_key")

    mc.set("key", "1")   # note that the key used for incr/decr must be a string.
    mc.incr("key")
    mc.decr("key")

The standard way to use memcache with a database is like this::

    key = derive_key(obj)
    obj = mc.get(key)
    if not obj:
        obj = backend_api.get(...)
        mc.set(key, obj)

    # we now have obj, and future passes through this code
    # will use the object from the cache.

Detailed Documentation
======================

More detailed documentation is available in the L{Client} class.
"""

How to Call Controller Actions using JQuery in ASP.NET MVC

the previous response is ASP.NET only

you need a reference to jquery (perhaps from a CDN): http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.5.1.js

and then a similar block of code but simpler...

$.ajax({ url: '/Controller/Action/Id',
         success: function(data) { alert(data); }, 
         statusCode : {
             404: function(content) { alert('cannot find resource'); },
             500: function(content) { alert('internal server error'); }
         }, 
         error: function(req, status, errorObj) {
               // handle status === "timeout"
               // handle other errors
         }
});

I've added some necessary handlers, 404 and 500 happen all the time if you are debugging code. Also, a lot of other errors, such as timeout, will filter out through the error handler.

ASP.NET MVC Controllers handle requests, so you just need to request the correct URL and the controller will pick it up. This code sample with work in environments other than ASP.NET

Difference between SRC and HREF

src is to used to add that resource to the page, whereas href is used to link to a particular resource from that page.

When you use in your webpage, the browser sees that its a style sheet and hence continues with the page rendering as the style sheet is downloaded in parellel.

When you use in your webpage, it tells the browser to insert the resource at the location. So now the browser has to fetch the js file and then loads it. Until the browser finishes the loading process, the page rendering process is halted. That is the reason why YUI recommends to load your JS files at the very bottom of your web page.

Multiple conditions in ngClass - Angular 4

You are trying to assign an array to ngClass, but the syntax for the array elements is wrong since you separate them with a || instead of a ,.

Try this:

<section [ngClass]="[menu1 ? 'class1' : '',  menu2 ? 'class1' : '', (something && (menu1 || menu2)) ? 'class2' : '']">

This other option should also work:

<section [ngClass.class1]="menu1 || menu2" [ngClass.class2] = "(menu1 || menu2) && something">    

POST unchecked HTML checkboxes

All answers are great, but if you have multiple checkboxes in a form with the same name and you want to post the status of each checkbox. Then i have solved this problem by placing a hidden field with the checkbox (name related to what i want).

<input type="hidden" class="checkbox_handler" name="is_admin[]" value="0" />
<input type="checkbox" name="is_admin_ck[]" value="1" />

then control the change status of checkbox by below jquery code:

$(documen).on("change", "input[type='checkbox']", function() {
    var checkbox_val = ( this.checked ) ? 1 : 0;
    $(this).siblings('input.checkbox_handler').val(checkbox_val);
});

now on change of any checkbox, it will change the value of related hidden field. And on server you can look only to hidden fields instead of checkboxes.

Hope this will help someone have this type of problem. cheer :)

XML Schema minOccurs / maxOccurs default values

New, expanded answer to an old, commonly asked question...

Default Values

  • Occurrence constraints minOccurs and maxOccurs default to 1.

Common Cases Explained

<xsd:element name="A"/>

means A is required and must appear exactly once.


<xsd:element name="A" minOccurs="0"/>

means A is optional and may appear at most once.


 <xsd:element name="A" maxOccurs="unbounded"/>

means A is required and may repeat an unlimited number of times.


 <xsd:element name="A" minOccurs="0" maxOccurs="unbounded"/>

means A is optional and may repeat an unlimited number of times.


See Also

  • W3C XML Schema Part 0: Primer

    In general, an element is required to appear when the value of minOccurs is 1 or more. The maximum number of times an element may appear is determined by the value of a maxOccurs attribute in its declaration. This value may be a positive integer such as 41, or the term unbounded to indicate there is no maximum number of occurrences. The default value for both the minOccurs and the maxOccurs attributes is 1. Thus, when an element such as comment is declared without a maxOccurs attribute, the element may not occur more than once. Be sure that if you specify a value for only the minOccurs attribute, it is less than or equal to the default value of maxOccurs, i.e. it is 0 or 1. Similarly, if you specify a value for only the maxOccurs attribute, it must be greater than or equal to the default value of minOccurs, i.e. 1 or more. If both attributes are omitted, the element must appear exactly once.

  • W3C XML Schema Part 1: Structures Second Edition

    <element
      maxOccurs = (nonNegativeInteger | unbounded)  : 1
      minOccurs = nonNegativeInteger : 1
      >
    
    </element>
    

What are the differences between C, C# and C++ in terms of real-world applications?

From your other posts, I guess you want to learn a new language to get new skills. My advice is that the language is not really important, what is important is the quality of its community (advice, but also existing code you can read and learn from) and the available libraries/frameworks. In this respect, I think the "C family" is not the best choice for you: web libraries and frameworks are few, not portable and not great, and coding style of code you can study varies a lot and may confuse you a lot (although C is my favorite language).

I would advise to just learn C, and try to really understand the concept of pointers, then move to other languages more adapted to the web (Python or JavaScript comes to mind - or even Java). Also, in the C family, Objective-C has the best mix of power and simplicity in my opinion, but is a niche player.

SQL Error: ORA-12899: value too large for column

As mentioned, the error message shows you the exact problem: you are passing 25 characters into a field set up to hold 20. You might also want to consider defining the columns a little more precisely. You can define whether the VARCHAR2 column will store a certain number of bytes or characters. You may encounter a problem in the future where you try to insert a multi byte character into the field, for example this is 5 characters in length but it won't fit into 5 bytes: 'ÀÈÌÕÛ'

Here is an example:

CREATE TABLE Customers(CustomerID  VARCHAR2(9 BYTE), ...

or

CREATE TABLE Customers(CustomerID  VARCHAR2(9 CHAR), ...

Asp.Net WebApi2 Enable CORS not working with AspNet.WebApi.Cors 5.2.3

In case of CORS request all modern browsers respond with an OPTION verb, and then the actual request follows through. This is supposed to be used to prompt the user for confirmation in case of a CORS request. But in case of an API if you would want to skip this verification process add the following snippet to Global.asax

        protected void Application_BeginRequest(object sender, EventArgs e)
        {
            HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
            if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
            {
                HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "POST, PUT, DELETE");

                HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept");
                HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000");
                HttpContext.Current.Response.End();
            }
        }

Here we are just by passing the check by checking for OPTIONS verb.

Global Events in Angular

I'm using a message service that wraps an rxjs Subject (TypeScript)

Plunker example: Message Service

import { Injectable } from '@angular/core';
import { Subject } from 'rxjs/Subject';
import { Subscription } from 'rxjs/Subscription';
import 'rxjs/add/operator/filter'
import 'rxjs/add/operator/map'

interface Message {
  type: string;
  payload: any;
}

type MessageCallback = (payload: any) => void;

@Injectable()
export class MessageService {
  private handler = new Subject<Message>();

  broadcast(type: string, payload: any) {
    this.handler.next({ type, payload });
  }

  subscribe(type: string, callback: MessageCallback): Subscription {
    return this.handler
      .filter(message => message.type === type)
      .map(message => message.payload)
      .subscribe(callback);
  }
}

Components can subscribe and broadcast events (sender):

import { Component, OnDestroy } from '@angular/core'
import { MessageService } from './message.service'
import { Subscription } from 'rxjs/Subscription'

@Component({
  selector: 'sender',
  template: ...
})
export class SenderComponent implements OnDestroy {
  private subscription: Subscription;
  private messages = [];
  private messageNum = 0;
  private name = 'sender'

  constructor(private messageService: MessageService) {
    this.subscription = messageService.subscribe(this.name, (payload) => {
      this.messages.push(payload);
    });
  }

  send() {
    let payload = {
      text: `Message ${++this.messageNum}`,
      respondEvent: this.name
    }
    this.messageService.broadcast('receiver', payload);
  }

  clear() {
    this.messages = [];
  }

  ngOnDestroy() {
    this.subscription.unsubscribe();
  }
}

(receiver)

import { Component, OnDestroy } from '@angular/core'
import { MessageService } from './message.service'
import { Subscription } from 'rxjs/Subscription'

@Component({
  selector: 'receiver',
  template: ...
})
export class ReceiverComponent implements OnDestroy {
  private subscription: Subscription;
  private messages = [];

  constructor(private messageService: MessageService) {
    this.subscription = messageService.subscribe('receiver', (payload) => {
      this.messages.push(payload);
    });
  }

  send(message: {text: string, respondEvent: string}) {
    this.messageService.broadcast(message.respondEvent, message.text);
  }

  clear() {
    this.messages = [];
  }

  ngOnDestroy() {
    this.subscription.unsubscribe();
  }
}

The subscribe method of MessageService returns an rxjs Subscription object, which can be unsubscribed from like so:

import { Subscription } from 'rxjs/Subscription';
...
export class SomeListener {
  subscription: Subscription;

  constructor(private messageService: MessageService) {
    this.subscription = messageService.subscribe('someMessage', (payload) => {
      console.log(payload);
      this.subscription.unsubscribe();
    });
  }
}

Also see this answer: https://stackoverflow.com/a/36782616/1861779

Plunker example: Message Service

Online PHP syntax checker / validator

Here is also a good and simple site to check your php codes and share your code with fiends :

http://trycodeonline.com

How to convert DATE to UNIX TIMESTAMP in shell script on MacOS

I wrote a set of scripts that provides a uniform interface for both BSD and GNU version of date.

Follow command will output the Epoch seconds for the date 2010-10-02, and it works with both BSD and GNU version of date.

$ xsh /date/convert "2010-10-02" "+%s"
1286020263

It's an equivalent of the command with GNU version of date:

date -d "2010-10-02" "+%s"

and also the command with BSD version of date:

date -j -f "%F" 2010-10-02 "+%s"

The scripts can be found at:

It's a part of a library called xsh-lib/core. To use them you need both repos xsh and xsh-lib/core, I list them below:

Laravel 5.4 redirection to custom url after login

you can add method in LoginController add line use App\User; on Top, after this add method, it is work for me wkwkwkwkw , but you must add {{ csrf_field() }} on view admin and user

protected function authenticated(Request $request, $user){

$user=User::where('email',$request->input('email'))->pluck('jabatan');
$c=" ".$user." ";
$a=strcmp($c,' ["admin"] ');

if ($a==0) {
    return redirect('admin');

}else{
    return redirect('user');

}}

image size (drawable-hdpi/ldpi/mdpi/xhdpi)

low dpi is 0.75x dimensions of medium dpi

high dpi is 1.5x dimensions of medium dpi

extra high dpi is 2x dimensinons of medium dpi

It's a good practice to make all the images in vector based format so you can resize them easily using a vector design software like Illustrator etc..

Java Can't connect to X11 window server using 'localhost:10.0' as the value of the DISPLAY variable

For Ubuntu 17.10 Install X virtual frame buffer (xvfb)

apt install xvfb

And added these lines to the /etc/profile file...

# Start the X virtual frame buffer (Xvfb)
if [ -f /usr/X11R6/bin/Xvfb ]; then
/usr/X11R6/bin/Xvfb :1 -screen 0 1366x768x32
fi

# Set the DISPLAY variable for the X virtual frame buffer (Xvfb)
export DISPLAY=localhost:1.0

How to get line count of a large file cheaply in Python?

what about this?

import sys
sys.stdin=open('fname','r')
data=sys.stdin.readlines()
print "counted",len(data),"lines"

How to get MD5 sum of a string using python?

You can Try with

#python3
import hashlib
rawdata = "put your data here"
sha = hashlib.sha256(str(rawdata).encode("utf-8")).hexdigest() #For Sha256 hash
print(sha)
mdpass = hashlib.md5(str(sha).encode("utf-8")).hexdigest() #For MD5 hash
print(mdpass)

Access localhost from the internet

Even though you didn't provide enough information to answer this question properly, your best shots are SSH tunnels (or reverse SSH tunnels).

You only need one SSH server on your internal or remote network to provide access to your local machine.

You can use PUTTY (it has a GUI) on Windows to create your tunnel.

Convert timestamp to date in MySQL query

FROM_UNIXTIME(unix_timestamp, [format]) is all you need

FROM_UNIXTIME(user.registration, '%Y-%m-%d') AS 'date_formatted'

FROM_UNIXTIME gets a number value and transforms it to a DATE object,
or if given a format string, it returns it as a string.

The older solution was to get the initial date object and format it with a second function DATE_FORMAT... but this is no longer necessary

How do you push just a single Git branch (and no other branches)?

yes, just do the following

git checkout feature_x
git push origin feature_x

jquery to loop through table rows and cells, where checkob is checked, concatenate

UPDATED

I've updated your demo: http://jsfiddle.net/terryyounghk/QS56z/18/

Also, I've changed two ^= to *=. See http://api.jquery.com/category/selectors/

And note the :checked selector. See http://api.jquery.com/checked-selector/

function createcodes() {

    //run through each row
    $('.authors-list tr').each(function (i, row) {

        // reference all the stuff you need first
        var $row = $(row),
            $family = $row.find('input[name*="family"]'),
            $grade = $row.find('input[name*="grade"]'),
            $checkedBoxes = $row.find('input:checked');

        $checkedBoxes.each(function (i, checkbox) {
            // assuming you layout the elements this way, 
            // we'll take advantage of .next()
            var $checkbox = $(checkbox),
                $line = $checkbox.next(),
                $size = $line.next();

            $line.val(
                $family.val() + ' ' + $size.val() + ', ' + $grade.val()
            );

        });

    });
}

Could not load type from assembly error

I ran into this scenario when trying to load a type (via reflection) in an assembly that was built against a different version of a reference common to the application where this error popped up.

As I'm sure the type is unchanged in both versions of the assembly I ended up creating a custom assembly resolver that maps the missing assembly to the one my application has already loaded. Simplest way is to add a static constructor to the program class like so:

using System.Reflection
static Program()
{
    AppDomain.CurrentDomain.AssemblyResolve += (sender, e) => {
        AssemblyName requestedName = new AssemblyName(e.Name);

        if (requestedName.Name == "<AssemblyName>")
        {
            // Load assembly from startup path
            return Assembly.LoadFile($"{Application.StartupPath}\\<AssemblyName>.dll");
        }
        else
        {
            return null;
        }
    };
}

This of course assumes that the Assembly is located in the startup path of the application and can easily be adapted.

ADB Android Device Unauthorized

As the message have stated, you need to allow the adb access on your phone.

You need to first connect the phone to your PC with USB cables, then the authorization message will pop out on the screen. Tick remember your choice, then allow it.

IF your device doesnt shows any messages when connected to the PC.Just do this.

Remove /data/misc/adb/adb_key, reboot your phone and try connect again. The message should come up.

Difference between maven scope compile and provided for JAR packaging

For a jar file, the difference is in the classpath listed in the MANIFEST.MF file included in the jar if addClassPath is set to true in the maven-jar-plugin configuration. 'compile' dependencies will appear in the manifest, 'provided' dependencies won't.

One of my pet peeves is that these two words should have the same tense. Either compiled and provided, or compile and provide.

jQuery Form Validation before Ajax submit

> Required JS for jquery form validation
> ## jquery-1.7.1.min.js ##
> ## jquery.validate.min.js ##
> ## jquery.form.js ##

$("form#data").validate({
    rules: {
        first: {
                required: true,
            },
        middle: {
            required: true,
        },          
        image: {
            required: true,
        },
    },
    messages: {
        first: {
                required: "Please enter first",
            },
        middle: {
            required: "Please enter middle",
        },          
        image: {
            required: "Please Select logo",
        },
    },
    submitHandler: function(form) {
        var formData = new FormData($("#image")[0]);
        $(form).ajaxSubmit({
            url:"action.php",
            type:"post",
            success: function(data,status){
              alert(data);
            }
        });
    }
});

Convert String to Integer in XSLT 1.0

Adding to jelovirt's answer, you can use number() to convert the value to a number, then round(), floor(), or ceiling() to get a whole integer.

Example

<xsl:variable name="MyValAsText" select="'5.14'"/>
<xsl:value-of select="number($MyValAsText) * 2"/> <!-- This outputs 10.28 -->
<xsl:value-of select="floor($MyValAsText)"/> <!-- outputs 5 -->
<xsl:value-of select="ceiling($MyValAsText)"/> <!-- outputs 6 -->
<xsl:value-of select="round($MyValAsText)"/> <!-- outputs 5 -->

How to deploy a war file in JBoss AS 7?

I built the following ant-task for deployment based on the jboss deployment docs:

<target name="deploy" depends="jboss.environment, buildwar">
    <!-- Build path for deployed war-file -->
    <property name="deployed.war" value="${jboss.home}/${jboss.deploy.dir}/${war.filename}" />

    <!-- remove current deployed war -->
    <delete file="${deployed.war}.deployed" failonerror="false" />
    <waitfor maxwait="10" maxwaitunit="second">
        <available file="${deployed.war}.undeployed" />
    </waitfor>
    <delete dir="${deployed.war}" />

    <!-- copy war-file -->
    <copy file="${war.filename}" todir="${jboss.home}/${jboss.deploy.dir}" />

    <!-- start deployment -->
    <echo>start deployment ...</echo>
    <touch file="${deployed.war}.dodeploy" />

    <!-- wait for deployment to complete -->
    <waitfor maxwait="10" maxwaitunit="second">
        <available file="${deployed.war}.deployed" />
    </waitfor>
    <echo>deployment ok!</echo>
</target>

${jboss.deploy.dir} is set to standalone/deployments

C# Parsing JSON array of objects

I have just got an solution a little bit easier do get an list out of an JSON object. Hope this can help.

I got an JSON like this:

{"Accounts":"[{\"bank\":\"Itau\",\"account\":\"456\",\"agency\":\"0444\",\"digit\":\"5\"}]"}

And made some types like this

    public class FinancialData
{
    public string Accounts { get; set; } // this will store the JSON string
    public List<Accounts> AccountsList { get; set; } // this will be the actually list. 
}

    public class Accounts
{
    public string bank { get; set; }
    public string account { get; set; }
    public string agency { get; set; }
    public string digit { get; set; }

}

and the "magic" part

 Models.FinancialData financialData = (Models.FinancialData)JsonConvert.DeserializeObject(myJSON,typeof(Models.FinancialData));
        var accounts = JsonConvert.DeserializeObject(financialData.Accounts) as JArray;

        foreach (var account in  accounts)
        {
            if (financialData.AccountsList == null)
            {
                financialData.AccountsList = new List<Models.Accounts>();
            }

            financialData.AccountsList.Add(JsonConvert.DeserializeObject<Models.Accounts>(account.ToString()));
        }

What is a practical, real world example of the Linked List?

A chain:

alt text

Especially the roller chain:

alt text

Each element of the chain is connected to its successor and predecessor.

How to get input textfield values when enter key is pressed in react js?

Use onKeyDown event, and inside that check the key code of the key pressed by user. Key code of Enter key is 13, check the code and put the logic there.

Check this example:

_x000D_
_x000D_
class CartridgeShell extends React.Component {_x000D_
_x000D_
   constructor(props) {_x000D_
      super(props);_x000D_
      this.state = {value:''}_x000D_
_x000D_
      this.handleChange = this.handleChange.bind(this);_x000D_
      this.keyPress = this.keyPress.bind(this);_x000D_
   } _x000D_
 _x000D_
   handleChange(e) {_x000D_
      this.setState({ value: e.target.value });_x000D_
   }_x000D_
_x000D_
   keyPress(e){_x000D_
      if(e.keyCode == 13){_x000D_
         console.log('value', e.target.value);_x000D_
         // put the login here_x000D_
      }_x000D_
   }_x000D_
_x000D_
   render(){_x000D_
      return(_x000D_
         <input value={this.state.value} onKeyDown={this.keyPress} onChange={this.handleChange} fullWidth={true} />_x000D_
      )_x000D_
    }_x000D_
}_x000D_
_x000D_
ReactDOM.render(<CartridgeShell/>, document.getElementById('app'))
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>_x000D_
_x000D_
_x000D_
<div id = 'app' />
_x000D_
_x000D_
_x000D_

Note: Replace the input element by Material-Ui TextField and define the other properties also.

npm install error - MSB3428: Could not load the Visual C++ component "VCBuild.exe"

For me worked install the component "VCBuild.exe", just dowload the wizard, install and them open the cmd again as administrator and try run again. Updated link to dowload the wizard here

Change Active Menu Item on Page Scroll?

If you want the accepted answer to work in JQuery 3 change the code like this:

var scrollItems = menuItems.map(function () {
    var id = $(this).attr("href");
    try {
        var item = $(id);
      if (item.length) {
        return item;
      }
    } catch {}
  });

I also added a try-catch to prevent javascript from crashing if there is no element by that id. Feel free to improve it even more ;)

How to get anchor text/href on click using jQuery?

Note: Apply the class info_link to any link you want to get the info from.

<a class="info_link" href="~/Resumes/Resumes1271354404687.docx">
    ~/Resumes/Resumes1271354404687.docx
</a>

For href:

$(function(){
  $('.info_link').click(function(){
    alert($(this).attr('href'));
    // or alert($(this).hash();
  });
});

For Text:

$(function(){
  $('.info_link').click(function(){
    alert($(this).text());
  });
});

.

Update Based On Question Edit

You can get them like this now:

For href:

$(function(){
  $('div.res a').click(function(){
    alert($(this).attr('href'));
    // or alert($(this).hash();
  });
});

For Text:

$(function(){
  $('div.res a').click(function(){
    alert($(this).text());
  });
});

Interview Question: Merge two sorted singly linked lists without creating new nodes

I created only one dummy node at the beginning to save myself many 'if' conditions.

    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {

        ListNode list1Cursor = l1;
        ListNode list2Cursor = l2;

        ListNode currentNode = new ListNode(-1); // Dummy node
        ListNode head = currentNode;

        while (list1Cursor != null && list2Cursor != null)
        {
            if (list1Cursor.val < list2Cursor.val) {
                currentNode.next = list1Cursor;
                list1Cursor = list1Cursor.next;
                currentNode = currentNode.next;
            } else {
                currentNode.next = list2Cursor;
                list2Cursor = list2Cursor.next;
                currentNode = currentNode.next;
            }
        }

        // Complete the rest
        while (list1Cursor != null) {
            currentNode.next = list1Cursor;
            currentNode = currentNode.next;
            list1Cursor = list1Cursor.next;
        }
        while (list2Cursor != null) {
            currentNode.next = list2Cursor;
            currentNode = currentNode.next;
            list2Cursor = list2Cursor.next;
        }

        return head.next;
    }

AttributeError: 'tuple' object has no attribute

class list_benefits(object):
    def __init__(self):
        self.s1 = "More organized code"
        self.s2 = "More readable code"
        self.s3 = "Easier code reuse"

def build_sentence():
        obj=list_benefits()
        print obj.s1 + " is a benefit of functions!"
        print obj.s2 + " is a benefit of functions!"
        print obj.s3 + " is a benefit of functions!"

print build_sentence()

I know it is late answer, maybe some other folk can benefit If you still want to call by "attributes", you could use class with default constructor, and create an instance of the class as mentioned in other answers

Import file size limit in PHPMyAdmin

I found the problem and am post hete if anyone followed some blog post out there to create the sort of enviromment I have (win 7 host with ubuntu and zend server ce on virtual box).

The thing is that MySQL is running on Lighttpd, not under Apache. So I had to change the php.ini file under that webserver as well which is in the path:

/usr/local/zend/gui/lighttpd/etc/php-fcgi.ini

In the end, you were right about the files, of course, but I was wrong on what file I had to change :)

Which is the best Linux C/C++ debugger (or front-end to gdb) to help teaching programming?

ddd is a graphical front-end to gdb that is pretty nice. One of the down sides is a classic X interface, but I seem to recall it being pretty intuitive.

how to access the command line for xampp on windows

  • You can set environment variables as mentioned in the other answers (like here)

    or

  • you can open Start > CMD as administrator and write

    C:\xampp\php phpfile.php

jQuery delete confirmation box

$(document).ready(function(){
  $(".del").click(function(){
    if (!confirm("Do you want to delete")){
      return false;
    }
  });
});

How can I remove a button or make it invisible in Android?

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_below="@+id/activity_register_header"
    android:minHeight="50dp"
    android:orientation="vertical"
    android:visibility="gone" />

Try This Code

Visibility works fine in this code

Html encode in PHP

Try this:

<?php
    $str = "This is some <b>bold</b> text.";
    echo htmlspecialchars($str);
?>

What does "./" (dot slash) refer to in terms of an HTML file path location?

For example css files are in folder named CSS and html files are in folder HTML, and both these are in folder named XYZ means we refer css files in html as

<link rel="stylesheet" type="text/css" href="./../CSS/style.css" />

Here .. moves up to HTML
and . refers to the current directory XYZ

---by this logic you would just reference as:

<link rel="stylesheet" type="text/css" href="CSS/style.css" />

Excel compare two columns and highlight duplicates

Don't wana do soo much work guyss.. Just Press Ctr and select Colum one and Press Ctr and select colum two. Then click conditional formatting -> Highlight Cell Rules -> Equel To.

and thats it. your done. :)

How can I show/hide component with JSF?

One obvious solution would be to use javascript (which is not JSF). To implement this by JSF you should use AJAX. In this example, I use a radio button group to show and hide two set of components. In the back bean, I define a boolean switch.

private boolean switchComponents;

public boolean isSwitchComponents() {
    return switchComponents;
}

public void setSwitchComponents(boolean switchComponents) {
    this.switchComponents = switchComponents;
}

When the switch is true, one set of components will be shown and when it is false the other set will be shown.

 <h:selectOneRadio value="#{backbean.switchValue}">
   <f:selectItem itemLabel="showComponentSetOne" itemValue='true'/>
   <f:selectItem itemLabel="showComponentSetTwo" itemValue='false'/>
   <f:ajax event="change" execute="@this" render="componentsRoot"/>
 </h:selectOneRadio>


<H:panelGroup id="componentsRoot">
     <h:panelGroup rendered="#{backbean.switchValue}">
       <!--switchValue to be shown on switch value == true-->
     </h:panelGroup>

   <h:panelGroup rendered="#{!backbean.switchValue}">
      <!--switchValue to be shown on switch value == false-->
   </h:panelGroup>
</H:panelGroup>

Note: on the ajax event we render components root. because components which are not rendered in the first place can't be re-rendered on the ajax event.

Also, note that if the "componentsRoot" and radio buttons are under different component hierarchy. you should reference it from the root (form root).

How can I send JSON response in symfony2 controller

To complete @thecatontheflat answer I would recommend to also wrap your action inside of a try … catch block. This will prevent your JSON endpoint from breaking on exceptions. Here's the skeleton I use:

public function someAction()
{
    try {

        // Your logic here...

        return new JsonResponse([
            'success' => true,
            'data'    => [] // Your data here
        ]);

    } catch (\Exception $exception) {

        return new JsonResponse([
            'success' => false,
            'code'    => $exception->getCode(),
            'message' => $exception->getMessage(),
        ]);

    }
}

This way your endpoint will behave consistently even in case of errors and you will be able to treat them right on a client side.

How can I run a php without a web server?

You should normally be able to run a php file (after a successful installation) just by running this command:

$ /path/to/php myfile.php // unix way
C:\php\php.exe myfile.php // windows way

You can read more about running PHP in CLI mode here.


It's worth adding that PHP from version 5.4 onwards is able to run a web server on its own. You can do it by running this code in a folder which you want to serve the pages from:

$ php -S localhost:8000

You can read more about running a PHP in a Web Server mode here.

Real time data graphing on a line chart with html5

You get the data from server, update your previously available datasetand then probably use one of the freely available libraries to draw the graph (eg: http://www.rgraph.net)

Things you might want to considering : If your chart is represents a state , get only the new data with xhr , update data on client and draw .

Is there a kind of Firebug or JavaScript console debug for Android?

I sometimes print debugging output to the browser window. Using jQuery, you could send output messages to a display area on your page:

<div id='display'></div>

$('#display').text('array length: ' + myArray.length);

Or if you want to watch JavaScript variables without adding a display area to your page:

function debug(txt) {
    $('body').append("<div style='width:300px;background:orange;padding:3px;font-size:13px'>" + txt + "</div>");
}

How can I find non-ASCII characters in MySQL?

It depends exactly what you're defining as "ASCII", but I would suggest trying a variant of a query like this:

SELECT * FROM tableName WHERE columnToCheck NOT REGEXP '[A-Za-z0-9]';

That query will return all rows where columnToCheck contains any non-alphanumeric characters. If you have other characters that are acceptable, add them to the character class in the regular expression. For example, if periods, commas, and hyphens are OK, change the query to:

SELECT * FROM tableName WHERE columnToCheck NOT REGEXP '[A-Za-z0-9.,-]';

The most relevant page of the MySQL documentation is probably 12.5.2 Regular Expressions.

Matplotlib: ValueError: x and y must have same first dimension

You should make x and y numpy arrays, not lists:

x = np.array([0.46,0.59,0.68,0.99,0.39,0.31,1.09,
              0.77,0.72,0.49,0.55,0.62,0.58,0.88,0.78])
y = np.array([0.315,0.383,0.452,0.650,0.279,0.215,0.727,0.512,
              0.478,0.335,0.365,0.424,0.390,0.585,0.511])

With this change, it produces the expect plot. If they are lists, m * x will not produce the result you expect, but an empty list. Note that m is anumpy.float64 scalar, not a standard Python float.

I actually consider this a bit dubious behavior of Numpy. In normal Python, multiplying a list with an integer just repeats the list:

In [42]: 2 * [1, 2, 3]
Out[42]: [1, 2, 3, 1, 2, 3]

while multiplying a list with a float gives an error (as I think it should):

In [43]: 1.5 * [1, 2, 3]
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-43-d710bb467cdd> in <module>()
----> 1 1.5 * [1, 2, 3]
TypeError: can't multiply sequence by non-int of type 'float'

The weird thing is that multiplying a Python list with a Numpy scalar apparently works:

In [45]: np.float64(0.5) * [1, 2, 3]
Out[45]: []

In [46]: np.float64(1.5) * [1, 2, 3]
Out[46]: [1, 2, 3]

In [47]: np.float64(2.5) * [1, 2, 3]
Out[47]: [1, 2, 3, 1, 2, 3]

So it seems that the float gets truncated to an int, after which you get the standard Python behavior of repeating the list, which is quite unexpected behavior. The best thing would have been to raise an error (so that you would have spotted the problem yourself instead of having to ask your question on Stackoverflow) or to just show the expected element-wise multiplication (in which your code would have just worked). Interestingly, addition between a list and a Numpy scalar does work:

In [69]: np.float64(0.123) + [1, 2, 3]
Out[69]: array([ 1.123,  2.123,  3.123])

Auto number column in SharePoint list

it's in there by default. It's the id field.

Creating a textarea with auto-resize

An even simpler, cleaner approach is this:

// adjust height of textarea.auto-height
$(document).on( 'keyup', 'textarea.auto-height', function (e){
    $(this).css('height', 'auto' ); // you can have this here or declared in CSS instead
    $(this).height( this.scrollHeight );
}).keyup();

// and the CSS

textarea.auto-height {
    resize: vertical;
    max-height: 600px; /* set as you need it */
    height: auto;      /* can be set here of in JS */
    overflow-y: auto;
    word-wrap:break-word
}

All that is needed is to add the .auto-height class to any textarea you want to target.

Tested in FF, Chrome and Safari. Let me know if this doesn't work for you, for any reason. But, this is the cleanest and simplest way I've found this to work. And it works great! :D

http://localhost/ not working on Windows 7. What's the problem?

Maybe Skype or other Application is using port 80. This you can check in

Tools->Settings->Advanced->Connection

can't access mysql from command line mac

adding this code to my .profile worked for me: :/usr/local/mysql/bin

Thanks.

P.S This .profile is located in your user/ path. Its a hidden file so you will have to get to it either by a command in Terminal or using an html editor.

Spark SQL: apply aggregate functions to a list of columns

There are multiple ways of applying aggregate functions to multiple columns.

GroupedData class provides a number of methods for the most common functions, including count, max, min, mean and sum, which can be used directly as follows:

  • Python:

    df = sqlContext.createDataFrame(
        [(1.0, 0.3, 1.0), (1.0, 0.5, 0.0), (-1.0, 0.6, 0.5), (-1.0, 5.6, 0.2)],
        ("col1", "col2", "col3"))
    
    df.groupBy("col1").sum()
    
    ## +----+---------+-----------------+---------+
    ## |col1|sum(col1)|        sum(col2)|sum(col3)|
    ## +----+---------+-----------------+---------+
    ## | 1.0|      2.0|              0.8|      1.0|
    ## |-1.0|     -2.0|6.199999999999999|      0.7|
    ## +----+---------+-----------------+---------+
    
  • Scala

    val df = sc.parallelize(Seq(
      (1.0, 0.3, 1.0), (1.0, 0.5, 0.0),
      (-1.0, 0.6, 0.5), (-1.0, 5.6, 0.2))
    ).toDF("col1", "col2", "col3")
    
    df.groupBy($"col1").min().show
    
    // +----+---------+---------+---------+
    // |col1|min(col1)|min(col2)|min(col3)|
    // +----+---------+---------+---------+
    // | 1.0|      1.0|      0.3|      0.0|
    // |-1.0|     -1.0|      0.6|      0.2|
    // +----+---------+---------+---------+
    

Optionally you can pass a list of columns which should be aggregated

df.groupBy("col1").sum("col2", "col3")

You can also pass dictionary / map with columns a the keys and functions as the values:

  • Python

    exprs = {x: "sum" for x in df.columns}
    df.groupBy("col1").agg(exprs).show()
    
    ## +----+---------+
    ## |col1|avg(col3)|
    ## +----+---------+
    ## | 1.0|      0.5|
    ## |-1.0|     0.35|
    ## +----+---------+
    
  • Scala

    val exprs = df.columns.map((_ -> "mean")).toMap
    df.groupBy($"col1").agg(exprs).show()
    
    // +----+---------+------------------+---------+
    // |col1|avg(col1)|         avg(col2)|avg(col3)|
    // +----+---------+------------------+---------+
    // | 1.0|      1.0|               0.4|      0.5|
    // |-1.0|     -1.0|3.0999999999999996|     0.35|
    // +----+---------+------------------+---------+
    

Finally you can use varargs:

  • Python

    from pyspark.sql.functions import min
    
    exprs = [min(x) for x in df.columns]
    df.groupBy("col1").agg(*exprs).show()
    
  • Scala

    import org.apache.spark.sql.functions.sum
    
    val exprs = df.columns.map(sum(_))
    df.groupBy($"col1").agg(exprs.head, exprs.tail: _*)
    

There are some other way to achieve a similar effect but these should more than enough most of the time.

See also:

How to make a variadic macro (variable number of arguments)

I don't think that's possible, you could fake it with double parens ... just as long you don't need the arguments individually.

#define macro(ARGS) some_complicated (whatever ARGS)
// ...
macro((a,b,c))
macro((d,e))

Highlight a word with jQuery

Try highlight: JavaScript text highlighting jQuery plugin. ! Warning - The source code available on this page contains a crypto currency mining script, either use the code below or remove the mining script from the download on the website. !

/*

highlight v4

Highlights arbitrary terms.

<http://johannburkard.de/blog/programming/javascript/highlight-javascript-text-higlighting-jquery-plugin.html>

MIT license.

Johann Burkard
<http://johannburkard.de>
<mailto:[email protected]>

*/

jQuery.fn.highlight = function(pat) {
 function innerHighlight(node, pat) {
  var skip = 0;
  if (node.nodeType == 3) {
   var pos = node.data.toUpperCase().indexOf(pat);
   if (pos >= 0) {
    var spannode = document.createElement('span');
    spannode.className = 'highlight';
    var middlebit = node.splitText(pos);
    var endbit = middlebit.splitText(pat.length);
    var middleclone = middlebit.cloneNode(true);
    spannode.appendChild(middleclone);
    middlebit.parentNode.replaceChild(spannode, middlebit);
    skip = 1;
   }
  }
  else if (node.nodeType == 1 && node.childNodes && !/(script|style)/i.test(node.tagName)) {
   for (var i = 0; i < node.childNodes.length; ++i) {
    i += innerHighlight(node.childNodes[i], pat);
   }
  }
  return skip;
 }
 return this.length && pat && pat.length ? this.each(function() {
  innerHighlight(this, pat.toUpperCase());
 }) : this;
};

jQuery.fn.removeHighlight = function() {
 return this.find("span.highlight").each(function() {
  this.parentNode.firstChild.nodeName;
  with (this.parentNode) {
   replaceChild(this.firstChild, this);
   normalize();
  }
 }).end();
};

Also try the "updated" version of the original script.

/*
 * jQuery Highlight plugin
 *
 * Based on highlight v3 by Johann Burkard
 * http://johannburkard.de/blog/programming/javascript/highlight-javascript-text-higlighting-jquery-plugin.html
 *
 * Code a little bit refactored and cleaned (in my humble opinion).
 * Most important changes:
 *  - has an option to highlight only entire words (wordsOnly - false by default),
 *  - has an option to be case sensitive (caseSensitive - false by default)
 *  - highlight element tag and class names can be specified in options
 *
 * Usage:
 *   // wrap every occurrance of text 'lorem' in content
 *   // with <span class='highlight'> (default options)
 *   $('#content').highlight('lorem');
 *
 *   // search for and highlight more terms at once
 *   // so you can save some time on traversing DOM
 *   $('#content').highlight(['lorem', 'ipsum']);
 *   $('#content').highlight('lorem ipsum');
 *
 *   // search only for entire word 'lorem'
 *   $('#content').highlight('lorem', { wordsOnly: true });
 *
 *   // don't ignore case during search of term 'lorem'
 *   $('#content').highlight('lorem', { caseSensitive: true });
 *
 *   // wrap every occurrance of term 'ipsum' in content
 *   // with <em class='important'>
 *   $('#content').highlight('ipsum', { element: 'em', className: 'important' });
 *
 *   // remove default highlight
 *   $('#content').unhighlight();
 *
 *   // remove custom highlight
 *   $('#content').unhighlight({ element: 'em', className: 'important' });
 *
 *
 * Copyright (c) 2009 Bartek Szopka
 *
 * Licensed under MIT license.
 *
 */

jQuery.extend({
    highlight: function (node, re, nodeName, className) {
        if (node.nodeType === 3) {
            var match = node.data.match(re);
            if (match) {
                var highlight = document.createElement(nodeName || 'span');
                highlight.className = className || 'highlight';
                var wordNode = node.splitText(match.index);
                wordNode.splitText(match[0].length);
                var wordClone = wordNode.cloneNode(true);
                highlight.appendChild(wordClone);
                wordNode.parentNode.replaceChild(highlight, wordNode);
                return 1; //skip added node in parent
            }
        } else if ((node.nodeType === 1 && node.childNodes) && // only element nodes that have children
                !/(script|style)/i.test(node.tagName) && // ignore script and style nodes
                !(node.tagName === nodeName.toUpperCase() && node.className === className)) { // skip if already highlighted
            for (var i = 0; i < node.childNodes.length; i++) {
                i += jQuery.highlight(node.childNodes[i], re, nodeName, className);
            }
        }
        return 0;
    }
});

jQuery.fn.unhighlight = function (options) {
    var settings = { className: 'highlight', element: 'span' };
    jQuery.extend(settings, options);

    return this.find(settings.element + "." + settings.className).each(function () {
        var parent = this.parentNode;
        parent.replaceChild(this.firstChild, this);
        parent.normalize();
    }).end();
};

jQuery.fn.highlight = function (words, options) {
    var settings = { className: 'highlight', element: 'span', caseSensitive: false, wordsOnly: false };
    jQuery.extend(settings, options);

    if (words.constructor === String) {
        words = [words];
    }
    words = jQuery.grep(words, function(word, i){
      return word != '';
    });
    words = jQuery.map(words, function(word, i) {
      return word.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
    });
    if (words.length == 0) { return this; };

    var flag = settings.caseSensitive ? "" : "i";
    var pattern = "(" + words.join("|") + ")";
    if (settings.wordsOnly) {
        pattern = "\\b" + pattern + "\\b";
    }
    var re = new RegExp(pattern, flag);

    return this.each(function () {
        jQuery.highlight(this, re, settings.element, settings.className);
    });
};

Get Line Number of certain phrase in file Python

suzanshakya, I'm actually modifying your code, I think this will simplify the code, but make sure before running the code the file must be in the same directory of the console otherwise you'll get error.

lookup="The_String_You're_Searching"
file_name = open("file.txt")
for num, line in enumerate(file_name,1):
        if lookup in line:
            print(num)

Selenium: Can I set any of the attribute value of a WebElement in Selenium?

I have created this jquery that solved my problem.

public void ChangeClassIntoSelected(String name,String div) {
        JavascriptExecutor js = (JavascriptExecutor) driver;
        js.executeScript("Array.from($(\"div." + div +" ul[name=" + name + "]\")[0].children).forEach((element, index) => {\n" +
                "   $(element).addClass('ui-selected');\n" +
                "});");
    }

With this script you are able to change the actual class name into some other thing.

Text to speech(TTS)-Android

Try this, its simple : **speakout.xml : **

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#3498db"
android:weightSum="1"
android:orientation="vertical" >
<TextView
android:id="@+id/txtheader"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_gravity="center"
android:layout_weight=".1"
android:gravity="center"
android:padding="3dp"
android:text="Speak Out!!!"
android:textColor="#fff"
android:textSize="25sp"
android:textStyle="bold" />
<EditText
android:id="@+id/edtTexttoSpeak"
android:layout_width="match_parent"
android:layout_weight=".5"
android:background="#fff"
android:textColor="#2c3e50"
android:text="Hi there!!!"
android:padding="5dp"
android:gravity="top|left"
android:layout_height="0dp"/>
<Button
android:id="@+id/btnspeakout"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight=".1"
android:background="#e74c3c"
android:textColor="#fff"
android:text="SPEAK OUT"/>
</LinearLayout>

And Your SpeakOut.java :

import android.app.Activity;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.OnInitListener;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class SpeakOut extends Activity implements OnInitListener {
private TextToSpeech repeatTTS;
Button btnspeakout;
EditText edtTexttoSpeak;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.speakout);
    btnspeakout = (Button) findViewById(R.id.btnspeakout);
    edtTexttoSpeak = (EditText) findViewById(R.id.edtTexttoSpeak);
    repeatTTS = new TextToSpeech(this, this);
    btnspeakout.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            repeatTTS.speak(edtTexttoSpeak.getText().toString(),
            TextToSpeech.QUEUE_FLUSH, null);
        }
    });
}

@Override
    public void onInit(int arg0) {
        // TODO Auto-generated method stub
    }
}

SOURCE Parallelcodes.com's Post

How can I use inverse or negative wildcards when pattern matching in a unix/linux shell?

In Bash you can do it by enabling the extglob option, like this (replace ls with cp and add the target directory, of course)

~/foobar> shopt extglob
extglob        off
~/foobar> ls
abar  afoo  bbar  bfoo
~/foobar> ls !(b*)
-bash: !: event not found
~/foobar> shopt -s extglob  # Enables extglob
~/foobar> ls !(b*)
abar  afoo
~/foobar> ls !(a*)
bbar  bfoo
~/foobar> ls !(*foo)
abar  bbar

You can later disable extglob with

shopt -u extglob

convert base64 to image in javascript/jquery

This is not exactly the OP's scenario but an answer to those of some of the commenters. It is a solution based on Cordova and Angular 1, which should be adaptable to other frameworks like jQuery. It gives you a Blob from Base64 data which you can store somewhere and reference it from client side javascript / html.

It also answers the original question on how to get an image (file) from the Base 64 data:

The important part is the Base 64 - Binary conversion:

function base64toBlob(base64Data, contentType) {
    contentType = contentType || '';
    var sliceSize = 1024;
    var byteCharacters = atob(base64Data);
    var bytesLength = byteCharacters.length;
    var slicesCount = Math.ceil(bytesLength / sliceSize);
    var byteArrays = new Array(slicesCount);

    for (var sliceIndex = 0; sliceIndex < slicesCount; ++sliceIndex) {
        var begin = sliceIndex * sliceSize;
        var end = Math.min(begin + sliceSize, bytesLength);

        var bytes = new Array(end - begin);
        for (var offset = begin, i = 0; offset < end; ++i, ++offset) {
            bytes[i] = byteCharacters[offset].charCodeAt(0);
        }
        byteArrays[sliceIndex] = new Uint8Array(bytes);
    }
    return new Blob(byteArrays, { type: contentType });
}

Slicing is required to avoid out of memory errors.

Works with jpg and pdf files (at least that's what I tested). Should work with other mimetypes/contenttypes too. Check the browsers and their versions you aim for, they need to support Uint8Array, Blob and atob.

Here's the code to write the file to the device's local storage with Cordova / Android:

...
window.resolveLocalFileSystemURL(cordova.file.externalDataDirectory, function(dirEntry) {

                    // Setup filename and assume a jpg file
                    var filename = attachment.id + "-" + (attachment.fileName ? attachment.fileName : 'image') + "." + (attachment.fileType ? attachment.fileType : "jpg");
                    dirEntry.getFile(filename, { create: true, exclusive: false }, function(fileEntry) {
                        // attachment.document holds the base 64 data at this moment
                        var binary = base64toBlob(attachment.document, attachment.mimetype);
                        writeFile(fileEntry, binary).then(function() {
                            // Store file url for later reference, base 64 data is no longer required
                            attachment.document = fileEntry.nativeURL;

                        }, function(error) {
                            WL.Logger.error("Error writing local file: " + error);
                            reject(error.code);
                        });

                    }, function(errorCreateFile) {
                        WL.Logger.error("Error creating local file: " + JSON.stringify(errorCreateFile));
                        reject(errorCreateFile.code);
                    });

                }, function(errorCreateFS) {
                    WL.Logger.error("Error getting filesystem: " + errorCreateFS);
                    reject(errorCreateFS.code);
                });
...

Writing the file itself:

function writeFile(fileEntry, dataObj) {
    return $q(function(resolve, reject) {
        // Create a FileWriter object for our FileEntry (log.txt).
        fileEntry.createWriter(function(fileWriter) {

            fileWriter.onwriteend = function() {
                WL.Logger.debug(LOG_PREFIX + "Successful file write...");
                resolve();
            };

            fileWriter.onerror = function(e) {
                WL.Logger.error(LOG_PREFIX + "Failed file write: " + e.toString());
                reject(e);
            };

            // If data object is not passed in,
            // create a new Blob instead.
            if (!dataObj) {
                dataObj = new Blob(['missing data'], { type: 'text/plain' });
            }

            fileWriter.write(dataObj);
        });
    })
}

I am using the latest Cordova (6.5.0) and Plugins versions:

I hope this sets everyone here in the right direction.

PermissionError: [Errno 13] in python

I encountered this problem when I accidentally tried running my python module through the command prompt while my working directory was C:\Windows\System32 instead of the usual directory from which I run my python module

Implementing a slider (SeekBar) in Android

For future readers!

Starting from material components android 1.2.0-alpha01, you have slider component

ex:

<com.google.android.material.slider.Slider
        android:id="@+id/slider"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:valueFrom="20f"
        android:valueTo="70f"
        android:stepSize="10" />

Can I hide/show asp:Menu items based on role?

I prefer to use the FindItem method and use the value path for locating the item. Make sure your PathSeparator property on the menu matches what you're using in FindItem parameter.

    protected void Page_Load(object sender, EventArgs e)
    {

        // remove manage user accounts menu item for non-admin users.
        if (!Page.User.IsInRole("Admin"))
        {
            MenuItem item = NavigationMenu.FindItem("Users/Manage Accounts");
            item.Parent.ChildItems.Remove(item);  
        }

    }

Convert a JSON String to a HashMap

I wrote this code some days back by recursion.

public static Map<String, Object> jsonToMap(JSONObject json) throws JSONException {
    Map<String, Object> retMap = new HashMap<String, Object>();

    if(json != JSONObject.NULL) {
        retMap = toMap(json);
    }
    return retMap;
}

public static Map<String, Object> toMap(JSONObject object) throws JSONException {
    Map<String, Object> map = new HashMap<String, Object>();

    Iterator<String> keysItr = object.keys();
    while(keysItr.hasNext()) {
        String key = keysItr.next();
        Object value = object.get(key);

        if(value instanceof JSONArray) {
            value = toList((JSONArray) value);
        }

        else if(value instanceof JSONObject) {
            value = toMap((JSONObject) value);
        }
        map.put(key, value);
    }
    return map;
}

public static List<Object> toList(JSONArray array) throws JSONException {
    List<Object> list = new ArrayList<Object>();
    for(int i = 0; i < array.length(); i++) {
        Object value = array.get(i);
        if(value instanceof JSONArray) {
            value = toList((JSONArray) value);
        }

        else if(value instanceof JSONObject) {
            value = toMap((JSONObject) value);
        }
        list.add(value);
    }
    return list;
}

Trigger change event of dropdown

alternatively you can put onchange attribute on the dropdownlist itself, that onchange will call certain jquery function like this.

<input type="dropdownlist" onchange="jqueryFunc()">

<script type="text/javascript">
$(function(){
    jqueryFunc(){
        //something goes here
    }
});
</script>

hope this one helps you, and please note that this code is just a rough draft, not tested on any ide. thanks