Programs & Examples On #Web component

Web components are reusable client-side elements made using native code or third party libraries.

How to consume a SOAP web service in Java

As some sugested you can use apache or jax-ws. You can also use tools that generate code from WSDL such as ws-import but in my opinion the best way to consume web service is to create a dynamic client and invoke only operations you want not everything from wsdl. You can do this by creating a dynamic client: Sample code:

String endpointUrl = ...;

QName serviceName = new QName("http://com/ibm/was/wssample/echo/",
 "EchoService");
QName portName = new QName("http://com/ibm/was/wssample/echo/",
 "EchoServicePort");

/** Create a service and add at least one port to it. **/ 
Service service = Service.create(serviceName);
service.addPort(portName, SOAPBinding.SOAP11HTTP_BINDING, endpointUrl);

/** Create a Dispatch instance from a service.**/ 
Dispatch<SOAPMessage> dispatch = service.createDispatch(portName, 
SOAPMessage.class, Service.Mode.MESSAGE);

/** Create SOAPMessage request. **/
// compose a request message
MessageFactory mf = MessageFactory.newInstance(SOAPConstants.SOAP_1_1_PROTOCOL);

// Create a message.  This example works with the SOAPPART.
SOAPMessage request = mf.createMessage();
SOAPPart part = request.getSOAPPart();

// Obtain the SOAPEnvelope and header and body elements.
SOAPEnvelope env = part.getEnvelope();
SOAPHeader header = env.getHeader();
SOAPBody body = env.getBody();

// Construct the message payload.
SOAPElement operation = body.addChildElement("invoke", "ns1",
 "http://com/ibm/was/wssample/echo/");
SOAPElement value = operation.addChildElement("arg0");
value.addTextNode("ping");
request.saveChanges();

/** Invoke the service endpoint. **/
SOAPMessage response = dispatch.invoke(request);

/** Process the response. **/

How to set a timer in android

As I have seen it, java.util.Timer is the most used for implementing a timer.

For a repeating task:

new Timer().scheduleAtFixedRate(task, after, interval);

For a single run of a task:

new Timer().schedule(task, after);


task being the method to be executed
after the time to initial execution
(interval the time for repeating the execution)

Updating version numbers of modules in a multi-module Maven project

the easiest way is to change version in every pom.xml to arbitrary version. then check that dependency management to use the correct version of the module used in this module! for example, if u want increase versioning for a tow module project u must do like flowing:

in childe module :

    <parent>
       <artifactId>A-application</artifactId>
       <groupId>com.A</groupId>
       <version>new-version</version>
    </parent>

and in parent module :

<groupId>com.A</groupId>
<artifactId>A-application</artifactId>
<version>new-version</version>

Where is the user's Subversion config file stored on the major operating systems?

@Baxter's is mostly correct but it is missing one important Windows-specific detail.

Subversion's runtime configuration area is stored in the %APPDATA%\Subversion\ directory. The files are config and servers.

However, in addition to text-based configuration files, Subversion clients can use Windows Registry to store the client settings. It makes it possible to modify the settings with PowerShell in a convenient manner, and also distribute these settings to user workstations in Active Directory environment via AD Group Policy. See SVNBook | Configuration and the Windows Registry (you can find examples and a sample *.reg file there).

enter image description here

How do I get Fiddler to stop ignoring traffic to localhost?

Go to Tools, Fiddler Options ..., select the Connections tab, then make sure Monitor all connections is ticked. Like Antony Scott said, but also make sure that the "Web Sessions" pane is set to "Capturing" and [ "Web Browsers" OR "All Processes" ]. Looks like the default is "Non-Browser".

Make a nav bar stick

add to your .nav css block the

position: fixed

and it will work

How do I bind a WPF DataGrid to a variable number of columns?

I have found a blog article by Deborah Kurata with a nice trick how to show variable number of columns in a DataGrid:

Populating a DataGrid with Dynamic Columns in a Silverlight Application using MVVM

Basically, she creates a DataGridTemplateColumn and puts ItemsControl inside that displays multiple columns.

How to add a button dynamically in Android?

Actually I add to the xml layout file anything that could be used! Then from the source code of the specific Activity I get the object by its id and I "play" with the visibility method.

Here is an example:

((Spinner)findViewById(R.id.email_spinner)).setVisibility(View.GONE);

Oracle : how to subtract two dates and get minutes of the result

I can handle this way:

select to_number(to_char(sysdate,'MI')) - to_number(to_char(*YOUR_DATA_VALUE*,'MI')),max(exp_time)  from ...

Or if you want to the hour just change the MI;

select to_number(to_char(sysdate,'HH24')) - to_number(to_char(*YOUR_DATA_VALUE*,'HH24')),max(exp_time)  from ...

the others don't work for me. Good luck.

How can I group by date time column without taking time into consideration

Cast/Convert the values to a Date type for your group by.

GROUP BY CAST(myDateTime AS DATE)

Understanding repr( ) function in Python

str() is used for creating output for end user while repr() is used for debuggin development.And it's represent the official of object.

Example:

>>> import datetime
>>> today = datetime.datetime.now()
>>> str(today)
'2018-04-08 18:00:15.178404'
>>> repr(today)
'datetime.datetime(2018, 4, 8, 18, 3, 21, 167886)'

From output we see that repr() shows the official representation of date object.

How do I manually configure a DataSource in Java?

Basically in JDBC most of these properties are not configurable in the API like that, rather they depend on implementation. The way JDBC handles this is by allowing the connection URL to be different per vendor.

So what you do is register the driver so that the JDBC system can know what to do with the URL:

 DriverManager.registerDriver((Driver) Class.forName("com.mysql.jdbc.Driver").newInstance());

Then you form the URL:

 String url = "jdbc:mysql://[host][,failoverhost...][:port]/[database][?propertyName1][=propertyValue1][&propertyName2][=propertyValue2]"

And finally, use it to get a connection:

 Connection c = DriverManager.getConnection(url);

In more sophisticated JDBC, you get involved with connection pools and the like, and application servers often have their own way of registering drivers in JNDI and you look up a DataSource from there, and call getConnection on it.

In terms of what properties MySQL supports, see here.

EDIT: One more thought, technically just having a line of code which does Class.forName("com.mysql.jdbc.Driver") should be enough, as the class should have its own static initializer which registers a version, but sometimes a JDBC driver doesn't, so if you aren't sure, there is little harm in registering a second one, it just creates a duplicate object in memeory.

What is the proper way to test if a parameter is empty in a batch file?

I got in in just under a month old (even though it was asked 8 years ago)... I hope s/he's moved beyond batch files by now. ;-) I used to do this all the time. I'm not sure what the ultimate goal is, though. If s/he's lazy like me, my go.bat works for stuff like that. (See below) But, 1, the command in the OP could be invalid if you are directly using the input as a command. i.e.,

"C:/Users/Me"

is an invalid command (or used to be if you were on a different drive). You need to break it in two parts.

C:
cd /Users/Me

And, 2, what does 'defined' or 'undefined' mean? GIGO. I use the default to catch errors. If the input doesn't get caught, it drops to help (or a default command). So, no input is not an error. You can try to cd to the input and catch the error if there is one. (Ok, using go "downloads (only one paren) is caught by DOS. (Harsh!))

cd "%1"
if %errorlevel% neq 0 goto :error

And, 3, quotes are needed only around the path, not the command. i.e.,

"cd C:\Users" 

was bad (or used to in the old days) unless you were on a different drive.

cd "\Users" 

is functional.

cd "\Users\Dr Whos infinite storage space"

works if you have spaces in your path.

@REM go.bat
@REM The @ sigh prevents echo on the current command
@REM The echo on/off turns on/off the echo command. Turn on for debugging
@REM You can't see this.
@echo off
if "help" == "%1" goto :help

if "c" == "%1" C:
if "c" == "%1" goto :done

if "d" == "%1" D:
if "d" == "%1" goto :done

if "home"=="%1" %homedrive%
if "home"=="%1" cd %homepath%
if "home"=="%1" if %errorlevel% neq 0 goto :error
if "home"=="%1" goto :done

if "docs" == "%1" goto :docs

@REM goto :help
echo Default command
cd %1
if %errorlevel% neq 0 goto :error
goto :done

:help
echo "Type go and a code for a location/directory
echo For example
echo go D
echo will change disks (D:)
echo go home
echo will change directories to the users home directory (%homepath%)
echo go pictures
echo will change directories to %homepath%\pictures
echo Notes
echo @ sigh prevents echo on the current command
echo The echo on/off turns on/off the echo command. Turn on for debugging
echo Paths (only) with folder names with spaces need to be inclosed in         quotes (not the ommand)
goto :done

:docs
echo executing "%homedrive%%homepath%\Documents"
%homedrive%
cd "%homepath%\Documents"\test error\
if %errorlevel% neq 0 goto :error
goto :done

:error
echo Error: Input (%1 %2 %3 %4 %5 %6 %7 %8 %9) or command is invalid
echo go help for help
goto :done

:done

"Not allowed to load local resource: file:///C:....jpg" Java EE Tomcat

sending tag <img src="c:\images\mypic.jpg"> would cause user browser to access image from his filesystem. if you have to store images in folder located in c:\images i would suggest to create an servlet like images.jsp, that as a parameter takes name of a file, then sets servlet response content to an image/jpg and then loads bytes of image from server location and put it to a response.

But what you use to create your application? is it pure servlet? Spring? JSF?

Here you can find some info about, how to do it.

round value to 2 decimals javascript

Just multiply the number by 100, round, and divide the resulting number by 100.

android: how to align image in the horizontal center of an imageview?

Use this attribute: android:layout_centerHorizontal="true"

Persistent invalid graphics state error when using ggplot2

try to get out grafics with x11() or win.graph() and solve this trouble.

Enable tcp\ip remote connections to sql server express already installed database with code or script(query)

I tested below code with SQL Server 2008 R2 Express and I believe we should have solution for all 6 steps you outlined. Let's take on them one-by-one:

1 - Enable TCP/IP

We can enable TCP/IP protocol with WMI:

set wmiComputer = GetObject( _
    "winmgmts:" _
    & "\\.\root\Microsoft\SqlServer\ComputerManagement10")
set tcpProtocols = wmiComputer.ExecQuery( _
    "select * from ServerNetworkProtocol " _
    & "where InstanceName = 'SQLEXPRESS' and ProtocolName = 'Tcp'")

if tcpProtocols.Count = 1 then
    ' set tcpProtocol = tcpProtocols(0)
    ' I wish this worked, but unfortunately 
    ' there's no int-indexed Item property in this type

    ' Doing this instead
    for each tcpProtocol in tcpProtocols
        dim setEnableResult
            setEnableResult = tcpProtocol.SetEnable()
            if setEnableResult <> 0 then 
                Wscript.Echo "Failed!"
            end if
    next
end if

2 - Open the right ports in the firewall

I believe your solution will work, just make sure you specify the right port. I suggest we pick a different port than 1433 and make it a static port SQL Server Express will be listening on. I will be using 3456 in this post, but please pick a different number in the real implementation (I feel that we will see a lot of applications using 3456 soon :-)

3 - Modify TCP/IP properties enable a IP address

We can use WMI again. Since we are using static port 3456, we just need to update two properties in IPAll section: disable dynamic ports and set the listening port to 3456:

set wmiComputer = GetObject( _
    "winmgmts:" _
    & "\\.\root\Microsoft\SqlServer\ComputerManagement10")
set tcpProperties = wmiComputer.ExecQuery( _
    "select * from ServerNetworkProtocolProperty " _
    & "where InstanceName='SQLEXPRESS' and " _
    & "ProtocolName='Tcp' and IPAddressName='IPAll'")

for each tcpProperty in tcpProperties
    dim setValueResult, requestedValue

    if tcpProperty.PropertyName = "TcpPort" then
        requestedValue = "3456"
    elseif tcpProperty.PropertyName ="TcpDynamicPorts" then
        requestedValue = ""
    end if

    setValueResult = tcpProperty.SetStringValue(requestedValue)
    if setValueResult = 0 then 
        Wscript.Echo "" & tcpProperty.PropertyName & " set."
    else
        Wscript.Echo "" & tcpProperty.PropertyName & " failed!"
    end if
next

Note that I didn't have to enable any of the individual addresses to make it work, but if it is required in your case, you should be able to extend this script easily to do so.

Just a reminder that when working with WMI, WBEMTest.exe is your best friend!

4 - Enable mixed mode authentication in sql server

I wish we could use WMI again, but unfortunately this setting is not exposed through WMI. There are two other options:

  1. Use LoginMode property of Microsoft.SqlServer.Management.Smo.Server class, as described here.

  2. Use LoginMode value in SQL Server registry, as described in this post. Note that by default the SQL Server Express instance is named SQLEXPRESS, so for my SQL Server 2008 R2 Express instance the right registry key was HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SQL Server\MSSQL10_50.SQLEXPRESS\MSSQLServer.

5 - Change user (sa) default password

You got this one covered.

6 - Finally (connect to the instance)

Since we are using a static port assigned to our SQL Server Express instance, there's no need to use instance name in the server address anymore.

SQLCMD -U sa -P newPassword -S 192.168.0.120,3456

Please let me know if this works for you (fingers crossed!).

How to save a Python interactive session?

You can use built-in function open: I use it in all of my programs in which I need to store some history (Including Calculator, etc.) for example:

#gk-test.py or anything else would do
try: # use the try loop only if you haven't created the history file outside program
    username = open("history.txt").readline().strip("\n")
    user_age = open("history.txt").readlines()[1].strip("\n")
except FileNotFoundError:
    username = input("Enter Username: ")
    user_age = input("Enter User's Age: ")
    open("history.txt", "w").write(f"{username}\n{user_age}")
#Rest of the code is secret! try it your own!

I would thank to all of them who liked my comments! Thank you for reading this!

Substitute a comma with a line break in a cell

Windows (unlike some other OS's, like Linux), uses CR+LF for line breaks:

  • CR = 13 = 0x0D = ^M = \r = carriage return

  • LF = 10 = 0x0A = ^J = \n = new line

The characters need to be in that order, if you want the line breaks to be consistently visible when copied to other Windows programs. So the Excel function would be:

=SUBSTITUTE(A1,",",CHAR(13) & CHAR(10))

Where can I find jenkins restful api reference?

Jenkins has a link to their REST API in the bottom right of each page. This link appears on every page of Jenkins and points you to an API output for the exact page you are browsing. That should provide some understanding into how to build the API URls.

You can additionally use some wrapper, like I do, in Python, using http://jenkinsapi.readthedocs.io/en/latest/

Here is their website: https://wiki.jenkins-ci.org/display/JENKINS/Remote+access+API

Client on Node.js: Uncaught ReferenceError: require is not defined

I am coming from an Electron environment, where I need IPC communication between a renderer process and the main process. The renderer process sits in an HTML file between script tags and generates the same error.

The line

const {ipcRenderer} = require('electron')

throws the Uncaught ReferenceError: require is not defined

I was able to work around that by specifying Node.js integration as true when the browser window (where this HTML file is embedded) was originally created in the main process.

function createAddItemWindow() {

    // Create a new window
    addItemWindown = new BrowserWindow({
        width: 300,
        height: 200,
        title: 'Add Item',

        // The lines below solved the issue
        webPreferences: {
            nodeIntegration: true
        }
})}

That solved the issue for me. The solution was proposed here.

How to run a specific Android app using Terminal?

You can Start the android Service by this command.

adb shell am startservice -n packageName/.ServiceClass

Class JavaLaunchHelper is implemented in both. One of the two will be used. Which one is undefined

  1. Install Java 7u21 from here: http://www.oracle.com/technetwork/java/javase/downloads/java-archive-downloads-javase7-521261.html#jdk-7u21-oth-JPR

  2. set these variables:

    export JAVA_HOME="/Library/Java/JavaVirtualMachines/jdk1.7.0_21.jdk/Contents/Home"
    export PATH=$JAVA_HOME/bin:$PATH
    
  3. Run your app and fun :)

(Minor update: put variable value in quote)

Exception in thread "main" java.lang.Error: Unresolved compilation problems

Your problem is in this line: Message messageObject = new Message ();
This error says that the Message class is not known at compile time.

So you need to import the Message class.

Something like this:

import package1.package2.Message;

Check this out.

http://docs.oracle.com/javase/tutorial/java/package/usepkgs.html

Convert a date format in PHP

There are two ways to implement this:

1.

    $date = strtotime(date);
    $new_date = date('d-m-Y', $date);

2.

    $cls_date = new DateTime($date);
    echo $cls_date->format('d-m-Y');

onclick="location.href='link.html'" does not load page in Safari

You can try this:

 <a href="link.html">
       <input type="button" value="Visit Page" />
    </a>

This will create button inside a link and it works on any browser

How can I find out what version of git I'm running?

In a command prompt:

$ git --version

IE9 JavaScript error: SCRIPT5007: Unable to get value of the property 'ui': object is null or undefined

This worked for me in IE 11:

<meta http-equiv="x-ua-compatible" content="IE=edge; charset=UTF-8">

How to get all table names from a database?

In your example problem is passed table name pattern in getTables function of DatabaseMetaData.

Some database supports Uppercase identifier, some support lower case identifiers. For example oracle fetches the table name in upper case, while postgreSQL fetch it in lower case.

DatabaseMetaDeta provides a method to determine how the database stores identifiers, can be mixed case, uppercase, lowercase see:http://docs.oracle.com/javase/7/docs/api/java/sql/DatabaseMetaData.html#storesMixedCaseIdentifiers()

From below example, you can get all tables and view of providing table name pattern, if you want only tables then remove "VIEW" from TYPES array.

public class DBUtility {
    private static final String[] TYPES = {"TABLE", "VIEW"};
    public static void getTableMetadata(Connection jdbcConnection, String tableNamePattern, String schema, String catalog, boolean isQuoted) throws HibernateException {
            try {
                DatabaseMetaData meta = jdbcConnection.getMetaData();
                ResultSet rs = null;
                try {
                    if ( (isQuoted && meta.storesMixedCaseQuotedIdentifiers())) {
                        rs = meta.getTables(catalog, schema, tableNamePattern, TYPES);
                    } else if ( (isQuoted && meta.storesUpperCaseQuotedIdentifiers())
                        || (!isQuoted && meta.storesUpperCaseIdentifiers() )) {
                        rs = meta.getTables(
                                StringHelper.toUpperCase(catalog),
                                StringHelper.toUpperCase(schema),
                                StringHelper.toUpperCase(tableNamePattern),
                                TYPES
                            );
                    }
                    else if ( (isQuoted && meta.storesLowerCaseQuotedIdentifiers())
                            || (!isQuoted && meta.storesLowerCaseIdentifiers() )) {
                        rs = meta.getTables( 
                                StringHelper.toLowerCase( catalog ),
                                StringHelper.toLowerCase(schema), 
                                StringHelper.toLowerCase(tableNamePattern), 
                                TYPES 
                            );
                    }
                    else {
                        rs = meta.getTables(catalog, schema, tableNamePattern, TYPES);
                    }

                    while ( rs.next() ) {
                        String tableName = rs.getString("TABLE_NAME");
                        System.out.println("table = " + tableName);
                    }



                }
                finally {
                    if (rs!=null) rs.close();
                }
            }
            catch (SQLException sqlException) {
                // TODO 
                sqlException.printStackTrace();
            }

    }

    public static void main(String[] args) {
        Connection jdbcConnection;
        try {
            jdbcConnection = DriverManager.getConnection("", "", "");
            getTableMetadata(jdbcConnection, "tbl%", null, null, false);
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

Adding image to JFrame

If you are using Netbeans to develop, use jLabel and change it's icon property.

What is the 'dynamic' type in C# 4.0 used for?

  1. You can call into dynamic languages such as CPython using pythonnet:

dynamic np = Py.Import("numpy")

  1. You can cast generics to dynamic when applying numerical operators on them. This provides type safety and avoids limitations of generics. This is in essence *duck typing:

T y = x * (dynamic)x, where typeof(x) is T

MySQL Workbench: How to keep the connection alive

in mysql-workbech 5.7 edit->preference-> SSH -> SSH Connect timeout (for SSH DB connection) enter image description here

Hash and salt passwords in C#

What blowdart said, but with a little less code. Use Linq or CopyTo to concatenate arrays.

public static byte[] Hash(string value, byte[] salt)
{
    return Hash(Encoding.UTF8.GetBytes(value), salt);
}

public static byte[] Hash(byte[] value, byte[] salt)
{
    byte[] saltedValue = value.Concat(salt).ToArray();
    // Alternatively use CopyTo.
    //var saltedValue = new byte[value.Length + salt.Length];
    //value.CopyTo(saltedValue, 0);
    //salt.CopyTo(saltedValue, value.Length);

    return new SHA256Managed().ComputeHash(saltedValue);
}

Linq has an easy way to compare your byte arrays too.

public bool ConfirmPassword(string password)
{
    byte[] passwordHash = Hash(password, _passwordSalt);

    return _passwordHash.SequenceEqual(passwordHash);
}

Before implementing any of this however, check out this post. For password hashing you may want a slow hash algorithm, not a fast one.

To that end there is the Rfc2898DeriveBytes class which is slow (and can be made slower), and may answer the second part of the original question in that it can take a password and salt and return a hash. See this question for more information. Note, Stack Exchange is using Rfc2898DeriveBytes for password hashing (source code here).

Clicking a button within a form causes page refresh

I use directive to prevent default behaviour:

module.directive('preventDefault', function() {
    return function(scope, element, attrs) {
        angular.element(element).bind('click', function(event) {
            event.preventDefault();
            event.stopPropagation();
        });
    }
});

And then, in html:

<button class="secondaryButton" prevent-default>Secondary action</button>

This directive can also be used with <a> and all other tags

How do you plot bar charts in gnuplot?

You can directly use the style histograms provide by gnuplot. This is an example if you have two file in output:

set style data histograms
 set style fill solid
 set boxwidth 0.5
 plot "file1.dat" using 5 title "Total1" lt rgb "#406090",\
      "file2.dat" using 5 title "Total2" lt rgb "#40FF00"

Invoking a PHP script from a MySQL trigger

A cronjob could monitor this log and based on events created by your trigger it could invoke a php script. That is if you absolutely have no control over you insertion.. If you have transaction logs in you MySQL, you can create a trigger for purpose of a log instance creation.

Setting selected values for ng-options bound select elements

You can use the ID field as the equality identifier. You can't use the adhoc object for this case because AngularJS checks references equality when comparing objects.

<select 
    ng-model="Choice.SelectedOption.ID" 
    ng-options="choice.ID as choice.Name for choice in Choice.Options">
</select>

How to post object and List using postman

Try this one,

{
  "address": "colombo",
  "username": "hesh",
  "password": "123",
  "registetedDate": "2015-4-3",
  "firstname": "hesh",
  "contactNo": "07762",
  "accountNo": "16161",
  "lastName": "jay",
  "skill":[1436517454492,1436517476993]
}

How to "wait" a Thread in Android

Write Thread.sleep(1000); it will make the thread sleep for 1000ms

How to find the extension of a file in C#?

You will not be able to restrict the file type that the user uploads at the client side[*]. You'll only be able to do this at the server side. If a user uploads an incorrect file you will only be able to recognise that once the file is uploaded uploaded. There is no reliable and safe way to stop a user uploading whatever file format they want.

[*] yes, you can do all kinds of clever stuff to detect the file extension before starting the upload, but don't rely on it. Someone will get around it and upload whatever they like sooner or later.

How to increment a letter N times per iteration and store in an array?

Here is your solution for the problem,

$letter = array();
for ($i = 'A'; $i !== 'ZZ'; $i++){
        if(ord($i) % 2 != 0)
           $letter[] .= $i;
}
print_r($letter);

You need to get the ASCII value for that character which will solve your problem.

Here is ord doc and working code.

For your requirement, you can do like this,

for ($i = 'A'; $i !== 'ZZ'; ord($i)+$x){
  $letter[] .= $i;
}
print_r($letter);

Here set $x as per your requirement.

Python - OpenCV - imread - Displaying Image

This can help you

namedWindow( "Display window", CV_WINDOW_AUTOSIZE );// Create a window for display.
imshow( "Display window", image );                   // Show our image inside it.

How to use document.getElementByName and getElementByTag?

If you have given same text name for both of your Id and Name properties you can give like document.getElementByName('frmMain')[index] other wise object required error will come.And if you have only one table in your page you can use document.getElementBytag('table')[index].

EDIT:

You can replace the index according to your form, if its first form place 0 for index.

UnicodeDecodeError: 'ascii' codec can't decode byte 0xc2

You need to decode data from input string into unicode, before using it, to avoid encoding problems.

field.text = data.decode("utf8")

Font scaling based on width of container

100% is relative to the base font size, which, if you haven't set it, would be the browser's user-agent default.

To get the effect you're after, I would use a piece of JavaScript code to adjust the base font size relative to the window dimensions.

List of Timezone IDs for use with FindTimeZoneById() in C#?

I know it's old and old question but Microsoft appears to have provided this through MSDN now.

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

How to have Ellipsis effect on Text

use numberOfLines

https://rnplay.org/plays/ImmKkA/edit

or if you know/or can compute the max character count per row, JS substring may be used.

<Text>{ ((mytextvar).length > maxlimit) ? 
    (((mytextvar).substring(0,maxlimit-3)) + '...') : 
    mytextvar }
</Text>

jQuery show/hide options from one select drop down, when option on other select dropdown is slected

A litle late perhaps but I would suggest

$(document).ready(function() {
    var layout_select_html = $('#layout_select').html(); //save original dropdown list

    $("#column_select").change(function () {
        var cur_column_val = $(this).val(); //save the selected value of the first dropdown
        $('#layout_select').html(layout_select_html); //set original dropdown list back
        $('#layout_select').children('option').each(function(){ //loop through options
        if($(this).val().indexOf(cur_column_val)== -1){ //do your conditional and if it should not be in the dropdown list
           $(this).remove(); //remove option from list
        }
    });
});

How could I convert data from string to long in c#

This answer no longer works, and I cannot come up with anything better then the other answers (see below) listed here. Please review and up-vote them.

Convert.ToInt64("1100.25")

Method signature from MSDN:

public static long ToInt64(
    string value
)

Get Element value with minidom with Python

you can use something like this.It worked out for me

doc = parse('C:\\eve.xml')
my_node_list = doc.getElementsByTagName("name")
my_n_node = my_node_list[0]
my_child = my_n_node.firstChild
my_text = my_child.data 
print my_text

Java Try Catch Finally blocks without Catch

The finally block is always run after the try block ends, whether try ends normally or abnormally due to an exception, er, throwable.

If an exception is thrown by any of the code within the try block, then the current method simply re-throws (or continues to throw) the same exception (after running the finally block).

If the finally block throws an exception / error / throwable, and there is already a pending throwable, it gets ugly. Quite frankly, I forget exactly what happens (so much for my certification years ago). I think both throwables get linked together, but there is some special voodoo you have to do (i.e. - a method call I would have to look up) to get the original problem before the "finally" barfed, er, threw up.

Incidentally, try/finally is a pretty common thing to do for resource management, since java has no destructors.

E.g. -

r = new LeakyThing();
try { useResource( r); }
finally { r.release(); }  // close, destroy, etc

"Finally", one more tip: if you do bother to put in a catch, either catch specific (expected) throwable subclasses, or just catch "Throwable", not "Exception", for a general catch-all error trap. Too many problems, such as reflection goofs, throw "Errors", rather than "Exceptions", and those will slip right by any "catch all" coded as:

catch ( Exception e) ...  // doesn't really catch *all*, eh?

do this instead:

catch ( Throwable t) ...

Vim: faster way to select blocks of text in visual mode

v35G will select everything from the cursor up to line 35.

v puts you in select mode, 35 specifies the line number that you want to G go to.

You could also use v} which will select everything up to the beginning of the next paragraph.

Split String into an array of String

You need a regular expression like "\\s+", which means: split whenever at least one whitespace is encountered. The full Java code is:

try {
    String[] splitArray = input.split("\\s+");
} catch (PatternSyntaxException ex) {
    // 
}

Excel VBA Open workbook, perform actions, save as, close

I'll try and answer several different things, however my contribution may not cover all of your questions. Maybe several of us can take different chunks out of this. However, this info should be helpful for you. Here we go..

Opening A Seperate File:

ChDir "[Path here]"                          'get into the right folder here
Workbooks.Open Filename:= "[Path here]"      'include the filename in this path

'copy data into current workbook or whatever you want here

ActiveWindow.Close                          'closes out the file

Opening A File With Specified Date If It Exists:

I'm not sure how to search your directory to see if a file exists, but in my case I wouldn't bother to search for it, I'd just try to open it and put in some error checking so that if it doesn't exist then display this message or do xyz.

Some common error checking statements:

On Error Resume Next   'if error occurs continues on to the next line (ignores it)

ChDir "[Path here]"                         
Workbooks.Open Filename:= "[Path here]"      'try to open file here

Or (better option):

if one doesn't exist then bring up either a message box or dialogue box to say "the file does not exist, would you like to create a new one?

you would most likely want to use the GoTo ErrorHandler shown below to achieve this

On Error GoTo ErrorHandler:

ChDir "[Path here]"                         
Workbooks.Open Filename:= "[Path here]"      'try to open file here

ErrorHandler:
'Display error message or any code you want to run on error here

Much more info on Error handling here: http://www.cpearson.com/excel/errorhandling.htm


Also if you want to learn more or need to know more generally in VBA I would recommend Siddharth Rout's site, he has lots of tutorials and example code here: http://www.siddharthrout.com/vb-dot-net-and-excel/

Hope this helps!


Example on how to ensure error code doesn't run EVERYtime:

if you debug through the code without the Exit Sub BEFORE the error handler you'll soon realize the error handler will be run everytime regarldess of if there is an error or not. The link below the code example shows a previous answer to this question.

  Sub Macro

    On Error GoTo ErrorHandler:

    ChDir "[Path here]"                         
    Workbooks.Open Filename:= "[Path here]"      'try to open file here

    Exit Sub      'Code will exit BEFORE ErrorHandler if everything goes smoothly
                  'Otherwise, on error, ErrorHandler will be run

    ErrorHandler:
    'Display error message or any code you want to run on error here

  End Sub

Also, look at this other question in you need more reference to how this works: goto block not working VBA


What is the purpose of a self executing function in javascript?

One difference is that the variables that you declare in the function are local, so they go away when you exit the function and they don't conflict with other variables in other or same code.

How to get indices of a sorted array in Python

If you do not want to use numpy,

sorted(range(len(seq)), key=seq.__getitem__)

is fastest, as demonstrated here.

Get name of currently executing test in JUnit 4

Consider using SLF4J (Simple Logging Facade for Java) provides some neat improvements using parameterized messages. Combining SLF4J with JUnit 4 rule implementations can provide more efficient test class logging techniques.

import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.MethodRule;
import org.junit.rules.TestWatchman;
import org.junit.runners.model.FrameworkMethod;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class LoggingTest {

  @Rule public MethodRule watchman = new TestWatchman() {
    public void starting(FrameworkMethod method) {
      logger.info("{} being run...", method.getName());
    }
  };

  final Logger logger =
    LoggerFactory.getLogger(LoggingTest.class);

  @Test
  public void testA() {

  }

  @Test
  public void testB() {

  }
}

how to use getSharedPreferences in android

If someone used this:

val sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context)

PreferenceManager is now depricated, refactor to this:

val sharedPreferences = context.getSharedPreferences(context.packageName + "_preferences", Context.MODE_PRIVATE)

How do I import a pre-existing Java project into Eclipse and get up and running?

This assumes Eclipse and an appropriate JDK are installed on your system

  1. Open Eclipse and create a new Workspace by specifying an empty directory.
  2. Make sure you're in the Java perspective by selecting Window -> Open Perspective ..., select Other... and then Java
  3. Right click anywhere in the Package Explorer pane and select New -> Java Project
  4. In the dialog that opens give the project a name and then click the option that says "Crate project from existing sources."
  5. In the text box below the option you selected in Step 4 point to the root directory where you checked out the project. This should be the directory that contains "com"
  6. Click Finish. For this particular project you don't need to do any additional setup for your classpath since it only depends on classes that are part of the Java SE API.

How do I get the coordinate position after using jQuery drag and drop?

_x000D_
_x000D_
$(function() _x000D_
  {_x000D_
    $( "#element" ).draggable({ snap: ".ui-widget-header",grid: [ 1, 1 ]});_x000D_
  });_x000D_
    $(document).ready(function() {_x000D_
        $("#element").draggable({ _x000D_
                containment: '#snaptarget', _x000D_
                scroll: false_x000D_
         }).mousemove(function(){_x000D_
                var coord = $(this).position();_x000D_
                var width = $(this).width();_x000D_
               var height = $(this).height();_x000D_
                $("p.position").text( "(" + coord.left + "," + coord.top + ")" );_x000D_
                $("p.size").text( "(" + width + "," + height + ")" );_x000D_
         }).mouseup(function(){_x000D_
                var coord = $(this).position();_x000D_
                var width = $(this).width();_x000D_
                var height = $(this).height();_x000D_
                $.post('/test/layout_view.php', {x: coord.left, y: coord.top, w: width, h: height});_x000D_
               _x000D_
                });_x000D_
        });
_x000D_
#element {background:#666;border:1px #000 solid;cursor:move;height:110px;width:110px;padding:10px 10px 10px 10px;}_x000D_
#snaptarget { height:610px; width:1000px;}_x000D_
.draggable { width: 90px; height: 80px; float: left; margin: 0 0 0 0; font-size: .9em; }_x000D_
.wrapper_x000D_
{ _x000D_
background-image:linear-gradient(0deg, transparent 24%, rgba(255, 255, 255, .05) 25%, rgba(255, 255, 255, .05) 26%, transparent 27%, transparent 74%, rgba(255, 255, 255, .05) 75%, rgba(255, 255, 255, .05) 76%, transparent 77%, transparent), linear-gradient(90deg, transparent 24%, rgba(255, 255, 255, .05) 25%, rgba(255, 255, 255, .05) 26%, transparent 27%, transparent 74%, rgba(255, 255, 255, .05) 75%, rgba(255, 255, 255, .05) 76%, transparent 77%, transparent);_x000D_
height:100%;_x000D_
background-size:45px 45px;_x000D_
border: 1px solid black;_x000D_
background-color: #434343;_x000D_
margin: 20px 0px 0px 20px;_x000D_
}
_x000D_
<!doctype html>_x000D_
<html lang="en">_x000D_
  <head>_x000D_
    <meta charset="utf-8">_x000D_
    <title>Layout</title>_x000D_
    <link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">_x000D_
    <script src="//code.jquery.com/jquery-1.10.2.js"></script>_x000D_
    <script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>_x000D_
    <link rel="stylesheet" href="../themes/default/css/test4.css" type="text/css" charset="utf-8"/>_x000D_
    <script src="../themes/default/js/layout.js"></script>_x000D_
  </head>_x000D_
<body>_x000D_
    <div id="snaptarget" class="wrapper">_x000D_
        <div id="element" class="draggable ui-widget-content">_x000D_
          <p class="position"></p>_x000D_
          <p class="size"></p>_x000D_
        </div>_x000D_
    </div> _x000D_
    <div></div>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Android check permission for LocationManager

SIMPLE SOLUTION

I wanted to support apps pre api 23 and instead of using checkSelfPermission I used a try / catch

try {
   location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
} catch (SecurityException e) {
   dialogGPS(this.getContext()); // lets the user know there is a problem with the gps
}

Setting session variable using javascript

A session is stored server side, you can't modify it with JavaScript. Sessions may contain sensitive data.

You can modify cookies using document.cookie.

You can easily find many examples how to modify cookies.

Radio buttons and label to display in same line

If the problem is that the label and input are wrapping to two lines when the window is too narrow, remove the whitespace between them; e.g.:

<label for="one">First Item</label>
<input type="radio" id="one" name="first_item" value="1" />

If you need space between the elements, use non-breaking spaces (&amp; nbsp;) or CSS.

How can I include null values in a MIN or MAX?

It's a bit ugly but because the NULLs have a special meaning to you, this is the cleanest way I can think to do it:

SELECT recordid, MIN(startdate),
   CASE WHEN MAX(CASE WHEN enddate IS NULL THEN 1 ELSE 0 END) = 0
        THEN MAX(enddate)
   END
FROM tmp GROUP BY recordid

That is, if any row has a NULL, we want to force that to be the answer. Only if no rows contain a NULL should we return the MIN (or MAX).

How to create a file on Android Internal Storage?

Write a file

When saving a file to internal storage, you can acquire the appropriate directory as a File by calling one of two methods:

getFilesDir()

      Returns a File representing an internal directory for your app.

getCacheDir()

     Returns a File representing an internal directory for your 
     app's temporary cache files.
     Be sure to delete each file once it is no longer needed and implement a reasonable 
     size limit for the amount of memory you use at any given time, such as 1MB.

Caution: If the system runs low on storage, it may delete your cache files without warning.

Is it better to use C void arguments "void foo(void)" or not "void foo()"?

Besides syntactical differences, many people also prefer using void function(void) for pracitical reasons:

If you're using the search function and want to find the implementation of the function, you can search for function(void), and it will return the prototype as well as the implementation.

If you omit the void, you have to search for function() and will therefore also find all function calls, making it more difficult to find the actual implementation.

Angular 2 change event - model changes

That's a known issue. Currently you have to use a workaround like shown in your question.

This is working as intended. When the change event is emitted ngModelChange (the (...) part of [(ngModel)] hasn't updated the bound model yet:

<input type="checkbox"  (ngModelChange)="myModel=$event" [ngModel]="mymodel">

See also

How can I print out just the index of a pandas dataframe?

You can use lamba function:

index = df.index[lambda x : for x in df.index() ]
print(index)

android:drawableLeft margin and/or padding

As cephus mentioned android:drawablePadding will only force padding between the text and the drawable if the button is small enough.

When laying out larger buttons you can use android:drawablePadding in conjunction with android:paddingLeft and android:paddingRight to force the text and drawable inward towards the center of the button. By adjusting the left and right padding separately you can make very detailed adjustments to the layout.

Here's an example button that uses padding to push the text and icon closer together than they would be by default:

<Button android:text="@string/button_label" 
    android:id="@+id/buttonId"
    android:layout_width="160dip"
    android:layout_height="60dip"
    android:layout_gravity="center"
    android:textSize="13dip"
    android:drawableLeft="@drawable/button_icon"
    android:drawablePadding="2dip"
    android:paddingLeft="30dip"
    android:paddingRight="26dip"
    android:singleLine="true"
    android:gravity="center" />  

Default value in Doctrine

I struggled with the same problem. I wanted to have the default value from the database into the entities (automatically). Guess what, I did it :)

<?php
/**
 * Created by JetBrains PhpStorm.
 * User: Steffen
 * Date: 27-6-13
 * Time: 15:36
 * To change this template use File | Settings | File Templates.
 */

require_once 'bootstrap.php';

$em->getConfiguration()->setMetadataDriverImpl(
    new \Doctrine\ORM\Mapping\Driver\DatabaseDriver(
        $em->getConnection()->getSchemaManager()
    )
);

$driver = new \Doctrine\ORM\Mapping\Driver\DatabaseDriver($em->getConnection()->getSchemaManager());
$driver->setNamespace('Models\\');

$em->getConfiguration()->setMetadataDriverImpl($driver);

$cmf = new \Doctrine\ORM\Tools\DisconnectedClassMetadataFactory();
$cmf->setEntityManager($em);
$metadata = $cmf->getAllMetadata();

// Little hack to have default values for your entities...
foreach ($metadata as $k => $t)
{
    foreach ($t->getFieldNames() as $fieldName)
    {
        $correctFieldName = \Doctrine\Common\Util\Inflector::tableize($fieldName);

        $columns = $tan = $em->getConnection()->getSchemaManager()->listTableColumns($t->getTableName());
        foreach ($columns as $column)
        {
            if ($column->getName() == $correctFieldName)
            {
                // We skip DateTime, because this needs to be a DateTime object.
                if ($column->getType() != 'DateTime')
                {
                    $metadata[$k]->fieldMappings[$fieldName]['default'] = $column->getDefault();
                }
                break;
            }
        }
    }
}

// GENERATE PHP ENTITIES!
$entityGenerator = new \Doctrine\ORM\Tools\EntityGenerator();
$entityGenerator->setGenerateAnnotations(true);
$entityGenerator->setGenerateStubMethods(true);
$entityGenerator->setRegenerateEntityIfExists(true);
$entityGenerator->setUpdateEntityIfExists(false);
$entityGenerator->generate($metadata, __DIR__);

echo "Entities created";

Angular @ViewChild() error: Expected 2 arguments, but got 1

In Angular 8, ViewChild always takes 2 param, and second params always has static: true or static: false

You can try like this:

@ViewChild('nameInput', {static: false}) component

Also,the static: false is going to be the default fallback behaviour in Angular 9.

What are static false/true: So as a rule of thumb you can go for the following:

  • { static: true } needs to be set when you want to access the ViewChild in ngOnInit.

    { static: false } can only be accessed in ngAfterViewInit. This is also what you want to go for when you have a structural directive (i.e. *ngIf) on your element in your template.

How to add style from code behind?

Try this:

Html Markup

<asp:HyperLink ID="HyperLink1" runat="server" NavigateUrl="#">HyperLink</asp:HyperLink>

Code

using System.Drawing;
using System.Web.UI;
using System.Web.UI.WebControls;

protected void Page_Load(object sender, EventArgs e)
{
    Style style = new Style();
    style.ForeColor = Color.Green;
    this.Page.Header.StyleSheet.CreateStyleRule(style, this, "#" + HyperLink1.ClientID + ":hover");
}

serialize/deserialize java 8 java.time with Jackson JSON mapper

If you are using ObjectMapper class of fasterxml, by default ObjectMapper do not understand the LocalDateTime class, so, you need to add another dependency in your gradle/maven :

compile 'com.fasterxml.jackson.datatype:jackson-datatype-jsr310:2.7.3'

Now you need to register the datatype support offered by this library into you objectmapper object, this can be done by following :

ObjectMapper objectMapper = new ObjectMapper();
objectMapper.findAndRegisterModules();

Now, in your jsonString, you can easily put your java.LocalDateTime field as follows :

{
    "user_id": 1,
    "score": 9,
    "date_time": "2016-05-28T17:39:44.937"
}

By doing all this, your Json file to Java object conversion will work fine, you can read the file by following :

objectMapper.readValue(jsonString, new TypeReference<List<User>>() {
            });

How to save MySQL query output to excel or .txt file?

You can write following codes to achieve this task:

SELECT ... FROM ... WHERE ... 
INTO OUTFILE 'textfile.csv'
FIELDS TERMINATED BY '|'

It export the result to CSV and then export it to excel sheet.

What is the difference between Cloud Computing and Grid Computing?

You should really read Wikipedia for in-depth understanding. In short, Cloud computing means you develop/run your software remotely on remote platform. This can be either using remote virtual infrastructure (amazon EC2), remote platform (google app engine), or remote application (force.com or gmail.com).

Grid computing means using many physical hardwares to do computations (in the broad sense) as if it was a single hardware. This means that you can run your application on several distinct machines at the same time.

not very accurate but enough to get you started.

How to copy Docker images from one host to another without using a repository

I assume you need to save couchdb-cartridge which has an image id of 7ebc8510bc2c:

stratos@Dev-PC:~$ docker images
REPOSITORY                             TAG                 IMAGE ID            CREATED             VIRTUAL SIZE
couchdb-cartridge                      latest              7ebc8510bc2c        17 hours ago        1.102 GB
192.168.57.30:5042/couchdb-cartridge   latest              7ebc8510bc2c        17 hours ago        1.102 GB
ubuntu                                 14.04               53bf7a53e890        3 days ago          221.3 MB

Save the archiveName image to a tar file. I will use the /media/sf_docker_vm/ to save the image.

stratos@Dev-PC:~$ docker save imageID > /media/sf_docker_vm/archiveName.tar

Copy the archiveName.tar file to your new Docker instance using whatever method works in your environment, for example FTP, SCP, etc.

Run the docker load command on your new Docker instance and specify the location of the image tar file.

stratos@Dev-PC:~$ docker load < /media/sf_docker_vm/archiveName.tar

Finally, run the docker images command to check that the image is now available.

stratos@Dev-PC:~$ docker images
REPOSITORY                             TAG        IMAGE ID         CREATED             VIRTUAL SIZE
couchdb-cartridge                      latest     7ebc8510bc2c     17 hours ago        1.102 GB
192.168.57.30:5042/couchdb-cartridge   latest     bc8510bc2c       17 hours ago        1.102 GB
ubuntu                                 14.04      4d2eab1c0b9a     3 days ago          221.3 MB

Please find this detailed post.

What languages are Windows, Mac OS X and Linux written in?

See under the heading One Operating System Running On Multiple Platforms where it states:

Most of the source code for Windows NT is written in C or C++.

Use jQuery to change value of a label

.text is correct, the following code works for me:

$('#lb'+(n+1)).text(a[i].attributes[n].name+": "+ a[i].attributes[n].value);

How can I add a box-shadow on one side of an element?

This could be a simple way

border-right : 1px solid #ddd;
height:85px;    
box-shadow : 10px 0px 5px 1px #eaeaea;

Assign this to any div

Django TemplateDoesNotExist?

Works on Django 3

I found I believe good way, I have the base.html in root folder, and all other html files in App folders, I settings.py

import os

# This settings are to allow store templates,static and media files in root folder

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
TEMPLATE_DIR = os.path.join(BASE_DIR,'templates')
STATIC_DIR = os.path.join(BASE_DIR,'static')
MEDIA_DIR = os.path.join(BASE_DIR,'media')

# This is default path from Django, must be added 
#AFTER our BASE_DIR otherwise DB will be broken.
BASE_DIR = Path(__file__).resolve().parent.parent

# add your apps to Installed apps
INSTALLED_APPS = [
    'main',
    'weblogin',
     ..........
]

# Now add TEMPLATE_DIR to  'DIRS' where in TEMPLATES like bellow
TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [TEMPLATE_DIR, BASE_DIR,],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]
# On end of Settings.py put this refferences to Static and Media files
STATICFILES_DIRS = [STATIC_DIR,]
STATIC_URL = '/static/'

MEDIA_ROOT = [MEDIA_DIR,]
MEDIA_URL = '/media/'

If you have problem with Database, please check if you put the original BASE_DIR bellow the new BASE_DIR otherwise change

# Original
'NAME': BASE_DIR / 'db.sqlite3',
# to
'NAME': os.path.join(BASE_DIR,'db.sqlite3'),

Django now will be able to find the HTML and Static files both in the App folders and in Root folder without need of adding the name of App folder in front of the file.

Struture:
-DjangoProject
    -static(css,JS ...)
    -templates(base.html, ....)
    -other django files like (manage.py, ....)
    -App1
        -templates(index1.html, other html files can extend now base.html too)
        -other App1 files
    -App2
        -templates(index2.html, other html files can extend now base.html too)
        -other App2 files

How can I rollback an UPDATE query in SQL server 2005?

You need this tool and you can find the transaction and reverse it.

ApexSQL Log

numpy.where() detailed, step-by-step explanation / examples

Here is a little more fun. I've found that very often NumPy does exactly what I wish it would do - sometimes it's faster for me to just try things than it is to read the docs. Actually a mixture of both is best.

I think your answer is fine (and it's OK to accept it if you like). This is just "extra".

import numpy as np

a = np.arange(4,10).reshape(2,3)

wh = np.where(a>7)
gt = a>7
x  = np.where(gt)

print "wh: ", wh
print "gt: ", gt
print "x:  ", x

gives:

wh:  (array([1, 1]), array([1, 2]))
gt:  [[False False False]
      [False  True  True]]
x:   (array([1, 1]), array([1, 2]))

... but:

print "a[wh]: ", a[wh]
print "a[gt]  ", a[gt]
print "a[x]:  ", a[x]

gives:

a[wh]:  [8 9]
a[gt]   [8 9]
a[x]:   [8 9]

Send form data using ajax

In your function form is a DOM object, In order to use attr() you need to convert it to jQuery object.

function f(form, fname, lname) {
    action = $(form).attr("action");
    $.post(att, {fname : fname , lname :lname}).done(function (data) {
        alert(data);
    });
    return true;
}

With .serialize()

function f(form, fname, lname) {
    action = $(form).attr("action");
    $.post(att, $(form).serialize() ).done(function (data) {
        alert(data);
    });
    return true;
}

Additionally, You can use .serialize()

How can I list (ls) the 5 last modified files in a directory?

Try using head or tail. If you want the 5 most-recently modified files:

ls -1t | head -5

The -1 (that's a one) says one file per line and the head says take the first 5 entries.

If you want the last 5 try

ls -1t | tail -5

Classes vs. Functions

Never create classes. At least the OOP kind of classes in Python being discussed.

Consider this simplistic class:

class Person(object):
    def __init__(self, id, name, city, account_balance):
        self.id = id
        self.name = name
        self.city = city
        self.account_balance = account_balance

    def adjust_balance(self, offset):
        self.account_balance += offset


if __name__ == "__main__":
    p = Person(123, "bob", "boston", 100.0)
    p.adjust_balance(50.0)
    print("done!: {}".format(p.__dict__))

vs this namedtuple version:

from collections import namedtuple

Person = namedtuple("Person", ["id", "name", "city", "account_balance"])


def adjust_balance(person, offset):
    return person._replace(account_balance=person.account_balance + offset)


if __name__ == "__main__":
    p = Person(123, "bob", "boston", 100.0)
    p = adjust_balance(p, 50.0)
    print("done!: {}".format(p))

The namedtuple approach is better because:

  • namedtuples have more concise syntax and standard usage.
  • In terms of understanding existing code, namedtuples are basically effortless to understand. Classes are more complex. And classes can get very complex for humans to read.
  • namedtuples are immutable. Managing mutable state adds unnecessary complexity.
  • class inheritance adds complexity, and hides complexity.

I can't see a single advantage to using OOP classes. Obviously, if you are used to OOP, or you have to interface with code that requires classes like Django.

BTW, most other languages have some record type feature like namedtuples. Scala, for example, has case classes. This logic applies equally there.

What is the difference between `git merge` and `git merge --no-ff`?

The --no-ff flag causes the merge to always create a new commit object, even if the merge could be performed with a fast-forward. This avoids losing information about the historical existence of a feature branch and groups together all commits that together added the feature

How to call JavaScript function instead of href in HTML

If you only have as "click event handler", use a <button> instead. A link has a specific semantic meaning.

E.g.:

<button onclick="ShowOld(2367,146986,2)">
    <img title="next page" alt="next page" src="/themes/me/img/arrn.png">
</button>

Alternative to file_get_contents?

If the file is local as your comment about SITE_PATH suggest, it's pretty simple just execute the script and cache the result in a variable using the output control functions :

function print_xml_data_file()
{
    include(XML_DATA_FILE_DIRECTORY . 'cms/data.php');
}

function get_xml_data()
{
    ob_start();
    print_xml_data_file();
    $xml_file = ob_get_contents();
    ob_end_clean();
    return $xml_file;
}

If it's remote as lot of others said curl is the way to go. If it isn't present try socket_create or fsockopen. If nothing work... change your hosting provider.

Example using Hyperlink in WPF

I liked Arthur's idea of a reusable handler, but I think there's a simpler way to do it:

private void Hyperlink_RequestNavigate(object sender, RequestNavigateEventArgs e)
{
    if (sender.GetType() != typeof (Hyperlink))
        return;
    string link = ((Hyperlink) sender).NavigateUri.ToString();
    Process.Start(link);
}

Obviously there could be security risks with starting any kind of process, so be carefull.

Create a symbolic link of directory in Ubuntu

That's what ln is documented to do when the target already exists and is a directory. If you want /etc/nginx to be a symlink rather than contain a symlink, you had better not create it as a directory first!

Activity, AppCompatActivity, FragmentActivity, and ActionBarActivity: When to Use Which?

2019: Use AppCompatActivity

At the time of this writing (check the link to confirm it is still true), the Android Documentation recommends using AppCompatActivity if you are using an App Bar.

This is the rational given:

Beginning with Android 3.0 (API level 11), all activities that use the default theme have an ActionBar as an app bar. However, app bar features have gradually been added to the native ActionBar over various Android releases. As a result, the native ActionBar behaves differently depending on what version of the Android system a device may be using. By contrast, the most recent features are added to the support library's version of Toolbar, and they are available on any device that can use the support library.

For this reason, you should use the support library's Toolbar class to implement your activities' app bars. Using the support library's toolbar helps ensure that your app will have consistent behavior across the widest range of devices. For example, the Toolbar widget provides a material design experience on devices running Android 2.1 (API level 7) or later, but the native action bar doesn't support material design unless the device is running Android 5.0 (API level 21) or later.

The general directions for adding a ToolBar are

  1. Add the v7 appcompat support library
  2. Make all your activities extend AppCompatActivity
  3. In the Manifest declare that you want NoActionBar.
  4. Add a ToolBar to each activity's xml layout.
  5. Get the ToolBar in each activity's onCreate.

See the documentation directions for more details. They are quite clear and helpful.

read string from .resx file in C#

Create a resource manager to retrieve resources.

ResourceManager rm = new ResourceManager("param1",Assembly.GetExecutingAssembly());

String str = rm.GetString("param2");

param1 = "AssemblyName.ResourceFolderName.ResourceFileName"

param2 = name of the string to be retrieved from the resource file

How to add scroll bar to the Relative Layout?

hi see the following sample code of xml file.

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/ScrollView01"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <RelativeLayout
        android:id="@+id/RelativeLayout01"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" >

        <LinearLayout
            android:id="@+id/LinearLayout01"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:orientation="vertical" >

            <TextView
                android:id="@+id/TextView01"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_margin="20dip"
                android:text="@+id/TextView01" >
            </TextView>

            <TextView
                android:id="@+id/TextView01"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_margin="20dip"
                android:text="@+id/TextView01" >
            </TextView>

            <TextView
                android:id="@+id/TextView01"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_margin="20dip"
                android:text="@+id/TextView01" >
            </TextView>

            <TextView
                android:id="@+id/TextView01"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_margin="20dip"
                android:text="@+id/TextView01" >
            </TextView>

            <TextView
                android:id="@+id/TextView01"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_margin="20dip"
                android:text="@+id/TextView01" >
            </TextView>

            <TextView
                android:id="@+id/TextView01"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_margin="20dip"
                android:text="@+id/TextView01" >
            </TextView>

            <TextView
                android:id="@+id/TextView01"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_margin="20dip"
                android:text="@+id/TextView01" >
            </TextView>

            <TextView
                android:id="@+id/TextView01"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_margin="20dip"
                android:text="@+id/TextView01" >
            </TextView>

            <TextView
                android:id="@+id/TextView01"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_margin="20dip"
                android:text="@+id/TextView01" >
            </TextView>
        </LinearLayout>
    </RelativeLayout>

</ScrollView>

Cannot use Server.MapPath

You need to add reference (System.Web) Reference to System.Web

How to implement "Access-Control-Allow-Origin" header in asp.net

From enable-cors.org:

CORS on ASP.NET

If you don't have access to configure IIS, you can still add the header through ASP.NET by adding the following line to your source pages:

Response.AppendHeader("Access-Control-Allow-Origin", "*");

See also: Configuring IIS6 / IIS7

What is the easiest way to disable/enable buttons and links (jQuery + Bootstrap)

Great answer and contributions from all! I had to extend this function slightly to include disabling of select elements:

jQuery.fn.extend({
disable: function (state) {
    return this.each(function () {
        var $this = jQuery(this);
        if ($this.is('input, button'))
            this.disabled = state;
        else if ($this.is('select') && state)
            $this.attr('disabled', 'disabled');
        else if ($this.is('select') && !state)
            $this.removeAttr('disabled');
        else
            $this.toggleClass('disabled', state);
    });
}});

Seems to be working for me. Thanks all!

Detecting endianness programmatically in a C++ program

The way C compilers (at least everyone I know of) work the endianness has to be decided at compile time. Even for biendian processors (like ARM och MIPS) you have to choose endianness at compile time. Further more the endianness is defined in all common file formats for executables (such as ELF). Although it is possible to craft a binary blob of biandian code (for some ARM server exploit maybe?) it probably has to be done in assembly.

How to convert IPython notebooks to PDF and HTML?

Also pass the --execute flag to generate the output cells

jupyter nbconvert --execute --to html notebook.ipynb
jupyter nbconvert --execute --to pdf notebook.ipynb

The best practice is to keep the output out of the notebook for version control, see: Using IPython notebooks under version control

But then, if you don't pass --execute, the output won't be present in the HTML, see also: How to run an .ipynb Jupyter Notebook from terminal?

For an HTML fragment without header: How to export an IPython notebook to HTML for a blog post?

Tested in Jupyter 4.4.0.

What is the <leader> in a .vimrc file?

Be aware that when you do press your <leader> key you have only 1000ms (by default) to enter the command following it.

This is exacerbated because there is no visual feedback (by default) that you have pressed your <leader> key and vim is awaiting the command; and so there is also no visual way to know when this time out has happened.

If you add set showcmd to your vimrc then you will see your <leader> key appear in the bottom right hand corner of vim (to the left of the cursor location) and perhaps more importantly you will see it disappear when the time out happens.

The length of the timeout can also be set in your vimrc, see :help timeoutlen for more information.

How do I get the function name inside a function in PHP?

If you are using PHP 5 you can try this:

function a() {
    $trace = debug_backtrace();
    echo $trace[0]["function"];
}

What is the use of GO in SQL Server Management Studio & Transact SQL?

GO is not a SQL keyword.

It's a batch separator used by client tools (like SSMS) to break the entire script up into batches

Answered before several times... example 1

Bootstrap 3 - How to load content in modal body via AJAX?

Check this SO answer out.

It looks like the only way is to provide the whole modal structure with your ajax response.

As you can check from the bootstrap source code, the load function is binded to the root element.

In case you can't modify the ajax response, a simple workaround could be an explicit call of the $(..).modal(..) plugin on your body element, even though it will probably break the show/hide functions of the root element.

How can I convert a Word document to PDF?

I agree with posters listing OpenOffice as a high-fidelity import/export facility of word / pdf docs with a Java API and it also works across platforms. OpenOffice import/export filters are pretty powerful and preserve most formatting during conversion to various formats including PDF. Docmosis and JODReports value-add to make life easier than learning the OpenOffice API directly which can be challenging because of the style of the UNO api and the crash-related bugs.

How to call a PHP function on the click of a button

The onclick attribute in HTML calls JavaScript functions, not PHP functions.

How to get active user's UserDetails

You can try this: By Using Authentication Object from Spring we can get User details from it in the controller method . Below is the example , by passing Authentication object in the controller method along with argument.Once user is authenticated the details are populated in the Authentication Object.

@GetMapping(value = "/mappingEndPoint") <ReturnType> methodName(Authentication auth) {
   String userName = auth.getName(); 
   return <ReturnType>;
}

Is there a limit to the length of a GET request?

Not in the RFC, no, but there are practical limits.

The HTTP protocol does not place any a priori limit on the length of a URI. Servers MUST be able to handle the URI of any resource they serve, and SHOULD be able to handle URIs of unbounded length if they provide GET-based forms that could generate such URIs. A server SHOULD return 414 (Request-URI Too Long) status if a URI is longer than the server can handle (see section 10.4.15).

Note: Servers should be cautious about depending on URI lengths above 255 bytes, because some older client or proxy implementations may not properly support these lengths.

Which is better: <script type="text/javascript">...</script> or <script>...</script>

With the latest Firefox, I must use:

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

Or else the script may not run properly.

Center fixed div with dynamic width (CSS)

<div id="container">
    <div id="some_kind_of_popup">
        center me
    </div>
</div>

You'd need to wrap it in a container. here's the css

#container{
    position: fixed;
    top: 100px;
    width: 100%;
    text-align: center;
}
#some_kind_of_popup{
    display:inline-block;
    width: 90%;
    max-width: 900px;  
    min-height: 300px;  
}

JSON and XML comparison

The XML (extensible Markup Language) is used often XHR because this is a standard broadcasting language, what can be used by any programming language, and supported both server and client side, so this is the most flexible solution. The XML can be separated for more parts so a specified group can develop the part of the program, without affecting the other parts. The XML format can also be determined by the XML DTD or XML Schema (XSL) and can be tested.

The JSON a data-exchange format which is getting more popular as the JavaScript applications possible format. Basically this is an object notation array. JSON has a very simple syntax so can be easily learned. And also the JavaScript support parsing JSON with the eval function. On the other hand, the eval function has got negatives. For example, the program can be very slow parsing JSON and because of security the eval can be very risky. This not mean that the JSON is not good, just we have to be more careful.

My suggestion is that you should use JSON for applications with light data-exchange, like games. Because you don't have to really care about the data-processing, this is very simple and fast.

The XML is best for the bigger websites, for example shopping sites or something like this. The XML can be more secure and clear. You can create basic data-struct and schema to easily test the correction and separate it into parts easily.

I suggest you use XML because of the speed and the security, but JSON for lightweight stuff.

can't start MySql in Mac OS 10.6 Snow Leopard

I'd guess that your iMac isn't 64-bit (you state in another thread it is an original white intel iMac). Try the 32-bit version of MySQL–it should install directly over the 64-bit version, I think.

How to tell if your Intel-based Mac has a 32-bit or 64-bit processor
http://support.apple.com/kb/HT3696

Displaying a webcam feed using OpenCV and Python

Try adding the line c = cv.WaitKey(10) at the bottom of your repeat() method.

This waits for 10 ms for the user to enter a key. Even if you're not using the key at all, put this in. I think there just needed to be some delay, so time.sleep(10) may also work.

In regards to the camera index, you could do something like this:

for i in range(3):
    capture = cv.CaptureFromCAM(i)
    if capture: break

This will find the index of the first "working" capture device, at least for indices from 0-2. It's possible there are multiple devices in your computer recognized as a proper capture device. The only way I know of to confirm you have the right one is manually looking at your light. Maybe get an image and check its properties?

To add a user prompt to the process, you could bind a key to switching cameras in your repeat loop:

import cv

cv.NamedWindow("w1", cv.CV_WINDOW_AUTOSIZE)
camera_index = 0
capture = cv.CaptureFromCAM(camera_index)

def repeat():
    global capture #declare as globals since we are assigning to them now
    global camera_index
    frame = cv.QueryFrame(capture)
    cv.ShowImage("w1", frame)
    c = cv.WaitKey(10)
    if(c=="n"): #in "n" key is pressed while the popup window is in focus
        camera_index += 1 #try the next camera index
        capture = cv.CaptureFromCAM(camera_index)
        if not capture: #if the next camera index didn't work, reset to 0.
            camera_index = 0
            capture = cv.CaptureFromCAM(camera_index)

while True:
    repeat()

disclaimer: I haven't tested this so it may have bugs or just not work, but might give you at least an idea of a workaround.

How to solve "Plugin execution not covered by lifecycle configuration" for Spring Data Maven Builds

Changing

<artifactId>aspectj-maven-plugin</artifactId>
<version>1.2</version>

into

<artifactId>aspectj-maven-plugin</artifactId>
<version>1.3</version>

solved the problem for me.

Getting "method not valid without suitable object" error when trying to make a HTTP request in VBA?

Check out this one:

https://github.com/VBA-tools/VBA-Web

It's a high level library for dealing with REST. It's OOP, works with JSON, but also works with any other format.

How to get the mobile number of current sim card in real device?

I have to make an application which shows the Contact no of the SIM card that is being used in the cell. For that I need to use Telephony Manager class. Can i get details on its usage?

Yes, You have to use Telephony Manager;If at all you not found the contact no. of user; You can get Sim Serial Number of Sim Card and Imei No. of Android Device by using the same Telephony Manager Class...

Add permission:

<uses-permission android:name="android.permission.READ_PHONE_STATE"/>

Import:

import android.telephony.TelephonyManager;

Use the below code:

TelephonyManager tm = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);

         // get IMEI
         imei = tm.getDeviceId();

         // get SimSerialNumber
         simSerialNumber = tm.getSimSerialNumber();

How do I get a file's directory using the File object?

In either case, I'd expect file.getParent() (or file.getParentFile()) to give you what you want.

Additionally, if you want to find out whether the original File does exist and is a directory, then exists() and isDirectory() are what you're after.

Why do I get PLS-00302: component must be declared when it exists?

I came here because I had the same problem.
What was the problem for me was that the procedure was defined in the package body, but not in the package header.
I was executing my function with a lose BEGIN END statement.

ImportError: No module named sklearn.cross_validation

Past : from sklearn.cross_validation (This package is deprecated in 0.18 version from 0.20 onwards it is changed to from sklearn import model_selection).

Present: from sklearn import model_selection

Example 2:

Past : from sklearn.cross_validation import cross_val_score (Version 0.18 which is deprecated)

Present : from sklearn.model_selection import cross_val_score

MavenError: Failed to execute goal on project: Could not resolve dependencies In Maven Multimodule project

In my case I forgot it was packaging conflict jar vs pom. I forgot to write

<packaging>pom</packaging>

In every child pom.xml file

MySQL dump by query

Combining much of above here is my real practical example, selecting records based on both meterid & timestamp. I have needed this command for years. Executes really quickly.

mysqldump -uuser -ppassword main_dbo trHourly --where="MeterID =5406 AND TIMESTAMP<'2014-10-13 05:00:00'" --no-create-info --skip-extended-insert | grep  '^INSERT' > 5406.sql

Work on a remote project with Eclipse via SSH

My solution is similar to the SAMBA one except using sshfs. Mount my remote server with sshfs, open my makefile project on the remote machine. Go from there.

It seems I can run a GUI frontend to mercurial this way as well.

Building my remote code is as simple as: ssh address remote_make_command

I am looking for a decent way to debug though. Possibly via gdbserver?

XSS filtering function in PHP

I have a similar problem. I need users to submit html content to a profile page with a great WYSIWYG editor (Redactorjs!), i wrote the following function to clean the submitted html:

    <?php function filterxss($str) {
//Initialize DOM:
$dom = new DOMDocument();
//Load content and add UTF8 hint:
$dom->loadHTML('<meta http-equiv="content-type" content="text/html; charset=utf-8">'.$str);
//Array holds allowed attributes and validation rules:
$check = array('src'=>'#(http://[^\s]+(?=\.(jpe?g|png|gif)))#i','href'=>'|^http(s)?://[a-z0-9-]+(.[a-z0-9-]+)*(:[0-9]+)?(/.*)?$|i');
//Loop all elements:
foreach($dom->getElementsByTagName('*') as $node){
    for($i = $node->attributes->length -1; $i >= 0; $i--){
        //Get the attribute:
        $attribute = $node->attributes->item($i);
        //Check if attribute is allowed:
        if( in_array($attribute->name,array_keys($check))) {
            //Validate by regex:    
            if(!preg_match($check[$attribute->name],$attribute->value)) { 
                //No match? Remove the attribute
                $node->removeAttributeNode($attribute); 
            }
        }else{
            //Not allowed? Remove the attribute:
            $node->removeAttributeNode($attribute);
        }
    }
}
var_dump($dom->saveHTML()); } ?>

The $check array holds all the allowed attributes and validation rules. Maybe this is useful for some of you. I haven't tested is yet, so tips are welcome

The definitive guide to form-based website authentication

Definitive Article

Sending credentials

The only practical way to send credentials 100% securely is by using SSL. Using JavaScript to hash the password is not safe. Common pitfalls for client-side password hashing:

  • If the connection between the client and server is unencrypted, everything you do is vulnerable to man-in-the-middle attacks. An attacker could replace the incoming javascript to break the hashing or send all credentials to their server, they could listen to client responses and impersonate the users perfectly, etc. etc. SSL with trusted Certificate Authorities is designed to prevent MitM attacks.
  • The hashed password received by the server is less secure if you don't do additional, redundant work on the server.

There's another secure method called SRP, but it's patented (although it is freely licensed) and there are few good implementations available.

Storing passwords

Don't ever store passwords as plaintext in the database. Not even if you don't care about the security of your own site. Assume that some of your users will reuse the password of their online bank account. So, store the hashed password, and throw away the original. And make sure the password doesn't show up in access logs or application logs. OWASP recommends the use of Argon2 as your first choice for new applications. If this is not available, PBKDF2 or scrypt should be used instead. And finally if none of the above are available, use bcrypt.

Hashes by themselves are also insecure. For instance, identical passwords mean identical hashes--this makes hash lookup tables an effective way of cracking lots of passwords at once. Instead, store the salted hash. A salt is a string appended to the password prior to hashing - use a different (random) salt per user. The salt is a public value, so you can store them with the hash in the database. See here for more on this.

This means that you can't send the user their forgotten passwords (because you only have the hash). Don't reset the user's password unless you have authenticated the user (users must prove that they are able to read emails sent to the stored (and validated) email address.)

Security questions

Security questions are insecure - avoid using them. Why? Anything a security question does, a password does better. Read PART III: Using Secret Questions in @Jens Roland answer here in this wiki.

Session cookies

After the user logs in, the server sends the user a session cookie. The server can retrieve the username or id from the cookie, but nobody else can generate such a cookie (TODO explain mechanisms).

Cookies can be hijacked: they are only as secure as the rest of the client's machine and other communications. They can be read from disk, sniffed in network traffic, lifted by a cross-site scripting attack, phished from a poisoned DNS so the client sends their cookies to the wrong servers. Don't send persistent cookies. Cookies should expire at the end of the client session (browser close or leaving your domain).

If you want to autologin your users, you can set a persistent cookie, but it should be distinct from a full-session cookie. You can set an additional flag that the user has auto-logged in, and needs to log in for real for sensitive operations. This is popular with shopping sites that want to provide you with a seamless, personalized shopping experience but still protect your financial details. For example, when you return to visit Amazon, they show you a page that looks like you're logged in, but when you go to place an order (or change your shipping address, credit card etc.), they ask you to confirm your password.

Financial websites such as banks and credit cards, on the other hand, only have sensitive data and should not allow auto-login or a low-security mode.

List of external resources

Chrome Uncaught Syntax Error: Unexpected Token ILLEGAL

I had the same error when multiline string included new line (\n) characters. Merging all lines into one (thus removing all new line characters) and sending it to a browser used to solve. But was very inconvenient to code.

Often could not understand why this was an issue in Chrome until I came across to a statement which said that the current version of JavaScript engine in Chrome doesn't support multiline strings which are wrapped in single quotes and have new line (\n) characters in them. To make it work, multiline string need to be wrapped in double quotes. Changing my code to this, resolved this issue.

I will try to find a reference to a standard or Chrome doc which proves this. Until then, try this solution and see if works for you as well.

Python - How to concatenate to a string in a for loop?

If you must, this is how you can do it in a for loop:

mylist = ['first', 'second', 'other']
endstring = ''
for s in mylist:
  endstring += s

but you should consider using join():

''.join(mylist)

How do I rename a file using VBScript?

Rename File using VB SCript.

  1. Create Folder Source and Archive in D : Drive. [You can choose other drive but make change in code from D:\Source to C:\Source in case you create folder in C: Drive]
  2. Save files in Source folder to be renamed.
  3. Save below code and save it as .vbs e.g ChangeFileName.vbs
  4. Run file and the file will be renamed with existing file name and current date

    Option Explicit

    Dim fso,sfolder,fs,f1,CFileName,strRename,NewFilename,GFileName,CFolderName,CFolderName1,Dfolder,afolder

    Dim myDate

    myDate =Date

    Function pd(n, totalDigits)

        if totalDigits > len(n) then 
    
            pd = String(totalDigits-len(n),"0") & n 
    
        else 
    
            pd = n 
    
        end if 
    

    End Function

    myDate= Pd(DAY(date()),2) & _

    Pd(Month(date()),2) & _

    YEAR(Date())

    'MsgBox ("Create Folders 'Source' 'Destination ' and 'Archive' in D drive. Save PDF files into Source Folder ")

    sfolder="D:\Source\"

    'Dfolder="D:\Destination\"

    afolder="D:\archive\"

    Set fso= CreateObject("Scripting.FileSystemObject")

    Set fs= fso.GetFolder(sfolder)

    For each f1 in fs.files

            CFileName=sfolder & f1.name
    
            CFolderName1=f1.name
    
            CFolderName=Replace(CFolderName1,"." & fso.GetExtensionName(f1.Path),"")
    
            'Msgbox CFileName 
    
            'MsgBox CFolderName 
    
            'MsgBox myDate
    
            GFileName=fso.GetFileName(sfolder)
    
            'strRename="DA009B_"& CFolderName &"_20032019"
    
            strRename= "DA009B_"& CFolderName &"_"& myDate &""
    
            NewFilename=replace(CFileName,CFolderName,strRename)
    
            'fso.CopyFile CFolderName1 , afolder
    
            fso.MoveFile CFileName , NewFilename
    
            'fso.CopyFile CFolderName, Dfolder
    

    Next

    MsgBox "File Renamed Successfully !!! "

    Set fso= Nothing

    Set fs=Nothing

How do I use vim registers?

One overlooked register is the '.' dot register which contains the last inserted text no matter how it was inserted eg ct] (change till ]). Then you realise you need to insert it elsewhere but can't use the dot repeat method.

 :reg .
 :%s/fred/<C-R>./

How to create a signed APK file using Cordova command line interface?

Step1:

Go to cordova\platforms\android ant create a fille called ant.properties file with the keystore file info (this keystore can be generated from your favorite Android SDK, studio...):

key.store=C:\\yourpath\\Yourkeystore.keystore
key.alias=youralias

Step2:

Go to cordova path and execute:

cordova build android --release

Note: You will be prompted asking your keystore and key password

An YourApp-release.apk will appear in \cordova\platforms\android\ant-build

How can I match multiple occurrences with a regex in JavaScript similar to PHP's preg_match_all()?

Splitting it looks like the best option in to me:

'1111342=Adam%20Franco&348572=Bob%20Jones'.split('&').map(x => x.match(/(?:&|&amp;)?([^=]+)=([^&]+)/))

What is PostgreSQL equivalent of SYSDATE from Oracle?

NOW() is the replacement of Oracle Sysdate in Postgres.

Try "Select now()", it will give you the system timestamp.

Dynamically add event listener

Here's my workaround:

I created a library with Angular 6. I added a common component commonlib-header which is used like this in an external application.

Note the serviceReference which is the class (injected in the component constructor(public serviceReference: MyService) that uses the commonlib-header) that holds the stringFunctionName method:

<commonlib-header
    [logo]="{ src: 'assets/img/logo.svg', alt: 'Logo', href: '#' }"
    [buttons]="[{ index: 0, innerHtml: 'Button', class: 'btn btn-primary', onClick: [serviceReference, 'stringFunctionName', ['arg1','arg2','arg3']] }]">
    </common-header>

The library component is programmed like this. The dynamic event is added in the onClick(fn: any) method:

export class HeaderComponent implements OnInit {

 _buttons: Array<NavItem> = []

 @Input()
  set buttons(buttons: Array<any>) {
    buttons.forEach(navItem => {
      let _navItem = new NavItem(navItem.href, navItem.innerHtml)

      _navItem.class = navItem.class

      _navItem.onClick = navItem.onClick // this is the array from the component @Input properties above

      this._buttons[navItem.index] = _navItem
    })
  }

  constructor() {}

  ngOnInit() {}

  onClick(fn: any){
    let ref = fn[0]
    let fnName = fn[1]
    let args = fn[2]

    ref[fnName].apply(ref, args)
  }

The reusable header.component.html:

<div class="topbar-right">
  <button *ngFor="let btn of _buttons"
    class="{{ btn.class }}"
    (click)="onClick(btn.onClick)"
    [innerHTML]="btn.innerHtml | keepHtml"></button>
</div>

The I/O operation has been aborted because of either a thread exit or an application request

What I do when it happens is Disable the COM port into the Device Manager and Enable it again.

It stop the communications with another program or thread and become free for you.

I hope this works for you. Regards.

LEFT JOIN in LINQ to entities?

Easy way is to use Let keyword. This works for me.

from AItem in Db.A
Let BItem = Db.B.Where(x => x.id == AItem.id ).FirstOrDefault() 
Where SomeCondition
Select new YourViewModel
{
    X1 = AItem.a,
    X2 = AItem.b,
    X3 = BItem.c
}

This is a simulation of Left Join. If each item in B table not match to A item , BItem return null

Datetime BETWEEN statement not working in SQL Server

Do you have times associated with your dates? BETWEEN is inclusive, but when you convert 2013-10-18 to a date it becomes 2013-10-18 00:00:000.00. Anything that is logged after the first second of the 18th will not shown using BETWEEN, unless you include a time value.

Try:

SELECT * FROM LOGS WHERE CHECK_IN BETWEEN CONVERT(datetime,'2013-10-17') AND CONVERT(datetime,'2013-10-18 23:59:59:999')

if you want to search the entire day of the 18th.

SQL DATETIME fields have milliseconds. So I added 999 to the field.

How to view Plugin Manager in Notepad++

I changed the plugin folder name. Restart Notepad ++ It works now, a

Removing object from array in Swift 3

Another nice and useful solution is to create this kind of extension:

extension Array where Element: Equatable {

    @discardableResult mutating func remove(object: Element) -> Bool {
        if let index = index(of: object) {
            self.remove(at: index)
            return true
        }
        return false
    }

    @discardableResult mutating func remove(where predicate: (Array.Iterator.Element) -> Bool) -> Bool {
        if let index = self.index(where: { (element) -> Bool in
            return predicate(element)
        }) {
            self.remove(at: index)
            return true
        }
        return false
    }

}

In this way, if you have your array with custom objects:

let obj1 = MyObject(id: 1)
let obj2 = MyObject(id: 2)
var array: [MyObject] = [obj1, obj2]

array.remove(where: { (obj) -> Bool in
    return obj.id == 1
})
// OR
array.remove(object: obj2) 

How to concatenate two numbers in javascript?

This is the easy way to do this

var value = 5 + "" + 6;

How to make links in a TextView clickable?

Add CDATA to your string resource

Strings.xml

<string name="txtCredits"><![CDATA[<a href=\"http://www.google.com\">Google</a>]]></string>

Authentication issues with WWW-Authenticate: Negotiate

Putting this information here for future readers' benefit.

  • 401 (Unauthorized) response header -> Request authentication header

  • Here are several WWW-Authenticate response headers. (The full list is at IANA: HTTP Authentication Schemes.)

    • WWW-Authenticate: Basic-> Authorization: Basic + token - Use for basic authentication
    • WWW-Authenticate: NTLM-> Authorization: NTLM + token (2 challenges)
    • WWW-Authenticate: Negotiate -> Authorization: Negotiate + token - used for Kerberos authentication
      • By the way: IANA has this angry remark about Negotiate: This authentication scheme violates both HTTP semantics (being connection-oriented) and syntax (use of syntax incompatible with the WWW-Authenticate and Authorization header field syntax).

You can set the Authorization: Basic header only when you also have the WWW-Authenticate: Basic header on your 401 challenge.

But since you have WWW-Authenticate: Negotiate this should be the case for Kerberos based authentication.

VBA code to set date format for a specific column as "yyyy-mm-dd"

You are applying the formatting to the workbook that has the code, not the added workbook. You'll want to get in the habit of fully qualifying sheet and range references. The code below does that and works for me in Excel 2010:

Sub test()
Dim wb As Excel.Workbook
Set wb = Workbooks.Add
With wb.Sheets(1)
    .Range("A1") = "Acctdate"
    .Range("B1") = "Ledger"
    .Range("C1") = "CY"
    .Range("D1") = "BusinessUnit"
    .Range("E1") = "OperatingUnit"
    .Range("F1") = "LOB"
    .Range("G1") = "Account"
    .Range("H1") = "TreatyCode"
    .Range("I1") = "Amount"
    .Range("J1") = "TransactionCurrency"
    .Range("K1") = "USDEquivalentAmount"
    .Range("L1") = "KeyCol"
    .Range("A2", "A50000").Value = Me.TextBox3.Value
    .Range("A2", "A50000").NumberFormat = "yyyy-mm-dd"
End With
End Sub

Return a 2d array from a function

A better alternative to using pointers to pointers is to use std::vector. That takes care of the details of memory allocation and deallocation.

std::vector<std::vector<int>> create2DArray(unsigned height, unsigned width)
{
   return std::vector<std::vector<int>>(height, std::vector<int>(width, 0));
}

Difference between INNER JOIN and LEFT SEMI JOIN

An INNER JOIN can return data from the columns from both tables, and can duplicate values of records on either side have more than one match. A LEFT SEMI JOIN can only return columns from the left-hand table, and yields one of each record from the left-hand table where there is one or more matches in the right-hand table (regardless of the number of matches). It's equivalent to (in standard SQL):

SELECT name
FROM table_1 a
WHERE EXISTS(
    SELECT * FROM table_2 b WHERE (a.name=b.name))

If there are multiple matching rows in the right-hand column, an INNER JOIN will return one row for each match on the right table, while a LEFT SEMI JOIN only returns the rows from the left table, regardless of the number of matching rows on the right side. That's why you're seeing a different number of rows in your result.

I am trying to get the names within table_1 that only appear in table_2.

Then a LEFT SEMI JOIN is the appropriate query to use.

Getting request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource

Basically, to make a cross domain AJAX requests, the requested server should allow the cross origin sharing of resources (CORS). You can read more about that from here: http://www.html5rocks.com/en/tutorials/cors/

In your scenario, you are setting the headers in the client which in fact needs to be set into http://localhost:8080/app server side code.

If you are using PHP Apache server, then you will need to add following in your .htaccess file:

Header set Access-Control-Allow-Origin "*"

test if event handler is bound to an element in jQuery

I think this might have updated with jQuery 1.9.*

I'm finding the this is the only thing that works for me at the moment:

$._data($("#yourElementID")[0]).events

How do I get the Back Button to work with an AngularJS ui-router state machine?

If you are looking for the simplest "back" button, then you could set up a directive like so:

    .directive('back', function factory($window) {
      return {
        restrict   : 'E',
        replace    : true,
        transclude : true,
        templateUrl: 'wherever your template is located',
        link: function (scope, element, attrs) {
          scope.navBack = function() {
            $window.history.back();
          };
        }
      };
    });

Keep in mind this is a fairly unintelligent "back" button because it is using the browser's history. If you include it on your landing page, it will send a user back to any url they came from prior to landing on yours.

How to check if a variable is both null and /or undefined in JavaScript

You can wrap it in your own function:

function isNullAndUndef(variable) {

    return (variable !== null && variable !== undefined);
}

Use nginx to serve static files from subdirectories of a given directory

It should work, however http://nginx.org/en/docs/http/ngx_http_core_module.html#alias says:

When location matches the last part of the directive’s value: it is better to use the root directive instead:

which would yield:

server {
  listen        8080;
  server_name   www.mysite.com mysite.com;
  error_log     /home/www-data/logs/nginx_www.error.log;
  error_page    404    /404.html;

  location /public/doc/ {
    autoindex on;
    root  /home/www-data/mysite;
  } 

  location = /404.html {
    root /home/www-data/mysite/static/html;
  }       
}

How to get StackPanel's children to fill maximum space downward?

You can use SpicyTaco.AutoGrid - a modified version of StackPanel:

<st:StackPanel Orientation="Horizontal" MarginBetweenChildren="10" Margin="10">
   <Button Content="Info" HorizontalAlignment="Left" st:StackPanel.Fill="Fill"/>
   <Button Content="Cancel"/>
   <Button Content="Save"/>
</st:StackPanel>

First button will be fill.

You can install it via NuGet:

Install-Package SpicyTaco.AutoGrid

I recommend taking a look at SpicyTaco.AutoGrid. It's very useful for forms in WPF instead of DockPanel, StackPanel and Grid and solve problem with stretching very easy and gracefully. Just look at readme on GitHub.

<st:AutoGrid Columns="160,*" ChildMargin="3">
    <Label Content="Name:"/>
    <TextBox/>

    <Label Content="E-Mail:"/>
    <TextBox/>

    <Label Content="Comment:"/>
    <TextBox/>
</st:AutoGrid>

How do I make a WPF TextBlock show my text on multiple lines?

This gets part way there. There is no ActualFontSize property but there is an ActualHeight and that would relate to the FontSize. Right now this only sizes for the original render. I could not figure out how to register the Converter as resize event. Actually maybe need to register the FontSize as a resize event. Please don't mark me down for an incomplete answer. I could not put code sample in a comment.

    <Window.Resources>
        <local:WidthConverter x:Key="widthConverter"/>
    </Window.Resources>
    <Grid>
        <Grid>
            <StackPanel VerticalAlignment="Center" Orientation="Vertical" >
                <Viewbox Margin="100,0,100,0">
                    <TextBlock x:Name="headerText" Text="Lorem ipsum dolor" Foreground="Black"/>
                </Viewbox>
                <TextBlock Margin="150,0,150,0" FontSize="{Binding ElementName=headerText, Path=ActualHeight, Converter={StaticResource widthConverter}}" x:Name="subHeaderText" Text="Lorem ipsum dolor, Lorem ipsum dolor, lorem isum dolor, Lorem ipsum dolor, Lorem ipsum dolor, lorem isum dolor, " TextWrapping="Wrap" Foreground="Gray" />
            </StackPanel>
        </Grid>
    </Grid>        

Converter

    [ValueConversion(typeof(double), typeof(double))]
    public class WidthConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            double width = (double)value*.7;
            return width; // columnsCount;
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    } 

Exception in thread "main" java.lang.OutOfMemoryError: Java heap space

You're out of memory. Try adding -Xmx256m to your java command line. The 256m is the amount of memory to give to the JVM (256 megabytes). It usually defaults to 64m.

org.hibernate.PersistentObjectException: detached entity passed to persist

Most likely the problem lies outside the code you are showing us here. You are trying to update an object that is not associated with the current session. If it is not the Invoice, then maybe it is an InvoiceItem that has already been persisted, obtained from the db, kept alive in some sort of session and then you try to persist it on a new session. This is not possible. As a general rule, never keep your persisted objects alive across sessions.

The solution will ie in obtaining the whole object graph from the same session you are trying to persist it with. In a web environment this would mean:

  • Obtain the session
  • Fetch the objects you need to update or add associations to. Preferabley by their primary key
  • Alter what is needed
  • Save/update/evict/delete what you want
  • Close/commit your session/transaction

If you keep having issues post some of the code that is calling your service.

How to center the text in a JLabel?

myLabel.setHorizontalAlignment(SwingConstants.CENTER);
myLabel.setVerticalAlignment(SwingConstants.CENTER);

If you cannot reconstruct the label for some reason, this is how you edit these properties of a pre-existent JLabel.

Read a text file line by line in Qt

QFile inputFile(QString("/path/to/file"));
inputFile.open(QIODevice::ReadOnly);
if (!inputFile.isOpen())
    return;

QTextStream stream(&inputFile);
QString line = stream.readLine();
while (!line.isNull()) {
    /* process information */

    line = stream.readLine();
};

How do I get a plist as a Dictionary in Swift?

This is what I do if I want to convert a .plist to a Swift dictionary:

if let path = NSBundle.mainBundle().pathForResource("Config", ofType: "plist") {
  if let dict = NSDictionary(contentsOfFile: path) as? Dictionary<String, AnyObject> {
    // use swift dictionary as normal
  }
}

Edited for Swift 2.0:

if let path = NSBundle.mainBundle().pathForResource("Config", ofType: "plist"), dict = NSDictionary(contentsOfFile: path) as? [String: AnyObject] {
    // use swift dictionary as normal
}

Edited for Swift 3.0:

if let path = Bundle.main.path(forResource: "Config", ofType: "plist"), let dict = NSDictionary(contentsOfFile: path) as? [String: AnyObject] {
        // use swift dictionary as normal
}

How do I fix the indentation of an entire file in Vi?

vim-autoformat formats your source files using external programs specific for your language, e.g. the "rbeautify" gem for Ruby files, "js-beautify" npm package for JavaScript.

Why emulator is very slow in Android Studio?

For those who enabled HAXM and the emulator still works slow here is what you should do:

  1. If Avast antivirus is running on your computer, it is most likely the culprit.

as per HAXM Release_Notes.txt (Version 7.5.2):

  • On Windows, Avast Antivirus may interfere with HAXM and cause Android Emulator or QEMU to run very slowly. A workaround is to uncheck "Use nested virtualization where available" in Avast Settings > Troubleshooting.

So open your Avast dashboard > Menu > Settings > Troubleshooting and disable "Enable hardware-assisted virtualization"

enter image description here

  1. Give a higher priority to your emulator's process in the Task Manager:

    Locate your emulator's process in the Task Manager > Details tab:

    Right-click on it and Set Priority -> Above normal enter image description here

Sorry that the screenshot is not in English but you got the point, right? That helped me significantly! I hope it will help you as well.

Also, one thing as per the Release Notes:

  • On Windows 8, 8.1 and 10, it is recommended to disable Hyper-V from Windows Features in order for the HAXM driver to properly function.

In my case, I didn't have any "Hyper-V" feature on my Windows 8.1 but you probably should try it, just in case. To locate and disable that feature see this article: https://support.bluestacks.com/hc/en-us/articles/115004254383-How-do-I-disable-Hyper-V-on-Windows-

Set Encoding of File to UTF8 With BOM in Sublime Text 3

By default, Sublime Text set 'UTF8 without BOM', but that wasn't specified.

The only specicified things is 'UTF8 with BOM'.

Hope this help :)

How to highlight text using javascript

Why using a selfmade highlighting function is a bad idea

The reason why it's probably a bad idea to start building your own highlighting function from scratch is because you will certainly run into issues that others have already solved. Challenges:

  • You would need to remove text nodes with HTML elements to highlight your matches without destroying DOM events and triggering DOM regeneration over and over again (which would be the case with e.g. innerHTML)
  • If you want to remove highlighted elements you would have to remove HTML elements with their content and also have to combine the splitted text-nodes for further searches. This is necessary because every highlighter plugin searches inside text nodes for matches and if your keywords will be splitted into several text nodes they will not being found.
  • You would also need to build tests to make sure your plugin works in situations which you have not thought about. And I'm talking about cross-browser tests!

Sounds complicated? If you want some features like ignoring some elements from highlighting, diacritics mapping, synonyms mapping, search inside iframes, separated word search, etc. this becomes more and more complicated.

Use an existing plugin

When using an existing, well implemented plugin, you don't have to worry about above named things. The article 10 jQuery text highlighter plugins on Sitepoint compares popular highlighter plugins.

Have a look at mark.js

mark.js is such a plugin that is written in pure JavaScript, but is also available as jQuery plugin. It was developed to offer more opportunities than the other plugins with options to:

  • search for keywords separately instead of the complete term
  • map diacritics (For example if "justo" should also match "justò")
  • ignore matches inside custom elements
  • use custom highlighting element
  • use custom highlighting class
  • map custom synonyms
  • search also inside iframes
  • receive not found terms

DEMO

Alternatively you can see this fiddle.

Usage example:

// Highlight "keyword" in the specified context
$(".context").mark("keyword");

// Highlight the custom regular expression in the specified context
$(".context").markRegExp(/Lorem/gmi);

It's free and developed open-source on GitHub (project reference).

Create File If File Does Not Exist

You don't even need to do the check manually, File.Open does it for you. Try:

using (StreamWriter sw = new StreamWriter(File.Open(path, System.IO.FileMode.Append))) 
{

Ref: http://msdn.microsoft.com/en-us/library/system.io.filemode.aspx

Using Auto Layout in UITableView for dynamic cell layouts & variable row heights

I wrapped @smileyborg's iOS7 solution in a category

I decided to wrap this clever solution by @smileyborg into a UICollectionViewCell+AutoLayoutDynamicHeightCalculation category.

The category also rectifies the issues outlined in @wildmonkey's answer (loading a cell from a nib and systemLayoutSizeFittingSize: returning CGRectZero)

It doesn't take into account any caching but suits my needs right now. Feel free to copy, paste and hack at it.

UICollectionViewCell+AutoLayoutDynamicHeightCalculation.h

#import <UIKit/UIKit.h>

typedef void (^UICollectionViewCellAutoLayoutRenderBlock)(void);

/**
 *  A category on UICollectionViewCell to aid calculating dynamic heights based on AutoLayout contraints.
 *
 *  Many thanks to @smileyborg and @wildmonkey
 *
 *  @see stackoverflow.com/questions/18746929/using-auto-layout-in-uitableview-for-dynamic-cell-layouts-variable-row-heights
 */
@interface UICollectionViewCell (AutoLayoutDynamicHeightCalculation)

/**
 *  Grab an instance of the receiving type to use in order to calculate AutoLayout contraint driven dynamic height. The method pulls the cell from a nib file and moves any Interface Builder defined contrainsts to the content view.
 *
 *  @param name Name of the nib file.
 *
 *  @return collection view cell for using to calculate content based height
 */
+ (instancetype)heightCalculationCellFromNibWithName:(NSString *)name;

/**
 *  Returns the height of the receiver after rendering with your model data and applying an AutoLayout pass
 *
 *  @param block Render the model data to your UI elements in this block
 *
 *  @return Calculated constraint derived height
 */
- (CGFloat)heightAfterAutoLayoutPassAndRenderingWithBlock:(UICollectionViewCellAutoLayoutRenderBlock)block collectionViewWidth:(CGFloat)width;

/**
 *  Directly calls `heightAfterAutoLayoutPassAndRenderingWithBlock:collectionViewWidth` assuming a collection view width spanning the [UIScreen mainScreen] bounds
 */
- (CGFloat)heightAfterAutoLayoutPassAndRenderingWithBlock:(UICollectionViewCellAutoLayoutRenderBlock)block;

@end

UICollectionViewCell+AutoLayoutDynamicHeightCalculation.m

#import "UICollectionViewCell+AutoLayout.h"

@implementation UICollectionViewCell (AutoLayout)

#pragma mark Dummy Cell Generator

+ (instancetype)heightCalculationCellFromNibWithName:(NSString *)name
{
    UICollectionViewCell *heightCalculationCell = [[[NSBundle mainBundle] loadNibNamed:name owner:self options:nil] lastObject];
    [heightCalculationCell moveInterfaceBuilderLayoutConstraintsToContentView];
    return heightCalculationCell;
}

#pragma mark Moving Constraints

- (void)moveInterfaceBuilderLayoutConstraintsToContentView
{
    [self.constraints enumerateObjectsUsingBlock:^(NSLayoutConstraint *constraint, NSUInteger idx, BOOL *stop) {
        [self removeConstraint:constraint];
        id firstItem = constraint.firstItem == self ? self.contentView : constraint.firstItem;
        id secondItem = constraint.secondItem == self ? self.contentView : constraint.secondItem;
        [self.contentView addConstraint:[NSLayoutConstraint constraintWithItem:firstItem
                                                                     attribute:constraint.firstAttribute
                                                                     relatedBy:constraint.relation
                                                                        toItem:secondItem
                                                                     attribute:constraint.secondAttribute
                                                                    multiplier:constraint.multiplier
                                                                      constant:constraint.constant]];
    }];
}

#pragma mark Height

- (CGFloat)heightAfterAutoLayoutPassAndRenderingWithBlock:(UICollectionViewCellAutoLayoutRenderBlock)block
{
    return [self heightAfterAutoLayoutPassAndRenderingWithBlock:block
                                            collectionViewWidth:CGRectGetWidth([[UIScreen mainScreen] bounds])];
}

- (CGFloat)heightAfterAutoLayoutPassAndRenderingWithBlock:(UICollectionViewCellAutoLayoutRenderBlock)block collectionViewWidth:(CGFloat)width
{
    NSParameterAssert(block);

    block();

    [self setNeedsUpdateConstraints];
    [self updateConstraintsIfNeeded];

    self.bounds = CGRectMake(0.0f, 0.0f, width, CGRectGetHeight(self.bounds));

    [self setNeedsLayout];
    [self layoutIfNeeded];

    CGSize calculatedSize = [self.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize];

    return calculatedSize.height;

}

@end

Usage example:

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    MYSweetCell *cell = [MYSweetCell heightCalculationCellFromNibWithName:NSStringFromClass([MYSweetCell class])];
    CGFloat height = [cell heightAfterAutoLayoutPassAndRenderingWithBlock:^{
        [(id<MYSweetCellRenderProtocol>)cell renderWithModel:someModel];
    }];
    return CGSizeMake(CGRectGetWidth(self.collectionView.bounds), height);
}

Thankfully we won't have to do this jazz in iOS8, but there it is for now!

What is the correct way to represent null XML elements?

You use xsi:nil when your schema semantics indicate that an element has a default value, and that the default value should be used if the element isn't present. I have to assume that there are smart people to whom the preceding sentence is not a self-evidently terrible idea, but it sounds like nine kinds of bad to me. Every XML format I've ever worked with represents null values by omitting the element. (Or attribute, and good luck marking an attribute with xsi:nil.)

Create empty file using python

Of course there IS a way to create files without opening. It's as easy as calling os.mknod("newfile.txt"). The only drawback is that this call requires root privileges on OSX.

C# elegant way to check if a property's property is null

This code is "the least amount of code", but not the best practice:

try
{
    return ObjectA.PropertyA.PropertyB.PropertyC;
}
catch(NullReferenceException)
{
     return null;
}

Localhost : 404 not found

If your server is still listening on port 80, check the permission on the DocumentRoot folder and if DirectoryIndex file existed.

What is the meaning of <> in mysql query?

<> means not equal to, != also means not equal to.

Documentation

Rails 4 - passing variable to partial

Syntactically a little different but it looks cleaner in my opinion:

render 'my_partial', locals: { title: "My awesome title" }

# not a big fan of the arrow key syntax
render 'my_partial', :locals => { :title => "My awesome title" }

How can I simulate an array variable in MySQL?

Isn't the point of arrays to be efficient? If you're just iterating through values, I think a cursor on a temporary (or permanent) table makes more sense than seeking commas, no? Also cleaner. Lookup "mysql DECLARE CURSOR".

For random access a temporary table with numerically indexed primary key. Unfortunately the fastest access you'll get is a hash table, not true random access.

How to declare a global variable in C++

I have read that any variable declared outside a function is a global variable. I have done so, but in another *.cpp File that variable could not be found. So it was not realy global.

According to the concept of scope, your variable is global. However, what you've read/understood is overly-simplified.


Possibility 1

Perhaps you forgot to declare the variable in the other translation unit (TU). Here's an example:

a.cpp

int x = 5; // declaration and definition of my global variable

b.cpp

// I want to use `x` here, too.
// But I need b.cpp to know that it exists, first:
extern int x; // declaration (not definition)

void foo() {
   cout << x;  // OK
}

Typically you'd place extern int x; in a header file that gets included into b.cpp, and also into any other TU that ends up needing to use x.


Possibility 2

Additionally, it's possible that the variable has internal linkage, meaning that it's not exposed across translation units. This will be the case by default if the variable is marked const ([C++11: 3.5/3]):

a.cpp

const int x = 5; // file-`static` by default, because `const`

b.cpp

extern const int x;    // says there's a `x` that we can use somewhere...

void foo() {
   cout << x;    // ... but actually there isn't. So, linker error.
}

You could fix this by applying extern to the definition, too:

a.cpp

extern const int x = 5;

This whole malarky is roughly equivalent to the mess you go through making functions visible/usable across TU boundaries, but with some differences in how you go about it.

Maven error :Perhaps you are running on a JRE rather than a JDK?

If the above solutions doesn't work then try to place java path before maven in path of environment variable. It worked for me.

%JAVA_HOME%\bin

C:\Program Files\apache-maven-3.6.1-bin\apache-maven-3.6.1\bin

In Node.js, how do I "include" functions from my other files?

Include file and run it in given (non-global) context

fileToInclude.js

define({
    "data": "XYZ"
});

main.js

var fs = require("fs");
var vm = require("vm");

function include(path, context) {
    var code = fs.readFileSync(path, 'utf-8');
    vm.runInContext(code, vm.createContext(context));
}


// Include file

var customContext = {
    "define": function (data) {
        console.log(data);
    }
};
include('./fileToInclude.js', customContext);

Efficiently replace all accented characters in a string?

For the lads using TypeScript and those who don't want to deal with string prototypes, here is a typescript version of Ed.'s answer:

    // Usage example:
    "Some string".replace(/[^a-zA-Z0-9-_]/g, char => ToLatinMap.get(char) || '')

    // Map:
    export let ToLatinMap: Map<string, string> = new Map<string, string>([
        ["Á", "A"],
        ["A", "A"],
        ["?", "A"],
        ["?", "A"],
        ["?", "A"],
        ["?", "A"],
        ["?", "A"],
        ["A", "A"],
        ["Â", "A"],
        ["?", "A"],
        ["?", "A"],
        ["?", "A"],
        ["?", "A"],
        ["?", "A"],
        ["Ä", "A"],
        ["A", "A"],
        ["?", "A"],
        ["?", "A"],
        ["?", "A"],
        ["?", "A"],
        ["À", "A"],
        ["?", "A"],
        ["?", "A"],
        ["A", "A"],
        ["A", "A"],
        ["Å", "A"],
        ["?", "A"],
        ["?", "A"],
        ["?", "A"],
        ["Ã", "A"],
        ["?", "AA"],
        ["Æ", "AE"],
        ["?", "AE"],
        ["?", "AE"],
        ["?", "AO"],
        ["?", "AU"],
        ["?", "AV"],
        ["?", "AV"],
        ["?", "AY"],
        ["?", "B"],
        ["?", "B"],
        ["?", "B"],
        ["?", "B"],
        ["?", "B"],
        ["?", "B"],
        ["C", "C"],
        ["C", "C"],
        ["Ç", "C"],
        ["?", "C"],
        ["C", "C"],
        ["C", "C"],
        ["?", "C"],
        ["?", "C"],
        ["D", "D"],
        ["?", "D"],
        ["?", "D"],
        ["?", "D"],
        ["?", "D"],
        ["?", "D"],
        ["?", "D"],
        ["?", "D"],
        ["?", "D"],
        ["Ð", "D"],
        ["?", "D"],
        ["?", "DZ"],
        ["?", "DZ"],
        ["É", "E"],
        ["E", "E"],
        ["E", "E"],
        ["?", "E"],
        ["?", "E"],
        ["Ê", "E"],
        ["?", "E"],
        ["?", "E"],
        ["?", "E"],
        ["?", "E"],
        ["?", "E"],
        ["?", "E"],
        ["Ë", "E"],
        ["E", "E"],
        ["?", "E"],
        ["?", "E"],
        ["È", "E"],
        ["?", "E"],
        ["?", "E"],
        ["E", "E"],
        ["?", "E"],
        ["?", "E"],
        ["E", "E"],
        ["?", "E"],
        ["?", "E"],
        ["?", "E"],
        ["?", "ET"],
        ["?", "F"],
        ["ƒ", "F"],
        ["?", "G"],
        ["G", "G"],
        ["G", "G"],
        ["G", "G"],
        ["G", "G"],
        ["G", "G"],
        ["?", "G"],
        ["?", "G"],
        ["G", "G"],
        ["?", "H"],
        ["?", "H"],
        ["?", "H"],
        ["H", "H"],
        ["?", "H"],
        ["?", "H"],
        ["?", "H"],
        ["?", "H"],
        ["H", "H"],
        ["Í", "I"],
        ["I", "I"],
        ["I", "I"],
        ["Î", "I"],
        ["Ï", "I"],
        ["?", "I"],
        ["I", "I"],
        ["?", "I"],
        ["?", "I"],
        ["Ì", "I"],
        ["?", "I"],
        ["?", "I"],
        ["I", "I"],
        ["I", "I"],
        ["I", "I"],
        ["I", "I"],
        ["?", "I"],
        ["?", "D"],
        ["?", "F"],
        ["?", "G"],
        ["?", "R"],
        ["?", "S"],
        ["?", "T"],
        ["?", "IS"],
        ["J", "J"],
        ["?", "J"],
        ["?", "K"],
        ["K", "K"],
        ["K", "K"],
        ["?", "K"],
        ["?", "K"],
        ["?", "K"],
        ["?", "K"],
        ["?", "K"],
        ["?", "K"],
        ["?", "K"],
        ["L", "L"],
        ["?", "L"],
        ["L", "L"],
        ["L", "L"],
        ["?", "L"],
        ["?", "L"],
        ["?", "L"],
        ["?", "L"],
        ["?", "L"],
        ["?", "L"],
        ["?", "L"],
        ["?", "L"],
        ["?", "L"],
        ["L", "L"],
        ["?", "LJ"],
        ["?", "M"],
        ["?", "M"],
        ["?", "M"],
        ["?", "M"],
        ["N", "N"],
        ["N", "N"],
        ["N", "N"],
        ["?", "N"],
        ["?", "N"],
        ["?", "N"],
        ["?", "N"],
        ["?", "N"],
        ["?", "N"],
        ["?", "N"],
        ["?", "N"],
        ["Ñ", "N"],
        ["?", "NJ"],
        ["Ó", "O"],
        ["O", "O"],
        ["O", "O"],
        ["Ô", "O"],
        ["?", "O"],
        ["?", "O"],
        ["?", "O"],
        ["?", "O"],
        ["?", "O"],
        ["Ö", "O"],
        ["?", "O"],
        ["?", "O"],
        ["?", "O"],
        ["?", "O"],
        ["O", "O"],
        ["?", "O"],
        ["Ò", "O"],
        ["?", "O"],
        ["O", "O"],
        ["?", "O"],
        ["?", "O"],
        ["?", "O"],
        ["?", "O"],
        ["?", "O"],
        ["?", "O"],
        ["?", "O"],
        ["?", "O"],
        ["O", "O"],
        ["?", "O"],
        ["?", "O"],
        ["O", "O"],
        ["O", "O"],
        ["O", "O"],
        ["Ø", "O"],
        ["?", "O"],
        ["Õ", "O"],
        ["?", "O"],
        ["?", "O"],
        ["?", "O"],
        ["?", "OI"],
        ["?", "OO"],
        ["?", "E"],
        ["?", "O"],
        ["?", "OU"],
        ["?", "P"],
        ["?", "P"],
        ["?", "P"],
        ["?", "P"],
        ["?", "P"],
        ["?", "P"],
        ["?", "P"],
        ["?", "Q"],
        ["?", "Q"],
        ["R", "R"],
        ["R", "R"],
        ["R", "R"],
        ["?", "R"],
        ["?", "R"],
        ["?", "R"],
        ["?", "R"],
        ["?", "R"],
        ["?", "R"],
        ["?", "R"],
        ["?", "R"],
        ["?", "C"],
        ["?", "E"],
        ["S", "S"],
        ["?", "S"],
        ["Š", "S"],
        ["?", "S"],
        ["S", "S"],
        ["S", "S"],
        ["?", "S"],
        ["?", "S"],
        ["?", "S"],
        ["?", "S"],
        ["T", "T"],
        ["T", "T"],
        ["?", "T"],
        ["?", "T"],
        ["?", "T"],
        ["?", "T"],
        ["?", "T"],
        ["?", "T"],
        ["?", "T"],
        ["T", "T"],
        ["T", "T"],
        ["?", "A"],
        ["?", "L"],
        ["?", "M"],
        ["?", "V"],
        ["?", "TZ"],
        ["Ú", "U"],
        ["U", "U"],
        ["U", "U"],
        ["Û", "U"],
        ["?", "U"],
        ["Ü", "U"],
        ["U", "U"],
        ["U", "U"],
        ["U", "U"],
        ["U", "U"],
        ["?", "U"],
        ["?", "U"],
        ["U", "U"],
        ["?", "U"],
        ["Ù", "U"],
        ["?", "U"],
        ["U", "U"],
        ["?", "U"],
        ["?", "U"],
        ["?", "U"],
        ["?", "U"],
        ["?", "U"],
        ["?", "U"],
        ["U", "U"],
        ["?", "U"],
        ["U", "U"],
        ["U", "U"],
        ["U", "U"],
        ["?", "U"],
        ["?", "U"],
        ["?", "V"],
        ["?", "V"],
        ["?", "V"],
        ["?", "V"],
        ["?", "VY"],
        ["?", "W"],
        ["W", "W"],
        ["?", "W"],
        ["?", "W"],
        ["?", "W"],
        ["?", "W"],
        ["?", "W"],
        ["?", "X"],
        ["?", "X"],
        ["Ý", "Y"],
        ["Y", "Y"],
        ["Ÿ", "Y"],
        ["?", "Y"],
        ["?", "Y"],
        ["?", "Y"],
        ["?", "Y"],
        ["?", "Y"],
        ["?", "Y"],
        ["?", "Y"],
        ["?", "Y"],
        ["?", "Y"],
        ["Z", "Z"],
        ["Ž", "Z"],
        ["?", "Z"],
        ["?", "Z"],
        ["Z", "Z"],
        ["?", "Z"],
        ["?", "Z"],
        ["?", "Z"],
        ["?", "Z"],
        ["?", "IJ"],
        ["Œ", "OE"],
        ["?", "A"],
        ["?", "AE"],
        ["?", "B"],
        ["?", "B"],
        ["?", "C"],
        ["?", "D"],
        ["?", "E"],
        ["?", "F"],
        ["?", "G"],
        ["?", "G"],
        ["?", "H"],
        ["?", "I"],
        ["?", "R"],
        ["?", "J"],
        ["?", "K"],
        ["?", "L"],
        ["?", "L"],
        ["?", "M"],
        ["?", "N"],
        ["?", "O"],
        ["?", "OE"],
        ["?", "O"],
        ["?", "OU"],
        ["?", "P"],
        ["?", "R"],
        ["?", "N"],
        ["?", "R"],
        ["?", "S"],
        ["?", "T"],
        ["?", "E"],
        ["?", "R"],
        ["?", "U"],
        ["?", "V"],
        ["?", "W"],
        ["?", "Y"],
        ["?", "Z"],
        ["á", "a"],
        ["a", "a"],
        ["?", "a"],
        ["?", "a"],
        ["?", "a"],
        ["?", "a"],
        ["?", "a"],
        ["a", "a"],
        ["â", "a"],
        ["?", "a"],
        ["?", "a"],
        ["?", "a"],
        ["?", "a"],
        ["?", "a"],
        ["ä", "a"],
        ["a", "a"],
        ["?", "a"],
        ["?", "a"],
        ["?", "a"],
        ["?", "a"],
        ["à", "a"],
        ["?", "a"],
        ["?", "a"],
        ["a", "a"],
        ["a", "a"],
        ["?", "a"],
        ["?", "a"],
        ["å", "a"],
        ["?", "a"],
        ["?", "a"],
        ["?", "a"],
        ["ã", "a"],
        ["?", "aa"],
        ["æ", "ae"],
        ["?", "ae"],
        ["?", "ae"],
        ["?", "ao"],
        ["?", "au"],
        ["?", "av"],
        ["?", "av"],
        ["?", "ay"],
        ["?", "b"],
        ["?", "b"],
        ["?", "b"],
        ["?", "b"],
        ["?", "b"],
        ["?", "b"],
        ["b", "b"],
        ["?", "b"],
        ["?", "o"],
        ["c", "c"],
        ["c", "c"],
        ["ç", "c"],
        ["?", "c"],
        ["c", "c"],
        ["?", "c"],
        ["c", "c"],
        ["?", "c"],
        ["?", "c"],
        ["d", "d"],
        ["?", "d"],
        ["?", "d"],
        ["?", "d"],
        ["?", "d"],
        ["?", "d"],
        ["?", "d"],
        ["?", "d"],
        ["?", "d"],
        ["?", "d"],
        ["?", "d"],
        ["d", "d"],
        ["?", "d"],
        ["?", "d"],
        ["i", "i"],
        ["?", "j"],
        ["?", "j"],
        ["?", "j"],
        ["?", "dz"],
        ["?", "dz"],
        ["é", "e"],
        ["e", "e"],
        ["e", "e"],
        ["?", "e"],
        ["?", "e"],
        ["ê", "e"],
        ["?", "e"],
        ["?", "e"],
        ["?", "e"],
        ["?", "e"],
        ["?", "e"],
        ["?", "e"],
        ["ë", "e"],
        ["e", "e"],
        ["?", "e"],
        ["?", "e"],
        ["è", "e"],
        ["?", "e"],
        ["?", "e"],
        ["e", "e"],
        ["?", "e"],
        ["?", "e"],
        ["?", "e"],
        ["e", "e"],
        ["?", "e"],
        ["?", "e"],
        ["?", "e"],
        ["?", "e"],
        ["?", "et"],
        ["?", "f"],
        ["ƒ", "f"],
        ["?", "f"],
        ["?", "f"],
        ["?", "g"],
        ["g", "g"],
        ["g", "g"],
        ["g", "g"],
        ["g", "g"],
        ["g", "g"],
        ["?", "g"],
        ["?", "g"],
        ["?", "g"],
        ["g", "g"],
        ["?", "h"],
        ["?", "h"],
        ["?", "h"],
        ["h", "h"],
        ["?", "h"],
        ["?", "h"],
        ["?", "h"],
        ["?", "h"],
        ["?", "h"],
        ["?", "h"],
        ["h", "h"],
        ["?", "hv"],
        ["í", "i"],
        ["i", "i"],
        ["i", "i"],
        ["î", "i"],
        ["ï", "i"],
        ["?", "i"],
        ["?", "i"],
        ["?", "i"],
        ["ì", "i"],
        ["?", "i"],
        ["?", "i"],
        ["i", "i"],
        ["i", "i"],
        ["?", "i"],
        ["?", "i"],
        ["i", "i"],
        ["?", "i"],
        ["?", "d"],
        ["?", "f"],
        ["?", "g"],
        ["?", "r"],
        ["?", "s"],
        ["?", "t"],
        ["?", "is"],
        ["j", "j"],
        ["j", "j"],
        ["?", "j"],
        ["?", "j"],
        ["?", "k"],
        ["k", "k"],
        ["k", "k"],
        ["?", "k"],
        ["?", "k"],
        ["?", "k"],
        ["?", "k"],
        ["?", "k"],
        ["?", "k"],
        ["?", "k"],
        ["?", "k"],
        ["l", "l"],
        ["l", "l"],
        ["?", "l"],
        ["l", "l"],
        ["l", "l"],
        ["?", "l"],
        ["?", "l"],
        ["?", "l"],
        ["?", "l"],
        ["?", "l"],
        ["?", "l"],
        ["?", "l"],
        ["?", "l"],
        ["?", "l"],
        ["?", "l"],
        ["?", "l"],
        ["l", "l"],
        ["?", "lj"],
        ["?", "s"],
        ["?", "s"],
        ["?", "s"],
        ["?", "s"],
        ["?", "m"],
        ["?", "m"],
        ["?", "m"],
        ["?", "m"],
        ["?", "m"],
        ["?", "m"],
        ["n", "n"],
        ["n", "n"],
        ["n", "n"],
        ["?", "n"],
        ["?", "n"],
        ["?", "n"],
        ["?", "n"],
        ["?", "n"],
        ["?", "n"],
        ["?", "n"],
        ["?", "n"],
        ["?", "n"],
        ["?", "n"],
        ["?", "n"],
        ["ñ", "n"],
        ["?", "nj"],
        ["ó", "o"],
        ["o", "o"],
        ["o", "o"],
        ["ô", "o"],
        ["?", "o"],
        ["?", "o"],
        ["?", "o"],
        ["?", "o"],
        ["?", "o"],
        ["ö", "o"],
        ["?", "o"],
        ["?", "o"],
        ["?", "o"],
        ["?", "o"],
        ["o", "o"],
        ["?", "o"],
        ["ò", "o"],
        ["?", "o"],
        ["o", "o"],
        ["?", "o"],
        ["?", "o"],
        ["?", "o"],
        ["?", "o"],
        ["?", "o"],
        ["?", "o"],
        ["?", "o"],
        ["?", "o"],
        ["?", "o"],
        ["o", "o"],
        ["?", "o"],
        ["?", "o"],
        ["o", "o"],
        ["o", "o"],
        ["ø", "o"],
        ["?", "o"],
        ["õ", "o"],
        ["?", "o"],
        ["?", "o"],
        ["?", "o"],
        ["?", "oi"],
        ["?", "oo"],
        ["?", "e"],
        ["?", "e"],
        ["?", "o"],
        ["?", "o"],
        ["?", "ou"],
        ["?", "p"],
        ["?", "p"],
        ["?", "p"],
        ["?", "p"],
        ["?", "p"],
        ["?", "p"],
        ["?", "p"],
        ["?", "p"],
        ["?", "p"],
        ["?", "q"],
        ["?", "q"],
        ["?", "q"],
        ["?", "q"],
        ["r", "r"],
        ["r", "r"],
        ["r", "r"],
        ["?", "r"],
        ["?", "r"],
        ["?", "r"],
        ["?", "r"],
        ["?", "r"],
        ["?", "r"],
        ["?", "r"],
        ["?", "r"],
        ["?", "r"],
        ["?", "r"],
        ["?", "r"],
        ["?", "r"],
        ["?", "r"],
        ["?", "c"],
        ["?", "c"],
        ["?", "e"],
        ["?", "r"],
        ["s", "s"],
        ["?", "s"],
        ["š", "s"],
        ["?", "s"],
        ["s", "s"],
        ["s", "s"],
        ["?", "s"],
        ["?", "s"],
        ["?", "s"],
        ["?", "s"],
        ["?", "s"],
        ["?", "s"],
        ["?", "s"],
        ["?", "s"],
        ["g", "g"],
        ["?", "o"],
        ["?", "o"],
        ["?", "u"],
        ["t", "t"],
        ["t", "t"],
        ["?", "t"],
        ["?", "t"],
        ["?", "t"],
        ["?", "t"],
        ["?", "t"],
        ["?", "t"],
        ["?", "t"],
        ["?", "t"],
        ["?", "t"],
        ["?", "t"],
        ["t", "t"],
        ["?", "t"],
        ["t", "t"],
        ["?", "th"],
        ["?", "a"],
        ["?", "ae"],
        ["?", "e"],
        ["?", "g"],
        ["?", "h"],
        ["?", "h"],
        ["?", "h"],
        ["?", "i"],
        ["?", "k"],
        ["?", "l"],
        ["?", "m"],
        ["?", "m"],
        ["?", "oe"],
        ["?", "r"],
        ["?", "r"],
        ["?", "r"],
        ["?", "r"],
        ["?", "t"],
        ["?", "v"],
        ["?", "w"],
        ["?", "y"],
        ["?", "tz"],
        ["ú", "u"],
        ["u", "u"],
        ["u", "u"],
        ["û", "u"],
        ["?", "u"],
        ["ü", "u"],
        ["u", "u"],
        ["u", "u"],
        ["u", "u"],
        ["u", "u"],
        ["?", "u"],
        ["?", "u"],
        ["u", "u"],
        ["?", "u"],
        ["ù", "u"],
        ["?", "u"],
        ["u", "u"],
        ["?", "u"],
        ["?", "u"],
        ["?", "u"],
        ["?", "u"],
        ["?", "u"],
        ["?", "u"],
        ["u", "u"],
        ["?", "u"],
        ["u", "u"],
        ["?", "u"],
        ["u", "u"],
        ["u", "u"],
        ["?", "u"],
        ["?", "u"],
        ["?", "ue"],
        ["?", "um"],
        ["?", "v"],
        ["?", "v"],
        ["?", "v"],
        ["?", "v"],
        ["?", "v"],
        ["?", "v"],
        ["?", "v"],
        ["?", "vy"],
        ["?", "w"],
        ["w", "w"],
        ["?", "w"],
        ["?", "w"],
        ["?", "w"],
        ["?", "w"],
        ["?", "w"],
        ["?", "w"],
        ["?", "x"],
        ["?", "x"],
        ["?", "x"],
        ["ý", "y"],
        ["y", "y"],
        ["ÿ", "y"],
        ["?", "y"],
        ["?", "y"],
        ["?", "y"],
        ["?", "y"],
        ["?", "y"],
        ["?", "y"],
        ["?", "y"],
        ["?", "y"],
        ["?", "y"],
        ["?", "y"],
        ["z", "z"],
        ["ž", "z"],
        ["?", "z"],
        ["?", "z"],
        ["?", "z"],
        ["z", "z"],
        ["?", "z"],
        ["?", "z"],
        ["?", "z"],
        ["?", "z"],
        ["?", "z"],
        ["?", "z"],
        ["z", "z"],
        ["?", "z"],
        ["?", "ff"],
        ["?", "ffi"],
        ["?", "ffl"],
        ["?", "fi"],
        ["?", "fl"],
        ["?", "ij"],
        ["œ", "oe"],
        ["?", "st"],
        ["?", "a"],
        ["?", "e"],
        ["?", "i"],
        ["?", "j"],
        ["?", "o"],
        ["?", "r"],
        ["?", "u"],
        ["?", "v"],
        ["?", "x"],
    ]);

How to clear variables in ipython?

%reset seems to clear defined variables.

CSS: Fix row height

I haven't tried it but if you put a div in your table cell set so that it will have scrollbars if needed, then you could insert in there, with a fixed height on the div and it should keep your table row to a fixed height.

VBA to copy a file from one directory to another

This method is even easier if you're ok with fewer options:

FileCopy source, destination

Why is exception.printStackTrace() considered bad practice?

As some guys already mentioned here the problem is with the exception swallowing in case you just call e.printStackTrace() in the catch block. It won't stop the thread execution and will continue after the try block as in normal condition.

Instead of that you need either try to recover from the exception (in case it is recoverable), or to throw RuntimeException, or to bubble the exception to the caller in order to avoid silent crashes (for example, due to improper logger configuration).

What does "subject" mean in certificate?

Subject is the certificate's common name and is a critical property for the certificate in a lot of cases if it's a server certificate and clients are looking for a positive identification.

As an example on an SSL certificate for a web site the subject would be the domain name of the web site.

jquery ajax get responsetext from http url

in jquery ajax functions, the success callback signature is:

function (data, textStatus) {
  // data could be xmlDoc, jsonObj, html, text, etc...
  this; // the options for this ajax request
}

depending on the data type you've asked, using the 'dataType' parameter, you'll get the 'data' argument.

from the docs:

dataType (String) Default: Intelligent Guess (xml or html). The type of data that you're expecting back from the server. If none is specified, jQuery will intelligently pass either responseXML or responseText to your success callback, based on the MIME type of the response.

The available types (and the result passed as the first argument to your success callback) are:

"xml": Returns a XML document that can be processed via jQuery.

"html": Returns HTML as plain text; included script tags are evaluated when inserted in the DOM.

"script": Evaluates the response as JavaScript and returns it as plain text. Disables caching unless option "cache" is used. Note: This will turn POSTs into GETs for remote-domain requests.

"json": Evaluates the response as JSON and returns a JavaScript Object.

"jsonp": Loads in a JSON block using JSONP. Will add an extra "?callback=?" to the end of your URL to specify the callback. (Added in jQuery 1.2)

"text": A plain text string.

see http://docs.jquery.com/Ajax/jQuery.ajax#options

Why am I getting this error: No mapping specified for the following EntitySet/AssociationSet - Entity1?

Error 3027: No mapping specified for the following EntitySet/AssociationSet ..." - Entity Framework headaches

If you are developing model with Entities Framework then you may run into this annoying error at times:

Error 3027: No mapping specified for the following EntitySet/AssociationSet [Entity or Association Name]

This may make no sense when everything looks fine on the EDM, but that's because this error has nothing to do with the EDM usually. What it should say is "regenerate your database files".

You see, Entities checks against the SSDL and MSL during build, so if you just changed your EDM but doesn't use Generate Database Model... then it complains that there's stuff missing in your sql scripts.

so, in short, the solution is: "Don't forget to Generate Database Model every time after you update your EDM if you are doing model first development. I hope your problem is solved".

select dept names who have more than 2 employees whose salary is greater than 1000

select D.DeptName from [Department] D where D.DeptID in 
( 
    select E.DeptId from [Employee] E
    where E.Salary > 1000
    group by E.DeptId
    having count(*) > 2
)

How do I verify that a string only contains letters, numbers, underscores and dashes?

A regular expression will do the trick with very little code:

import re

...

if re.match("^[A-Za-z0-9_-]*$", my_little_string):
    # do something here

Casting a variable using a Type variable

When it comes to casting to Enum type:

private static Enum GetEnum(Type type, int value)
    {
        if (type.IsEnum)
            if (Enum.IsDefined(type, value))
            {
                return (Enum)Enum.ToObject(type, value);
            }

        return null;
    }

And you will call it like that:

var enumValue = GetEnum(typeof(YourEnum), foo);

This was essential for me in case of getting Description attribute value of several enum types by int value:

public enum YourEnum
{
    [Description("Desc1")]
    Val1,
    [Description("Desc2")]
    Val2,
    Val3,
}

public static string GetDescriptionFromEnum(Enum value, bool inherit)
    {
        Type type = value.GetType();

        System.Reflection.MemberInfo[] memInfo = type.GetMember(value.ToString());

        if (memInfo.Length > 0)
        {
            object[] attrs = memInfo[0].GetCustomAttributes(typeof(DescriptionAttribute), inherit);
            if (attrs.Length > 0)
                return ((DescriptionAttribute)attrs[0]).Description;
        }

        return value.ToString();
    }

and then:

string description = GetDescriptionFromEnum(GetEnum(typeof(YourEnum), foo));
string description2 = GetDescriptionFromEnum(GetEnum(typeof(YourEnum2), foo2));
string description3 = GetDescriptionFromEnum(GetEnum(typeof(YourEnum3), foo3));

Alternatively (better approach), such casting could look like that:

 private static T GetEnum<T>(int v) where T : struct, IConvertible
    {
        if (typeof(T).IsEnum)
            if (Enum.IsDefined(typeof(T), v))
            {
                return (T)Enum.ToObject(typeof(T), v);
            }

        throw new ArgumentException(string.Format("{0} is not a valid value of {1}", v, typeof(T).Name));
    }

SVN: Folder already under version control but not comitting?

I found a solution in case you have installed Eclipse(Luna) with the SVN Client JavaHL(JNI) 1.8.13 and Tortoise:

Open Eclipse: First try to add the project / maven module to Version Control (Project -> Context Menu -> Team -> Add to Version Control)

You will see the following Eclipse error message:

org.apache.subversion.javahl.ClientException: Entry already exists svn: 'PathToYouProject' is already under version control

After that you have to open your workspace directory in your explorer, select your project and resolve it via Tortoise (Project -> Context Menu -> TortoiseSVN -> Resolve)

You will see the following message dialog: "File list is empty"

Press cancel and refresh the project in Eclipse. Your project should be under version control again.

Unfortunately it is not possible to resolve more the one project at the same time ... you don't have to delete anything but depending on the size of your project it could be a little bit laborious.

jQuery - simple input validation - "empty" and "not empty"

JQuery's :empty selector selects all elements on the page that are empty in the sense that they have no child elements, including text nodes, not all inputs that have no text in them.

Jquery: How to check if an input element has not been filled in.

Here's the code stolen from the above thread:

$('#apply-form input').blur(function()          //whenever you click off an input element
{                   
    if( !$(this).val() ) {                      //if it is blank. 
         alert('empty');    
    }
});

This works because an empty string in JavaScript is a 'falsy value', which basically means if you try to use it as a boolean value it will always evaluate to false. If you want, you can change the conditional to $(this).val() === '' for added clarity. :D

How to calculate a time difference in C++

This seems to work fine for intel Mac 10.7:

#include <time.h>

time_t start = time(NULL);


    //Do your work


time_t end = time(NULL);
std::cout<<"Execution Time: "<< (double)(end-start)<<" Seconds"<<std::endl;

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

It's also useful for polyglot programs:

#!/usr/bin/env sh
':' //; exec "$(command -v node)" "$0" "$@"
~function(){ ... }

This is now both an executable shell-script and a JavaScript program: meaning ./filename.js, sh filename.js, and node filename.js all work.

(Definitely a little bit of a strange usage, but effective nonetheless.)


Some explication, as requested:

  • Shell-scripts are evaluated line-by-line; and the exec command, when run, terminates the shell and replaces it's process with the resultant command. This means that to the shell, the program looks like this:

    #!/usr/bin/env sh
    ':' //; exec "$(command -v node)" "$0" "$@"
    
  • As long as no parameter expansion or aliasing is occurring in the word, any word in a shell-script can be wrapped in quotes without changing its' meaning; this means that ':' is equivalent to : (we've only wrapped it in quotes here to achieve the JavaScript semantics described below)

  • ... and as described above, the first command on the first line is a no-op (it translates to : //, or if you prefer to quote the words, ':' '//'. Notice that the // carries no special meaning here, as it does in JavaScript; it's just a meaningless word that's being thrown away.)

  • Finally, the second command on the first line (after the semicolon), is the real meat of the program: it's the exec call which replaces the shell-script being invoked, with a Node.js process invoked to evaluate the rest of the script.

  • Meanwhile, the first line, in JavaScript, parses as a string-literal (':'), and then a comment, which is deleted; thus, to JavaScript, the program looks like this:

    ':'
    ~function(){ ... }
    

    Since the string-literal is on a line by itself, it is a no-op statement, and is thus stripped from the program; that means that the entire line is removed, leaving only your program-code (in this example, the function(){ ... } body.)

MSSQL Select statement with incremental integer column... not from a table

For SQL 2005 and up

SELECT ROW_NUMBER() OVER( ORDER BY SomeColumn ) AS 'rownumber',*
    FROM YourTable

for 2000 you need to do something like this

SELECT IDENTITY(INT, 1,1) AS Rank ,VALUE
INTO #Ranks FROM YourTable WHERE 1=0

INSERT INTO #Ranks
SELECT SomeColumn  FROM YourTable
ORDER BY SomeColumn 

SELECT * FROM #Ranks
Order By Ranks

see also here Row Number

Importing class/java files in Eclipse

You can import a bunch of .java files to your existing project without creating a new project. Here are the steps:

  1. Right-click on the Default Package in the Project Manager pane underneath your project and choose Import
  2. An Import Wizard window will display. Choose File system and select the Next button
  3. You are now prompted to choose a file
  4. Simply browse your folder with .java files in it
  5. Select desired .java files
  6. Click on Finish to finish the import wizard

Check the following webpage for more information: http://people.cs.uchicago.edu/~kaharris/10200/tutorials/eclipse/Step_04.html

Open file by its full path in C++

You can use a full path with the fstream classes. The folowing code attempts to open the file demo.txt in the root of the C: drive. Note that as this is an input operation, the file must already exist.

#include <fstream>
#include <iostream>
using namespace std;

int main() {
   ifstream ifs( "c:/demo.txt" );       // note no mode needed
   if ( ! ifs.is_open() ) {                 
      cout <<" Failed to open" << endl;
   }
   else {
      cout <<"Opened OK" << endl;
   }
}

What does this code produce on your system?

Cron job every three days

I am not a cron specialist, but how about:

0 */72 * * *

It will run every 72 hours non-interrupted.

https://crontab.guru/#0_/72___

Android Studio was unable to find a valid Jvm (Related to MAC OS)

Change this key in the Info.plist

I changed from

<key>JVMVersion</key>
<string>1.6*</string>

to

<key>JVMVersion</key>
<string>1.8*</string>

and it worked fine now..

Edited:
Per the official statement as mentioned above by hasternet and aried3r, the solution by Antonio Jose is correct.

Thanks!

The RPC server is unavailable. (Exception from HRESULT: 0x800706BA)

Check to see if the Remote Procedure Call (RPC) service is running. If it is, then it's a firewall issue between your workstation and the server. You can test it by temporary disabling the firewall and retrying the command.

Edit after comment:

Ok, it's a firewall issue. You'll have to either limit the ports WMI/RPC work on, or open a lot of ports in the McAfee firewall.

Here are a few sites that explain this:

  1. Microsoft KB for limiting ports
  2. McAfee site talking about the same thing

How to change onClick handler dynamically?

Nobody addressed the actual problem which was happening, to explain why the alert was issued.

This code: document.getElementById("foo").click = new function() { alert('foo'); }; assigns the click property of the #foo element to an empty object. The anonymous function in here is meant to initialize the object. I like to think of this type of function as a constructor. You put the alert in there, so it gets called because the function gets called immediately.

See this question.

Access to the path is denied

The following tip isn't an answer to this thread's original question, but might help some other users who end up on this webpage, after making the same stupid mistake I just did...

I was attempting to get an ASP.Net FileUpload control to upload it's file to a network address which contained a "hidden share", namely:

\MyNetworkServer\c$\SomeDirectoryOrOther

I didn't understand it. If I ran the webpage in Debug mode in Visual Studio, it'd work fine. But when the project was deployed, and was running via an Application Pool user, it refused to find this network directory.

I had checked which user my IIS site was running under, gave this user full permissions to this directory on the "MyNetworkServer" server, etc etc, but nothing worked.

The reason (of course!) is that only Administrators are able to "see" these hidden drive shares.

My solution was simply to create a "normal" share to

\MyNetworkServer\SomeDirectoryOrOther

and this got rid of the "Access to the path... is denied" error. The FileUpload was able to successfully run the command

fileUpload.SaveAs(networkFilename);

Hope this helps some other users who make the same mistake I did !

Note also that if you're uploading large files (over 4Mb), then IIS7 requires that you modify the web.config file in two places. Click on this link to read what you need to do: Uploading large files in ASP.Net

How do I access ViewBag from JS

ViewBag is server side code.
Javascript is client side code.

You can't really connect them.

You can do something like this:

var x = $('#' + '@(ViewBag.CC)').val();

But it will get parsed on the server, so you didn't really connect them.

send mail from linux terminal in one line

You can use an echo with a pipe to avoid prompts or confirmation.

echo "This is the body" | mail -s "This is the subject" [email protected]