Programs & Examples On #Ora 04098

Oracle Trigger ORA-04098: trigger is invalid and failed re-validation

Cause: A trigger was attempted to be retrieved for execution and was found to be invalid. This also means that compilation/authorization failed for the trigger.

Action: Options are to resolve the compilation/authorization errors, disable the trigger, or drop the trigger.

Syntax

ALTER TRIGGER trigger Name DISABLE;

ALTER TRIGGER trigger_Name ENABLE;

The matching wildcard is strict, but no declaration can be found for element 'tx:annotation-driven'

FWIW I had this same issue. Turned out my xsi:schemaLocation entries were incorrect, so I went to the official docs and pasted theirs into mine:

http://docs.spring.io/spring/docs/current/spring-framework-reference/html/transaction.html section 16.5.6

I had to add a couple more but that was ok. Next up is to find out why this fixed the problem...

reading HttpwebResponse json response, C#

First you need an object

public class MyObject {
  public string Id {get;set;}
  public string Text {get;set;}
  ...
}

Then in here

    using (var twitpicResponse = (HttpWebResponse)request.GetResponse()) {

        using (var reader = new StreamReader(twitpicResponse.GetResponseStream())) {
            JavaScriptSerializer js = new JavaScriptSerializer();
            var objText = reader.ReadToEnd();
            MyObject myojb = (MyObject)js.Deserialize(objText,typeof(MyObject));
        }

    }

I haven't tested with the hierarchical object you have, but this should give you access to the properties you want.

JavaScriptSerializer System.Web.Script.Serialization

Oracle 11g SQL to get unique values in one column of a multi-column query

I'd use the RANK() function in a subselect and then just pull the row where rank = 1.

select person, language
from
( 
    select person, language, rank() over(order by language) as rank
    from table A
    group by person, language
)
where rank = 1

How to resize an image with OpenCV2.0 and Python2.6

If you wish to use CV2, you need to use the resize function.

For example, this will resize both axes by half:

small = cv2.resize(image, (0,0), fx=0.5, fy=0.5) 

and this will resize the image to have 100 cols (width) and 50 rows (height):

resized_image = cv2.resize(image, (100, 50)) 

Another option is to use scipy module, by using:

small = scipy.misc.imresize(image, 0.5)

There are obviously more options you can read in the documentation of those functions (cv2.resize, scipy.misc.imresize).


Update:
According to the SciPy documentation:

imresize is deprecated in SciPy 1.0.0, and will be removed in 1.2.0.
Use skimage.transform.resize instead.

Note that if you're looking to resize by a factor, you may actually want skimage.transform.rescale.

Using a cursor with dynamic SQL in a stored procedure

First off, avoid using a cursor if at all possible. Here are some resources for rooting it out when it seems you can't do without:

There Must Be 15 Ways To Lose Your Cursors... part 1, Introduction

Row-By-Row Processing Without Cursor

That said, though, you may be stuck with one after all--I don't know enough from your question to be sure that either of those apply. If that's the case, you've got a different problem--the select statement for your cursor must be an actual SELECT statement, not an EXECUTE statement. You're stuck.

But see the answer from cmsjr (which came in while I was writing) about using a temp table. I'd avoid global cursors even more than "plain" ones....

POST data to a URL in PHP

If you're looking to post data to a URL from PHP code itself (without using an html form) it can be done with curl. It will look like this:

$url = 'http://www.someurl.com';
$myvars = 'myvar1=' . $myvar1 . '&myvar2=' . $myvar2;

$ch = curl_init( $url );
curl_setopt( $ch, CURLOPT_POST, 1);
curl_setopt( $ch, CURLOPT_POSTFIELDS, $myvars);
curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt( $ch, CURLOPT_HEADER, 0);
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1);

$response = curl_exec( $ch );

This will send the post variables to the specified url, and what the page returns will be in $response.

How can I map "insert='false' update='false'" on a composite-id key-property which is also used in a one-to-many FK?

"Dino TW" has provided the link to the comment Hibernate Mapping Exception : Repeated column in mapping for entity which has the vital information.

The link hints to provide "inverse=true" in the set mapping, I tried it and it actually works. It is such a rare situation wherein a Set and Composite key come together. Make inverse=true, we leave the insert & update of the table with Composite key to be taken care by itself.

Below can be the required mapping,

<class name="com.example.CompanyEntity" table="COMPANY">
    <id name="id" column="COMPANY_ID"/>
    <set name="names" inverse="true" table="COMPANY_NAME" cascade="all-delete-orphan" fetch="join" batch-size="1" lazy="false">
        <key column="COMPANY_ID" not-null="true"/>
        <one-to-many entity-name="vendorName"/>
    </set>
</class>

Error: JAVA_HOME is not defined correctly executing maven

Use these two commands (for Java 8):

sudo update-java-alternatives --set java-8-oracle
java -XshowSettings 2>&1 | grep -e 'java.home' | awk '{print "JAVA_HOME="$3}' | sed "s/\/jre//g" >> /etc/environment

What's the easy way to auto create non existing dir in ansible

Right now, this is the only way

- name: Ensures {{project_root}}/conf dir exists
  file: path={{project_root}}/conf state=directory
- name: Copy file
  template:
    src: code.conf.j2
    dest: "{{project_root}}/conf/code.conf"

HTML input textbox with a width of 100% overflows table cells

The problem has been explained previously so I will only reiterate: width doesn't take into account border and padding. One possible answer to this not discussed but which I have found helped me out a bunch is to wrap your inputs. Here's the code, and I'll explain how this helps in a second:

<table>
  <tr>
    <td><div style="overflow:hidden"><input style="width:100%" type="text" name="name" value="hello world" /></div></td>
  </tr>
</table>

The DIV wrapping the INPUT has no padding nor does it have a border. This is the solution. A DIV will expand to its container's size, but it will also respect border and padding. Now, the INPUT will have no issue expanding to the size of its container since it is border-less and pad-less. Also note that the DIV has its overflow set to hidden. It seems that by default items can fall outside of their container with the default overflow of visible. This just ensures that the input stays inside its container and doesn't attempt to poke through.

I've tested this in Chrome and in Fire Fox. Both seem to respect this solution well.

UPDATE: Since I just got a random downvote, I would like to say that a better way to deal with overflow is with the CSS3 box-sizing attribute as described by pricco:

.myinput {
    -moz-box-sizing: border-box;
    -webkit-box-sizing: border-box;
    -ms-box-sizing: border-box;
    -o-box-sizing: border-box;
    box-sizing: border-box;
}

This seems to be pretty well supported by the major browsers and isn't "hacky" like the overflow trick. There are, however, some minor issues on current browsers with this approach (see http://caniuse.com/#search=box-sizing Known Issues).

Is it possible to decrypt MD5 hashes?

MD5 has its weaknesses (see Wikipedia), so there are some projects, which try to precompute Hashes. Wikipedia does also hint at some of these projects. One I know of (and respect) is ophrack. You can not tell the user their own password, but you might be able to tell them a password that works. But i think: Just mail thrm a new password in case they forgot.

Can't connect to local MySQL server through socket homebrew

  1. If you are able to see "mysql stopped" when you run below command;

    brew services list
    
  2. and if you are able to start mysql with below command;

    mysql server start
    

this means; mysql is able to start manually, but it doesn't start automatically when the operating system is started. Adding mysql to services will fix this problem. To do so, you can run below command;

brew services start mysql

After that, you may restart your operating system and try connecting to mysql to see if it started automatically. I did the same and stop receiving below error;

ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2)

I hope this helps.

How can I programmatically get the MAC address of an iphone

I wanted something to return the address regardless of whether or not wifi was enabled, so the chosen solution didn't work for me. I used another call I found on some forum after some tweaking. I ended up with the following (excuse my rusty C ) :

#include <sys/types.h>
#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <net/if_dl.h>
#include <ifaddrs.h>


char*  getMacAddress(char* macAddress, char* ifName) {

int  success;
struct ifaddrs * addrs;
struct ifaddrs * cursor;
const struct sockaddr_dl * dlAddr;
const unsigned char* base;
int i;

success = getifaddrs(&addrs) == 0;
if (success) {
    cursor = addrs;
    while (cursor != 0) {
        if ( (cursor->ifa_addr->sa_family == AF_LINK)
            && (((const struct sockaddr_dl *) cursor->ifa_addr)->sdl_type == IFT_ETHER) && strcmp(ifName,  cursor->ifa_name)==0 ) {
            dlAddr = (const struct sockaddr_dl *) cursor->ifa_addr;
            base = (const unsigned char*) &dlAddr->sdl_data[dlAddr->sdl_nlen];
            strcpy(macAddress, ""); 
            for (i = 0; i < dlAddr->sdl_alen; i++) {
                if (i != 0) {
                    strcat(macAddress, ":");
                }
                char partialAddr[3];
                sprintf(partialAddr, "%02X", base[i]);
                strcat(macAddress, partialAddr);

            }
        }
        cursor = cursor->ifa_next;
    }

    freeifaddrs(addrs);
}    
return macAddress;
}

And then I would call it asking for en0, as follows:

char* macAddressString= (char*)malloc(18);
NSString* macAddress= [[NSString alloc] initWithCString:getMacAddress(macAddressString, "en0")
                                              encoding:NSMacOSRomanStringEncoding];
free(macAddressString);

How to do tag wrapping in VS code?

A quick search on the VSCode marketplace: https://marketplace.visualstudio.com/items/bradgashler.htmltagwrap.

  1. Launch VS Code Quick Open (Ctrl+P)

  2. paste ext install htmltagwrap and enter

  3. select HTML

  4. press Alt + W (Option + W for Mac).

Unit testing with mockito for constructors

Here is the code to mock this functionality using PowerMockito API.

Second mockedSecond = PowerMockito.mock(Second.class);
PowerMockito.whenNew(Second.class).withNoArguments().thenReturn(mockedSecond);

You need to use Powermockito runner and need to add required test classes (comma separated ) which are required to be mocked by powermock API .

@RunWith(PowerMockRunner.class)
@PrepareForTest({First.class,Second.class})
class TestClassName{
    // your testing code
}

Why is Github asking for username/password when following the instructions on screen and pushing a new repo?

Here is an official answer to this:

If Git prompts you for a username and password every time you try to interact with GitHub, you're probably using the HTTPS clone URL for your repository.

Using an HTTPS remote URL has some advantages: it's easier to set up than SSH, and usually works through strict firewalls and proxies. However, it also prompts you to enter your GitHub credentials every time you pull or push a repository.

You can configure Git to store your password for you. If you'd like to set that up, read all about setting up password caching.

java.lang.IllegalArgumentException: No converter found for return value of type

While using Spring Boot 2.2 I run into a similiar error message and while googling my error message

No converter for [class java.util.ArrayList] with preset Content-Type 'null'

this question here is on top, but all answers here did not work for me, so I think it's a good idea to add the answer I found myself:

I had to add the following dependencies to the pom.xml:

<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-oxm</artifactId>
</dependency>

<dependency>
  <groupId>com.thoughtworks.xstream</groupId>
  <artifactId>xstream</artifactId>
  <version>1.4.11.1</version>
</dependency>

After this I need to add the following to the WebApplication class:

@SpringBootApplication
public class WebApplication
 {
  // ...

  @Bean
  public HttpMessageConverter<Object> createXmlHttpMessageConverter()
   {
    final MarshallingHttpMessageConverter xmlConverter = new MarshallingHttpMessageConverter();
    final XStreamMarshaller xstreamMarshaller = new XStreamMarshaller();
    xstreamMarshaller.setAutodetectAnnotations(true);
    xmlConverter.setMarshaller(xstreamMarshaller);
    xmlConverter.setUnmarshaller(xstreamMarshaller);
    return xmlConverter;
   }

}

Last but not least within my @Controller I used:

@GetMapping(produces = {MediaType.APPLICATION_XML_VALUE, MediaType. APPLICATION_JSON_VALUE})
@ResponseBody
public List<MeterTypeEntity> listXmlJson(final Model model)
 {
  return this.service.list();
 }

So now I got JSON and XML return values depending on the requests Accept header.

To make the XML output more readable (remove the complete package name from tag names) you could also add @XStreamAlias the following to your entity class:

@Table("ExampleTypes")
@XStreamAlias("ExampleType")
public class ExampleTypeEntity
 {
  // ...
 }

Hopefully this will help others with the same problem.

go to link on button click - jquery

Why not just change the second line to

document.location.href="www.example.com/index.php?id=" + $(this).attr('id');

Replace given value in vector

Why the fuss?

replace(haystack, haystack %in% needles, replacements)

Demo:

haystack <- c("q", "w", "e", "r", "t", "y")
needles <- c("q", "w")
replacements <- c("a", "z")

replace(haystack, haystack %in% needles, replacements)
#> [1] "a" "z" "e" "r" "t" "y"

Drop all duplicate rows across multiple columns in Python Pandas

This is much easier in pandas now with drop_duplicates and the keep parameter.

import pandas as pd
df = pd.DataFrame({"A":["foo", "foo", "foo", "bar"], "B":[0,1,1,1], "C":["A","A","B","A"]})
df.drop_duplicates(subset=['A', 'C'], keep=False)

How to remove leading and trailing white spaces from a given html string?

var trim = your_string.replace(/^\s+|\s+$/g, '');

How can you program if you're blind?

One place to start is the Blinux project:

http://leb.net/blinux/

That project describes how to get Emacspeak (editor with text-to-speech) and has a lot of other resources.

I worked with one person who's eye sight all but prevented them from using a monitor - they did well with Screen reader software and spent a lot of time using text based applications and the shell.

Wikipedia's list of screen reader packages is another place to start: http://en.wikipedia.org/wiki/List_of_screen_readers

How do I display Ruby on Rails form validation error messages one at a time?

ActiveRecord stores validation errors in an array called errors. If you have a User model then you would access the validation errors in a given instance like so:

@user = User.create[params[:user]] # create will automatically call validators

if @user.errors.any? # If there are errors, do something

  # You can iterate through all messages by attribute type and validation message
  # This will be something like:
  # attribute = 'name'
  # message = 'cannot be left blank'
  @user.errors.each do |attribute, message|
    # do stuff for each error
  end

  # Or if you prefer, you can get the full message in single string, like so:
  # message = 'Name cannot be left blank'
  @users.errors.full_messages.each do |message|
    # do stuff for each error
  end

  # To get all errors associated with a single attribute, do the following:
  if @user.errors.include?(:name)
    name_errors = @user.errors[:name]

    if name_errors.kind_of?(Array)
      name_errors.each do |error|
        # do stuff for each error on the name attribute
      end
    else
      error = name_errors
      # do stuff for the one error on the name attribute.
    end
  end
end

Of course you can also do any of this in the views instead of the controller, should you want to just display the first error to the user or something.

How can I get a list of all classes within current module in Python?

import pyclbr
print(pyclbr.readmodule(__name__).keys())

Note that the stdlib's Python class browser module uses static source analysis, so it only works for modules that are backed by a real .py file.

TypeError: ObjectId('') is not JSON serializable

Most users who receive the "not JSON serializable" error simply need to specify default=str when using json.dumps. For example:

json.dumps(my_obj, default=str)

This will force a conversion to str, preventing the error. Of course then look at the generated output to confirm that it is what you need.

How to run a script at a certain time on Linux?

Usually in Linux you use crontab for this kind of scduled tasks. But you have to specify the time when you "setup the timer" - so if you want it to be configurable in the file itself, you will have to create some mechanism to do that.

But in general, you would use for example:

30 1 * * 5 /path/to/script/script.sh

Would execute the script every Friday at 1:30 (AM) Here:

30 is minutes

1 is hour

next 2 *'s are day of month and month (in that order) and 5 is weekday

Listing files in a directory matching a pattern in Java

Since Java 8 you can use lambdas and achieve shorter code:

File dir = new File(xmlFilesDirectory);
File[] files = dir.listFiles((d, name) -> name.endsWith(".xml"));

Yes or No confirm box using jQuery

I needed to apply a translation to the Ok and Cancel buttons. I modified the code to except dynamic text (calls my translation function)


_x000D_
_x000D_
$.extend({_x000D_
    confirm: function(message, title, okAction) {_x000D_
        $("<div></div>").dialog({_x000D_
            // Remove the closing 'X' from the dialog_x000D_
            open: function(event, ui) { $(".ui-dialog-titlebar-close").hide(); },_x000D_
            width: 500,_x000D_
            buttons: [{_x000D_
                text: localizationInstance.translate("Ok"),_x000D_
                click: function () {_x000D_
                    $(this).dialog("close");_x000D_
                    okAction();_x000D_
                }_x000D_
            },_x000D_
                {_x000D_
                text: localizationInstance.translate("Cancel"),_x000D_
                click: function() {_x000D_
                    $(this).dialog("close");_x000D_
                }_x000D_
            }],_x000D_
            close: function(event, ui) { $(this).remove(); },_x000D_
            resizable: false,_x000D_
            title: title,_x000D_
            modal: true_x000D_
        }).text(message);_x000D_
    }_x000D_
});
_x000D_
_x000D_
_x000D_

How to add a primary key to a MySQL table?

Try this,

alter table goods add column `id` int(10) unsigned primary key auto_increment

Correct owner/group/permissions for Apache 2 site files/folders under Mac OS X?

2 month old thread, but better late than never! On 10.6, I have my webserver documents folder set to:

owner:root
group:_www
permission:755

_www is the user that runs apache under Mac OS X. I then added an ACL to allow full permissions to the Administrators group. That way, I can still make any changes with my admin user without having to authenticate as root. Also, when I want to allow the webserver to write to a folder, I can simply chmod to 775, leaving everyone other than root:_www with only read/execute permissions (excluding any ACLs that I have applied)

Most efficient conversion of ResultSet to JSON?

If anyone plan to use this implementation, You might wanna check this out and this

This is my version of that convertion code:

public class ResultSetConverter {
public static JSONArray convert(ResultSet rs) throws SQLException,
        JSONException {
    JSONArray json = new JSONArray();
    ResultSetMetaData rsmd = rs.getMetaData();
    int numColumns = rsmd.getColumnCount();
    while (rs.next()) {

        JSONObject obj = new JSONObject();

        for (int i = 1; i < numColumns + 1; i++) {
            String column_name = rsmd.getColumnName(i);

            if (rsmd.getColumnType(i) == java.sql.Types.ARRAY) {
                obj.put(column_name, rs.getArray(column_name));
            } else if (rsmd.getColumnType(i) == java.sql.Types.BIGINT) {
                obj.put(column_name, rs.getLong(column_name));
            } else if (rsmd.getColumnType(i) == java.sql.Types.REAL) {
                obj.put(column_name, rs.getFloat(column_name));
            } else if (rsmd.getColumnType(i) == java.sql.Types.BOOLEAN) {
                obj.put(column_name, rs.getBoolean(column_name));
            } else if (rsmd.getColumnType(i) == java.sql.Types.BLOB) {
                obj.put(column_name, rs.getBlob(column_name));
            } else if (rsmd.getColumnType(i) == java.sql.Types.DOUBLE) {
                obj.put(column_name, rs.getDouble(column_name));
            } else if (rsmd.getColumnType(i) == java.sql.Types.FLOAT) {
                obj.put(column_name, rs.getDouble(column_name));
            } else if (rsmd.getColumnType(i) == java.sql.Types.INTEGER) {
                obj.put(column_name, rs.getInt(column_name));
            } else if (rsmd.getColumnType(i) == java.sql.Types.NVARCHAR) {
                obj.put(column_name, rs.getNString(column_name));
            } else if (rsmd.getColumnType(i) == java.sql.Types.VARCHAR) {
                obj.put(column_name, rs.getString(column_name));
            } else if (rsmd.getColumnType(i) == java.sql.Types.CHAR) {
                obj.put(column_name, rs.getString(column_name));
            } else if (rsmd.getColumnType(i) == java.sql.Types.NCHAR) {
                obj.put(column_name, rs.getNString(column_name));
            } else if (rsmd.getColumnType(i) == java.sql.Types.LONGNVARCHAR) {
                obj.put(column_name, rs.getNString(column_name));
            } else if (rsmd.getColumnType(i) == java.sql.Types.LONGVARCHAR) {
                obj.put(column_name, rs.getString(column_name));
            } else if (rsmd.getColumnType(i) == java.sql.Types.TINYINT) {
                obj.put(column_name, rs.getByte(column_name));
            } else if (rsmd.getColumnType(i) == java.sql.Types.SMALLINT) {
                obj.put(column_name, rs.getShort(column_name));
            } else if (rsmd.getColumnType(i) == java.sql.Types.DATE) {
                obj.put(column_name, rs.getDate(column_name));
            } else if (rsmd.getColumnType(i) == java.sql.Types.TIME) {
                obj.put(column_name, rs.getTime(column_name));
            } else if (rsmd.getColumnType(i) == java.sql.Types.TIMESTAMP) {
                obj.put(column_name, rs.getTimestamp(column_name));
            } else if (rsmd.getColumnType(i) == java.sql.Types.BINARY) {
                obj.put(column_name, rs.getBytes(column_name));
            } else if (rsmd.getColumnType(i) == java.sql.Types.VARBINARY) {
                obj.put(column_name, rs.getBytes(column_name));
            } else if (rsmd.getColumnType(i) == java.sql.Types.LONGVARBINARY) {
                obj.put(column_name, rs.getBinaryStream(column_name));
            } else if (rsmd.getColumnType(i) == java.sql.Types.BIT) {
                obj.put(column_name, rs.getBoolean(column_name));
            } else if (rsmd.getColumnType(i) == java.sql.Types.CLOB) {
                obj.put(column_name, rs.getClob(column_name));
            } else if (rsmd.getColumnType(i) == java.sql.Types.NUMERIC) {
                obj.put(column_name, rs.getBigDecimal(column_name));
            } else if (rsmd.getColumnType(i) == java.sql.Types.DECIMAL) {
                obj.put(column_name, rs.getBigDecimal(column_name));
            } else if (rsmd.getColumnType(i) == java.sql.Types.DATALINK) {
                obj.put(column_name, rs.getURL(column_name));
            } else if (rsmd.getColumnType(i) == java.sql.Types.REF) {
                obj.put(column_name, rs.getRef(column_name));
            } else if (rsmd.getColumnType(i) == java.sql.Types.STRUCT) {
                obj.put(column_name, rs.getObject(column_name)); // must be a custom mapping consists of a class that implements the interface SQLData and an entry in a java.util.Map object.
            } else if (rsmd.getColumnType(i) == java.sql.Types.DISTINCT) {
                obj.put(column_name, rs.getObject(column_name)); // must be a custom mapping consists of a class that implements the interface SQLData and an entry in a java.util.Map object.
            } else if (rsmd.getColumnType(i) == java.sql.Types.JAVA_OBJECT) {
                obj.put(column_name, rs.getObject(column_name));
            } else {
                obj.put(column_name, rs.getString(i));
            }
        }

        json.put(obj);
    }

    return json;
}
}

Are types like uint32, int32, uint64, int64 defined in any stdlib header?

The questioner actually asked about int16 (etc) rather than (ugly) int16_t (etc).

There are no standard headers - nor any in Linux's /usr/include/ folder that define them without the "_t".

ERROR Android emulator gets killed

For me, just deleting ANDROID_SDK_HOME from the environment variable list solved the problem

Copy text from nano editor to shell

The copy buffer can't be accessed outside of nano, and nowhere I found any buffer file to read.

Here is a dirty alternative when in full NOX: Printing a given file line in the bash history.

So the given line is available as a command with the UP key.

sed "LINEq;d" FILENAME >> ~/.bash_history

Example:

sed "342q;d" doc.txt >> ~/.bash_history

Then to reload the history into the current session:

history -n

Or to make history reloading automatic at new prompts, paste this in .bash_profile:

PROMPT_COMMAND='history -n ; $PROMPT_COMMAND'

Note for AZERTY keyboards and very probably others layouts that require SHIFT for printing numbers from the top keys.

To toggle nano text selection (Mark Set/Unset) the shortcut is:

CTRL + SHIFT + 2

Or

ALT + a

You can then select the text with the arrows keys.

All of the others shortcuts works fine as the documentation:

CTRL + k or F9 to cut.

CTRL + u or F10 to paste.

Job for httpd.service failed because the control process exited with error code. See "systemctl status httpd.service" and "journalctl -xe" for details

Some other service may be using port 80: try to stop the other services: HTTPD, SSL, NGINX, PHP, with the command sudo systemctl stop and then use the command sudo systemctl start httpd

Is there a method that calculates a factorial in Java?


public static long factorial(int number) {
    if (number < 0) {
        throw new ArithmeticException(number + " is negative");
    }
    long fact = 1;
    for (int i = 1; i <= number; ++i) {
        fact *= i;
    }
    return fact;
}

using recursion.


public static long factorial(int number) {
    if (number < 0) {
        throw new ArithmeticException(number + " is negative");
    }
    return number == 0 || number == 1 ? 1 : number * factorial(number - 1);
}

source

How to use a jQuery plugin inside Vue

You need to use either the globals loader or expose loader to ensure that webpack includes the jQuery lib in your source code output and so that it doesn't throw errors when your use $ in your components.

// example with expose loader:
npm i --save-dev expose-loader

// somewhere, import (require) this jquery, but pipe it through the expose loader
require('expose?$!expose?jQuery!jquery')

If you prefer, you can import (require) it directly within your webpack config as a point of entry, so I understand, but I don't have an example of this to hand

Alternatively, you can use the globals loader like this: https://www.npmjs.com/package/globals-loader

Does MS Access support "CASE WHEN" clause if connect with ODBC?

Since you are using Access to compose the query, you have to stick to Access's version of SQL.

To choose between several different return values, use the switch() function. So to translate and extend your example a bit:

select switch(
  age > 40, 4,
  age > 25, 3,
  age > 20, 2,
  age > 10, 1,
  true, 0
) from demo

The 'true' case is the default one. If you don't have it and none of the other cases match, the function will return null.

The Office website has documentation on this but their example syntax is VBA and it's also wrong. I've given them feedback on this but you should be fine following the above example.

Multiple left joins on multiple tables in one query

The JOIN statements are also part of the FROM clause, more formally a join_type is used to combine two from_item's into one from_item, multiple one of which can then form a comma-separated list after the FROM. See http://www.postgresql.org/docs/9.1/static/sql-select.html .

So the direct solution to your problem is:

SELECT something
FROM
    master as parent LEFT JOIN second as parentdata
        ON parent.secondary_id = parentdata.id,
    master as child LEFT JOIN second as childdata
        ON child.secondary_id = childdata.id
WHERE parent.id = child.parent_id AND parent.parent_id = 'rootID'

A better option would be to only use JOIN's, as it has already been suggested.

Check if string matches pattern

import re
pattern = re.compile("^([A-Z][0-9]+)+$")
pattern.search(string)

HTML CSS Invisible Button

button {
    background:transparent;
    border:none;
    outline:none;
    display:block;
    height:200px;
    width:200px;
    cursor:pointer;
}

Give the height and width with respect to the image in the background.This removes the borders and color of a button.You might also need to position it absolute so you can correctly place it where you need.I cant help you further without posting you code

To make it truly invisible you have to set outline:none; otherwise there would be a blue outline in some browsers and you have to set display:block if you need to click it and set dimensions to it

How to improve performance of ngRepeat over a huge dataset (angular.js)?

Sometimes what happened,you get the data from server (or back-end) in few ms (for example I'm I am assuming it 100ms) but it takes more time to display in our web page (let's say it is taking 900ms to display).

So, What is happening here is 800ms It is taking just to render web page.

What I have done in my web application is, I have used pagination (or you can use infinite scrolling also) to display list of data. Let's say I am showing 50 data/page.

So I will not load render all the data at once,only 50 data I am loading initially which takes only 50ms (I'm assuming here).

so total time here decreased from 900ms to 150ms, once user request next page then display next 50 data and so on.

Hope this will help you to improve the performance. All the best

How to subtract hours from a date in Oracle so it affects the day also

sysdate-(2/11)

A day consists of 24 hours. So, to subtract 2 hours from a day you need to divide it by 24:

DATE_value - 2/24

Using interval for the same:

DATE_value - interval '2' hour

Angular.js vs Knockout.js vs Backbone.js

It depends on the nature of your application. And, since you did not describe it in great detail, it is an impossible question to answer. I find Backbone to be the easiest, but I work in Angular all day. Performance is more up to the coder than the framework, in my opinion.

Are you doing heavy DOM manipulation? I would use jQuery and Backbone.

Very data driven app? Angular with its nice data binding.

Game programming? None - direct to canvas; maybe a game engine.

how to redirect to home page

window.location.href = "/";

This worked for me. If you have multiple folders/directories, you can use this:

window.location.href = "/folder_name/";

Submit form using AJAX and jQuery

First give your form an id attribute, then use code like this:

$(document).ready( function() {
  var form = $('#my_awesome_form');

  form.find('select:first').change( function() {
    $.ajax( {
      type: "POST",
      url: form.attr( 'action' ),
      data: form.serialize(),
      success: function( response ) {
        console.log( response );
      }
    } );
  } );

} );

So this code uses .serialize() to pull out the relevant data from the form. It also assumes the select you care about is the first one in the form.

For future reference, the jQuery docs are very, very good.

adb uninstall failed

In my case I often get this issue when I first complise a app in debug mode and later try to install the google signed app.

That is because both apps have the same package name but diffent signatures. Since I upgraded to Android lollypop I sometimes even get this error if I uninstall the app via the settings\Apps. If you have this problem check if the app is installed in a other User profile and uninstall it in all user accounts.

When do Java generics require <? extends T> instead of <T> and is there any downside of switching?

One way for me to understand wildcards is to think that the wildcard isn't specifying the type of the possible objects that given generic reference can "have", but the type of other generic references that it is is compatible with (this may sound confusing...) As such, the first answer is very misleading in it's wording.

In other words, List<? extends Serializable> means you can assign that reference to other Lists where the type is some unknown type which is or a subclass of Serializable. DO NOT think of it in terms of A SINGLE LIST being able to hold subclasses of Serializable (because that is incorrect semantics and leads to a misunderstanding of Generics).

How to redirect to another page using PHP

On click BUTTON action

   if(isset($_POST['save_btn']))
    {
        //write some of your code here, if necessary
        echo'<script> window.location="B.php"; </script> ';
     }

Bootstrap onClick button event

There is no show event in js - you need to bind your button either to the click event:

$('#id').on('click', function (e) {

     //your awesome code here

})

Mind that if your button is inside a form, you may prefer to bind the whole form to the submit event.

How to bind Close command to a button

Actually, it is possible without C# code. The key is to use interactions:

<Button Content="Close">
  <i:Interaction.Triggers>
    <i:EventTrigger EventName="Click">
      <ei:CallMethodAction TargetObject="{Binding ElementName=window}" MethodName="Close"/>
    </i:EventTrigger>
  </i:Interaction.Triggers>
</Button>

In order for this to work, just set the x:Name of your window to "window", and add these two namespaces:

xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity" 
xmlns:ei="http://schemas.microsoft.com/expression/2010/interactions"

This requires that you add the Expression Blend SDK DLL to your project, specifically Microsoft.Expression.Interactions.

In case you don't have Blend, the SDK can be downloaded here.

Expand and collapse with angular js

The problem comes in by me not knowing how to send a unique identifier with an ng-click to only expand/collapse the right content.

You can pass $event with ng-click (ng-dblclick, and ng- mouse events), then you can determine which element caused the event:

<a ng-click="doSomething($event)">do something</a>

Controller:

$scope.doSomething = function(ev) {
    var element = ev.srcElement ? ev.srcElement : ev.target;
    console.log(element, angular.element(element))
    ...
}

See also http://angular-ui.github.com/bootstrap/#/accordion

How to get the public IP address of a user in C#

In MVC IP can be obtained by the following Code

string ipAddress = Request.ServerVariables["REMOTE_ADDR"];

How get total sum from input box values using Javascript?

To sum with decimal use this:

In the javascript change parseInt with parseFloat and add this line tot.toFixed(2); for this result:

    function findTotal(){
    var arr = document.getElementsByName('qty');
    var tot=0;
    for(var i=0;i<arr.length;i++){
        if(parseFloat(arr[i].value))
            tot += parseFloat(arr[i].value);
    }
    document.getElementById('total').value = tot;
    tot.toFixed(2);
}

Use step=".01" min="0" type="number" in the input filed

Qty1 : <input onblur="findTotal()" step=".01" min="0" type="number" name="qty" id="qty1"/><br>
Qty2 : <input onblur="findTotal()" step=".01" min="0" type="number" name="qty" id="qty2"/><br>
Qty3 : <input onblur="findTotal()" step=".01" min="0" type="number" name="qty" id="qty3"/><br>
Qty4 : <input onblur="findTotal()" step=".01" min="0" type="number" name="qty" id="qty4"/><br>
Qty5 : <input onblur="findTotal()" step=".01" min="0" type="number" name="qty" id="qty5"/><br>
Qty6 : <input onblur="findTotal()" step=".01" min="0" type="number" name="qty" id="qty6"/><br>
Qty7 : <input onblur="findTotal()" step=".01" min="0" type="number" name="qty" id="qty7"/><br>
Qty8 : <input onblur="findTotal()" step=".01" min="0" type="number" name="qty" id="qty8"/><br>
<br><br>
Total : <input type="number" step=".01" min="0" name="total" id="total"/>

Java Replace Line In Text File

At the bottom, I have a general solution to replace lines in a file. But first, here is the answer to the specific question at hand. Helper function:

public static void replaceSelected(String replaceWith, String type) {
    try {
        // input the file content to the StringBuffer "input"
        BufferedReader file = new BufferedReader(new FileReader("notes.txt"));
        StringBuffer inputBuffer = new StringBuffer();
        String line;

        while ((line = file.readLine()) != null) {
            inputBuffer.append(line);
            inputBuffer.append('\n');
        }
        file.close();
        String inputStr = inputBuffer.toString();

        System.out.println(inputStr); // display the original file for debugging

        // logic to replace lines in the string (could use regex here to be generic)
        if (type.equals("0")) {
            inputStr = inputStr.replace(replaceWith + "1", replaceWith + "0"); 
        } else if (type.equals("1")) {
            inputStr = inputStr.replace(replaceWith + "0", replaceWith + "1");
        }

        // display the new file for debugging
        System.out.println("----------------------------------\n" + inputStr);

        // write the new string with the replaced line OVER the same file
        FileOutputStream fileOut = new FileOutputStream("notes.txt");
        fileOut.write(inputStr.getBytes());
        fileOut.close();

    } catch (Exception e) {
        System.out.println("Problem reading file.");
    }
}

Then call it:

public static void main(String[] args) {
    replaceSelected("Do the dishes", "1");   
}

Original Text File Content:

Do the dishes0
Feed the dog0
Cleaned my room1

Output:

Do the dishes0
Feed the dog0
Cleaned my room1
----------------------------------
Do the dishes1
Feed the dog0
Cleaned my room1

New text file content:

Do the dishes1
Feed the dog0
Cleaned my room1


And as a note, if the text file was:

Do the dishes1
Feed the dog0
Cleaned my room1

and you used the method replaceSelected("Do the dishes", "1");, it would just not change the file.


Since this question is pretty specific, I'll add a more general solution here for future readers (based on the title).

// read file one line at a time
// replace line as you read the file and store updated lines in StringBuffer
// overwrite the file with the new lines
public static void replaceLines() {
    try {
        // input the (modified) file content to the StringBuffer "input"
        BufferedReader file = new BufferedReader(new FileReader("notes.txt"));
        StringBuffer inputBuffer = new StringBuffer();
        String line;

        while ((line = file.readLine()) != null) {
            line = ... // replace the line here
            inputBuffer.append(line);
            inputBuffer.append('\n');
        }
        file.close();

        // write the new string with the replaced line OVER the same file
        FileOutputStream fileOut = new FileOutputStream("notes.txt");
        fileOut.write(inputBuffer.toString().getBytes());
        fileOut.close();

    } catch (Exception e) {
        System.out.println("Problem reading file.");
    }
}

scroll image with continuous scrolling using marquee tag

You cannot scroll images continuously using the HTML marquee tag - it must have JavaScript added for the continuous scrolling functionality.

There is a JavaScript plugin called crawler.js available on the dynamic drive forum for achieving this functionality. This plugin was created by John Davenport Scheuer and has been modified over time to suit new browsers.

I have also implemented this plugin into my blog to document all the steps to use this plugin. Here is the sample code:

<head>
    <script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
    <script src="assets/js/crawler.js" type="text/javascript" ></script>
</head>

<div id="mycrawler2" style="margin-top: -3px; " class="productswesupport">
    <img src="assets/images/products/ie.png" />
    <img src="assets/images/products/browser.png" />
    <img src="assets/images/products/chrome.png" />
    <img src="assets/images/products/safari.png" />
</div>

Here is the plugin configration:

marqueeInit({
    uniqueid: 'mycrawler2',
    style: {
    },
    inc: 5, //speed - pixel increment for each iteration of this marquee's movement
    mouse: 'cursor driven', //mouseover behavior ('pause' 'cursor driven' or false)
    moveatleast: 2,
    neutral: 150,
    savedirection: true,
    random: true
});

How do I get specific properties with Get-AdUser

This worked for me as well:

Get-ADUser -Filter * -SearchBase "ou=OU,dc=Domain,dc=com" -Properties Enabled, CanonicalName, Displayname, Givenname, Surname, EmployeeNumber, EmailAddress, Department, StreetAddress, Title | select Enabled, CanonicalName, Displayname, GivenName, Surname, EmployeeNumber, EmailAddress, Department, Title | Export-CSV "C:\output.csv"

Java generics - get class?

You are seeing the result of Type Erasure. From that page...

When a generic type is instantiated, the compiler translates those types by a technique called type erasure — a process where the compiler removes all information related to type parameters and type arguments within a class or method. Type erasure enables Java applications that use generics to maintain binary compatibility with Java libraries and applications that were created before generics.

For instance, Box<String> is translated to type Box, which is called the raw type — a raw type is a generic class or interface name without any type arguments. This means that you can't find out what type of Object a generic class is using at runtime.

This also looks like this question which has a pretty good answer as well.

Stop Chrome Caching My JS Files

When doing updates to my web applications I will either use a handler to return a single JS file to avoid the massive hits on my server, or add a small query string to them:

<script type="text/javascript" src="/mine/myscript?20111205"></script>

AngularJs: How to set radio button checked based on model

One way that I see more powerful and avoid having a isDefault in all the models is by using the ng-attributes ng-model, ng-value and ng-checked.

ng-model: binds the value to your model.

ng-value: the value to pass to the ng-model binding.

ng-checked: value or expression that is evaluated. Useful for radio-button and check-boxes.

Example of use: In the following example, I have my model and a list of languages that my site supports. To display the different languages supported and updating the model with the selecting language we can do it in this way.

<!-- Radio -->
<div ng-repeat="language in languages">

  <div>
    <label>

      <input ng-model="site.lang"
             ng-value="language"
             ng-checked="(site.lang == language)"
             name="localizationOptions"
             type="radio">

      <span> {{language}} </span>

    </label>
  </div>

</div>
<!-- end of Radio -->

Our model site.lang will get a language value whenever the expression under evaluation (site.lang == language) is true. This will allow you to sync it with server easily since your model already has the change.

A good Sorted List for Java

You need no sorted list. You need no sorting at all.

I need to add/remove keys from the list when object is added / removed from database.

But not immediately, the removal can wait. Use an ArrayList containing the ID's all alive objects plus at most some bounded percentage of deleted objects. Use a separate HashSet to keep track of deleted objects.

private List<ID> mostlyAliveIds = new ArrayList<>();
private Set<ID> deletedIds = new HashSet<>();

I want to randomly select few dozens of element from the whole list.

ID selectOne(Random random) {
    checkState(deletedIds.size() < mostlyAliveIds.size());
    while (true) {
        int index = random.nextInt(mostlyAliveIds.size());
        ID id = mostlyAliveIds.get(index);
        if (!deletedIds.contains(ID)) return ID;
    }
}

Set<ID> selectSome(Random random, int count) {
    checkArgument(deletedIds.size() <= mostlyAliveIds.size() - count);
    Set<ID> result = new HashSet<>();
    while (result.size() < count) result.add(selectOne(random));
}

For maintaining the data, do something like

void insert(ID id) {
    if (!deletedIds.remove(id)) mostlyAliveIds.add(ID);
} 

void delete(ID id) {
    if (!deletedIds.add(id)) {
         throw new ImpossibleException("Deleting a deleted element);
    }
    if (deletedIds.size() > 0.1 * mostlyAliveIds.size()) {
        mostlyAliveIds.removeAll(deletedIds);
        deletedIds.clear();
    }
}

The only tricky part is the insert which has to check if an already deleted ID was resurrected.

The delete ensures that no more than 10% of elements in mostlyAliveIds are deleted IDs. When this happens, they get all removed in one sweep (I didn't check the JDK sources, but I hope, they do it right) and the show goes on.

With no more than 10% of dead IDs, the overhead of selectOne is no more than 10% on the average.

I'm pretty sure that it's faster than any sorting as the amortized complexity is O(n).

Laravel 5.2 not reading env file

Also additional to what @andrewtweber suggested make sure that you don't have spaces between the KEY= and the value unless it is between quotes

.env file e.g.:

...
SITE_NAME= My website
MAIL_PORT= 587
MAIL_FROM_NAME= websitename
...

to:

...
SITE_NAME="My website"
MAIL_PORT=587
MAIL_FROM_NAME=websitename
...

Linux: copy and create destination dir if it does not exist

with all my respect for answers above, I prefer to use rsync as follow:

$  rsync -a directory_name /path_where_to_inject_your_directory/

example:

$ rsync -a test /usr/local/lib/

Simple way to check if a string contains another string in C?

if (strstr(request, "favicon") != NULL) {
    // contains
}

How do I refresh a DIV content?

To reload a section of the page, you could use jquerys load with the current url and specify the fragment you need, which would be the same element that load is called on, in this case #here:

function updateDiv()
{ 
    $( "#here" ).load(window.location.href + " #here" );
}
  • Don't disregard the space within the load element selector: + " #here"

This function can be called within an interval, or attached to a click event

How to give environmental variable path for file appender in configuration file in log4j

Since you are using unix you can use a path like this.

  /home/Production/modulename/logs/message.log

path should start with /

Is It Possible to NSLog C Structs (Like CGRect or CGPoint)?

You can try this:

NSLog(@"%@", NSStringFromCGPoint(cgPoint));

There are a number of functions provided by UIKit that convert the various CG structs into NSStrings. The reason it doesn't work is because %@ signifies an object. A CGPoint is a C struct (and so are CGRects and CGSizes).

MySQL query to get column names?

Not sure if this is what you were looking for, but this worked for me:

$query = query("DESC YourTable");  
$col_names = array_column($query, 'Field');

That returns a simple array of the column names / variable names in your table or array as strings, which is what I needed to dynamically build MySQL queries. My frustration was that I simply don't know how to index arrays in PHP very well, so I wasn't sure what to do with the results from DESC or SHOW. Hope my answer is helpful to beginners like myself!

To check result: print_r($col_names);

Python: Best way to add to sys.path relative to the current running script

Using python 3.4+
Barring the use of cx_freeze or using in IDLE.

import sys
from pathlib import Path

sys.path.append(Path(__file__).parent / "lib")

git diff between cloned and original remote repository

1) Add any remote repositories you want to compare:

git remote add foobar git://github.com/user/foobar.git

2) Update your local copy of a remote:

git fetch foobar

Fetch won't change your working copy.

3) Compare any branch from your local repository to any remote you've added:

git diff master foobar/master

How do I navigate to another page when PHP script is done?

if ($done)
{
    header("Location: /url/to/the/other/page");
    exit;
}

Is there a free GUI management tool for Oracle Database Express?

There are a few options:

  • Database.net is a windows GUI to connect to many different types of databases, oracle included.
  • Oracle SQL Developer is a free tool from Oracle.
  • SQuirreL SQL is a java based client that can connect to any database that uses JDBC drivers.

I'm sure there are others out there that you could use too...

IndentationError expected an indented block

You've mixed tabs and spaces. This can lead to some confusing errors.

I'd suggest using only tabs or only spaces for indentation.

Using only spaces is generally the easier choice. Most editors have an option for automatically converting tabs to spaces. If your editor has this option, turn it on.


As an aside, your code is more verbose than it needs to be. Instead of this:

if str_p == str_q:
    result = True
else:
    result = False
return result

Just do this:

return str_p == str_q

You also appear to have a bug on this line:

str_q = p[b+1:]

I'll leave you to figure out what the error is.

Efficient way of having a function only execute once in a loop

Here's an explicit way to code this up, where the state of which functions have been called is kept locally (so global state is avoided). I don't much like the non-explicit forms suggested in other answers: it's too surprising to see f() and for this not to mean that f() gets called.

This works by using dict.pop which looks up a key in a dict, removes the key from the dict, and takes a default value to use in case the key isn't found.

def do_nothing(*args, *kwargs):
    pass

# A list of all the functions you want to run just once.
actions = [
    my_function,
    other_function
]
actions = dict((action, action) for action in actions)

while True:
    if some_condition:
        actions.pop(my_function, do_nothing)()
    if some_other_condition:
        actions.pop(other_function, do_nothing)()

Resource from src/main/resources not found after building with maven

You can replace the src/main/resources/ directly by classpath:

So for your example you will replace this line:

new BufferedReader(new FileReader(new File("src/main/resources/config.txt")));

By this line:

new BufferedReader(new FileReader(new File("classpath:config.txt")));

Appending an id to a list if not already present in a string

I agree with other answers that you are doing something weird here. You have a list containing a string with multiple entries that are themselves integers that you are comparing to an integer id.

This is almost surely not what you should be doing. You probably should be taking input and converting it to integers before storing in your list. You could do that with:

input = '350882 348521 350166\r\n'
list.append([int(x) for x in input.split()])

Then your test will pass. If you really are sure you don't want to do what you're currently doing, the following should do what you want, which is to not add the new id that already exists:

list = ['350882 348521 350166\r\n']
id = 348521
if id not in [int(y) for x in list for y in x.split()]:
    list.append(id)
print list

How to append data to a json file?

Append entry to the file contents if file exists, otherwise append the entry to an empty list and write in in the file:

a = []
if not os.path.isfile(fname):
    a.append(entry)
    with open(fname, mode='w') as f:
        f.write(json.dumps(a, indent=2))
else:
    with open(fname) as feedsjson:
        feeds = json.load(feedsjson)

    feeds.append(entry)
    with open(fname, mode='w') as f:
        f.write(json.dumps(feeds, indent=2))

Removing certain characters from a string in R

try: gsub('\\$', '', '$5.00$')

Setting state on componentDidMount()

According to the React Documentation it's perfectly OK to call setState() from within the componentDidMount() function.

It will cause render() to be called twice, which is less efficient than only calling it once, but other than that it's perfectly fine.

You can find the documentation here:

https://reactjs.org/docs/react-component.html#componentdidmount

Here is the excerpt from the documentation:

You may call setState() immediately in componentDidMount(). It will trigger an extra rendering, but it will happen before the browser updates the screen. This guarantees that even though the render() will be called twice in this case, the user won’t see the intermediate state. Use this pattern with caution because it often causes performance issues...

Possible to access MVC ViewBag object from Javascript file?

In controllers action add:

 public ActionResult Index()
        {
            try
            {
                int a, b, c;
                a = 2; b = 2;
                c = a / b;
                ViewBag.ShowMessage = false;
            }
            catch (Exception e)
            {
                ViewBag.ShowMessage = true;
                ViewBag.data = e.Message.ToString();
            }
            return View();    // return View();

        }

in Index.cshtml
Place at the bottom:

<input type="hidden" value="@ViewBag.data" id="hdnFlag" />

@if (ViewBag.ShowMessage)
{
    <script type="text/javascript">

        var h1 = document.getElementById('hdnFlag');

        alert(h1.value);

    </script>
    <div class="message-box">Some Message here</div>
}

Setting default checkbox value in Objective-C?

Documentation on UISwitch says:

[mySwitch setOn:NO]; 

In Interface Builder, select your switch and in the Attributes inspector you'll find State which can be set to on or off.

Set auto height and width in CSS/HTML for different screen sizes

///UPDATED DEMO 2 WATCH SOLUTION////

I hope that is the solution you're looking for! DEMO1 DEMO2

With that solution the only scrollbar in the page is on your contents section in the middle! In that section build your structure with a sidebar or whatever you want!

You can do that with that code here:

<div class="navTop">
<h1>Title</h1>
    <nav>Dynamic menu</nav>
</div>
<div class="container">
    <section>THE CONTENTS GOES HERE</section>
</div>
<footer class="bottomFooter">
    Footer
</footer>

With that css:

.navTop{
width:100%;
border:1px solid black;
float:left;
}
.container{
width:100%;
float:left;
overflow:scroll;
}
.bottomFooter{
float:left;
border:1px solid black;
width:100%;
}

And a bit of jquery:

$(document).ready(function() {
  function setHeight() {
    var top = $('.navTop').outerHeight();
    var bottom = $('footer').outerHeight();
    var totHeight = $(window).height();
    $('section').css({ 
      'height': totHeight - top - bottom + 'px'
    });
  }

  $(window).on('resize', function() { setHeight(); });
  setHeight();
});

DEMO 1

If you don't want jquery

<div class="row">
    <h1>Title</h1>
    <nav>NAV</nav>
</div>

<div class="row container">
    <div class="content">
        <div class="sidebar">
            SIDEBAR
        </div>
        <div class="contents">
            CONTENTS
        </div>
    </div>
    <footer>Footer</footer>
</div>

CSS

*{
margin:0;padding:0;    
}
html,body{
height:100%;
width:100%;
}
body{
display:table;
}
.row{
width: 100%;
background: yellow;
display:table-row;
}
.container{
background: pink;
height:100%; 
}
.content {
display: block;
overflow:auto;
height:100%;
padding-bottom: 40px;
box-sizing: border-box;
}
footer{ 
position: fixed; 
bottom: 0; 
left: 0; 
background: yellow;
height: 40px;
line-height: 40px;
width: 100%;
text-align: center;
}
.sidebar{
float:left;
background:green;
height:100%;
width:10%;
}
.contents{
float:left;
background:red;
height:100%;
width:90%;
overflow:auto;
}

DEMO 2

Excel 2013 VBA Clear All Filters macro

Here's the one-liner I use. It checks for an auto-filter and if found, removes it.

Unlike some answers, this code won't create an auto-filter if used on a worksheet that is not auto-filtered in the first place.

If Cells.AutoFilter Then Cells.AutoFilter

How to use vim in the terminal?

Run vim from the terminal. For the basics, you're advised to run the command vimtutor.

# On your terminal command line:
$ vim

If you have a specific file to edit, pass it as an argument.

$ vim yourfile.cpp

Likewise, launch the tutorial

$ vimtutor

Joining two table entities in Spring Data JPA

For a typical example of employees owning one or more phones, see this wikibook section.

For your specific example, if you want to do a one-to-one relationship, you should change the next code in ReleaseDateType model:

@Column(nullable = true) 
private Integer media_Id;

for:

@OneToOne(fetch = FetchType.LAZY)
@JoinColumn(name="CACHE_MEDIA_ID", nullable=true)
private CacheMedia cacheMedia ;

and in CacheMedia model you need to add:

@OneToOne(cascade=ALL, mappedBy="ReleaseDateType")
private ReleaseDateType releaseDateType;

then in your repository you should replace:

@Query("Select * from A a  left join B b on a.id=b.id")
public List<ReleaseDateType> FindAllWithDescriptionQuery();

by:

//In this case a query annotation is not need since spring constructs the query from the method name
public List<ReleaseDateType> findByCacheMedia_Id(Integer id); 

or by:

@Query("FROM ReleaseDateType AS rdt WHERE cm.rdt.cacheMedia.id = ?1")    //This is using a named query method
public List<ReleaseDateType> FindAllWithDescriptionQuery(Integer id);

Or if you prefer to do a @OneToMany and @ManyToOne relation, you should change the next code in ReleaseDateType model:

@Column(nullable = true) 
private Integer media_Id;

for:

@OneToMany(cascade=ALL, mappedBy="ReleaseDateType")
private List<CacheMedia> cacheMedias ;

and in CacheMedia model you need to add:

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name="RELEASE_DATE_TYPE_ID", nullable=true)
private ReleaseDateType releaseDateType;

then in your repository you should replace:

@Query("Select * from A a  left join B b on a.id=b.id")
public List<ReleaseDateType> FindAllWithDescriptionQuery();

by:

//In this case a query annotation is not need since spring constructs the query from the method name
public List<ReleaseDateType> findByCacheMedias_Id(Integer id); 

or by:

@Query("FROM ReleaseDateType AS rdt LEFT JOIN rdt.cacheMedias AS cm WHERE cm.id = ?1")    //This is using a named query method
public List<ReleaseDateType> FindAllWithDescriptionQuery(Integer id);

Is it possible to assign numeric value to an enum in Java?

I realize this is an older question, but it comes up first in a Google search, and among the excellent answers provided, I didn't see anything fully comprehensive, so I did a little more digging and I ended up writing an enum class that not only allowed me to assign multiple custom values to the enum constants, I even added a method that allows me to assign values to them on the fly during code execution.

This enum class is for a "server" program that I run on a Raspberry Pi. The program receives commands from a client then it executes terminal commands that make adjustments to a webcam that is affixed to my 3D printer.

Using the Linux program 'v4l2-ctl' on the Pi, you can extract all of the possible adjustment commands for a given attached webcam, which also provides the setting datatype, the min and max values, the number of value steps in a given value range etc., so I took all of those and put them in an enum and created an enum interface that makes it easy to both set and get values for each command as well as a simple method to get the actual terminal command that is executed (using the Process and Runtime classes) in order to adjust the setting.

It is a rather large class and I apologize for that, but for me, it's always easier to learn something when I can see it working in full context, so I decided not to scale it down. However, even though it's large, it is definitely simple and it should be obvious what's happening in the class with minimal effort.

package constants;

import java.util.HashMap;
import java.util.Map;

public enum PICam {
    BRIGHTNESS                  ("brightness",                  0,      "int",      0,      100,    1,  50),
    CONTRAST                    ("contrast",                    1,      "int",      100,    100,    1,  0),
    SATURATION                  ("saturation",                  2,      "int",      100,    100,    1,  0),
    RED_BALANCE                 ("red_balance",                 3,      "intmenu",  1,      7999,   1,  1000),
    BLUE_BALANCE                ("blue_balance",                4,      "int",      1,      7999,   1,  1000),
    HORIZONTAL_FLIP             ("horizontal_flip",             5,      "bool",     0,      1,      1,  0),
    VERTICAL_FLIP               ("vertical_flip",               6,      "bool",     0,      1,      1,  0),
    POWER_LINE_FREQUENCY        ("power_line_frequency",        7,      "menu",     0,      3,      1,  1),
    SHARPNESS                   ("sharpness",                   8,      "int",      100,    100,    1,  0),
    COLOR_EFFECTS               ("color_effects",               9,      "menu",     0,      15,     1,  0),
    ROTATE                      ("rotate",                      10,     "int",      0,      360,    90, 0),
    COLOR_EFFECTS_CBCR          ("color_effects_cbcr",          11,     "int",      0,      65535,  1,  32896),
    VIDEO_BITRATE_MODE          ("video_bitrate_mode",          12,     "menu",     0,      1,      1,  0),
    VIDEO_BITRATE               ("video_bitrate",               13,     "int",      25000,  25000000,   25000,  10000000),
    REPEAT_SEQUENCE_HEADER      ("repeat_sequence_header",      14,     "bool",     0,      1,      1,  0),
    H264_I_FRAME_PERIOD         ("h_264_i_frame_period",        15,     "int",      0,      2147483647,1,   60),
    H264_LEVEL                  ("h_264_level",                 16,     "menu",     0,      11,     1,  11),
    H264_PROFILE                ("h_264_profile",               17,     "menu",     0,      4,      1,  4),
    AUTO_EXPOSURE               ("auto_exposure",               18,     "menu",     0,      3,      1,  0),
    EXPOSURE_TIME_ABSOLUTE      ("exposure_time_absolute",      19,     "int",      1,      10000,  1,  1000),
    EXPOSURE_DYNAMIC_FRAMERATE  ("exposure_dynamic_framerate",  20,     "bool",     0,      1,      1,  0),
    AUTO_EXPOSURE_BIAS          ("auto_exposure_bias",          21,     "intmenu",  0,      24,     1,  12),
    WHITE_BALANCE_AUTO_PRESET   ("white_balance_auto_preset",   22,     "menu",     0,      9,      1,  1),
    IMAGE_STABILIZATION         ("image_stabilization",         23,     "bool",     0,      1,      1,  0),
    ISO_SENSITIVITY             ("iso_sensitivity",             24,     "intmenu",  0,      4,      1,  0),
    ISO_SENSITIVITY_AUTO        ("iso_sensitivity_auto",        25,     "menu",     0,      1,      1,  1),
    EXPOSURE_METERING_MODE      ("exposure_metering_mode",      26,     "menu",     0,      2,      1,  0),
    SCENE_MODE                  ("scene_mode",                  27,     "menu",     0,      13,     1,  0),
    COMPRESSION_QUALITY         ("compression_quality",         28,     "int",      1,      100,    1,  30);


    private static final Map<String, PICam>    LABEL_MAP       = new HashMap<>();
    private static final Map<Integer, PICam>   INDEX_MAP       = new HashMap<>();
    private static final Map<String, PICam>    TYPE_MAP        = new HashMap<>();
    private static final Map<Integer, PICam>   MIN_MAP         = new HashMap<>();
    private static final Map<Integer, PICam>   MAX_MAP         = new HashMap<>();
    private static final Map<Integer, PICam>   STEP_MAP        = new HashMap<>();
    private static final Map<Integer, PICam>   DEFAULT_MAP     = new HashMap<>();
    private static final Map<Integer, Integer> THIS_VALUE_MAP  = new HashMap<>();

    private static final String                baseCommandLine = "/usr/bin/v4l2-ctl -d /dev/video0 --set-ctrl=";

    static {
        for (PICam e: values()) {
            LABEL_MAP.put(e.label, e);
            INDEX_MAP.put(e.index, e);
            TYPE_MAP.put(e.type, e);
            MIN_MAP.put(e.min, e);
            MAX_MAP.put(e.max, e);
            STEP_MAP.put(e.step, e);
            DEFAULT_MAP.put(e.defaultValue, e);
        }
    }

    public final String label;
    public final int index;
    public final String type;
    public final int min;
    public final int max;
    public final int step;
    public final int defaultValue;

    private PICam(String label, int index, String type, int min, int max, int step, int defaultValue) {
        this.label = label;
        this.index = index;
        this.type = type;
        this.min = min;
        this.max = max;
        this.step = step;
        this.defaultValue = defaultValue;
    }

    public static void setValue(Integer index, Integer value) {
        if (THIS_VALUE_MAP.containsKey(index)) THIS_VALUE_MAP.replace(index, value);
        else THIS_VALUE_MAP.put(index, value);
    }

    public Integer getValue (Integer index) {
        return THIS_VALUE_MAP.getOrDefault(index, null);
    }

    public static PICam getLabel(String label) {
        return LABEL_MAP.get(label);
    }

    public static PICam getType(String type) {
        return TYPE_MAP.get(type);
    }

    public static PICam getMin(int min) {
        return MIN_MAP.get(min);
    }

    public static PICam getMax(int max) {
        return MAX_MAP.get(max);
    }

    public static PICam getStep(int step) {
        return STEP_MAP.get(step);
    }

    public static PICam getDefault(int defaultValue) {
        return DEFAULT_MAP.get(defaultValue);
    }

    public static String getCommandFor(int index, int newValue) {
        PICam picam = INDEX_MAP.get(index);
        String commandValue = "";
        if ("bool".equals(picam.type)) {
            commandValue = (newValue == 0) ? "false" : "true";
        }
        else {
            commandValue = String.valueOf(newValue);
        }
        return baseCommandLine + INDEX_MAP.get(index).label + "=" + commandValue;
    }

    public static String getCommandFor(PICam picam, Integer newValue) {
        String commandValue = "";
        if ("bool".equals(picam.type)) {
            commandValue = (newValue == 0) ? "false" : "true";
        }
        else {
            commandValue = String.valueOf(newValue);
        }
        return baseCommandLine + INDEX_MAP.get(picam.index).label + "=" + commandValue;
    }

    public static String getCommandFor(PICam piCam) {
        int    newValue     = piCam.defaultValue;
        String commandValue = "";
        if ("bool".equals(piCam.type)) {
            commandValue = (newValue == 0) ? "false" : "true";
        }
        else {
            commandValue = String.valueOf(newValue);
        }
        return baseCommandLine + piCam.label + "=" + commandValue;
    }

    public static String getCommandFor(Integer index) {
        PICam piCam = INDEX_MAP.get(index);
        int    newValue     = piCam.defaultValue;
        String commandValue = "";
        if ("bool".equals(piCam.type)) {
            commandValue = (newValue == 0) ? "false" : "true";
        }
        else {
            commandValue = String.valueOf(newValue);
        }
        return baseCommandLine + piCam.label + "=" + commandValue;
    }
}

Here are some ways that the class can be interacted with:

This code:

public static void test() {
    PICam.setValue(0,127); //Set brightness to 125
    PICam.setValue(PICam.SHARPNESS,143); //Set sharpness to 125
    String command1 = PICam.getSetCommandStringFor(PICam.BRIGHTNESS); //Get command line string to include the brightness value that we previously set referencing it by enum constant.
    String command2 = PICam.getSetCommandStringFor(0); //Get command line string to include the brightness value that we previously set referencing it by index number.
    String command3 = PICam.getDefaultCamString(PICam.BRIGHTNESS); //Get command line string with the default value
    String command4 = PICam.getSetCommandStringFor(PICam.SHARPNESS); //Get command line string with the sharpness value that we previously set.
    String command5 = PICam.getDefaultCamString(PICam.SHARPNESS); //Get command line string with the default sharpness value.
    System.out.println(command1);
    System.out.println(command2);
    System.out.println(command3);
    System.out.println(command4);
    System.out.println(command5);
}

Produces these results:

/usr/bin/v4l2-ctl -d /dev/video0 --set-ctrl=brightness=127
/usr/bin/v4l2-ctl -d /dev/video0 --set-ctrl=brightness=127
/usr/bin/v4l2-ctl -d /dev/video0 --set-ctrl=brightness=50
/usr/bin/v4l2-ctl -d /dev/video0 --set-ctrl=sharpness=143
/usr/bin/v4l2-ctl -d /dev/video0 --set-ctrl=sharpness=0

Read lines from a text file but skip the first two lines

That whole Open <file path> For Input As <some number> thing is so 1990s. It's also slow and very error-prone.

In your VBA editor, Select References from the Tools menu and look for "Microsoft Scripting Runtime" (scrrun.dll) which should be available on pretty much any XP or Vista machine. It it's there, select it. Now you have access to a (to me at least) rather more robust solution:

With New Scripting.FileSystemObject
    With .OpenTextFile(sFilename, ForReading)

        If Not .AtEndOfStream Then .SkipLine
        If Not .AtEndOfStream Then .SkipLine

        Do Until .AtEndOfStream
            DoSomethingImportantTo .ReadLine
        Loop

    End With
End With

Deleting a SQL row ignoring all foreign keys and constraints

You can set the constraints on that table / column to not check temporarily, then re-enable the constraints. General form would be:

ALTER TABLE TableName NOCHECK CONSTRAINT ConstraintName

Then re-enable all constraints with

ALTER TABLE TableName CHECK CONSTRAINT ConstraintName

I assume that this would be temporary though? You obviously wouldn't want to do this consistently.

filter items in a python dictionary where keys contain a specific string

input = {"A":"a", "B":"b", "C":"c"}
output = {k:v for (k,v) in input.items() if key_satifies_condition(k)}

How do I append text to a file?

Follow up to accepted answer.

You need something other than CTRL-D to designate the end if using this in a script. Try this instead:

cat << EOF >> filename
This is text entered via the keyboard or via a script.
EOF

This will append text to the stated file (not including "EOF").

It utilizes a here document (or heredoc).

However if you need sudo to append to the stated file, you will run into trouble utilizing a heredoc due to I/O redirection if you're typing directly on the command line.

This variation will work when you are typing directly on the command line:

sudo sh -c 'cat << EOF >> filename
This is text entered via the keyboard.
EOF'

Or you can use tee instead to avoid the command line sudo issue seen when using the heredoc with cat:

tee -a filename << EOF
This is text entered via the keyboard or via a script.
EOF

Store text file content line by line into array

You can use this code. This works very fast!

public String[] loadFileToArray(String fileName) throws IOException {
    String s = new String(Files.readAllBytes(Paths.get(fileName)));
    return Arrays.stream(s.split("\n")).toArray(String[]::new);
}

IE6/IE7 css border on select element

i was having this same issue with ie, then i inserted this meta tag and it allowed me to edit the borders in ie

<meta http-equiv="X-UA-Compatible" content="IE=100" >

Interactive shell using Docker Compose

You can do docker-compose exec SERVICE_NAME sh on the command line. The SERVICE_NAME is defined in your docker-compose.yml. For example,

services:
    zookeeper:
        image: wurstmeister/zookeeper
        ports:
          - "2181:2181"

The SERVICE_NAME would be "zookeeper".

How to add to the PYTHONPATH in Windows, so it finds my modules/packages?

Windows 7 Professional I Modified @mongoose_za's answer to make it easier to change the python version:

  1. [Right Click]Computer > Properties >Advanced System Settings > Environment Variables
  2. Click [New] under "System Variable"
  3. Variable Name: PY_HOME, Variable Value:C:\path\to\python\version enter image description here
  4. Click [OK]
  5. Locate the "Path" System variable and click [Edit]
  6. Add the following to the existing variable:

    %PY_HOME%;%PY_HOME%\Lib;%PY_HOME%\DLLs;%PY_HOME%\Lib\lib-tk; enter image description here

  7. Click [OK] to close all of the windows.

As a final sanity check open a command prompt and enter python. You should see

>python [whatever version you are using]

If you need to switch between versions, you only need to modify the PY_HOME variable to point to the proper directory. This is bit easier to manage if you need multiple python versions installed.

Oracle to_date, from mm/dd/yyyy to dd-mm-yyyy

You don't need to muck about with extracting parts of the date. Just cast it to a date using to_date and the format in which its stored, then cast that date to a char in the format you want. Like this:

select to_char(to_date('1/10/2011','mm/dd/yyyy'),'mm-dd-yyyy') from dual

How can I align all elements to the left in JPanel?

My favorite method to use would be the BorderLayout method. Here are the five examples with each position the component could go in. The example is for if the component were a button. We will add it to a JPanel, p. The button will be called b.

//To align it to the left
p.add(b, BorderLayout.WEST);

//To align it to the right
p.add(b, BorderLayout.EAST);

//To align it at the top
p.add(b, BorderLayout.NORTH);

//To align it to the bottom
p.add(b, BorderLayout.SOUTH);

//To align it to the center
p.add(b, BorderLayout.CENTER);

Don't forget to import it as well by typing:

import java.awt.BorderLayout;

There are also other methods in the BorderLayout class involving things like orientation, but you can do your own research on that if you curious about that. I hope this helped!

How to execute a file within the python interpreter?

Python 2 + Python 3

exec(open("./path/to/script.py").read(), globals())

This will execute a script and put all it's global variables in the interpreter's global scope (the normal behavior in most scripting environments).

Python 3 exec Documentation

Is there an equivalent for var_dump (PHP) in Javascript?

A lot of modern browsers support the following syntax:

JSON.stringify(myVar);

HTML5 pattern for formatting input box to take date mm/dd/yyyy?

Easiest way is use read only attribute to prevent direct user input:

 <input class="datepicker" type="text" name="date" value="" readonly />

Or you could use HTML5 validation based on pattern attribute. Date input pattern (dd/mm/yyyy or mm/dd/yyyy):

<input type="text" pattern="\d{1,2}/\d{1,2}/\d{4}" class="datepicker" name="date" value="" />

How do I automatically resize an image for a mobile site?

if you use bootstrap 3 , just add img-responsive class in your img tag

<img class="img-responsive"  src="...">

if you use bootstrap 4, add img-fluid class in your img tag

<img class="img-fluid"  src="...">

which does the staff: max-width: 100%, height: auto, and display:block to the image

How can I post data as form data instead of a request payload?

I took a few of the other answers and made something a bit cleaner, put this .config() call on the end of your angular.module in your app.js:

.config(['$httpProvider', function ($httpProvider) {
  // Intercept POST requests, convert to standard form encoding
  $httpProvider.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded";
  $httpProvider.defaults.transformRequest.unshift(function (data, headersGetter) {
    var key, result = [];

    if (typeof data === "string")
      return data;

    for (key in data) {
      if (data.hasOwnProperty(key))
        result.push(encodeURIComponent(key) + "=" + encodeURIComponent(data[key]));
    }
    return result.join("&");
  });
}]);

Load view from an external xib file in storyboard

My full example is here, but I will provide a summary below.

Layout

Add a .swift and .xib file each with the same name to your project. The .xib file contains your custom view layout (using auto layout constraints preferably).

Make the swift file the xib file's owner.

enter image description here Code

Add the following code to the .swift file and hook up the outlets and actions from the .xib file.

import UIKit
class ResuableCustomView: UIView {

    let nibName = "ReusableCustomView"
    var contentView: UIView?

    @IBOutlet weak var label: UILabel!
    @IBAction func buttonTap(_ sender: UIButton) {
        label.text = "Hi"
    }

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

        guard let view = loadViewFromNib() else { return }
        view.frame = self.bounds
        self.addSubview(view)
        contentView = view
    }

    func loadViewFromNib() -> UIView? {
        let bundle = Bundle(for: type(of: self))
        let nib = UINib(nibName: nibName, bundle: bundle)
        return nib.instantiate(withOwner: self, options: nil).first as? UIView
    }
}

Use it

Use your custom view anywhere in your storyboard. Just add a UIView and set the class name to your custom class name.

enter image description here


For a while Christopher Swasey's approach was the best approach I had found. I asked a couple of the senior devs on my team about it and one of them had the perfect solution! It satisfies every one of the concerns that Christopher Swasey so eloquently addressed and it doesn't require boilerplate subclass code(my main concern with his approach). There is one gotcha, but other than that it is fairly intuitive and easy to implement.

  1. Create a custom UIView class in a .swift file to control your xib. i.e. MyCustomClass.swift
  2. Create a .xib file and style it as you want. i.e. MyCustomClass.xib
  3. Set the File's Owner of the .xib file to be your custom class (MyCustomClass)
  4. GOTCHA: leave the class value (under the identity Inspector) for your custom view in the .xib file blank. So your custom view will have no specified class, but it will have a specified File's Owner.
  5. Hook up your outlets as you normally would using the Assistant Editor.
    • NOTE: If you look at the Connections Inspector you will notice that your Referencing Outlets do not reference your custom class (i.e. MyCustomClass), but rather reference File's Owner. Since File's Owner is specified to be your custom class, the outlets will hook up and work propery.
  6. Make sure your custom class has @IBDesignable before the class statement.
  7. Make your custom class conform to the NibLoadable protocol referenced below.
    • NOTE: If your custom class .swift file name is different from your .xib file name, then set the nibName property to be the name of your .xib file.
  8. Implement required init?(coder aDecoder: NSCoder) and override init(frame: CGRect) to call setupFromNib() like the example below.
  9. Add a UIView to your desired storyboard and set the class to be your custom class name (i.e. MyCustomClass).
  10. Watch IBDesignable in action as it draws your .xib in the storyboard with all of it's awe and wonder.

Here is the protocol you will want to reference:

public protocol NibLoadable {
    static var nibName: String { get }
}

public extension NibLoadable where Self: UIView {

    public static var nibName: String {
        return String(describing: Self.self) // defaults to the name of the class implementing this protocol.
    }

    public static var nib: UINib {
        let bundle = Bundle(for: Self.self)
        return UINib(nibName: Self.nibName, bundle: bundle)
    }

    func setupFromNib() {
        guard let view = Self.nib.instantiate(withOwner: self, options: nil).first as? UIView else { fatalError("Error loading \(self) from nib") }
        addSubview(view)
        view.translatesAutoresizingMaskIntoConstraints = false
        view.leadingAnchor.constraint(equalTo: self.safeAreaLayoutGuide.leadingAnchor, constant: 0).isActive = true
        view.topAnchor.constraint(equalTo: self.safeAreaLayoutGuide.topAnchor, constant: 0).isActive = true
        view.trailingAnchor.constraint(equalTo: self.safeAreaLayoutGuide.trailingAnchor, constant: 0).isActive = true
        view.bottomAnchor.constraint(equalTo: self.safeAreaLayoutGuide.bottomAnchor, constant: 0).isActive = true
    }
}

And here is an example of MyCustomClass that implements the protocol (with the .xib file being named MyCustomClass.xib):

@IBDesignable
class MyCustomClass: UIView, NibLoadable {

    @IBOutlet weak var myLabel: UILabel!

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

    override init(frame: CGRect) {
        super.init(frame: frame)
        setupFromNib()
    }

}

NOTE: If you miss the Gotcha and set the class value inside your .xib file to be your custom class, then it will not draw in the storyboard and you will get a EXC_BAD_ACCESS error when you run the app because it gets stuck in an infinite loop of trying to initialize the class from the nib using the init?(coder aDecoder: NSCoder) method which then calls Self.nib.instantiate and calls the init again.

How to pass parameters or arguments into a gradle task

Its nothing more easy.

run command: ./gradlew clean -PjobId=9999

and

in gradle use: println(project.gradle.startParameter.projectProperties)

You will get clue.

If file exists then delete the file

You're close, you just need to delete the file before trying to over-write it.

dim infolder: set infolder = fso.GetFolder(IN_PATH)
dim file: for each file in infolder.Files

    dim name: name = file.name
    dim parts: parts = split(name, ".")

    if UBound(parts) = 2 then

       ' file name like a.c.pdf    

        dim newname: newname = parts(0) & "." & parts(2)
        dim newpath: newpath = fso.BuildPath(OUT_PATH, newname)

        ' warning:
        ' if we have source files C:\IN_PATH\ABC.01.PDF, C:\IN_PATH\ABC.02.PDF, ...
        ' only one of them will be saved as D:\OUT_PATH\ABC.PDF

        if fso.FileExists(newpath) then
            fso.DeleteFile newpath
        end if

        file.Move newpath

    end if

next

SQL Server: Get data for only the past year

declare @iMonth int
declare @sYear varchar(4)
declare @sMonth varchar(2)
set @iMonth = 0
while @iMonth > -12
begin
    set @sYear = year(DATEADD(month,@iMonth,GETDATE()))
    set @sMonth = right('0'+cast(month(DATEADD(month,@iMonth,GETDATE())) as varchar(2)),2)
    select @sYear + @sMonth
    set @iMonth = @iMonth - 1
end

How to check if a process is running via a batch script

I'm assuming windows here. So, you'll need to use WMI to get that information. Check out The Scripting Guy's archives for a lot of examples on how to use WMI from a script.

How do I force Maven to use my local repository rather than going out to remote repos to retrieve artifacts?

Use mvn --help and you can see the options list.

There is an option like -nsu,--no-snapshot-updates Suppress SNAPSHOT updates

So use command mvn install -nsu can force compile with local repository.

Why is __init__() always called after __new__()?

An update to @AntonyHatchkins answer, you probably want a separate dictionary of instances for each class of the metatype, meaning that you should have an __init__ method in the metaclass to initialize your class object with that dictionary instead of making it global across all the classes.

class MetaQuasiSingleton(type):
    def __init__(cls, name, bases, attibutes):
        cls._dict = {}

    def __call__(cls, key):
        if key in cls._dict:
            print('EXISTS')
            instance = cls._dict[key]
        else:
            print('NEW')
            instance = super().__call__(key)
            cls._dict[key] = instance
        return instance

class A(metaclass=MetaQuasiSingleton):
    def __init__(self, key):
        print 'INIT'
        self.key = key
        print()

I have gone ahead and updated the original code with an __init__ method and changed the syntax to Python 3 notation (no-arg call to super and metaclass in the class arguments instead of as an attribute).

Either way, the important point here is that your class initializer (__call__ method) will not execute either __new__ or __init__ if the key is found. This is much cleaner than using __new__, which requires you to mark the object if you want to skip the default __init__ step.

How to set "style=display:none;" using jQuery's attr method?

You can use the jquery attr() method to achieve the setting of teh attribute and the method removeAttr() to delete the attribute for your element msform As seen in the code

$('#msform').attr('style', 'display:none;');


$('#msform').removeAttr('style');

adding and removing classes in angularJs using ng-click

for Reactive forms -

HTML file

_x000D_
_x000D_
<div class="col-sm-2">_x000D_
  <button type="button"  [class]= "btn_class"  id="b1" (click)="changeMe()">{{ btn_label }}</button>_x000D_
</div>
_x000D_
_x000D_
_x000D_

TS file

_x000D_
_x000D_
changeMe() {_x000D_
  switch (this.btn_label) {_x000D_
    case 'Yes ': this.btn_label = 'Custom' ;_x000D_
    this.btn_class = 'btn btn-danger btn-lg btn-block';_x000D_
    break;_x000D_
    case 'Custom': this.btn_label = ' No ' ;_x000D_
    this.btn_class = 'btn btn-success btn-lg btn-block';_x000D_
    break;_x000D_
    case ' No ': this.btn_label = 'Yes ';_x000D_
      this.btn_class = 'btn btn-primary btn-lg btn-block';_x000D_
      break;_x000D_
  }
_x000D_
_x000D_
_x000D_

How do I mock an autowired @Value field in Spring with Mockito?

You can use the magic of Spring's ReflectionTestUtils.setField in order to avoid making any modifications whatsoever to your code.

The comment from Michal Stochmal provides an example:

use ReflectionTestUtils.setField(bean, "fieldName", "value"); before invoking your bean method during test.

Check out this tutorial for even more information, although you probably won't need it since the method is very easy to use

UPDATE

Since the introduction of Spring 4.2.RC1 it is now possible to set a static field without having to supply an instance of the class. See this part of the documentation and this commit.

How to scroll up or down the page to an anchor using jQuery?

following solution worked for me:

$("a[href^=#]").click(function(e)
        {
            e.preventDefault();
            var aid = $(this).attr('href');
            console.log(aid);
            aid = aid.replace("#", "");
            var aTag = $("a[name='"+ aid +"']");
            if(aTag == null || aTag.offset() == null)
                aTag = $("a[id='"+ aid +"']");

            $('html,body').animate({scrollTop: aTag.offset().top}, 1000);
        }
    );

Show hide divs on click in HTML and CSS without jQuery

Of course! jQuery is just a library that utilizes javascript after all.

You can use document.getElementById to get the element in question, then change its height accordingly, through element.style.height.

elementToChange = document.getElementById('collapseableEl');
elementToChange.style.height = '100%';

Wrap that up in a neat little function that caters for toggling back and forth and you have yourself a solution.

How to perform a LEFT JOIN in SQL Server between two SELECT statements?

Try this:

SELECT user.userID, edge.TailUser, edge.Weight 
FROM user
LEFT JOIN edge ON edge.HeadUser = User.UserID
WHERE edge.HeadUser=5043

OR

AND edge.HeadUser=5043

instead of WHERE clausule.

Adding a newline character within a cell (CSV)

I struggled with this as well but heres the solution. If you add " before and at the end of the csv string you are trying to display, it will consolidate them into 1 cell while honoring new line.

csvString += "\""+"Date Generated: \n" ; 
csvString += "Doctor: " + "\n"+"\"" + "\n"; 

Reading a UTF8 CSV file with Python

Worth noting that if nothing worked for you, you may have forgotten to escape your path.
For example, this code:

f = open("C:\Some\Path\To\file.csv")

Would result in an error:

SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape

To fix, simply do:

f = open("C:\\Some\\Path\\To\\file.csv")

Error - trustAnchors parameter must be non-empty

Another reason for this is it's actually a valid error. Some nefarious Wi-Fi hotspots will mess with certificates and man-in-the-middle attack you to do who knows what (run away!).

Some large employers will do this same trick, especially in sensitive network zones so they can monitor all the encrypted traffic (not great from end user perspective, but there may be good reasons for this).

.htaccess, order allow, deny, deny from all: confused?

This is a quite confusing way of using Apache configuration directives.

Technically, the first bit is equivalent to

Allow From All

This is because Order Deny,Allow makes the Deny directive evaluated before the Allow Directives. In this case, Deny and Allow conflict with each other, but Allow, being the last evaluated will match any user, and access will be granted.

Now, just to make things clear, this kind of configuration is BAD and should be avoided at all cost, because it borders undefined behaviour.

The Limit sections define which HTTP methods have access to the directory containing the .htaccess file.

Here, GET and POST methods are allowed access, and PUT and DELETE methods are denied access. Here's a link explaining what the various HTTP methods are: http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html

However, it's more than often useless to use these limitations as long as you don't have custom CGI scripts or Apache modules that directly handle the non-standard methods (PUT and DELETE), since by default, Apache does not handle them at all.

It must also be noted that a few other methods exist that can also be handled by Limit, namely CONNECT, OPTIONS, PATCH, PROPFIND, PROPPATCH, MKCOL, COPY, MOVE, LOCK, and UNLOCK.

The last bit is also most certainly useless, since any correctly configured Apache installation contains the following piece of configuration (for Apache 2.2 and earlier):

#
# The following lines prevent .htaccess and .htpasswd files from being 
# viewed by Web clients. 
#
<Files ~ "^\.ht">
    Order allow,deny
    Deny from all
    Satisfy all
</Files>

which forbids access to any file beginning by ".ht".

The equivalent Apache 2.4 configuration should look like:

<Files ~ "^\.ht">
    Require all denied
</Files>

How to pass ArrayList<CustomeObject> from one activity to another?

You can pass an ArrayList<E> the same way, if the E type is Serializable.

You would call the putExtra (String name, Serializable value) of Intent to store, and getSerializableExtra (String name) for retrieval.

Example:

ArrayList<String> myList = new ArrayList<String>();
intent.putExtra("mylist", myList);

In the other Activity:

ArrayList<String> myList = (ArrayList<String>) getIntent().getSerializableExtra("mylist");

C# how to wait for a webpage to finish loading before continuing

yuna and bnl code failed in the case below;

failing example:

1st one waits for completed.but, 2nd one with the invokemember("submit") didnt . invoke works. but ReadyState.Complete acts like its Completed before its REALLY completed:

wb.Navigate(url);
while(wb.ReadyState != WebBrowserReadyState.Complete)
{
   Application.DoEvents();
}
MessageBox.Show("ok this waits Complete");

//navigates to new page
wb.Document.GetElementById("formId").InvokeMember("submit");
while(wb.ReadyState != WebBrowserReadyState.Complete)
{
   Application.DoEvents();
}
MessageBox.Show("webBrowser havent navigated  yet. it gave me previous page's html.");  
var html = wb.Document.GetElementsByTagName("HTML")[0].OuterHtml;

how to fix this unwanted situation:

usage

    public myForm1 {

        myForm1_load() { }

        // func to make browser wait is inside the Extended class More tidy.
        WebBrowserEX wbEX = new WebBrowserEX();

        button1_click(){
            wbEX.Navigate("site1.com");
            wbEX.waitWebBrowserToComplete(wb);

            wbEX.Document.GetElementById("input1").SetAttribute("Value", "hello");
            //submit does navigation
            wbEX.Document.GetElementById("formid").InvokeMember("submit");
            wbEX.waitWebBrowserToComplete(wb);
            // this actually waits for document Compelete. worked for me.

            var processedHtml = wbEX.Document.GetElementsByTagName("HTML")[0].OuterHtml;
            var rawHtml = wbEX.DocumentText;
         }
     }

//put this  extended class in your code.
//(ie right below form class, or seperate cs file doesnt matter)
public class WebBrowserEX : WebBrowser
{
   //ctor
   WebBrowserEX()
   {
     //wired aumatically here. we dont need to worry our sweet brain.
     this.DocumentCompleted += (o, e) => { webbrowserDocumentCompleted = true;};
   }
     //instead of checking  readState, get state from DocumentCompleted Event 
     // via bool value
     bool webbrowserDocumentCompleted = false;
     public void waitWebBrowserToComplete()
     {
       while (!webbrowserDocumentCompleted )
       { Application.DoEvents();  }
       webbrowserDocumentCompleted = false;
     }

 }

Check if a string contains another string

You can also use the special word like:

Public Sub Search()
  If "My Big String with, in the middle" Like "*,*" Then
    Debug.Print ("Found ','")
  End If
End Sub

curl posting with header application/x-www-form-urlencoded

<?php
//
// A very simple PHP example that sends a HTTP POST to a remote site
//

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL,"http://xxxxxxxx.xxx/xx/xx");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,
            "dispnumber=567567567&extension=6");
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));


// receive server response ...
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$server_output = curl_exec ($ch);

curl_close ($ch);

// further processing ....
if ($server_output == "OK") { ... } else { ... }

?>

fatal error LNK1104: cannot open file 'libboost_system-vc110-mt-gd-1_51.lib'

Yet another solution:

I was stumped because I was including boost_regex-vc120-mt-gd-1_58.lib in my Link->Additional Dependencies property, but the link kept telling me it couldn't open libboost_regex-vc120-mt-gd-1_58.lib (note the lib prefix). I didn't specify libboost_regex-vc120-mt-gd-1_58.lib.

I was trying to use (and had built) the boost dynamic libraries (.dlls) but did not have the BOOST_ALL_DYN_LINK macro defined. Apparently there are hints in the compile to include a library, and without BOOST_ALL_DYN_LINK it looks for the static library (with the lib prefix), not the dynamic library (without a lib prefix).

Is there a foreach in MATLAB? If so, how does it behave if the underlying data changes?

As of today (Feb 27), there is a new For-Each toolbox on the MATLAB File Exchange that accomplishes the concept of foreach. foreach is not a part of the MATLAB language but use of this toolbox gives us the ability to emulate what foreach would do.

Paging with LINQ for objects

There are two main options:

.NET >= 4.0 Dynamic LINQ:

  1. Add using System.Linq.Dynamic; at the top.
  2. Use: var people = people.AsQueryable().OrderBy("Make ASC, Year DESC").ToList();

You can also get it by NuGet.

.NET < 4.0 Extension Methods:

private static readonly Hashtable accessors = new Hashtable();

private static readonly Hashtable callSites = new Hashtable();

private static CallSite<Func<CallSite, object, object>> GetCallSiteLocked(string name) {
    var callSite = (CallSite<Func<CallSite, object, object>>)callSites[name];
    if(callSite == null)
    {
        callSites[name] = callSite = CallSite<Func<CallSite, object, object>>.Create(
                    Binder.GetMember(CSharpBinderFlags.None, name, typeof(AccessorCache),
                new CSharpArgumentInfo[] { CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null) }));
    }
    return callSite;
}

internal static Func<dynamic,object> GetAccessor(string name)
{
    Func<dynamic, object> accessor = (Func<dynamic, object>)accessors[name];
    if (accessor == null)
    {
        lock (accessors )
        {
            accessor = (Func<dynamic, object>)accessors[name];
            if (accessor == null)
            {
                if(name.IndexOf('.') >= 0) {
                    string[] props = name.Split('.');
                    CallSite<Func<CallSite, object, object>>[] arr = Array.ConvertAll(props, GetCallSiteLocked);
                    accessor = target =>
                    {
                        object val = (object)target;
                        for (int i = 0; i < arr.Length; i++)
                        {
                            var cs = arr[i];
                            val = cs.Target(cs, val);
                        }
                        return val;
                    };
                } else {
                    var callSite = GetCallSiteLocked(name);
                    accessor = target =>
                    {
                        return callSite.Target(callSite, (object)target);
                    };
                }
                accessors[name] = accessor;
            }
        }
    }
    return accessor;
}
public static IOrderedEnumerable<dynamic> OrderBy(this IEnumerable<dynamic> source, string property)
{
    return Enumerable.OrderBy<dynamic, object>(source, AccessorCache.GetAccessor(property), Comparer<object>.Default);
}
public static IOrderedEnumerable<dynamic> OrderByDescending(this IEnumerable<dynamic> source, string property)
{
    return Enumerable.OrderByDescending<dynamic, object>(source, AccessorCache.GetAccessor(property), Comparer<object>.Default);
}
public static IOrderedEnumerable<dynamic> ThenBy(this IOrderedEnumerable<dynamic> source, string property)
{
    return Enumerable.ThenBy<dynamic, object>(source, AccessorCache.GetAccessor(property), Comparer<object>.Default);
}
public static IOrderedEnumerable<dynamic> ThenByDescending(this IOrderedEnumerable<dynamic> source, string property)
{
    return Enumerable.ThenByDescending<dynamic, object>(source, AccessorCache.GetAccessor(property), Comparer<object>.Default);
}

C# Convert List<string> to Dictionary<string, string>

By using ToDictionary:

var dictionary = list.ToDictionary(s => s);

If it is possible that any string could be repeated, either do a Distinct call first on the list (to remove duplicates), or use ToLookup which allows for multiple values per key.

how to use JSON.stringify and json_decode() properly

When you save some data using JSON.stringify() and then need to read that in php. The following code worked for me.

json_decode( html_entity_decode( stripslashes ($jsonString ) ) );

Thanks to @Thisguyhastwothumbs

System.currentTimeMillis() vs. new Date() vs. Calendar.getInstance().getTime()

Looking at the JDK, innermost constructor for Calendar.getInstance() has this:

public GregorianCalendar(TimeZone zone, Locale aLocale) {
    super(zone, aLocale);
    gdate = (BaseCalendar.Date) gcal.newCalendarDate(zone);
    setTimeInMillis(System.currentTimeMillis());
}

so it already automatically does what you suggest. Date's default constructor holds this:

public Date() {
    this(System.currentTimeMillis());
}

So there really isn't need to get system time specifically unless you want to do some math with it before creating your Calendar/Date object with it. Also I do have to recommend joda-time to use as replacement for Java's own calendar/date classes if your purpose is to work with date calculations a lot.

Simple CSS: Text won't center in a button

As a more brute force method that I found worked for me:

First wrap the text inside the button in a span, and then apply this css to that span

var spanStyle = {
      position: "absolute",
      top: "50%",
      left: "50%",
      transform: "translate(-50%, -50%)"
    }

*above setup for inline styling

Redirecting exec output to a buffer or file

For sending the output to another file (I'm leaving out error checking to focus on the important details):

if (fork() == 0)
{
    // child
    int fd = open(file, O_RDWR | O_CREAT, S_IRUSR | S_IWUSR);

    dup2(fd, 1);   // make stdout go to file
    dup2(fd, 2);   // make stderr go to file - you may choose to not do this
                   // or perhaps send stderr to another file

    close(fd);     // fd no longer needed - the dup'ed handles are sufficient

    exec(...);
}

For sending the output to a pipe so you can then read the output into a buffer:

int pipefd[2];
pipe(pipefd);

if (fork() == 0)
{
    close(pipefd[0]);    // close reading end in the child

    dup2(pipefd[1], 1);  // send stdout to the pipe
    dup2(pipefd[1], 2);  // send stderr to the pipe

    close(pipefd[1]);    // this descriptor is no longer needed

    exec(...);
}
else
{
    // parent

    char buffer[1024];

    close(pipefd[1]);  // close the write end of the pipe in the parent

    while (read(pipefd[0], buffer, sizeof(buffer)) != 0)
    {
    }
}

Where to put a textfile I want to use in eclipse?

If this is a simple project, you should be able to drag the txt file right into the project folder. Specifically, the "project folder" would be the highest level folder. I tried to do this (for a homework project that I'm doing) by putting the txt file in the src folder, but that didn't work. But finally I figured out to put it in the project file.

A good tutorial for this is http://www.vogella.com/articles/JavaIO/article.html. I used this as an intro to i/o and it helped.

How can I copy a Python string?

Copying a string can be done two ways either copy the location a = "a" b = a or you can clone which means b wont get affected when a is changed which is done by a = 'a' b = a[:]

Python constructor and default value

Let's illustrate what's happening here:

Python 3.1.2 (r312:79147, Sep 27 2010, 09:45:41) 
[GCC 4.4.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> class Foo:
...     def __init__(self, x=[]):
...         x.append(1)
... 
>>> Foo.__init__.__defaults__
([],)
>>> f = Foo()
>>> Foo.__init__.__defaults__
([1],)
>>> f2 = Foo()
>>> Foo.__init__.__defaults__
([1, 1],)

You can see that the default arguments are stored in a tuple which is an attribute of the function in question. This actually has nothing to do with the class in question and goes for any function. In python 2, the attribute will be func.func_defaults.

As other posters have pointed out, you probably want to use None as a sentinel value and give each instance it's own list.

Convert string to Python class object?

You could do something like:

globals()[class_name]

Java enum - why use toString instead of name

It really depends on what you want to do with the returned value:

  • If you need to get the exact name used to declare the enum constant, you should use name() as toString may have been overriden
  • If you want to print the enum constant in a user friendly way, you should use toString which may have been overriden (or not!).

When I feel that it might be confusing, I provide a more specific getXXX method, for example:

public enum Fields {
    LAST_NAME("Last Name"), FIRST_NAME("First Name");

    private final String fieldDescription;

    private Fields(String value) {
        fieldDescription = value;
    }

    public String getFieldDescription() {
        return fieldDescription;
    }
}

How do I concatenate a string with a variable?

This can happen because java script allows white spaces sometimes if a string is concatenated with a number. try removing the spaces and create a string and then pass it into getElementById.

example:

var str = 'horseThumb_'+id;

str = str.replace(/^\s+|\s+$/g,"");

function AddBorder(id){

    document.getElementById(str).className='hand positionLeft'

}

Can't specify the 'async' modifier on the 'Main' method of a console app

Newest version of C# - C# 7.1 allows to create async console app. To enable C# 7.1 in project, you have to upgrade your VS to at least 15.3, and change C# version to C# 7.1 or C# latest minor version. To do this, go to Project properties -> Build -> Advanced -> Language version.

After this, following code will work:

internal class Program
{
    public static async Task Main(string[] args)
    {
         (...)
    }

Truncate with condition

No, TRUNCATE is all or nothing. You can do a DELETE FROM <table> WHERE <conditions> but this loses the speed advantages of TRUNCATE.

How to execute a command prompt command from python

how about simply:

import os
os.system('dir c:\\')

react hooks useEffect() cleanup for only componentWillUnmount?

you can use more than one useEffect

for example if my variable is data1 i can use all of this in my component

useEffect( () => console.log("mount"), [] );
useEffect( () => console.log("will update data1"), [ data1 ] );
useEffect( () => console.log("will update any") );
useEffect( () => () => console.log("will update data1 or unmount"), [ data1 ] );
useEffect( () => () => console.log("unmount"), [] );

Cannot get to $rootScope

You can not ask for instance during configuration phase - you can ask only for providers.

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

// configure stuff
app.config(function($routeProvider, $locationProvider) {
  // you can inject any provider here
});

// run blocks
app.run(function($rootScope) {
  // you can inject any instance here
});

See http://docs.angularjs.org/guide/module for more info.

Regex to match string containing two names in any order

You can do checks using lookarounds:

^(?=.*\bjack\b)(?=.*\bjames\b).*$

Test it.

This approach has the advantage that you can easily specify multiple conditions.

^(?=.*\bjack\b)(?=.*\bjames\b)(?=.*\bjason\b)(?=.*\bjules\b).*$

Select multiple elements from a list

mylist[c(5,7,9)] should do it.

You want the sublists returned as sublists of the result list; you don't use [[]] (or rather, the function is [[) for that -- as Dason mentions in comments, [[ grabs the element.

Angular 4.3 - HttpClient set params

Just wanted to add that if you want to add several parameters with the same key name for example: www.test.com/home?id=1&id=2

let params = new HttpParams();
params = params.append(key, value);

Use append, if you use set, it will overwrite the previous value with the same key name.

What's the difference between process.cwd() vs __dirname?

As per node js doc process.cwd()

cwd is a method of global object process, returns a string value which is the current working directory of the Node.js process.

As per node js doc __dirname

The directory name of current script as a string value. __dirname is not actually a global but rather local to each module.

Let me explain with example,

suppose we have a main.js file resides inside C:/Project/main.js and running node main.js both these values return same file

or simply with following folder structure

Project 
+-- main.js
+--lib
   +-- script.js

main.js

console.log(process.cwd())
// C:\Project
console.log(__dirname)
// C:\Project
console.log(__dirname===process.cwd())
// true

suppose we have another file script.js files inside a sub directory of project ie C:/Project/lib/script.js and running node main.js which require script.js

main.js

require('./lib/script.js')
console.log(process.cwd())
// C:\Project
console.log(__dirname)
// C:\Project
console.log(__dirname===process.cwd())
// true

script.js

console.log(process.cwd())
// C:\Project
console.log(__dirname)
// C:\Project\lib
console.log(__dirname===process.cwd())
// false

How to create full path with node's fs.mkdirSync?

An asynchronous way to create directories recursively:

import fs from 'fs'

const mkdirRecursive = function(path, callback) {
  let controlledPaths = []
  let paths = path.split(
    '/' // Put each path in an array
  ).filter(
    p => p != '.' // Skip root path indicator (.)
  ).reduce((memo, item) => {
    // Previous item prepended to each item so we preserve realpaths
    const prevItem = memo.length > 0 ? memo.join('/').replace(/\.\//g, '')+'/' : ''
    controlledPaths.push('./'+prevItem+item)
    return [...memo, './'+prevItem+item]
  }, []).map(dir => {
    fs.mkdir(dir, err => {
      if (err && err.code != 'EEXIST') throw err
      // Delete created directory (or skipped) from controlledPath
      controlledPaths.splice(controlledPaths.indexOf(dir), 1)
      if (controlledPaths.length === 0) {
        return callback()
      }
    })
  })
}

// Usage
mkdirRecursive('./photos/recent', () => {
  console.log('Directories created succesfully!')
})

Execute combine multiple Linux commands in one line

If you want to execute each command only if the previous one succeeded, then combine them using the && operator:

cd /my_folder && rm *.jar && svn co path to repo && mvn compile package install

If one of the commands fails, then all other commands following it won't be executed.

If you want to execute all commands regardless of whether the previous ones failed or not, separate them with semicolons:

cd /my_folder; rm *.jar; svn co path to repo; mvn compile package install

In your case, I think you want the first case where execution of the next command depends on the success of the previous one.

You can also put all commands in a script and execute that instead:

#! /bin/sh
cd /my_folder \
&& rm *.jar \
&& svn co path to repo \
&& mvn compile package install

(The backslashes at the end of the line are there to prevent the shell from thinking that the next line is a new command; if you omit the backslashes, you would need to write the whole command in a single line.)

Save that to a file, for example myscript, and make it executable:

chmod +x myscript

You can now execute that script like other programs on the machine. But if you don't place it inside a directory listed in your PATH environment variable (for example /usr/local/bin, or on some Linux distributions ~/bin), then you will need to specify the path to that script. If it's in the current directory, you execute it with:

./myscript

The commands in the script work the same way as the commands in the first example; the next command only executes if the previous one succeeded. For unconditional execution of all commands, simply list each command on its own line:

#! /bin/sh
cd /my_folder
rm *.jar
svn co path to repo
mvn compile package install

Are there benefits of passing by pointer over passing by reference in C++?

Clarifications to the preceding posts:


References are NOT a guarantee of getting a non-null pointer. (Though we often treat them as such.)

While horrifically bad code, as in take you out behind the woodshed bad code, the following will compile & run: (At least under my compiler.)

bool test( int & a)
{
  return (&a) == (int *) NULL;
}

int
main()
{
  int * i = (int *)NULL;
  cout << ( test(*i) ) << endl;
};

The real issue I have with references lies with other programmers, henceforth termed IDIOTS, who allocate in the constructor, deallocate in the destructor, and fail to supply a copy constructor or operator=().

Suddenly there's a world of difference between foo(BAR bar) and foo(BAR & bar). (Automatic bitwise copy operation gets invoked. Deallocation in destructor gets invoked twice.)

Thankfully modern compilers will pick up this double-deallocation of the same pointer. 15 years ago, they didn't. (Under gcc/g++, use setenv MALLOC_CHECK_ 0 to revisit the old ways.) Resulting, under DEC UNIX, in the same memory being allocated to two different objects. Lots of debugging fun there...


More practically:

  • References hide that you are changing data stored someplace else.
  • It's easy to confuse a Reference with a Copied object.
  • Pointers make it obvious!

Passing 'this' to an onclick event

The code that you have would work, but is executed from the global context, which means that this refers to the global object.

<script type="text/javascript">
var foo = function(param) {
    param.innerHTML = "Not a button";
};
</script>
<button onclick="foo(this)" id="bar">Button</button>

You can also use the non-inline alternative, which attached to and executed from the specific element context which allows you to access the element from this.

<script type="text/javascript">
document.getElementById('bar').onclick = function() {
    this.innerHTML = "Not a button";
};
</script>
<button id="bar">Button</button>

Sublime Text 3, convert spaces to tabs

You can do replace tabs with spaces in all project files by:

  1. Doing a Replace all Ctrl+Shif+F
  2. Set regex search ^\A(.*)$
  3. Set directory to Your dir
  4. Replace by \1

    enter image description here

  5. This will cause all project files to be opened, with their buffer marked as dirty. With this, you can now optionally enable these next Sublime Text settings, to trim all files trailing white space and ensure a new line at the end of every file.

    You can enabled these settings by going on the menu Preferences -> Settings and adding these contents to your settings file:

    1. "ensure_newline_at_eof_on_save": true,
    2. "trim_trailing_white_space_on_save": true,
  6. Open the Sublime Text console, by going on the menu View -> Show Console (Ctrl+`) and run the command: import threading; threading.Thread( args=(set(),), target=lambda counterset: [ (view.run_command( "expand_tabs", {"set_translate_tabs": True} ), print( "Processing {:>5} view of {:>5}, view id {} {}".format( len( counterset ) + 1, len( window.views() ), view.id(), ( "Finished converting!" if len( counterset ) > len( window.views() ) - 2 else "" ) ) ), counterset.add( len( counterset ) ) ) for view in window.views() ] ).start()
  7. Now, save all changed files by going to the menu File -> Save All

Lost connection to MySQL server during query?

This was happening to me with mariadb because I made a varchar(255) column a unique key.. guess that's too heavy for a unique, as the insert was timing out.

Onclick CSS button effect

Push down the whole button. I suggest this it is looking nice in button.

#button:active {
    position: relative;
    top: 1px;
}

if you only want to push text increase top-padding and decrease bottom padding. You can also use line-height.

How to stop BackgroundWorker correctly

CancelAsync doesn't actually abort your thread or anything like that. It sends a message to the worker thread that work should be cancelled via BackgroundWorker.CancellationPending. Your DoWork delegate that is being run in the background must periodically check this property and handle the cancellation itself.

The tricky part is that your DoWork delegate is probably blocking, meaning that the work you do on your DataSource must complete before you can do anything else (like check for CancellationPending). You may need to move your actual work to yet another async delegate (or maybe better yet, submit the work to the ThreadPool), and have your main worker thread poll until this inner worker thread triggers a wait state, OR it detects CancellationPending.

http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.cancelasync.aspx

http://www.codeproject.com/KB/cpp/BackgroundWorker_Threads.aspx

Android Center text on canvas

Add these to your onDraw method:

paint.setColor(getContext().getResources().getColor(R.color.black));
paint.setTextAlign(Paint.Align.CENTER);
canvas.drawText("Text", (float) getHeight() / 2f, (float) getWidth() / 2f, paint);

Ruby combining an array into one string

Here's my solution:

@arr = ['<p>Hello World</p>', '<p>This is a test</p>']
@arr.reduce(:+)
=> <p>Hello World</p><p>This is a test</p>

Test for array of string type in TypeScript

You cannot test for string[] in the general case but you can test for Array quite easily the same as in JavaScript https://stackoverflow.com/a/767492/390330

If you specifically want for string array you can do something like:

if (Array.isArray(value)) {
   var somethingIsNotString = false;
   value.forEach(function(item){
      if(typeof item !== 'string'){
         somethingIsNotString = true;
      }
   })
   if(!somethingIsNotString && value.length > 0){
      console.log('string[]!');
   }
}

How to get a random number between a float range?

Most commonly, you'd use:

import random
random.uniform(a, b) # range [a, b) or [a, b] depending on floating-point rounding

Python provides other distributions if you need.

If you have numpy imported already, you can used its equivalent:

import numpy as np
np.random.uniform(a, b) # range [a, b)

Again, if you need another distribution, numpy provides the same distributions as python, as well as many additional ones.

Email validation using jQuery

Validate email while typing, with button state handling.

$("#email").on("input", function(){
    var email = $("#email").val();
    var filter = /^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
    if (!filter.test(email)) {
      $(".invalid-email:empty").append("Invalid Email Address");
      $("#submit").attr("disabled", true);
    } else {
      $("#submit").attr("disabled", false);
      $(".invalid-email").empty();
    }
  });

Android load from URL to Bitmap

very fast way , this method works very quickly:

private Bitmap getBitmap(String url) 
    {
        File f=fileCache.getFile(url);

        //from SD cache
        Bitmap b = decodeFile(f);
        if(b!=null)
            return b;

        //from web
        try {
            Bitmap bitmap=null;
            URL imageUrl = new URL(url);
            HttpURLConnection conn = (HttpURLConnection)imageUrl.openConnection();
            conn.setConnectTimeout(30000);
            conn.setReadTimeout(30000);
            conn.setInstanceFollowRedirects(true);
            InputStream is=conn.getInputStream();
            OutputStream os = new FileOutputStream(f);
            Utils.CopyStream(is, os);
            os.close();
            bitmap = decodeFile(f);
            return bitmap;
        } catch (Exception ex){
           ex.printStackTrace();
           return null;
        }
    }

    //decodes image and scales it to reduce memory consumption
    private Bitmap decodeFile(File f){
        try {
            //decode image size
            BitmapFactory.Options o = new BitmapFactory.Options();
            o.inJustDecodeBounds = true;
            BitmapFactory.decodeStream(new FileInputStream(f),null,o);

            //Find the correct scale value. It should be the power of 2.
            final int REQUIRED_SIZE=70;
            int width_tmp=o.outWidth, height_tmp=o.outHeight;
            int scale=1;
            while(true){
                if(width_tmp/2<REQUIRED_SIZE || height_tmp/2<REQUIRED_SIZE)
                    break;
                width_tmp/=2;
                height_tmp/=2;
                scale*=2;
            }

            //decode with inSampleSize
            BitmapFactory.Options o2 = new BitmapFactory.Options();
            o2.inSampleSize=scale;
            return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
        } catch (FileNotFoundException e) {}
        return null;
    }

How can I clone a JavaScript object except for one key?

Here are my two cents, on Typescript, slightly derived from @Paul's answer and using reduce instead.

function objectWithoutKey(object: object, keys: string[]) {
    return keys.reduce((previousValue, currentValue) => {
        // @ts-ignore
        const {[currentValue]: undefined, ...clean} = previousValue;
        return clean
    }, object)
}

// usage
console.log(objectWithoutKey({a: 1, b: 2, c: 3}, ['a', 'b']))

Centering controls within a form in .NET (Winforms)?

You can put the control you want to center inside a Panel and set the left and right padding values to something larger than the default. As long as they are equal and your control is anchored to the sides of the Panel, then it will appear centered in that Panel. Then you can anchor the container Panel to its parent as needed.

How can I select an element by name with jQuery?

Personally, what I've done in the past is give them a common class id and used that to select them. It may not be ideal as they have a class specified that may not exist, but it makes the selection a hell of a lot easier. Just make sure you're unique in your classnames.

i.e. for the example above I'd use your selection by class. Better still would be to change the class name from bold to 'tcol1', so you don't get any accidental inclusions into the jQuery results. If bold does actually refer to a CSS class, you can always specify both in the class property - i.e. 'class="tcol1 bold"'.

In summary, if you can't select by Name, either use a complicated jQuery selector and accept any related performance hit or use Class selectors.

You can always limit the jQuery scope by including the table name i.e. $('#tableID > .bold')

That should restrict jQuery from searching the "world".

Its could still be classed as a complicated selector, but it quickly constrains any searching to within the table with the ID of '#tableID', so keeps the processing to a minimum.

An alternative of this if you're looking for more than 1 element within #table1 would be to look this up separately and then pass it to jQuery as this limits the scope, but saves a bit of processing to look it up each time.

var tbl = $('#tableID');
var boldElements = $('.bold',tbl);
var rows = $('tr',tbl);
if (rows.length) {
   var row1 = rows[0]; 
   var firstRowCells = $('td',row1); 
}

Read contents of a local file into a variable in Rails

Answering my own question here... turns out it's a Windows only quirk that happens when reading binary files (in my case a JPEG) that requires an additional flag in the open or File.open function call. I revised it to open("/path/to/file", 'rb') {|io| a = a + io.read} and all was fine.

Difference between scaling horizontally and vertically for databases

The accepted answer is spot on the basic definition of horizontal vs vertical scaling. But unlike the common belief that horizontal scaling of databases is only possible with Cassandra, MongoDB, etc I would like to add that horizontal scaling is also very much possible with any traditional RDMS; that too without using any third party solutions.

I know of many companies, specially SaaS based companies that do this. This is done using simple application logic. You basically take a set of users and divide them over multiple DB servers. So for example, you would typically have a "meta" database/table that would store clients, DB server/connection strings, etc and a table that stores client/server mapping.

Then simply direct requests from each client to the DB server they are mapped to.

Now some may say this is akin to horizontal partitioning and not "true" horizontal scaling and they will be right in some ways. But the end result is that you have scaled your DB over multiple Db servers.

The only difference between the two approaches to horizontal scaling is that one approach (MongoDB, etc) the scaling is done by the DB software itself. In that sense you are "buying" the scaling. In the other approach (for RDBMS horizontal scaling), the scaling is built by application code/logic.

Buy vs Build

How to create permanent PowerShell Aliases

Open a Windows PowerShell window and type:

notepad $profile

Then create a function, such as:

function goSomewhereThenOpenGoogleThenDeleteSomething {
    cd C:\Users\
    Start-Process -FilePath "http://www.google.com"
    rm fileName.txt
}

Then type this under the function name:

Set-Alias google goSomewhereThenOpenGoogleThenDeleteSomething

Now you can type the word "google" into Windows PowerShell and have it execute the code within your function!

Using Excel as front end to Access database (with VBA)

If the end user has Access, it might be easier to develop the whole thing in Access. Access has some WYSIWYG form design tools built-in.

Declaring variables inside or outside of a loop

One solution to this problem could be to provide a variable scope encapsulating the while loop:

{
  // all tmp loop variables here ....
  // ....
  String str;
  while(condition){
      str = calculateStr();
      .....
  }
}

They would be automatically de-reference when the outer scope ends.

Submit form using <a> tag

Try this:

Suppose HTML like this :

   <form id="myform" name="myform" method="POST" action="process_edit_questionnaire.php?project=<?php echo $project_id; ?>">
      <div id="question_block">
            testing form
        </div>
     <a href="javascript: submit();">Submit</a>
        </form>

JS :

   <script type='text/javascript'>
     function submit()
      {
         document.forms["myform"].submit();
      }
   </script>

you can check it out here : http://jsfiddle.net/Zm426/7/

How to change sender name (not email address) when using the linux mail command for autosending mail?

You just need to add a From: header. By default there is none.

echo "Test" | mail -a "From: Someone <[email protected]>" [email protected]

You can add any custom headers using -a:

echo "Test" | mail -a "From: Someone <[email protected]>" \
                   -a "Subject: This is a test" \
                   -a "X-Custom-Header: yes" [email protected]

Import XXX cannot be resolved for Java SE standard classes

This is an issue relating JRE.In my case (eclipse Luna with Maven plugin, JDK 7) I solved this by making following change in pom.xml and then Maven Update Project.

from:

 <configuration>
        <source>1.8</source>
        <target>1.8</target>
</configuration>

to:

 <configuration>
        <source>1.7</source>
        <target>1.7</target>
</configuration>

Screenshot showing problem in JRE: enter image description here

Convert a bitmap into a byte array

Save the Image to a MemoryStream and then grab the byte array.

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

  Byte[] data;

  using (var memoryStream = new MemoryStream())
  {
    image.Save(memoryStream, ImageFormat.Bmp);

    data = memoryStream.ToArray();
  }

Writing a VLOOKUP function in vba

Have you tried:

Dim result As String 
Dim sheet As Worksheet 
Set sheet = ActiveWorkbook.Sheets("Data") 
result = Application.WorksheetFunction.VLookup(sheet.Range("AN2"), sheet.Range("AA9:AF20"), 5, False)

C++: constructor initializer for arrays

Only the default constructor can be called when creating objects in an array.

Seeking useful Eclipse Java code templates

My favorite few are...

1: Javadoc, to insert doc about the method being a Spring object injection method.

 Method to set the <code>I${enclosing_type}</code> implementation that this class will use.
* 
* @param ${enclosing_method_arguments}<code>I${enclosing_type}</code> instance 

2: Debug window, to create a FileOutputStream and write the buffer's content's to a file. Used for when you want to compare a buffer with a past run (using BeyondCompare), or if you can't view the contents of a buffer (via inspect) because its too large...

java.io.FileOutputStream fos = new java.io.FileOutputStream( new java.io.File("c:\\x.x"));
fos.write(buffer.toString().getBytes());
fos.flush();
fos.close();

Various ways to remove local Git changes

It all depends on exactly what you are trying to undo/revert. Start out by reading the post in Ube's link. But to attempt an answer:

Hard reset

git reset --hard [HEAD]

completely remove all staged and unstaged changes to tracked files.

I find myself often using hard resetting, when I'm like "just undo everything like if I had done a complete re-clone from the remote". In your case, where you just want your repo pristine, this would work.

Clean

git clean [-f]

Remove files that are not tracked.

For removing temporary files, but keep staged and unstaged changes to already tracked files. Most times, I would probably end up making an ignore-rule instead of repeatedly cleaning - e.g. for the bin/obj folders in a C# project, which you would usually want to exclude from your repo to save space, or something like that.

The -f (force) option will also remove files, that are not tracked and are also being ignored by git though ignore-rule. In the case above, with an ignore-rule to never track the bin/obj folders, even though these folders are being ignored by git, using the force-option will remove them from your file system. I've sporadically seen a use for this, e.g. when scripting deployment, and you want to clean your code before deploying, zipping or whatever.

Git clean will not touch files, that are already being tracked.

Checkout "dot"

git checkout .

I had actually never seen this notation before reading your post. I'm having a hard time finding documentation for this (maybe someone can help), but from playing around a bit, it looks like it means:

"undo all changes in my working tree".

I.e. undo unstaged changes in tracked files. It apparently doesn't touch staged changes and leaves untracked files alone.

Stashing

Some answers mention stashing. As the wording implies, you would probably use stashing when you are in the middle of something (not ready for a commit), and you have to temporarily switch branches or somehow work on another state of your code, later to return to your "messy desk". I don't see this applies to your question, but it's definitely handy.

To sum up

Generally, if you are confident you have committed and maybe pushed to a remote important changes, if you are just playing around or the like, using git reset --hard HEAD followed by git clean -f will definitively cleanse your code to the state, it would be in, had it just been cloned and checked out from a branch. It's really important to emphasize, that the resetting will also remove staged, but uncommitted changes. It will wipe everything that has not been committed (except untracked files, in which case, use clean).

All the other commands are there to facilitate more complex scenarios, where a granularity of "undoing stuff" is needed :)

I feel, your question #1 is covered, but lastly, to conclude on #2: the reason you never found the need to use git reset --hard was that you had never staged anything. Had you staged a change, neither git checkout . nor git clean -f would have reverted that.

Hope this covers.

StringLength vs MaxLength attributes ASP.NET MVC with Entity Framework EF Code First

MaxLengthAttribute means Max. length of array or string data allowed

StringLengthAttribute means Min. and max. length of characters that are allowed in a data field

Visit http://joeylicc.wordpress.com/2013/06/20/asp-net-mvc-model-validation-using-data-annotations/

Add to python path mac os x

Setting the $PYTHONPATH environment variable does not seem to affect the Spyder IDE's iPython terminals on a Mac. However, Spyder's application menu contains a "PYTHONPATH manager." Adding my path here solved my problem. The "PYTHONPATH manager" is also persistent across application restarts.

This is specific to a Mac, because setting the PYTHONPATH environment variable on my Windows PC gives the expected behavior (modules are found) without using the PYTHONPATH manager in Spyder.

How to handle the new window in Selenium WebDriver using Java?

I have a sample program for this:

public class BrowserBackForward {

/**
 * @param args
 * @throws InterruptedException 
 */
public static void main(String[] args) throws InterruptedException {
    WebDriver driver = new FirefoxDriver();
    driver.get("http://seleniumhq.org/");
    driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
    //maximize the window
    driver.manage().window().maximize();

    driver.findElement(By.linkText("Documentation")).click();
    System.out.println(driver.getCurrentUrl());
    driver.navigate().back();
    System.out.println(driver.getCurrentUrl());
    Thread.sleep(30000);
    driver.navigate().forward();
    System.out.println("Forward");
    Thread.sleep(30000);
    driver.navigate().refresh();

}

}

How to upgrade PowerShell version from 2.0 to 3.0

The latest PowerShell version as of Aug 2016 is PowerShell 5.1. It's bundled with Windows Management Framework 5.1.

Here's the download page for PowerShell 5.1 for all versions of Windows, including Windows 7 x64 and x86.

It is worth noting that PowerShell 5.1 is the first version available in two editions of "Desktop" and "Core". Powershell Core 6.x is cross-platform, its latest version for Jan 2019 is 6.1.2. It also works on Windows 7 SP1.

Server configuration by allow_url_fopen=0 in

Edit your php.ini, find allow_url_fopen and set it to allow_url_fopen = 1

GIT: Checkout to a specific folder

I defined an git alias to achieve just this (before I found this question).

It's a short bash function which saves the current path, switch to the git repo, does a checkout and return where it started.

git checkto develop ~/my_project_git

This e.g. would checkout the develop branch into "~/my_project_git" directory.

This is the alias code inside ~/.gitconfig:

[alias]
    checkTo = "!f(){ [ -z \"$1\" ] && echo \"Need to specify branch.\" && \
               exit 1; [ -z \"$2\" ] && echo \"Need to specify target\
               dir\" && exit 2; cDir=\"$(pwd)\"; cd \"$2\"; \
               git checkout \"$1\"; cd \"$cDir\"; };f"

Jquery/Ajax call with timer

If you want to set something on a timer, you can use JavaScript's setTimeout or setInterval methods:

setTimeout ( expression, timeout );
setInterval ( expression, interval );

Where expression is a function and timeout and interval are integers in milliseconds. setTimeout runs the timer once and runs the expression once whereas setInterval will run the expression every time the interval passes.

So in your case it would work something like this:

setInterval(function() {
    //call $.ajax here
}, 5000); //5 seconds

As far as the Ajax goes, see jQuery's ajax() method. If you run an interval, there is nothing stopping you from calling the same ajax() from other places in your code.


If what you want is for an interval to run every 30 seconds until a user initiates a form submission...and then create a new interval after that, that is also possible:

setInterval() returns an integer which is the ID of the interval.

var id = setInterval(function() {
    //call $.ajax here
}, 30000); // 30 seconds

If you store that ID in a variable, you can then call clearInterval(id) which will stop the progression.

Then you can reinstantiate the setInterval() call after you've completed your ajax form submission.

Change the size of a JTextField inside a JBorderLayout

Any component added to the GridLayout will be resized to the same size as the largest component added. If you want a component to remain at its preferred size, then wrap that component in a JPanel and then the panel will be resized:

JPanel displayPanel = new JPanel(new GridLayout(4, 2)); 
JTextField titleText = new JTextField("title"); 
JPanel wrapper = new JPanel( new FlowLayout(0, 0, FlowLayout.LEADING) );
wrapper.add( titleText );
displayPanel.add(wrapper); 
//displayPanel.add(titleText); 

Compile a DLL in C/C++, then call it from another program

There is but one difference. You have to take care or name mangling win C++. But on windows you have to take care about 1) decrating the functions to be exported from the DLL 2) write a so called .def file which lists all the exported symbols.

In Windows while compiling a DLL have have to use

__declspec(dllexport)

but while using it you have to write __declspec(dllimport)

So the usual way of doing that is something like

#ifdef BUILD_DLL
#define EXPORT __declspec(dllexport)
#else
#define EXPORT __declspec(dllimport)
#endif

The naming is a bit confusing, because it is often named EXPORT.. But that's what you'll find in most of the headers somwhere. So in your case you'd write (with the above #define)

int DLL_EXPORT add.... int DLL_EXPORT mult...

Remember that you have to add the Preprocessor directive BUILD_DLL during building the shared library.

Regards Friedrich

python max function using 'key' and lambda expression

max is built in function which takes first argument an iterable (like list or tuple)

keyword argument key has it's default value None but it accept function to evaluate, consider it as wrapper which evaluates iterable based on function

Consider this example dictionary:

d = {'aim':99, 'aid': 45, 'axe': 59, 'big': 9, 'short': 995, 'sin':12, 'sword':1, 'friend':1000, 'artwork':23}

Ex:

>>> max(d.keys())
'sword'

As you can see if you only pass the iterable without kwarg(a function to key) it is returning maximum value of key(alphabetically)

Ex. Instead of finding max value of key alphabetically you might need to find max key by length of key:

>>>max(d.keys(), key=lambda x: len(x))
'artwork'

in this example lambda function is returning length of key which will be iterated hence while evaluating values instead of considering alphabetically it will keep track of max length of key and returns key which has max length

Ex.

>>> max(d.keys(), key=lambda x: d[x])
'friend'

in this example lambda function is returning value of corresponding dictionary key which has maximum value

jQuery equivalent to Prototype array.last()

SugarJS

It's not jQuery but another library you may find useful in addition to jQuery: Try SugarJS.

Sugar is a Javascript library that extends native objects with helpful methods. It is designed to be intuitive, unobtrusive, and let you do more with less code.

With SugarJS, you can do:

[1,2,3,4].last()    //  => 4

That means, your example does work out of the box:

var array = [1,2,3,4];
var lastEl = array.last();    //  => 4

More Info

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.

Can't compile C program on a Mac after upgrade to Mojave

I tried almost all the posted solutions and nothing worked for me. I use Mojave OS (10.14.6) and what finally worked for me (after removing and re-installing Xcode and CLTs and SDK headers):

  1. Install Clang v8 from https://cran.r-project.org/bin/macosx/tools/
  2. Modify the following lines from ~/.R/Makevars file
CC=/usr/local/opt/llvm/bin/clang -fopenmp
CXX=/usr/local/opt/llvm/bin/clang++

with

CC=/usr/local/clang8/bin/clang -fopenmp
CXX=/usr/local/clang8/bin/clang++

Now R packages that rely on C compilers install successfully

Why is “while ( !feof (file) )” always wrong?

It's wrong because (in the absence of a read error) it enters the loop one more time than the author expects. If there is a read error, the loop never terminates.

Consider the following code:

/* WARNING: demonstration of bad coding technique!! */

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

FILE *Fopen(const char *path, const char *mode);

int main(int argc, char **argv)
{
    FILE *in;
    unsigned count;

    in = argc > 1 ? Fopen(argv[1], "r") : stdin;
    count = 0;

    /* WARNING: this is a bug */
    while( !feof(in) ) {  /* This is WRONG! */
        fgetc(in);
        count++;
    }
    printf("Number of characters read: %u\n", count);
    return EXIT_SUCCESS;
}

FILE * Fopen(const char *path, const char *mode)
{
    FILE *f = fopen(path, mode);
    if( f == NULL ) {
        perror(path);
        exit(EXIT_FAILURE);
    }
    return f;
}

This program will consistently print one greater than the number of characters in the input stream (assuming no read errors). Consider the case where the input stream is empty:

$ ./a.out < /dev/null
Number of characters read: 1

In this case, feof() is called before any data has been read, so it returns false. The loop is entered, fgetc() is called (and returns EOF), and count is incremented. Then feof() is called and returns true, causing the loop to abort.

This happens in all such cases. feof() does not return true until after a read on the stream encounters the end of file. The purpose of feof() is NOT to check if the next read will reach the end of file. The purpose of feof() is to determine the status of a previous read function and distinguish between an error condition and the end of the data stream. If fread() returns 0, you must use feof/ferror to decide whether an error occurred or if all of the data was consumed. Similarly if fgetc returns EOF. feof() is only useful after fread has returned zero or fgetc has returned EOF. Before that happens, feof() will always return 0.

It is always necessary to check the return value of a read (either an fread(), or an fscanf(), or an fgetc()) before calling feof().

Even worse, consider the case where a read error occurs. In that case, fgetc() returns EOF, feof() returns false, and the loop never terminates. In all cases where while(!feof(p)) is used, there must be at least a check inside the loop for ferror(), or at the very least the while condition should be replaced with while(!feof(p) && !ferror(p)) or there is a very real possibility of an infinite loop, probably spewing all sorts of garbage as invalid data is being processed.

So, in summary, although I cannot state with certainty that there is never a situation in which it may be semantically correct to write "while(!feof(f))" (although there must be another check inside the loop with a break to avoid a infinite loop on a read error), it is the case that it is almost certainly always wrong. And even if a case ever arose where it would be correct, it is so idiomatically wrong that it would not be the right way to write the code. Anyone seeing that code should immediately hesitate and say, "that's a bug". And possibly slap the author (unless the author is your boss in which case discretion is advised.)

<code> vs <pre> vs <samp> for inline and block code snippets

Consider Prism.js: https://prismjs.com/#examples

It makes <pre><code> work and is attractive.

Open images? Python

if location == a2:
    img = Image.open("picture.jpg")
    Img.show

Make sure the name of the image is in parantheses this should work

Is it possible to decompile a compiled .pyc file into a .py file?

Yes, it is possible.

There is a perfect open-source Python (.PYC) decompiler, called Decompyle++ https://github.com/zrax/pycdc/

Decompyle++ aims to translate compiled Python byte-code back into valid and human-readable Python source code. While other projects have achieved this with varied success, Decompyle++ is unique in that it seeks to support byte-code from any version of Python.

How can I count the rows with data in an Excel sheet?

With formulas, what you can do is:

  • in a new column (say col D - cell D2), add =COUNTA(A2:C2)
  • drag this formula till the end of your data (say cell D4 in our example)
  • add a last formula to sum it up (e.g in cell D5): =SUM(D2:D4)

What key in windows registry disables IE connection parameter "Automatically Detect Settings"?

I think you can change the "Automatically detect settings" via the registry key name "AutoConfigURL". here is the code that I check in c#. Wish you luck.

    RegistryKey registry = Registry.CurrentUser.OpenSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings", true);
                    if(registry.GetValue("AutoConfigURL") != null)
                    {
                        //Proxy Server disabled (Untick Proxy Server)
                        registry.DeleteValue("AutoConfigURL");
                    }

Simplest SOAP example

Simplest example would consist of:

  1. Getting user input.
  2. Composing XML SOAP message similar to this

    <soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                   xmlns:xsd="http://www.w3.org/2001/XMLSchema"
                   xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
      <soap:Body>
        <GetInfoByZIP xmlns="http://www.webserviceX.NET">
          <USZip>string</USZip>
        </GetInfoByZIP>
      </soap:Body>
    </soap:Envelope>
    
  3. POSTing message to webservice url using XHR

  4. Parsing webservice's XML SOAP response similar to this

    <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"
                   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                   xmlns:xsd="http://www.w3.org/2001/XMLSchema">
     <soap:Body>
      <GetInfoByZIPResponse xmlns="http://www.webserviceX.NET">
       <GetInfoByZIPResult>
        <NewDataSet xmlns="">
         <Table>
          <CITY>...</CITY>
          <STATE>...</STATE>
          <ZIP>...</ZIP>
          <AREA_CODE>...</AREA_CODE>
          <TIME_ZONE>...</TIME_ZONE>
         </Table>
        </NewDataSet>
       </GetInfoByZIPResult>
      </GetInfoByZIPResponse>
     </soap:Body>
    </soap:Envelope>
    
  5. Presenting results to user.

But it's a lot of hassle without external JavaScript libraries.

Icons missing in jQuery UI

you have workaround by setting background color instead of this missing icon. Here are the steps to follow:

  • open relevant 'jquery-ui-x.-.x.css' file
  • search for the missing file name in css file(eg: ui-bg_flat_75_ffffff_40x100.png")
  • Remove/comment the line that calls this background image
  • instead add the following line to replace the background color 'background-color: #ffffff'

That will probably work

Convert an enum to List<string>

Use Enum's static method, GetNames. It returns a string[], like so:

Enum.GetNames(typeof(DataSourceTypes))

If you want to create a method that does only this for only one type of enum, and also converts that array to a List, you can write something like this:

public List<string> GetDataSourceTypes()
{
    return Enum.GetNames(typeof(DataSourceTypes)).ToList();
}

You will need Using System.Linq; at the top of your class to use .ToList()