Programs & Examples On #Fixed length file

how to make a specific text on TextView BOLD

While you can use Html.fromHtml() you can use a more native approach which is SpannableStringBuilder , this post may be helful.

SpannableStringBuilder str = new SpannableStringBuilder("Your awesome text");
str.setSpan(new android.text.style.StyleSpan(android.graphics.Typeface.BOLD), INT_START, INT_END, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
TextView tv=new TextView(context);
tv.setText(str);

Spring configure @ResponseBody JSON format

AngerClown pointed me to the right direction.

This is what I finally did, just in case anyone find it useful.

<bean
    class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
    <property name="messageConverters">
        <list>
            <bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
                <property name="objectMapper" ref="jacksonObjectMapper" />
            </bean>
        </list>
    </property>
</bean>

<!-- jackson configuration : https://stackoverflow.com/questions/3661769 -->
<bean id="jacksonObjectMapper" class="org.codehaus.jackson.map.ObjectMapper" />
<bean id="jacksonSerializationConfig" class="org.codehaus.jackson.map.SerializationConfig"
    factory-bean="jacksonObjectMapper" factory-method="getSerializationConfig" />
<bean
    class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
    <property name="targetObject" ref="jacksonSerializationConfig" />
    <property name="targetMethod" value="setSerializationInclusion" />
    <property name="arguments">
        <list>
            <value type="org.codehaus.jackson.map.annotate.JsonSerialize.Inclusion">NON_DEFAULT</value>
        </list>
    </property>
</bean>

I still have to figure out how to configure the other properties such as:

om.configure(JsonGenerator.Feature.QUOTE_FIELD_NAMES, true);

Converting Long to Date in Java returns 1970

The long values, most likely, correspond to Epoch timestamps, and the values are:

1220227200 = Mon, 01 Sep 2008 00:00:00 GMT

1220832000 = Mon, 08 Sep 2008 00:00:00 GMT

1221436800 = Mon, 15 Sep 2008 00:00:00 GMT

One can convert these long values to java.util.Date, taking into account the fact java.util.Date uses millisecs – as previously hinted, but with some flaw - like this:

// note: enforcing long literals (L), without it the values would just be wrong.
Date date = new Date(1220227200L * 1000L); 

Now, to display the date correctly, one can use java.text.DateFormat as illustrated hereafter:

DateFormat df = DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL);
df.setTimeZone(TimeZone.getTimeZone("UTC"));
System.out.println("Wrong date time value: " + date);
System.out.println("Correct date time value: " + df.format(date));

Below are the results of displaying the converted long value to java.util.Date without using and using the DateFormat:

Date wrong (off by 2 hours): Mon Sep 01 02:00:00 CEST 2008
Correct date : Monday, 1 September 2008 00:00:00 o'clock UTC

Should I use .done() and .fail() for new jQuery AJAX code instead of success and error

When we are going to migrate JQuery from 1.x to 2x or 3.x in our old existing application , then we will use .done,.fail instead of success,error as JQuery up gradation is going to be deprecated these methods.For example when we make a call to server web methods then server returns promise objects to the calling methods(Ajax methods) and this promise objects contains .done,.fail..etc methods.Hence we will the same for success and failure response. Below is the example(it is for POST request same way we can construct for request type like GET...)

 $.ajax({
            type: "POST",
            url: url,
            data: '{"name" :"sheo"}',
            contentType: "application/json; charset=utf-8",
            async: false,
            cache: false
            }).done(function (Response) {
                  //do something when get response            })
           .fail(function (Response) {
                    //do something when any error occurs.
                });

SSL cert "err_cert_authority_invalid" on mobile chrome only

I hope i am not too late, this solution here worked for me, i am using COMODO SSL, the above solutions seem invalid over time, my website lifetanstic.co.ke

Instead of contacting Comodo Support and gain a CA bundle file You can do the following:

When You get your new SSL cert from Comodo (by mail) they have a zip file attached. You need to unzip the zip-file and open the following files in a text editor like notepad:

AddTrustExternalCARoot.crt
COMODORSAAddTrustCA.crt
COMODORSADomainValidationSecureServerCA.crt

Then copy the text of each ".crt" file and paste the texts above eachother in the "Certificate Authority Bundle (optional)" field.

After that just add the SSL cert as usual in the "Certificate" field and click at "Autofil by Certificate" button and hit "Install".

Inspired by this gist: https://gist.github.com/ipedrazas/6d6c31144636d586dcc3

alternatives to REPLACE on a text or ntext datatype

Assuming SQL Server 2000, the following StackOverflow question should address your problem.

If using SQL Server 2005/2008, you can use the following code (taken from here):

select cast(replace(cast(myntext as nvarchar(max)),'find','replace') as ntext)
from myntexttable

AngularJS Uploading An Image With ng-upload

You can try ng-file-upload angularjs plugin (instead of ng-upload).

It's fairly easy to setup and deal with angularjs specifics. It also supports progress, cancel, drag and drop and is cross browser.

html

<!-- Note: MUST BE PLACED BEFORE angular.js-->
<script src="ng-file-upload-shim.min.js"></script> 
<script src="angular.min.js"></script>
<script src="ng-file-upload.min.js"></script> 

<div ng-controller="MyCtrl">
  <input type="file" ngf-select="onFileSelect($files)" multiple>
</div>

JS:

//inject angular file upload directives and service.
angular.module('myApp', ['ngFileUpload']);

var MyCtrl = [ '$scope', '$upload', function($scope, $upload) {
  $scope.onFileSelect = function($files) {
    //$files: an array of files selected, each file has name, size, and type.
    for (var i = 0; i < $files.length; i++) {
      var file = $files[i];
      $scope.upload = $upload.upload({
        url: 'server/upload/url', //upload.php script, node.js route, or servlet url
        data: {myObj: $scope.myModelObj},
        file: file,
      }).progress(function(evt) {
        console.log('percent: ' + parseInt(100.0 * evt.loaded / evt.total));
      }).then(function(response) {
        var data = response.data;
        // file is uploaded successfully
        console.log(data);
      });
    }
  };
}];

Java error: Implicit super constructor is undefined for default constructor

I had this error and fixed it by removing a thrown exception from beside the method to a try/catch block

For example: FROM:

public static HashMap<String, String> getMap() throws SQLException
{

}

TO:

public static Hashmap<String,String> getMap()
{
  try{

  }catch(SQLException)
  { 
  }
}

Delete all files in directory (but not directory) - one liner solution

public class DeleteFile {
    public static void main(String[] args) {
        String path="D:\test"; 
        File file = new File(path);
        File[] files = file.listFiles(); 
        for (File f:files) 
        {if (f.isFile() && f.exists) 
            { f.delete();
system.out.println("successfully deleted");
            }else{
system.out.println("cant delete a file due to open or error");
} }  }}

Sites not accepting wget user agent header

It seems Yahoo server does some heuristic based on User-Agent in a case Accept header is set to */*.

Accept: text/html

did the trick for me.

e.g.

wget  --header="Accept: text/html" --user-agent="Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:21.0) Gecko/20100101 Firefox/21.0"  http://yahoo.com

Note: if you don't declare Accept header then wget automatically adds Accept:*/* which means give me anything you have.

How to add style from code behind?

try this

 lblMsg.Text = @"Your search result for <b style=""color:green;"">" + txtCode.Text.Trim() + "</b> ";

Where to find extensions installed folder for Google Chrome on Mac?

They are found on either one of the below locations depending on how chrome was installed

  • When chrome is installed at the user level, it's located at:

~/Users/<username>/Library/Application\ Support/Google/Chrome/Default/Extensions

  • When installed at the root level, it's at:

/Library/Application\ Support/Google/Chrome/Default/Extensions

How to create a self-signed certificate with OpenSSL

Am I missing something? Is this the correct way to build a self-signed certificate?

It's easy to create a self-signed certificate. You just use the openssl req command. It can be tricky to create one that can be consumed by the largest selection of clients, like browsers and command line tools.

It's difficult because the browsers have their own set of requirements, and they are more restrictive than the IETF. The requirements used by browsers are documented at the CA/Browser Forums (see references below). The restrictions arise in two key areas: (1) trust anchors, and (2) DNS names.

Modern browsers (like the warez we're using in 2014/2015) want a certificate that chains back to a trust anchor, and they want DNS names to be presented in particular ways in the certificate. And browsers are actively moving against self-signed server certificates.

Some browsers don't exactly make it easy to import a self-signed server certificate. In fact, you can't with some browsers, like Android's browser. So the complete solution is to become your own authority.

In the absence of becoming your own authority, you have to get the DNS names right to give the certificate the greatest chance of success. But I would encourage you to become your own authority. It's easy to become your own authority, and it will sidestep all the trust issues (who better to trust than yourself?).


This is probably not the site you are looking for!
The site's security certificate is not trusted!

This is because browsers use a predefined list of trust anchors to validate server certificates. A self-signed certificate does not chain back to a trusted anchor.

The best way to avoid this is:

  1. Create your own authority (i.e., become a CA)
  2. Create a certificate signing request (CSR) for the server
  3. Sign the server's CSR with your CA key
  4. Install the server certificate on the server
  5. Install the CA certificate on the client

Step 1 - Create your own authority just means to create a self-signed certificate with CA: true and proper key usage. That means the Subject and Issuer are the same entity, CA is set to true in Basic Constraints (it should also be marked as critical), key usage is keyCertSign and crlSign (if you are using CRLs), and the Subject Key Identifier (SKI) is the same as the Authority Key Identifier (AKI).

To become your own certificate authority, see *How do you sign a certificate signing request with your certification authority? on Stack Overflow. Then, import your CA into the Trust Store used by the browser.

Steps 2 - 4 are roughly what you do now for a public facing server when you enlist the services of a CA like Startcom or CAcert. Steps 1 and 5 allows you to avoid the third-party authority, and act as your own authority (who better to trust than yourself?).

The next best way to avoid the browser warning is to trust the server's certificate. But some browsers, like Android's default browser, do not let you do it. So it will never work on the platform.

The issue of browsers (and other similar user agents) not trusting self-signed certificates is going to be a big problem in the Internet of Things (IoT). For example, what is going to happen when you connect to your thermostat or refrigerator to program it? The answer is, nothing good as far as the user experience is concerned.

The W3C's WebAppSec Working Group is starting to look at the issue. See, for example, Proposal: Marking HTTP As Non-Secure.


How to create a self-signed certificate with OpenSSL

The commands below and the configuration file create a self-signed certificate (it also shows you how to create a signing request). They differ from other answers in one respect: the DNS names used for the self signed certificate are in the Subject Alternate Name (SAN), and not the Common Name (CN).

The DNS names are placed in the SAN through the configuration file with the line subjectAltName = @alternate_names (there's no way to do it through the command line). Then there's an alternate_names section in the configuration file (you should tune this to suit your taste):

[ alternate_names ]

DNS.1       = example.com
DNS.2       = www.example.com
DNS.3       = mail.example.com
DNS.4       = ftp.example.com

# Add these if you need them. But usually you don't want them or
#   need them in production. You may need them for development.
# DNS.5       = localhost
# DNS.6       = localhost.localdomain
# IP.1        = 127.0.0.1
# IP.2        = ::1

It's important to put DNS name in the SAN and not the CN, because both the IETF and the CA/Browser Forums specify the practice. They also specify that DNS names in the CN are deprecated (but not prohibited). If you put a DNS name in the CN, then it must be included in the SAN under the CA/B policies. So you can't avoid using the Subject Alternate Name.

If you don't do put DNS names in the SAN, then the certificate will fail to validate under a browser and other user agents which follow the CA/Browser Forum guidelines.

Related: browsers follow the CA/Browser Forum policies; and not the IETF policies. That's one of the reasons a certificate created with OpenSSL (which generally follows the IETF) sometimes does not validate under a browser (browsers follow the CA/B). They are different standards, they have different issuing policies and different validation requirements.


Create a self signed certificate (notice the addition of -x509 option):

openssl req -config example-com.conf -new -x509 -sha256 -newkey rsa:2048 -nodes \
    -keyout example-com.key.pem -days 365 -out example-com.cert.pem

Create a signing request (notice the lack of -x509 option):

openssl req -config example-com.conf -new -sha256 -newkey rsa:2048 -nodes \
    -keyout example-com.key.pem -days 365 -out example-com.req.pem

Print a self-signed certificate:

openssl x509 -in example-com.cert.pem -text -noout

Print a signing request:

openssl req -in example-com.req.pem -text -noout

Configuration file (passed via -config option)

[ req ]
default_bits        = 2048
default_keyfile     = server-key.pem
distinguished_name  = subject
req_extensions      = req_ext
x509_extensions     = x509_ext
string_mask         = utf8only

# The Subject DN can be formed using X501 or RFC 4514 (see RFC 4519 for a description).
#   Its sort of a mashup. For example, RFC 4514 does not provide emailAddress.
[ subject ]
countryName         = Country Name (2 letter code)
countryName_default     = US

stateOrProvinceName     = State or Province Name (full name)
stateOrProvinceName_default = NY

localityName            = Locality Name (eg, city)
localityName_default        = New York

organizationName         = Organization Name (eg, company)
organizationName_default    = Example, LLC

# Use a friendly name here because it's presented to the user. The server's DNS
#   names are placed in Subject Alternate Names. Plus, DNS names here is deprecated
#   by both IETF and CA/Browser Forums. If you place a DNS name here, then you
#   must include the DNS name in the SAN too (otherwise, Chrome and others that
#   strictly follow the CA/Browser Baseline Requirements will fail).
commonName          = Common Name (e.g. server FQDN or YOUR name)
commonName_default      = Example Company

emailAddress            = Email Address
emailAddress_default        = [email protected]

# Section x509_ext is used when generating a self-signed certificate. I.e., openssl req -x509 ...
[ x509_ext ]

subjectKeyIdentifier        = hash
authorityKeyIdentifier    = keyid,issuer

# You only need digitalSignature below. *If* you don't allow
#   RSA Key transport (i.e., you use ephemeral cipher suites), then
#   omit keyEncipherment because that's key transport.
basicConstraints        = CA:FALSE
keyUsage            = digitalSignature, keyEncipherment
subjectAltName          = @alternate_names
nsComment           = "OpenSSL Generated Certificate"

# RFC 5280, Section 4.2.1.12 makes EKU optional
#   CA/Browser Baseline Requirements, Appendix (B)(3)(G) makes me confused
#   In either case, you probably only need serverAuth.
# extendedKeyUsage    = serverAuth, clientAuth

# Section req_ext is used when generating a certificate signing request. I.e., openssl req ...
[ req_ext ]

subjectKeyIdentifier        = hash

basicConstraints        = CA:FALSE
keyUsage            = digitalSignature, keyEncipherment
subjectAltName          = @alternate_names
nsComment           = "OpenSSL Generated Certificate"

# RFC 5280, Section 4.2.1.12 makes EKU optional
#   CA/Browser Baseline Requirements, Appendix (B)(3)(G) makes me confused
#   In either case, you probably only need serverAuth.
# extendedKeyUsage    = serverAuth, clientAuth

[ alternate_names ]

DNS.1       = example.com
DNS.2       = www.example.com
DNS.3       = mail.example.com
DNS.4       = ftp.example.com

# Add these if you need them. But usually you don't want them or
#   need them in production. You may need them for development.
# DNS.5       = localhost
# DNS.6       = localhost.localdomain
# DNS.7       = 127.0.0.1

# IPv6 localhost
# DNS.8     = ::1

You may need to do the following for Chrome. Otherwise Chrome may complain a Common Name is invalid (ERR_CERT_COMMON_NAME_INVALID). I'm not sure what the relationship is between an IP address in the SAN and a CN in this instance.

# IPv4 localhost
# IP.1       = 127.0.0.1

# IPv6 localhost
# IP.2     = ::1

There are other rules concerning the handling of DNS names in X.509/PKIX certificates. Refer to these documents for the rules:

RFC 6797 and RFC 7469 are listed, because they are more restrictive than the other RFCs and CA/B documents. RFCs 6797 and 7469 do not allow an IP address, either.

How to Convert Datetime to Date in dd/MM/yyyy format

Give a different alias

SELECT  Convert(varchar,A.InsertDate,103) as converted_Tran_Date from table as A
order by A.InsertDate 

Oracle query to fetch column names

The below query worked for me in Oracle database.

select COLUMN_NAME from ALL_TAB_COLUMNS where TABLE_NAME='MyTableName';

Switch to another Git tag

Clone the repository as normal:

git clone git://github.com/rspec/rspec-tmbundle.git RSpec.tmbundle

Then checkout the tag you want like so:

git checkout tags/1.1.4

This will checkout out the tag in a 'detached HEAD' state. In this state, "you can look around, make experimental changes and commit them, and [discard those commits] without impacting any branches by performing another checkout".

To retain any changes made, move them to a new branch:

git checkout -b 1.1.4-jspooner

You can get back to the master branch by using:

git checkout master

Note, as was mentioned in the first revision of this answer, there is another way to checkout a tag:

git checkout 1.1.4

But as was mentioned in a comment, if you have a branch by that same name, this will result in git warning you that the refname is ambiguous and checking out the branch by default:

warning: refname 'test' is ambiguous.
Switched to branch '1.1.4'

The shorthand can be safely used if the repository does not share names between branches and tags.

What is the point of "Initial Catalog" in a SQL Server connection string?

If the user name that is in the connection string has access to more then one database you have to specify the database you want the connection string to connect to. If your user has only one database available then you are correct that it doesn't matter. But it is good practice to put this in your connection string.

How to make HTTP Post request with JSON body in Swift

Swift4 - Apple Solution "POST" and "Codable"

Uploading Data to a Website using request.httpmethod = "Post" and Codable Stucts:

@see: Listing 2 Configuring a URL request

let userlogin = User(username: username, password: password, deviceid:UIDevice.current.identifierForVendor!.uuidString)

    guard let uploadData = try? JSONEncoder().encode(userlogin) else {
        print("Error UploadData: ")
        return
    }

    let urlUser = URL(string: APPURL.apiURL)!

    var request = URLRequest(url: urlUser)
    request.httpMethod = "POST"
    request.setValue("application/json", forHTTPHeaderField: "Content-Type")

    var responseStatus = 0

    let task = URLSession.shared.uploadTask(with: request, from: uploadData) { data, response, error in
        if let error = error {
            let code = (error as NSError).code
            print("Error:\(code) : \(error.localizedDescription)")
            completion(code)
            return
        }  
      guard let response = response as? HTTPURLResponse else {
            print("Invalid response")
            return
        }
// do your response handling here ...

Regular expression for excluding special characters

I would just white list the characters.

^[a-zA-Z0-9äöüÄÖÜ]*$

Building a black list is equally simple with regex but you might need to add much more characters - there are a lot of Chinese symbols in unicode ... ;)

^[^<>%$]*$

The expression [^(many characters here)] just matches any character that is not listed.

What is the difference between Forking and Cloning on GitHub?

Another weird subtle difference on GitHub is that changes to forks are not counted in your activity log until your changes are pulled into the original repo. What's more, to change a fork into a proper clone, you have to contact Github support, apparently.

From Why are my contributions not showing up:

Commit was made in a fork

Commits made in a fork will not count toward your contributions. To make them count, you must do one of the following:

Open a pull request to have your changes merged into the parent repository. To detach the fork and turn it into a standalone repository on GitHub, contact GitHub Support. If the fork has forks of its own, let support know if the forks should move with your repository into a new network or remain in the current network. For more information, see "About forks."

How to detect a route change in Angular?

simple answer for Angular 8.*

constructor(private route:ActivatedRoute) {
  console.log(route);
}

What GRANT USAGE ON SCHEMA exactly do?

For a production system, you can use this configuration :

--ACCESS DB
REVOKE CONNECT ON DATABASE nova FROM PUBLIC;
GRANT  CONNECT ON DATABASE nova  TO user;

--ACCESS SCHEMA
REVOKE ALL     ON SCHEMA public FROM PUBLIC;
GRANT  USAGE   ON SCHEMA public  TO user;

--ACCESS TABLES
REVOKE ALL ON ALL TABLES IN SCHEMA public FROM PUBLIC ;
GRANT SELECT                         ON ALL TABLES IN SCHEMA public TO read_only ;
GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA public TO read_write ;
GRANT ALL                            ON ALL TABLES IN SCHEMA public TO admin ;

Is an empty href valid?

It is valid.

However, standard practice is to use href="#" or sometimes href="javascript:;".

How to show an alert box in PHP?

When I just run this as a page

<?php
echo '<script language="javascript">';
echo 'alert("message successfully sent")';
echo '</script>';
exit;

it works fine.

What version of PHP are you running?

Could you try echoing something else after: $testObject->split_for_sms($Chat);

Maybe it doesn't get to that part of the code? You could also try these with the other function calls to check where your program stops/is getting to.

Hope you get a bit further with this.

sudo: docker-compose: command not found

If docker-compose is installed for your user but not installed for root user and if you need to run it only once and forget about it afterwords perform the next actions:

  • Find out path to docker-compose:

      which docker-compose
    
  • Run the command specifying full path to docker-compose from the previous command, eg:

      sudo /home/your-user/your-path-to-compose/docker-compose up
    

Python-Requests close http connection

I came to this question looking to solve the "too many open files" error, but I am using requests.session() in my code. A few searches later and I came up with an answer on the Python Requests Documentation which suggests to use the with block so that the session is closed even if there are unhandled exceptions:

with requests.Session() as s:
    s.get('http://google.com')

If you're not using Session you can actually do the same thing: https://2.python-requests.org/en/master/user/advanced/#session-objects

with requests.get('http://httpbin.org/get', stream=True) as r:
    # Do something

SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens on line 102

You didn't bind all your bindings here

$sql = "SELECT SQL_CALC_FOUND_ROWS *, UNIX_TIMESTAMP(publicationDate) AS publicationDate     FROM comments WHERE articleid = :art 
ORDER BY " . mysqli_escape_string($order) . " LIMIT :numRows";

$st = $conn->prepare( $sql );
$st->bindValue( ":art", $art, PDO::PARAM_INT );

You've declared a binding called :numRows but you never actually bind anything to it.

UPDATE 2019: I keep getting upvotes on this and that reminded me of another suggestion

Double quotes are string interpolation in PHP, so if you're going to use variables in a double quotes string, it's pointless to use the concat operator. On the flip side, single quotes are not string interpolation, so if you've only got like one variable at the end of a string it can make sense, or just use it for the whole string.

In fact, there's a micro op available here since the interpreter doesn't care about parsing the string for variables. The boost is nearly unnoticable and totally ignorable on a small scale. However, in a very large application, especially good old legacy monoliths, there can be a noticeable performance increase if strings are used like this. (and IMO, it's easier to read anyway)

NameError: uninitialized constant (rails)

In my case, I named a column name type and tried to set its value as UNPREPARED. And I got an error message like this:

Caused by: api_1 | NameError: uninitialized constant UNPREPARED

In rails, column type is reserved:

ActiveRecord::SubclassNotFound: The single-table inheritance mechanism failed to locate the subclass: 'UNPREPARED'. This error is raised because the column 'type' is reserved for storing the class in case of inheritance. Pl ease rename this column if you didn't intend it to be used for storing the inheritance class or overwrite Food.inheritance_column to use another column for that information

Laravel eloquent update record without loading from database

Post::where('id',3)->update(['title'=>'Updated title']);

How to set width and height dynamically using jQuery

Try this:

<div id="mainTable" style="width:100px; height:200px;"></div> 

$(document).ready(function() {
  $("#mainTable").width(100).height(200);
}) ;

How to leave space in HTML

If you want to leave blank space in HTML while editing the website just use <br /> and copy-paste it under the last one and keep going like that until you have enough space. Hope it helps.

How do I calculate the normal vector of a line segment?

Another way to think of it is to calculate the unit vector for a given direction and then apply a 90 degree counterclockwise rotation to get the normal vector.

The matrix representation of the general 2D transformation looks like this:

x' = x cos(t) - y sin(t)
y' = x sin(t) + y cos(t)

where (x,y) are the components of the original vector and (x', y') are the transformed components.

If t = 90 degrees, then cos(90) = 0 and sin(90) = 1. Substituting and multiplying it out gives:

x' = -y
y' = +x

Same result as given earlier, but with a little more explanation as to where it comes from.

Replace transparency in PNG images with white background

To actually remove the alpha channel from the file, use the alpha off option:

convert in.png -background white -alpha off out.png

How can I revert a single file to a previous version?

Git is very flexible. You shouldn't need hundreds of branches to do what you are asking. If you want to revert the state all the way back to the 2nd change (and it is indeed a change that was already committed and pushed), use git revert. Something like:

git revert a4r9593432 

where a4r9593432 is the starting characters of the hash of the commit you want to back out.

If the commit contains changes to many files, but you just want to revert just one of the files, you can use git reset (the 2nd or 3rd form):

git reset a4r9593432 -- path/to/file.txt
# the reverted state is added to the staging area, ready for commit
git diff --cached path/to/file.txt        # view the changes
git commit
git checkout HEAD path/to/file.txt        # make the working tree match HEAD           

But this is pretty complex, and git reset is dangerous. Use git checkout <hash> <file path> instead, as Jefromi suggests.

If you just want to view what the file looked like in commit x, you can use git show:

git show a4r9593432:path/to/file.txt

For all of the commands, there are many ways to refer to a commit other than via the commit hash (see Naming Commits in the Git User Manual).

Creating a triangle with for loops

  for (int i=0; i<6; i++)
  {
     for (int k=0; k<6-i; k++)
     {
        System.out.print(" ");
     }
     for (int j=0; j<i*2+1; j++)
     {
        System.out.print("*");
     }
     System.out.println("");
  }

SQL Server datetime LIKE select?

I solved my problem that way. Thank you for suggestions for improvements. Example in C#.

string dd, mm, aa, trc, data;
dd = nData.Text.Substring(0, 2);
mm = nData.Text.Substring(3, 2);
aa = nData.Text.Substring(6, 4);
trc = "-";
data = aa + trc + mm + trc + dd;

"Select * From bdPedidos Where Data Like '%" + data + "%'";

Return 0 if field is null in MySQL

None of the above answers were complete for me. If your field is named field, so the selector should be the following one:

IFNULL(`field`,0) AS field

For example in a SELECT query:

SELECT IFNULL(`field`,0) AS field, `otherfield` FROM `mytable`

Hope this can help someone to not waste time.

.htaccess - how to force "www." in a generic way?

this worked like magic for me

RewriteCond %{HTTP_HOST} ^sitename.com [NC] RewriteRule ^(.*)$ https://www.sitename.com/$1 [L,R=301,NC]

Delete last char of string

As an alternate to adding a comma for each item you could just using String.Join:

var strgroupids = String.Join(",",  groupIds);

This will add the seperator ("," in this instance) between each element in the array.

Declaring functions in JSP?

You need to enclose that in <%! %> as follows:

<%!

public String getQuarter(int i){
String quarter;
switch(i){
        case 1: quarter = "Winter";
        break;

        case 2: quarter = "Spring";
        break;

        case 3: quarter = "Summer I";
        break;

        case 4: quarter = "Summer II";
        break;

        case 5: quarter = "Fall";
        break;

        default: quarter = "ERROR";
}

return quarter;
}

%>

You can then invoke the function within scriptlets or expressions:

<%
     out.print(getQuarter(4));
%>

or

<%= getQuarter(17) %>

What is the difference between & vs @ and = in angularJS

Not my fiddle, but http://jsfiddle.net/maxisam/QrCXh/ shows the difference. The key piece is:

           scope:{
            /* NOTE: Normally I would set my attributes and bindings
            to be the same name but I wanted to delineate between 
            parent and isolated scope. */                
            isolatedAttributeFoo:'@attributeFoo',
            isolatedBindingFoo:'=bindingFoo',
            isolatedExpressionFoo:'&'
        }        

How to manually force a commit in a @Transactional method?

I know that due to this ugly anonymous inner class usage of TransactionTemplate doesn't look nice, but when for some reason we want to have a test method transactional IMHO it is the most flexible option.

In some cases (it depends on the application type) the best way to use transactions in Spring tests is a turned-off @Transactional on the test methods. Why? Because @Transactional may leads to many false-positive tests. You may look at this sample article to find out details. In such cases TransactionTemplate can be perfect for controlling transaction boundries when we want that control.

RuntimeWarning: invalid value encountered in divide

You are dividing by rr which may be 0.0. Check if rr is zero and do something reasonable other than using it in the denominator.

Keep values selected after form submission

If you are using WordPress (as is the case with the OP), you can use the selected function.

<form method="get" action="">
  <select name="name">
    <option value="a" <?php selected( isset($_POST['name']) ? $_POST['name'] : '', 'a' ); ?>>a</option>
    <option value="b" <?php selected( isset($_POST['name']) ? $_POST['name'] : '', 'b' ); ?>>b</option>
  </select>
  <select name="location">
    <option value="x" <?php selected( isset($_POST['location']) ? $_POST['location'] : '', 'x' ); ?>>x</option>
    <option value="y" <?php selected( isset($_POST['location']) ? $_POST['location'] : '', 'y' ); ?>>y</option>
  </select>
  <input type="submit" value="Submit" class="submit" />
</form>

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

I have a full explanation already posted here

Basically, General guidelines for designing images are:

ldpi is 0.75x dimensions of mdpi
hdpi is 1.5x dimensions of mdpi
xhdpi is 2x dimensinons of mdpi

Usually, I design mdpi images for a 320x480 screen and then multiply the dimensions as per the above rules to get images for other resolutions.

Please refer to the full explanation for a more detailed answer.

Set color of TextView span in Android

Another way that could be used in some situations is to set the link color in the properties of the view that is taking the Spannable.

If your Spannable is going to be used in a TextView, for example, you can set the link color in the XML like this:

<TextView
    android:id="@+id/myTextView"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:textColorLink="@color/your_color"
</TextView>

You can also set it in the code with:

TextView tv = (TextView) findViewById(R.id.myTextView);
tv.setLinkTextColor(your_color);

How to enable authentication on MongoDB through Docker?

a. You can use environment variables via terminal:

$ docker run -d --name container_name \
      -e MONGO_INITDB_ROOT_USERNAME=admin \
      -e MONGO_INITDB_ROOT_PASSWORD=password \
      mongo

If you like to test if everything works:

// ssh into the running container
// Change container name if necessary
$ docker exec -it mongo /bin/bash

// Enter into mongo shell
$ mongo

// Caret will change when you enter successfully
// Switch to admin database
$> use admin
$> db.auth("admin", passwordPrompt())

// Show available databases
$> show dbs

If you like to instantiate a database on first run, check option b.

b. You can use environment variables in your docker stack deploy file or compose file for versions 3.4 through 4.1.

As it is explained on the quick reference section of the official mongo image set MONGO_INITDB_ROOT_USERNAME and MONGO_INITDB_ROOT_PASSWORD in your yaml file:

mongo:
    image: mongo
    environment:
      MONGO_INITDB_ROOT_USERNAME: admin
      MONGO_INITDB_ROOT_PASSWORD: password

docker-entrypoint.sh file in mongo image checks for the existence of these two variables and sets --auth flag accordingly.

c. You can also use docker secrets.

MONGO_INITDB_ROOT_USERNAME and MONGO_INITDB_ROOT_PASSWORD is set indirectly by docker-entrypoint.sh from MONGO_INITDB_ROOT_USERNAME_FILE and MONGO_INITDB_ROOT_PASSWORD_FILE variables:

mongo:
    image: mongo
    environment:
        - MONGO_INITDB_ROOT_USERNAME_FILE=/run/secrets/db_root_username
        - MONGO_INITDB_ROOT_PASSWORD_FILE=/run/secrets/db_root_password
    secrets:
      - db_root_username
      - db_root_password

docker-entrypoint.sh converts MONGO_INITDB_ROOT_USERNAME_FILE and MONGO_INITDB_ROOT_PASSWORD_FILE to MONGO_INITDB_ROOT_USERNAME and MONGO_INITDB_ROOT_PASSWORD.

You can use MONGO_INITDB_ROOT_USERNAME and MONGO_INITDB_ROOT_PASSWORD in your .sh or .js scripts in docker-entrypoint-initdb.d folder while initializing database instance.

When a container is started for the first time it will execute files with extensions .sh and .js that are found in /docker-entrypoint-initdb.d. Files will be executed in alphabetical order. .js files will be executed by mongo using the database specified by the MONGO_INITDB_DATABASE variable, if it is present, or test otherwise. You may also switch databases within the .js script.

This last method is not in the reference docs, so it may not survive an update.

How does Zalgo text work?

Zalgo text works because of combining characters. These are special characters that allow to modify character that comes before.

enter image description here

OR

y + ̆ = y̆ which actually is

y + &#x0306; = y&#x0306;

Since you can stack them one atop the other you can produce the following:


y̆̆̆̆̆̆̆̆̆̆̆̆̆̆̆̆̆̆

which actually is:

y&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;

The same goes for putting stuff underneath:


y̰̰̰̰̰̰̰̰̰̰̰̰̰̰̰̆̆̆̆̆̆̆̆̆̆̆̆̆̆̆̆̆̆



that in fact is:

y&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0330;&#x0330;&#x0330;&#x0330;&#x0330;&#x0330;&#x0330;&#x0330;&#x0330;&#x0330;&#x0330;&#x0330;&#x0330;&#x0330;&#x0330;

In Unicode, the main block of combining diacritics for European languages and the International Phonetic Alphabet is U+0300–U+036F.

More about it here

To produce a list of combining diacritical marks you can use the following script (since links keep on dying)

_x000D_
_x000D_
for(var i=768; i<879; i++){console.log(new DOMParser().parseFromString("&#"+i+";", "text/html").documentElement.textContent +"  "+"&#"+i+";");}
_x000D_
_x000D_
_x000D_

Also check em out



Mͣͭͣ̾ Vͣͥͭ͛ͤͮͥͨͥͧ̾

Is there a way I can capture my iPhone screen as a video?

using ScreenCaptureView class we can capture the iphone screen as video.The source code is available here.The recorded video is saved in a NSUrl,outputURL.Use that NSUrl in a method like below to play the recorded video,

    -(void)playvideo
{

  MPMoviePlayerController *player = [[MPMoviePlayerController alloc] initWithContentURL:outputURL ];
       [player.view setFrame:CGRectMake(0,0,320,480)];

[player setMovieControlMode:MPMovieControlModeHidden];   

[player setScalingMode:MPMovieScalingModeAspectFit];

 [player setBackgroundColor:[UIColor blackColor]];

 [player setFullscreen:YES animated:YES];

[player play];

[self addSubview:player.view];

}

call this method before releasing NSUrl in completeRecordingSession method ..it will replay what you did in the iphone screen as a video.

Update TextView Every Second

It's a very old question and I'm sure there are a lot of resources out there. But it's never too much to spread the word to be at the safe side. Currently, if someone else ever want to achieve what the OP asked, you can use: android.widget.TextClock.

TextClock documentation here.

Here's what I've used:

<android.widget.TextClock
    android:id="@+id/digitalClock"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:timeZone="GMT+0000" <!--Greenwich -->
    android:format24Hour="dd MMM yyyy   k:mm:ss"
    android:format12Hour="@null"
    android:textStyle="bold"
    android:layout_alignParentEnd="true" />

How to make git mark a deleted and a new file as a file move?

For me it worked to stash save all the changes before the commit and pop them out again. This made git re-analyze the added / deleted files and it correctly marked them as moved.

Reading/parsing Excel (xls) files with Python

For xlsx I like the solution posted earlier as https://web.archive.org/web/20180216070531/https://stackoverflow.com/questions/4371163/reading-xlsx-files-using-python. I uses modules from the standard library only.

def xlsx(fname):
    import zipfile
    from xml.etree.ElementTree import iterparse
    z = zipfile.ZipFile(fname)
    strings = [el.text for e, el in iterparse(z.open('xl/sharedStrings.xml')) if el.tag.endswith('}t')]
    rows = []
    row = {}
    value = ''
    for e, el in iterparse(z.open('xl/worksheets/sheet1.xml')):
        if el.tag.endswith('}v'):  # Example: <v>84</v>                            
            value = el.text
        if el.tag.endswith('}c'):  # Example: <c r="A3" t="s"><v>84</v></c>                                 
            if el.attrib.get('t') == 's':
                value = strings[int(value)]
            letter = el.attrib['r']  # Example: AZ22                         
            while letter[-1].isdigit():
                letter = letter[:-1]
            row[letter] = value
            value = ''
        if el.tag.endswith('}row'):
            rows.append(row)
            row = {}
    return rows

Improvements added are fetching content by sheet name, using re to get the column and checking if sharedstrings are used.

def xlsx(fname,sheet):
    import zipfile
    from xml.etree.ElementTree import iterparse
    import re
    z = zipfile.ZipFile(fname)
    if 'xl/sharedStrings.xml' in z.namelist():
        # Get shared strings
        strings = [element.text for event, element
                   in iterparse(z.open('xl/sharedStrings.xml')) 
                   if element.tag.endswith('}t')]
    sheetdict = { element.attrib['name']:element.attrib['sheetId'] for event,element in iterparse(z.open('xl/workbook.xml'))
                                      if element.tag.endswith('}sheet') }
    rows = []
    row = {}
    value = ''

    if sheet in sheets:
    sheetfile = 'xl/worksheets/sheet'+sheets[sheet]+'.xml'
    #print(sheet,sheetfile)
    for event, element in iterparse(z.open(sheetfile)):
        # get value or index to shared strings
        if element.tag.endswith('}v') or element.tag.endswith('}t'):
            value = element.text
        # If value is a shared string, use value as an index
        if element.tag.endswith('}c'):
            if element.attrib.get('t') == 's':
                value = strings[int(value)]
            # split the row/col information so that the row leter(s) can be separate
            letter = re.sub('\d','',element.attrib['r'])
            row[letter] = value
            value = ''
        if element.tag.endswith('}row'):
            rows.append(row)
            row = {}

    return rows

How to access custom attributes from event object in React?

I think it's recommended to bind all methods where you need to use this.setState method which is defined in the React.Component class, inside the constructor, in your case you constructor should be like

    constructor() {
        super()
        //This binding removeTag is necessary to make `this` work in the callback
        this.removeTag = this.removeTag.bind(this)
    }
    removeTag(event){
        console.log(event.target)
        //use Object destructuring to fetch all element values''
        const {style, dataset} = event.target
        console.log(style)
        console.log(dataset.tag)
    }
   render() {
   ...
      <a data-tag={i} style={showStyle} onClick={this.removeTag.bind(null, i)}></a>
   ...},

For more reference on Object destructuring https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#Object_destructuring

Regex select all text between tags

You can use Pattern pattern = Pattern.compile( "[^<'tagname'/>]" );

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

From enable-cors.org:

CORS on ASP.NET

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

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

See also: Configuring IIS6 / IIS7

Use jQuery to get the file input's selected filename without the path

You just need to do the code below. The first [0] is to access the HTML element and second [0] is to access the first file of the file upload (I included a validation in case that there is no file):

    var filename = $('input[type=file]')[0].files.length ? ('input[type=file]')[0].files[0].name : "";

How to specify Memory & CPU limit in docker compose version 3

deploy:
  resources:
    limits:
      cpus: '0.001'
      memory: 50M
    reservations:
      cpus: '0.0001'
      memory: 20M

More: https://docs.docker.com/compose/compose-file/compose-file-v3/#resources

In you specific case:

version: "3"
services:
  node:
    image: USER/Your-Pre-Built-Image
    environment:
      - VIRTUAL_HOST=localhost
    volumes:
      - logs:/app/out/
    command: ["npm","start"]
    cap_drop:
      - NET_ADMIN
      - SYS_ADMIN
    deploy:
      resources:
        limits:
          cpus: '0.001'
          memory: 50M
        reservations:
          cpus: '0.0001'
          memory: 20M

volumes:
  - logs

networks:
  default:
    driver: overlay

Note:

  • Expose is not necessary, it will be exposed per default on your stack network.
  • Images have to be pre-built. Build within v3 is not possible
  • "Restart" is also deprecated. You can use restart under deploy with on-failure action
  • You can use a standalone one node "swarm", v3 most improvements (if not all) are for swarm

Also Note: Networks in Swarm mode do not bridge. If you would like to connect internally only, you have to attach to the network. You can 1) specify an external network within an other compose file, or have to create the network with --attachable parameter (docker network create -d overlay My-Network --attachable) Otherwise you have to publish the port like this:

ports:
  - 80:80

Open local folder from link

Only IE6-8 - there's an ActiveX workaround this local-files issue in JavaScript:

        function OpenImage(filePath)
        {
            var myshell = new ActiveXObject("WScript.shell");
            myshell.run(filePath, 1, true); 
        }

Declaring abstract method in TypeScript

I use to throw an exception in the base class.

protected abstractMethod() {
    throw new Error("abstractMethod not implemented");
}

Then you have to implement in the sub-class. The cons is that there is no build error, but run-time. The pros is that you can call this method from the super class, assuming that it will work :)

HTH!

Milton

What is float in Java?

The thing is that decimal numbers defaults to double. And since double doesn't fit into float you have to tell explicitely you intentionally define a float. So go with:

float b = 3.6f;

Hide div if screen is smaller than a certain width

The problem I was having is my css media queries and my IF statement in Jquery clashing. They were both set to 700px but one would think it's hit 700px before the other.

To get around this I created a empty Div right at the top of my HTML(outside my main container)

<div id="max-width"></div>

In css I set this div to display none

 #max-width {
        display: none;
    }

In my JS created a function

var hasSwitched = function () {
    var maxWidth = parseInt($('#max-width').css('max-width'), 10);
    return !isNaN(maxWidth);
};

So in my IF statement instead of saying if (hasSwitched<700) perform the following code, I did the following

if (!hasSwitched()) { Your code

}

else{ your code

}

By doing this CSS tells Jquery when it's hit 700px. So css and jquery are both synchronized... rather than having a couple of pixels difference. Do give this a try peeps it shall definitely not disappoint.

To get this same logic working for IE8 I used the Respond.js plugin(which also definitely works) It lets you use media queries for IE8. Only thing that wasn't supported was the viewport width and viewport height... hence my reason to try get my css and JS working together. Hope this helps you guys

Angular JS: What is the need of the directive’s link function when we already had directive’s controller with scope?

The controller function/object represents an abstraction model-view-controller (MVC). While there is nothing new to write about MVC, it is still the most significant advanatage of angular: split the concerns into smaller pieces. And that's it, nothing more, so if you need to react on Model changes coming from View the Controller is the right person to do that job.

The story about link function is different, it is coming from different perspective then MVC. And is really essential, once we want to cross the boundaries of a controller/model/view (template).

Let' start with the parameters which are passed into the link function:

function link(scope, element, attrs) {
  • scope is an Angular scope object.
  • element is the jqLite-wrapped element that this directive matches.
  • attrs is an object with the normalized attribute names and their corresponding values.

To put the link into the context, we should mention that all directives are going through this initialization process steps: Compile, Link. An Extract from Brad Green and Shyam Seshadri book Angular JS:

Compile phase (a sister of link, let's mention it here to get a clear picture):

In this phase, Angular walks the DOM to identify all the registered directives in the template. For each directive, it then transforms the DOM based on the directive’s rules (template, replace, transclude, and so on), and calls the compile function if it exists. The result is a compiled template function,

Link phase:

To make the view dynamic, Angular then runs a link function for each directive. The link functions typically creates listeners on the DOM or the model. These listeners keep the view and the model in sync at all times.

A nice example how to use the link could be found here: Creating Custom Directives. See the example: Creating a Directive that Manipulates the DOM, which inserts a "date-time" into page, refreshed every second.

Just a very short snippet from that rich source above, showing the real manipulation with DOM. There is hooked function to $timeout service, and also it is cleared in its destructor call to avoid memory leaks

.directive('myCurrentTime', function($timeout, dateFilter) {

 function link(scope, element, attrs) {

 ...

 // the not MVC job must be done
 function updateTime() {
   element.text(dateFilter(new Date(), format)); // here we are manipulating the DOM
 }

 function scheduleUpdate() {
   // save the timeoutId for canceling
   timeoutId = $timeout(function() {
     updateTime(); // update DOM
     scheduleUpdate(); // schedule the next update
   }, 1000);
 }

 element.on('$destroy', function() {
   $timeout.cancel(timeoutId);
 });

 ...

How can I pass a reference to a function, with parameters?

You can also overload the Function prototype:

// partially applies the specified arguments to a function, returning a new function
Function.prototype.curry = function( ) {
    var func = this;
    var slice = Array.prototype.slice;
    var appliedArgs = slice.call( arguments, 0 );

    return function( ) {
        var leftoverArgs = slice.call( arguments, 0 );
        return func.apply( this, appliedArgs.concat( leftoverArgs ) );
    };
};

// can do other fancy things:

// flips the first two arguments of a function
Function.prototype.flip = function( ) {
    var func = this;
    return function( ) {
        var first = arguments[0];
        var second = arguments[1];
        var rest = Array.prototype.slice.call( arguments, 2 );
        var newArgs = [second, first].concat( rest );

        return func.apply( this, newArgs );
    };
};

/*
e.g.

var foo = function( a, b, c, d ) { console.log( a, b, c, d ); }
var iAmA = foo.curry( "I", "am", "a" );
iAmA( "Donkey" );
-> I am a Donkey

var bah = foo.flip( );
bah( 1, 2, 3, 4 );
-> 2 1 3 4
*/

How to change the cursor into a hand when a user hovers over a list item?

Use for li:

li:hover {
    cursor: pointer;
}

See more cursor properties with examples after running snippet option:

An animation showing a cursor hovering over a div of each class

_x000D_
_x000D_
.auto          { cursor: auto; }_x000D_
.default       { cursor: default; }_x000D_
.none          { cursor: none; }_x000D_
.context-menu  { cursor: context-menu; }_x000D_
.help          { cursor: help; }_x000D_
.pointer       { cursor: pointer; }_x000D_
.progress      { cursor: progress; }_x000D_
.wait          { cursor: wait; }_x000D_
.cell          { cursor: cell; }_x000D_
.crosshair     { cursor: crosshair; }_x000D_
.text          { cursor: text; }_x000D_
.vertical-text { cursor: vertical-text; }_x000D_
.alias         { cursor: alias; }_x000D_
.copy          { cursor: copy; }_x000D_
.move          { cursor: move; }_x000D_
.no-drop       { cursor: no-drop; }_x000D_
.not-allowed   { cursor: not-allowed; }_x000D_
.all-scroll    { cursor: all-scroll; }_x000D_
.col-resize    { cursor: col-resize; }_x000D_
.row-resize    { cursor: row-resize; }_x000D_
.n-resize      { cursor: n-resize; }_x000D_
.e-resize      { cursor: e-resize; }_x000D_
.s-resize      { cursor: s-resize; }_x000D_
.w-resize      { cursor: w-resize; }_x000D_
.ns-resize     { cursor: ns-resize; }_x000D_
.ew-resize     { cursor: ew-resize; }_x000D_
.ne-resize     { cursor: ne-resize; }_x000D_
.nw-resize     { cursor: nw-resize; }_x000D_
.se-resize     { cursor: se-resize; }_x000D_
.sw-resize     { cursor: sw-resize; }_x000D_
.nesw-resize   { cursor: nesw-resize; }_x000D_
.nwse-resize   { cursor: nwse-resize; }_x000D_
_x000D_
.cursors > div {_x000D_
    float: left;_x000D_
    box-sizing: border-box;_x000D_
    background: #f2f2f2;_x000D_
    border:1px solid #ccc;_x000D_
    width: 20%;_x000D_
    padding: 10px 2px;_x000D_
    text-align: center;_x000D_
    white-space: nowrap;_x000D_
    &:nth-child(even) {_x000D_
       background: #eee;_x000D_
    }_x000D_
    &:hover {_x000D_
       opacity: 0.25_x000D_
    }_x000D_
}
_x000D_
<h1>Example of cursor</h1>_x000D_
_x000D_
<div class="cursors">_x000D_
    <div class="auto">auto</div>_x000D_
    <div class="default">default</div>_x000D_
    <div class="none">none</div>_x000D_
    <div class="context-menu">context-menu</div>_x000D_
    <div class="help">help</div>_x000D_
    <div class="pointer">pointer</div>_x000D_
    <div class="progress">progress</div>_x000D_
    <div class="wait">wait</div>_x000D_
    <div class="cell">cell</div>_x000D_
    <div class="crosshair">crosshair</div>_x000D_
    <div class="text">text</div>_x000D_
    <div class="vertical-text">vertical-text</div>_x000D_
    <div class="alias">alias</div>_x000D_
    <div class="copy">copy</div>_x000D_
    <div class="move">move</div>_x000D_
    <div class="no-drop">no-drop</div>_x000D_
    <div class="not-allowed">not-allowed</div>_x000D_
    <div class="all-scroll">all-scroll</div>_x000D_
    <div class="col-resize">col-resize</div>_x000D_
    <div class="row-resize">row-resize</div>_x000D_
    <div class="n-resize">n-resize</div>_x000D_
    <div class="s-resize">s-resize</div>_x000D_
    <div class="e-resize">e-resize</div>_x000D_
    <div class="w-resize">w-resize</div>_x000D_
    <div class="ns-resize">ns-resize</div>_x000D_
    <div class="ew-resize">ew-resize</div>_x000D_
    <div class="ne-resize">ne-resize</div>_x000D_
    <div class="nw-resize">nw-resize</div>_x000D_
    <div class="se-resize">se-resize</div>_x000D_
    <div class="sw-resize">sw-resize</div>_x000D_
    <div class="nesw-resize">nesw-resize</div>_x000D_
    <div class="nwse-resize">nwse-resize</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Are there inline functions in java?

Real life example:

public class Control {
    public static final long EXPIRED_ON = 1386082988202l;
    public static final boolean isExpired() {
        return (System.currentTimeMillis() > EXPIRED_ON);
    }
}

Then in other classes, I can exit if the code has expired. If I reference the EXPIRED_ON variable from another class, the constant is inline to the byte code, making it very hard to track down all places in the code that checks the expiry date. However, if the other classes invoke the isExpired() method, the actual method is called, meaning a hacker could replace the isExpired method with another which always returns false.

I agree it would be very nice to force a compiler to inline the static final method to all classes which reference it. In that case, you need not even include the Control class, as it would not be needed at runtime.

From my research, this cannot be done. Perhaps some Obfuscator tools can do this, or, you could modify your build process to edit sources before compile.

As for proving if the method from the control class is placed inline to another class during compile, try running the other class without the Control class in the classpath.

Commit empty folder structure (with git)

Traditionally whenever I've wanted to commit and empty directory structure, I create the structure and then in the leaf directories place an empty file called empty.txt.

Then when I put stuff in that's ready to commit, I can simply remove the empty.txt file and commit the real files.

i.e.

  • data/
    • images/
      • empty.txt

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

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

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

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

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

You can just do:

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

to show the actual output.

How to show code but hide output in RMarkdown?

For completely silencing the output, here what works for me

```{r error=FALSE, warning=FALSE, message=FALSE}
invisible({capture.output({


# Your code here
2 * 2
# etc etc


})})
```

The 5 measures used above are

  1. error = FALSE
  2. warning = FALSE
  3. message = FALSE
  4. invisible()
  5. capture.output()

How can I read SMS messages from the device programmatically in Android?

Step 1: first we have to add permissions in manifest file like

<uses-permission android:name="android.permission.RECEIVE_SMS" android:protectionLevel="signature" />
<uses-permission android:name="android.permission.READ_SMS" />

Step 2: then add service sms receiver class for receiving sms

<receiver android:name="com.aquadeals.seller.services.SmsReceiver">
    <intent-filter>
        <action android:name="android.provider.Telephony.SMS_RECEIVED"/>
    </intent-filter>
</receiver>

Step 3: Add run time permission

private boolean checkAndRequestPermissions()
{
    int sms = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_SMS);

    if (sms != PackageManager.PERMISSION_GRANTED)
    {
        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_SMS}, REQUEST_ID_MULTIPLE_PERMISSIONS);
        return false;
    }
    return true;
}

Step 4: Add this classes in your app and test Interface class

public interface SmsListener {
   public void messageReceived(String messageText);
}

SmsReceiver.java

public class SmsReceiver extends BroadcastReceiver {
    private static SmsListener mListener;
    public Pattern p = Pattern.compile("(|^)\\d{6}");
    @Override
    public void onReceive(Context context, Intent intent) {
        Bundle data  = intent.getExtras();
        Object[] pdus = (Object[]) data.get("pdus");
        for(int i=0;i<pdus.length;i++)
        {
            SmsMessage smsMessage = SmsMessage.createFromPdu((byte[]) pdus[i]);
            String sender = smsMessage.getDisplayOriginatingAddress();
            String phoneNumber = smsMessage.getDisplayOriginatingAddress();
            String senderNum = phoneNumber ;
            String messageBody = smsMessage.getMessageBody();
            try{
                if(messageBody!=null){
                    Matcher m = p.matcher(messageBody);
                    if(m.find()) {
                        mListener.messageReceived(m.group(0));
                    }
                }
            }
            catch(Exception e){}
        }
    }
    public static void bindListener(SmsListener listener) {
        mListener = listener; 
    }
}

Null pointer Exception on .setOnClickListener

Try giving your Button in your main.xml a more descriptive name such as:

<Button
                android:id="@+id/buttonXYZ"

(use lowercase in your xml files, at least, the first letter)

And then in your MainActivity class, declare it as:

Button buttonXYZ;

In your onCreate(Bundle savedInstanceState) method, define it as:

buttonXYZ = (Button) findViewById(R.id.buttonXYZ);

Also, move the Buttons/TextViews outside and place them before the .setOnClickListener - it makes the code cleaner.

Username = (EditText)findViewById(R.id.Username);
CompanyID = (EditText)findViewById(R.id.CompanyID);

iPad browser WIDTH & HEIGHT standard

There's no simple answer to this question. Apple's mobile version of WebKit, used in iPhones, iPod Touches, and iPads, will scale the page to fit the screen, at which point the user can zoom in and out freely.

That said, you can design your page to minimize the amount of zooming necessary. Your best bet is to make the width and height the same as the lower resolution of the iPad, since you don't know which way it's oriented; in other words, you would make your page 768x768, so that it will fit well on the iPad's screen whether it's oriented to be 1024x768 or 768x1024.

More importantly, you'd want to design your page with big controls with lots of space that are easy to hit with your thumbs - you could easily design a 768x768 page that was very cluttered and therefore required lots of zooming. To accomplish this, you'll likely want to divide your controls among a number of web pages.

On the other hand, it's not the most worthwhile pursuit. If while designing you find opportunities to make your page more "finger-friendly", then go for it...but the reality is that iPad users are very comfortable with moving around and zooming in and out of the page to get to things because it's necessary on most web sites. If anything, you probably want to design it so that it's conducive to this type of navigation.

Make boxes with relevant grouped data that can be easily double-tapped to focus on, and keep related controls close to each other. iPad users will most likely appreciate a page that facilitates the familiar zoom-and-pan navigation they're accustomed to more than they will a page that has fewer controls so that they don't have to.

Nginx location "not equal to" regex

i was looking for the same. and found this solution.

Use negative regex assertion:

location ~ ^/(?!(favicon\.ico|resources|robots\.txt)) { 
.... # your stuff 
} 

Source Negated Regular Expressions in location

Explanation of Regex :

If URL does not match any of the following path

example.com/favicon.ico
example.com/resources
example.com/robots.txt

Then it will go inside that location block and will process it.

Combine two data frames by rows (rbind) when they have different sets of columns

Maybe I completely misread your question, but the "I am hoping to retain the columns that do not match after the bind" makes me think you are looking for a left join or right join similar to an SQL query. R has the merge function that lets you specify left, right, or inner joins similar to joining tables in SQL.

There is already a great question and answer on this topic here: How to join (merge) data frames (inner, outer, left, right)?

How to replace all special character into a string using C#

Assume you want to replace symbols which are not digits or letters (and _ character as @Guffa correctly pointed):

string input = "Hello@Hello&Hello(Hello)";
string result = Regex.Replace(input, @"[^\w\d]", ",");
// Hello,Hello,Hello,Hello,

You can add another symbols which should not be replaced. E.g. if you want white space symbols to stay, then just add \s to pattern: \[^\w\d\s]

How to place a JButton at a desired location in a JFrame using Java

Use child.setLocation(0, 0) on the button, and parent.setLayout(null). Instead of using setBounds(...) on the JFrame to size it, consider using just setSize(...) and letting the OS position the frame.

//JPanel
JPanel pnlButton = new JPanel();
//Buttons
JButton btnAddFlight = new JButton("Add Flight");

public Control() {

    //JFrame layout
    this.setLayout(null);

    //JPanel layout
    pnlButton.setLayout(null);

    //Adding to JFrame
    pnlButton.add(btnAddFlight);
    add(pnlButton);

    // postioning
    pnlButton.setLocation(0,0);

Enable remote MySQL connection: ERROR 1045 (28000): Access denied for user

I was struggling with remote login to MYSQL for my Amazon EC2 Linux instance. Found the solution was to make sure my security group included an inbound rule for MySQL port 3306 to include my IP address (or 0.0.0.0/0 for anywhere). Immediately could connect remotely as soon as I added this rule.

Java "?" Operator for checking null - What is it? (Not Ternary!)

There you have it, null-safe invocation in Java 8:

public void someMethod() {
    String userName = nullIfAbsent(new Order(), t -> t.getAccount().getUser()
        .getName());
}

static <T, R> R nullIfAbsent(T t, Function<T, R> funct) {
    try {
        return funct.apply(t);
    } catch (NullPointerException e) {
        return null;
    }
}

How to hide reference counts in VS2013?

The other features of CodeLens like: Show Bugs, Show Test Status, etc (other than Show Reference) might be useful.

However, if the only way to disable Show References is to disable CodeLens altogether.

Then, I guess I could do just that.

Furthermore, I would do like I always have, 'right-click on a member and choose Find all References or Ctrl+K, R'

If I wanted to know what references the member -- I too like not having any extra information crammed into my code, like extra white-space.

In short, uncheck Codelens...

How do I declare class-level properties in Objective-C?

Here's a thread safe way of doing it:

// Foo.h
@interface Foo {
}

+(NSDictionary*) dictionary;

// Foo.m
+(NSDictionary*) dictionary
{
  static NSDictionary* fooDict = nil;

  static dispatch_once_t oncePredicate;

  dispatch_once(&oncePredicate, ^{
        // create dict
    });

  return fooDict;
}

These edits ensure that fooDict is only created once.

From Apple documentation: "dispatch_once - Executes a block object once and only once for the lifetime of an application."

WPF: Grid with column/row margin/padding?

As was stated before create a GridWithMargins class. Here is my working code example

public class GridWithMargins : Grid
{
    public Thickness RowMargin { get; set; } = new Thickness(10, 10, 10, 10);
    protected override Size ArrangeOverride(Size arrangeSize)
    {
        var basesize = base.ArrangeOverride(arrangeSize);

        foreach (UIElement child in InternalChildren)
        {
            var pos = GetPosition(child);
            pos.X += RowMargin.Left;
            pos.Y += RowMargin.Top;

            var actual = child.RenderSize;
            actual.Width -= (RowMargin.Left + RowMargin.Right);
            actual.Height -= (RowMargin.Top + RowMargin.Bottom);
            var rec = new Rect(pos, actual);
            child.Arrange(rec);
        }
        return arrangeSize;
    }

    private Point GetPosition(Visual element)
    {
        var posTransForm = element.TransformToAncestor(this);
        var areaTransForm = posTransForm.Transform(new Point(0, 0));
        return areaTransForm;
    }
}

Usage:

<Window x:Class="WpfApplication1.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:WpfApplication1"
    mc:Ignorable="d"
    Title="MainWindow" Height="350" Width="525">
    <Grid>
        <local:GridWithMargins ShowGridLines="True">
            <Grid.RowDefinitions>
                <RowDefinition />
                <RowDefinition />
                <RowDefinition />
                <RowDefinition />
                <RowDefinition />
            </Grid.RowDefinitions>
            <Grid.ColumnDefinitions>
                <ColumnDefinition />
                <ColumnDefinition />
                <ColumnDefinition />
            </Grid.ColumnDefinitions>
            <Rectangle Fill="Red" Grid.Row="0" Grid.Column="0" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" />
            <Rectangle Fill="Green" Grid.Row="1" Grid.Column="0" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" />
            <Rectangle Fill="Blue" Grid.Row="1" Grid.Column="1" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" />
        </local:GridWithMargins>
    </Grid>
</Window>

Angular JS - angular.forEach - How to get key of the object?

The first parameter to the iterator in forEach is the value and second is the key of the object.

angular.forEach(objectToIterate, function(value, key) {
    /* do something for all key: value pairs */
});

In your example, the outer forEach is actually:

angular.forEach($scope.filters, function(filterObj , filterKey)

Java: convert List<String> to a String

With a java 8 collector, this can be done with the following code:

Arrays.asList("Bill", "Bob", "Steve").stream()
.collect(Collectors.joining(" and "));

Also, the simplest solution in java 8:

String.join(" and ", "Bill", "Bob", "Steve");

or

String.join(" and ", Arrays.asList("Bill", "Bob", "Steve"));

What does this symbol mean in IntelliJ? (red circle on bottom-left corner of file name, with 'J' in it)

Another option if you're using Flavors in Android Studio:

Click Build -> Select Build Variant.

In the list click the variant you're working in and it will turn green and the others will have the red J.

Private Variables and Methods in Python

Because thats coding convention. See here for more.

JavaScript .replace only replaces first Match

Try using a regex instead of a string for the first argument.

"this is a test".replace(/ /g,'%20') // #=> "this%20is%20a%20test"

In SQL, is UPDATE always faster than DELETE+INSERT?

A bit too late with this answer, but since I faced a similar question, I made a test with JMeter and a MySQL server on same machine, where I have used:

  1. A transaction Controller (generating parent sample) that contained two JDBC Requests: a Delete and an Insert statement
  2. A sepparate JDBC Request containing the Update statement.

After running the test for 500 loops, I have obtained the following results:

DEL + INSERT - Average: 62ms

Update - Average: 30ms

Results: Results

if statements matching multiple values

I had the same problem but solved it with a switch statement switch(a value you are switching on) { case 1: the code you want to happen; case 2: the code you want to happen; default: return a value }

Simpler way to check if variable is not equal to multiple string values?

For your first code, you can use a short alteration of the answer given by @ShankarDamodaran using in_array():

if ( !in_array($some_variable, array('uk','in'), true ) ) {

or even shorter with [] notation available since php 5.4 as pointed out by @Forty in the comments

if ( !in_array($some_variable, ['uk','in'], true ) ) {

is the same as:

if ( $some_variable !== 'uk' && $some_variable !== 'in' ) {

... but shorter. Especially if you compare more than just 'uk' and 'in'. I do not use an additional variable (Shankar used $os) but instead define the array in the if statement. Some might find that dirty, i find it quick and neat :D

The problem with your second code is that it can easily be exchanged with just TRUE since:

if (true) {

equals

if ( $some_variable !== 'uk' || $some_variable !== 'in' ) {

You are asking if the value of a string is not A or Not B. If it is A, it is definitely not also B and if it is B it is definitely not A. And if it is C or literally anything else, it is also not A and not B. So that statement always (not taking into account schrödingers law here) returns true.

What is the best way to create a string array in python?

Sometimes I need a empty char array. You cannot do "np.empty(size)" because error will be reported if you fill in char later. Then I usually do something quite clumsy but it is still one way to do it:

# Suppose you want a size N char array
charlist = [' ']*N # other preset character is fine as well, like 'x'
chararray = np.array(charlist)
# Then you change the content of the array
chararray[somecondition1] = 'a'
chararray[somecondition2] = 'b'

The bad part of this is that your array has default values (if you forget to change them).

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

You can simple just require('./filename').

Eg.

// file: index.js
var express = require('express');
var app = express();
var child = require('./child');
app.use('/child', child);
app.get('/', function (req, res) {
  res.send('parent');
});
app.listen(process.env.PORT, function () {
  console.log('Example app listening on port '+process.env.PORT+'!');
});
// file: child.js
var express = require('express'),
child = express.Router();
console.log('child');
child.get('/child', function(req, res){
  res.send('Child2');
});
child.get('/', function(req, res){
  res.send('Child');
});

module.exports = child;

Please note that:

  1. you can't listen PORT on the child file, only parent express module has PORT listener
  2. Child is using 'Router', not parent Express moudle.

Check if a record exists in the database

MySqlCommand cmd = new MySqlCommand("select * from table where user = '" + user.Text + "'", con);
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
DataSet ds1 = new DataSet();
da.Fill(ds1);
int i = ds1.Tables[0].Rows.Count;
if (i > 0) {
    // Exist
}
else {
    // Add 
}

CORS with spring-boot and angularjs not working

In our Spring Boot app, we have set up CorsConfigurationSource like this.

Sequence of adding allowedOrigns first and then setting applyPermitDefaultValues() let Spring set up default values for allowed headers, exposed headers, allowed methods, etc. so we don't have to specify those.

    public CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOrigins(Arrays.asList("http://localhost:8084"));
        configuration.applyPermitDefaultValues();

        UrlBasedCorsConfigurationSource configurationSource = new UrlBasedCorsConfigurationSource();
        configurationSource.registerCorsConfiguration("/**", configuration);
        return configurationSource;
    }
    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http.authorizeRequests()
                .antMatchers("/api/**")
                .access("@authProvider.validateApiKey(request)")
                .anyRequest().authenticated()
                .and().cors()
                .and().csrf().disable()
                .httpBasic().authenticationEntryPoint(authenticationEntryPoint);

        http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
    }

PHP how to get value from array if key is in a variable

As others stated, it's likely failing because the requested key doesn't exist in the array. I have a helper function here that takes the array, the suspected key, as well as a default return in the event the key does not exist.

    protected function _getArrayValue($array, $key, $default = null)
    {
        if (isset($array[$key])) return $array[$key];
        return $default;
    }

hope it helps.

Difference between mkdir() and mkdirs() in java for java.io.File

mkdirs() also creates parent directories in the path this File represents.

javadocs for mkdirs():

Creates the directory named by this abstract pathname, including any necessary but nonexistent parent directories. Note that if this operation fails it may have succeeded in creating some of the necessary parent directories.

javadocs for mkdir():

Creates the directory named by this abstract pathname.

Example:

File  f = new File("non_existing_dir/someDir");
System.out.println(f.mkdir());
System.out.println(f.mkdirs());

will yield false for the first [and no dir will be created], and true for the second, and you will have created non_existing_dir/someDir

Why is the console window closing immediately once displayed my output?

Use Console.Read(); to prevent the program from closing, but make sure you add the Console.Read(); code before return statement, or else it will be a unreachable code .

    Console.Read(); 
    return 0; 

check this Console.Read

What are the main performance differences between varchar and nvarchar SQL Server data types?

I can speak from experience on this, beware of nvarchar. Unless you absolutely require it this data field type destroys performance on larger database. I inherited a database that was hurting in terms of performance and space. We were able to reduce a 30GB database in size by 70%! There were some other modifications made to help with performance but I'm sure the varchar's helped out significantly with that as well. If your database has the potential for growing tables to a million + records stay away from nvarchar at all costs.

Not showing placeholder for input type="date" field

As of today (2016), I have successfully used those 2 snippets (plus they work great with Bootstrap4).

Input data on the left, placeholder on the left

input[type=date] {
  text-align: right;
}

input[type="date"]:before {
  color: lightgrey;
  content: attr(placeholder) !important;
  margin-right: 0.5em;
}

Placeholder disappear when clicking

input[type="date"]:before {
  color: lightgrey;
  content: attr(placeholder) !important;
  margin-right: 0.5em;
}
input[type="date"]:focus:before {
  content: '' !important;
}

How to parse the Manifest.mbdb file in an iOS 4.0 iTunes Backup

In iOS 5, the Manifest.mbdx file was eliminated. For the purpose of this article, it was redundant anyway, because the domain and path are in Manifest.mbdb and the ID hash can be generated with SHA1.

Here is my update of galloglass's code so it works with backups of iOS 5 devices. The only changes are elimination of process_mbdx_file() and addition of a few lines in process_mbdb_file().

Tested with backups of an iPhone 4S and an iPad 1, both with plenty of apps and files.

#!/usr/bin/env python
import sys
import hashlib

mbdx = {}

def getint(data, offset, intsize):
    """Retrieve an integer (big-endian) and new offset from the current offset"""
    value = 0
    while intsize > 0:
        value = (value<<8) + ord(data[offset])
        offset = offset + 1
        intsize = intsize - 1
    return value, offset

def getstring(data, offset):
    """Retrieve a string and new offset from the current offset into the data"""
    if data[offset] == chr(0xFF) and data[offset+1] == chr(0xFF):
        return '', offset+2 # Blank string
    length, offset = getint(data, offset, 2) # 2-byte length
    value = data[offset:offset+length]
    return value, (offset + length)

def process_mbdb_file(filename):
    mbdb = {} # Map offset of info in this file => file info
    data = open(filename).read()
    if data[0:4] != "mbdb": raise Exception("This does not look like an MBDB file")
    offset = 4
    offset = offset + 2 # value x05 x00, not sure what this is
    while offset < len(data):
        fileinfo = {}
        fileinfo['start_offset'] = offset
        fileinfo['domain'], offset = getstring(data, offset)
        fileinfo['filename'], offset = getstring(data, offset)
        fileinfo['linktarget'], offset = getstring(data, offset)
        fileinfo['datahash'], offset = getstring(data, offset)
        fileinfo['unknown1'], offset = getstring(data, offset)
        fileinfo['mode'], offset = getint(data, offset, 2)
        fileinfo['unknown2'], offset = getint(data, offset, 4)
        fileinfo['unknown3'], offset = getint(data, offset, 4)
        fileinfo['userid'], offset = getint(data, offset, 4)
        fileinfo['groupid'], offset = getint(data, offset, 4)
        fileinfo['mtime'], offset = getint(data, offset, 4)
        fileinfo['atime'], offset = getint(data, offset, 4)
        fileinfo['ctime'], offset = getint(data, offset, 4)
        fileinfo['filelen'], offset = getint(data, offset, 8)
        fileinfo['flag'], offset = getint(data, offset, 1)
        fileinfo['numprops'], offset = getint(data, offset, 1)
        fileinfo['properties'] = {}
        for ii in range(fileinfo['numprops']):
            propname, offset = getstring(data, offset)
            propval, offset = getstring(data, offset)
            fileinfo['properties'][propname] = propval
        mbdb[fileinfo['start_offset']] = fileinfo
        fullpath = fileinfo['domain'] + '-' + fileinfo['filename']
        id = hashlib.sha1(fullpath)
        mbdx[fileinfo['start_offset']] = id.hexdigest()
    return mbdb

def modestr(val):
    def mode(val):
        if (val & 0x4): r = 'r'
        else: r = '-'
        if (val & 0x2): w = 'w'
        else: w = '-'
        if (val & 0x1): x = 'x'
        else: x = '-'
        return r+w+x
    return mode(val>>6) + mode((val>>3)) + mode(val)

def fileinfo_str(f, verbose=False):
    if not verbose: return "(%s)%s::%s" % (f['fileID'], f['domain'], f['filename'])
    if (f['mode'] & 0xE000) == 0xA000: type = 'l' # symlink
    elif (f['mode'] & 0xE000) == 0x8000: type = '-' # file
    elif (f['mode'] & 0xE000) == 0x4000: type = 'd' # dir
    else: 
        print >> sys.stderr, "Unknown file type %04x for %s" % (f['mode'], fileinfo_str(f, False))
        type = '?' # unknown
    info = ("%s%s %08x %08x %7d %10d %10d %10d (%s)%s::%s" % 
            (type, modestr(f['mode']&0x0FFF) , f['userid'], f['groupid'], f['filelen'], 
             f['mtime'], f['atime'], f['ctime'], f['fileID'], f['domain'], f['filename']))
    if type == 'l': info = info + ' -> ' + f['linktarget'] # symlink destination
    for name, value in f['properties'].items(): # extra properties
        info = info + ' ' + name + '=' + repr(value)
    return info

verbose = True
if __name__ == '__main__':
    mbdb = process_mbdb_file("Manifest.mbdb")
    for offset, fileinfo in mbdb.items():
        if offset in mbdx:
            fileinfo['fileID'] = mbdx[offset]
        else:
            fileinfo['fileID'] = "<nofileID>"
            print >> sys.stderr, "No fileID found for %s" % fileinfo_str(fileinfo)
        print fileinfo_str(fileinfo, verbose)

Change GridView row color based on condition

protected void DrugGridView_RowDataBound(object sender, GridViewRowEventArgs e)

{
    // To check condition on integer value
    if (Convert.ToInt16(DataBinder.Eval(e.Row.DataItem, "Dosage")) == 50)
    {
      e.Row.BackColor = System.Drawing.Color.Cyan;
    }
}

How do I upload a file with metadata using a REST web service?

I agree with Greg that a two phase approach is a reasonable solution, however I would do it the other way around. I would do:

POST http://server/data/media
body:
{
    "Name": "Test",
    "Latitude": 12.59817,
    "Longitude": 52.12873
}

To create the metadata entry and return a response like:

201 Created
Location: http://server/data/media/21323
{
    "Name": "Test",
    "Latitude": 12.59817,
    "Longitude": 52.12873,
    "ContentUrl": "http://server/data/media/21323/content"
}

The client can then use this ContentUrl and do a PUT with the file data.

The nice thing about this approach is when your server starts get weighed down with immense volumes of data, the url that you return can just point to some other server with more space/capacity. Or you could implement some kind of round robin approach if bandwidth is an issue.

Running Python from Atom

To run the python file on mac.

  1. Open the preferences in atom ide. To open the preferences press 'command + . ' ( ? + , )
  2. Click on the install in the preferences to install packages.

  3. Search for package "script" and click on install

  4. Now open the python file(with .py extension ) you want to run and press 'control + r ' (^ + r)

How do I remove a substring from the end of a string in Python?

This is a perfect use for regular expressions:

>>> import re
>>> re.match(r"(.*)\.com", "hello.com").group(1)
'hello'

Visual Studio: LINK : fatal error LNK1181: cannot open input file

You can also fix the spaces-in-path problem by specifying the library path in DOS "8.3" format.

To get the 8.3 form, do (at the command line):

DIR /AD /X

recursively through every level of the directories.

Create unique constraint with null columns

I think there is a semantic problem here. In my view, a user can have a (but only one) favourite recipe to prepare a specific menu. (The OP has menu and recipe mixed up; if I am wrong: please interchange MenuId and RecipeId below) That implies that {user,menu} should be a unique key in this table. And it should point to exactly one recipe. If the user has no favourite recipe for this specific menu no row should exist for this {user,menu} key pair. Also: the surrogate key (FaVouRiteId) is superfluous: composite primary keys are perfectly valid for relational-mapping tables.

That would lead to the reduced table definition:

CREATE TABLE Favorites
( UserId uuid NOT NULL REFERENCES users(id)
, MenuId uuid NOT NULL REFERENCES menus(id)
, RecipeId uuid NOT NULL REFERENCES recipes(id)
, PRIMARY KEY (UserId, MenuId)
);

Incorrect string value: '\xF0\x9F\x8E\xB6\xF0\x9F...' MySQL

FOR SQLALCHEMY AND PYTHON

The encoding used for Unicode has traditionally been 'utf8'. However, for MySQL versions 5.5.3 on forward, a new MySQL-specific encoding 'utf8mb4' has been introduced, and as of MySQL 8.0 a warning is emitted by the server if plain utf8 is specified within any server-side directives, replaced with utf8mb3. The rationale for this new encoding is due to the fact that MySQL’s legacy utf-8 encoding only supports codepoints up to three bytes instead of four. Therefore, when communicating with a MySQL database that includes codepoints more than three bytes in size, this new charset is preferred, if supported by both the database as well as the client DBAPI, as in:

e = create_engine(
    "mysql+pymysql://scott:tiger@localhost/test?charset=utf8mb4")
All modern DBAPIs should support the utf8mb4 charset.

enter link description here

Need to get current timestamp in Java

java.time

As of Java 8+ you can use the java.time package. Specifically, use DateTimeFormatterBuilder and DateTimeFormatter to format the patterns and literals.

DateTimeFormatter formatter = new DateTimeFormatterBuilder()
        .appendPattern("MM").appendLiteral("/")
        .appendPattern("dd").appendLiteral("/")
        .appendPattern("yyyy").appendLiteral(" ")
        .appendPattern("hh").appendLiteral(":")
        .appendPattern("mm").appendLiteral(":")
        .appendPattern("ss").appendLiteral(" ")
        .appendPattern("a")
        .toFormatter();
System.out.println(LocalDateTime.now().format(formatter));

The output ...

06/22/2015 11:59:14 AM

Or if you want different time zone

// system default
System.out.println(formatter.withZone(ZoneId.systemDefault()).format(Instant.now()));
// Chicago
System.out.println(formatter.withZone(ZoneId.of("America/Chicago")).format(Instant.now()));
// Kathmandu
System.out.println(formatter.withZone(ZoneId.of("Asia/Kathmandu")).format(Instant.now()));

The output ...

06/22/2015 12:38:42 PM
06/22/2015 02:08:42 AM
06/22/2015 12:53:42 PM

Get first date of current month in java

If you also want the time is set to 0 the code is:

import java.util.*;
import java.text.*;

public class DateCalculations {
  public static void main(String[] args) {

    Calendar aCalendar = Calendar.getInstance();

    aCalendar.set(Calendar.DATE, 1);
    aCalendar.set(Calendar.HOUR_OF_DAY, 0);
    aCalendar.set(Calendar.MINUTE, 0);
    aCalendar.set(Calendar.SECOND, 0);

    Date firstDateOfCurrentMonth = aCalendar.getTime();

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss zZ");
    sdf.setTimeZone(TimeZone.getTimeZone("UTC"));

    String dayFirst = sdf.format(firstDateOfCurrentMonth);
    System.out.println(dayFirst);
  }
}

You can check online easily without compiling by using: http://www.browxy.com/

How to alert using jQuery

For each works with JQuery as in

$(<selector>).each(function() {
   //this points to item
   alert('<msg>');
});

JQuery also, for a popup, has in the UI library a dialog widget: http://jqueryui.com/demos/dialog/

Check it out, works really well.

HTH.

Visual Studio: How to break on handled exceptions?

A technique I use is something like the following. Define a global variable that you can use for one or multiple try catch blocks depending on what you're trying to debug and use the following structure:

if(!GlobalTestingBool)
{
   try
   {
      SomeErrorProneMethod();
   }
   catch (...)
   {
      // ... Error handling ...
   }
}
else
{
   SomeErrorProneMethod();
}

I find this gives me a bit more flexibility in terms of testing because there are still some exceptions I don't want the IDE to break on.

Escape curly brace '{' in String.Format

Use double braces {{ or }} so your code becomes:

sb.AppendLine(String.Format("public {0} {1} {{ get; private set; }}", 
prop.Type, prop.Name));

// For prop.Type of "Foo" and prop.Name of "Bar", the result would be:
// public Foo Bar { get; private set; }

Import CSV file with mixed data types

For the case when you know how many columns of data there will be in your CSV file, one simple call to textscan like Amro suggests will be your best solution.

However, if you don't know a priori how many columns are in your file, you can use a more general approach like I did in the following function. I first used the function fgetl to read each line of the file into a cell array. Then I used the function textscan to parse each line into separate strings using a predefined field delimiter and treating the integer fields as strings for now (they can be converted to numeric values later). Here is the resulting code, placed in a function read_mixed_csv:

function lineArray = read_mixed_csv(fileName, delimiter)

  fid = fopen(fileName, 'r');         % Open the file
  lineArray = cell(100, 1);           % Preallocate a cell array (ideally slightly
                                      %   larger than is needed)
  lineIndex = 1;                      % Index of cell to place the next line in
  nextLine = fgetl(fid);              % Read the first line from the file
  while ~isequal(nextLine, -1)        % Loop while not at the end of the file
    lineArray{lineIndex} = nextLine;  % Add the line to the cell array
    lineIndex = lineIndex+1;          % Increment the line index
    nextLine = fgetl(fid);            % Read the next line from the file
  end
  fclose(fid);                        % Close the file

  lineArray = lineArray(1:lineIndex-1);              % Remove empty cells, if needed
  for iLine = 1:lineIndex-1                          % Loop over lines
    lineData = textscan(lineArray{iLine}, '%s', ...  % Read strings
                        'Delimiter', delimiter);
    lineData = lineData{1};                          % Remove cell encapsulation
    if strcmp(lineArray{iLine}(end), delimiter)      % Account for when the line
      lineData{end+1} = '';                          %   ends with a delimiter
    end
    lineArray(iLine, 1:numel(lineData)) = lineData;  % Overwrite line data
  end

end

Running this function on the sample file content from the question gives this result:

>> data = read_mixed_csv('myfile.csv', ';')

data = 

  Columns 1 through 7

    '04'    'abc'    'def'    'ghj'    'klm'    ''            ''        
    ''      ''       ''       ''       ''       'Test'        'text'    
    ''      ''       ''       ''       ''       'asdfhsdf'    'dsafdsag'

  Columns 8 through 10

    ''          ''    ''
    '0xFF'      ''    ''
    '0x0F0F'    ''    ''

The result is a 3-by-10 cell array with one field per cell where missing fields are represented by the empty string ''. Now you can access each cell or a combination of cells to format them as you like. For example, if you wanted to change the fields in the first column from strings to integer values, you could use the function str2double as follows:

>> data(:, 1) = cellfun(@(s) {str2double(s)}, data(:, 1))

data = 

  Columns 1 through 7

    [  4]    'abc'    'def'    'ghj'    'klm'    ''            ''        
    [NaN]    ''       ''       ''       ''       'Test'        'text'    
    [NaN]    ''       ''       ''       ''       'asdfhsdf'    'dsafdsag'

  Columns 8 through 10

    ''          ''    ''
    '0xFF'      ''    ''
    '0x0F0F'    ''    ''

Note that the empty fields results in NaN values.

How to check currently internet connection is available or not in android

use the next code:

public static boolean isNetworkAvaliable(Context ctx) {
    ConnectivityManager connectivityManager = (ConnectivityManager) ctx
            .getSystemService(Context.CONNECTIVITY_SERVICE);
    if ((connectivityManager
            .getNetworkInfo(ConnectivityManager.TYPE_MOBILE) != null && connectivityManager
            .getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState() == NetworkInfo.State.CONNECTED)
            || (connectivityManager
                    .getNetworkInfo(ConnectivityManager.TYPE_WIFI) != null && connectivityManager
                    .getNetworkInfo(ConnectivityManager.TYPE_WIFI)
                    .getState() == NetworkInfo.State.CONNECTED)) {
        return true;
    } else {
        return false;
    }
}

remember that yo need put in your manifest the next line:

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

Which Java library provides base64 encoding/decoding?

If you're an Android developer you can use android.util.Base64 class for this purpose.

Error: Argument is not a function, got undefined

In my case it was a simple typo in index.html:

<script src="assets/javascript/controllers/questionssIndexController.js"></script>

that should have been

<script src="assets/javascript/controllers/questionsIndexController.js"></script>

without the extra s in the controller's name.

Proper way to catch exception from JSON.parse

We can check error & 404 statusCode, and use try {} catch (err) {}.

You can try this :

_x000D_
_x000D_
const req = new XMLHttpRequest();_x000D_
req.onreadystatechange = function() {_x000D_
    if (req.status == 404) {_x000D_
        console.log("404");_x000D_
        return false;_x000D_
    }_x000D_
_x000D_
    if (!(req.readyState == 4 && req.status == 200))_x000D_
        return false;_x000D_
_x000D_
    const json = (function(raw) {_x000D_
        try {_x000D_
            return JSON.parse(raw);_x000D_
        } catch (err) {_x000D_
            return false;_x000D_
        }_x000D_
    })(req.responseText);_x000D_
_x000D_
    if (!json)_x000D_
        return false;_x000D_
_x000D_
    document.body.innerHTML = "Your city : " + json.city + "<br>Your isp : " + json.org;_x000D_
};_x000D_
req.open("GET", "https://ipapi.co/json/", true);_x000D_
req.send();
_x000D_
_x000D_
_x000D_

Read more :

How to check if an option is selected?

UPDATE

A more direct jQuery method to the option selected would be:

var selected_option = $('#mySelectBox option:selected');

Answering the question .is(':selected') is what you are looking for:

$('#mySelectBox option').each(function() {
    if($(this).is(':selected')) ...

The non jQuery (arguably best practice) way to do it would be:

$('#mySelectBox option').each(function() {
    if(this.selected) ...

Although, if you are just looking for the selected value try:

$('#mySelectBox').val()

If you are looking for the selected value's text do:

$('#mySelectBox option').filter(':selected').text();

Check out: http://api.jquery.com/selected-selector/

Next time look for duplicate SO questions:

Get current selected option or Set selected option or How to get $(this) selected option in jQuery? or option[selected=true] doesn't work

What's the difference between a mock & stub?

Plus useful answers, One of the most powerful point of using Mocks than Subs

If the collaborator [which the main code depend on it] is not under our control (e.g. from a third-party library),
In this case, stub is more difficult to write rather than mock.

Remove gutter space for a specific div only

Okay If you want to change the gutter inside one row, but want those (first and last) inner divs to align with the grid surrounding the .no-gutter row, you could copy-paste-merge most answers into the following snippet:

.row.no-gutter [class*='col-']:first-child:not(:only-child) {
    padding-right: 0;
}
.row.no-gutter [class*='col-']:last-child:not(:only-child) {
    padding-left: 0;
}
.row.no-gutter [class*='col-']:not(:first-child):not(:last-child):not(:only-child) {
    padding-right: 0;
    padding-left: 0;
}

If you like to have a smaller gutter instead of completly none, just change the 0's to what you like... (eg: 5px to get 10px gutter).

Export html table data to Excel using JavaScript / JQuery is not working properly in chrome browser

Regarding to sampopes answer from Jun 6 '14 at 11:59:

I have insert a css style with font-size of 20px to display the excel data greater. In sampopes code the leading <tr> tags are missing, so i first output the headline and than the other tables lines within a loop.

function fnExcelReport()
{
    var tab_text = '<table border="1px" style="font-size:20px" ">';
    var textRange; 
    var j = 0;
    var tab = document.getElementById('DataTableId'); // id of table
    var lines = tab.rows.length;

    // the first headline of the table
    if (lines > 0) {
        tab_text = tab_text + '<tr bgcolor="#DFDFDF">' + tab.rows[0].innerHTML + '</tr>';
    }

    // table data lines, loop starting from 1
    for (j = 1 ; j < lines; j++) {     
        tab_text = tab_text + "<tr>" + tab.rows[j].innerHTML + "</tr>";
    }

    tab_text = tab_text + "</table>";
    tab_text = tab_text.replace(/<A[^>]*>|<\/A>/g, "");             //remove if u want links in your table
    tab_text = tab_text.replace(/<img[^>]*>/gi,"");                 // remove if u want images in your table
    tab_text = tab_text.replace(/<input[^>]*>|<\/input>/gi, "");    // reomves input params
    // console.log(tab_text); // aktivate so see the result (press F12 in browser)

    var ua = window.navigator.userAgent;
    var msie = ua.indexOf("MSIE "); 

     // if Internet Explorer
    if (msie > 0 || !!navigator.userAgent.match(/Trident.*rv\:11\./)) {
        txtArea1.document.open("txt/html","replace");
        txtArea1.document.write(tab_text);
        txtArea1.document.close();
        txtArea1.focus(); 
        sa = txtArea1.document.execCommand("SaveAs", true, "DataTableExport.xls");
    }  
    else // other browser not tested on IE 11
        sa = window.open('data:application/vnd.ms-excel,' + encodeURIComponent(tab_text));  

    return (sa);
}   

Convert to absolute value in Objective-C

Depending on the type of your variable, one of abs(int), labs(long), llabs(long long), imaxabs(intmax_t), fabsf(float), fabs(double), or fabsl(long double).

Those functions are all part of the C standard library, and so are present both in Objective-C and plain C (and are generally available in C++ programs too.)

(Alas, there is no habs(short) function. Or scabs(signed char) for that matter...)


Apple's and GNU's Objective-C headers also include an ABS() macro which is type-agnostic. I don't recommend using ABS() however as it is not guaranteed to be side-effect-safe. For instance, ABS(a++) will have an undefined result.


If you're using C++ or Objective-C++, you can bring in the <cmath> header and use std::abs(), which is templated for all the standard integer and floating-point types.

How to create EditText accepts Alphabets only in android?

Allow only Alphabets in EditText android:

InputFilter letterFilter = new InputFilter() {
        public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
            String filtered = "";
            for (int i = start; i < end; i++) {
                char character = source.charAt(i);
                if (!Character.isWhitespace(character)&&Character.isLetter(character)) {
                    filtered += character;
                }
            }

            return filtered;
        }

    };
editText.setFilters(new InputFilter[]{letterFilter}); 

How to filter by string in JSONPath?

The browser testing tools while convenient can be a bit deceiving. Consider:

{
  "resourceType": "Encounter",
  "id": "EMR56788",
  "text": {
    "status": "generated",
    "div": "Patient admitted with chest pains</div>"
  },
  "status": "in-progress",
  "class": "inpatient",
  "patient": {
    "reference": "Patient/P12345",
    "display": "Roy Batty"
  }
}

Most tools returned this as false:

$[?(@.class==inpatient)]

But when I executed against

<dependency>
    <groupId>com.jayway.jsonpath</groupId>
    <artifactId>json-path</artifactId>
    <version>1.2.0</version>
</dependency>

It returned true. I recommend writing a simple unit test to verify rather than rely on the browser testing tools.

Customizing Bootstrap CSS template

I recently wrote a post about how I've been doing it at Udacity for the last couple years. This method has meant we've been able to update Bootstrap whenever we wanted to without having merge conflicts, thrown out work, etc. etc.

The post goes more in depth with examples, but the basic idea is:

  • Keep a pristine copy of bootstrap and overwrite it externally.
  • Modify one file (bootstrap's variables.less) to include your own variables.
  • Make your site file @include bootstrap.less and then your overrides.

This does mean using LESS, and compiling it down to CSS before shipping it to the client (client-side LESS if finicky, and I generally avoid it) but it is EXTREMELY good for maintainability/upgradability, and getting LESS compilation is really really easy. The linked github code has an example using grunt, but there are many ways to achieve this -- even GUIs if that's your thing.

Using this solution, your example problem would look like:

  • Change the nav bar color with @navbar-inverse-bg in your variables.less (not bootstrap's)
  • Add your own nav bar styles to your bootstrap_overrides.less, overwriting anything you need to as you go.
  • Happiness.

When it comes time to upgrade your bootstrap, you just swap out the pristine bootstrap copy and everything will still work (if bootstrap makes breaking changes, you'll need to update your overrides, but you'd have to do that anyway)

Blog post with walk-through is here.

Code example on github is here.

PDO Prepared Inserts multiple rows in single query

This is how I did it:

First define the column names you'll use, or leave it blank and pdo will assume you want to use all the columns on the table - in which case you'll need to inform the row values in the exact order they appear on the table.

$cols = 'name', 'middleName', 'eMail';
$table = 'people';

Now, suppose you have a two dimensional array already prepared. Iterate it, and construct a string with your row values, as such:

foreach ( $people as $person ) {
if(! $rowVals ) {
$rows = '(' . "'$name'" . ',' . "'$middleName'" . ',' .           "'$eMail'" . ')';
} else { $rowVals  = '(' . "'$name'" . ',' . "'$middleName'" . ',' . "'$eMail'" . ')';
}

Now, what you just did was check if $rows was already defined, and if not, create it and store row values and the necessary SQL syntax so it will be a valid statement. Note that strings should go inside double quotes and single quotes, so they will be promptly recognized as such.

All it's left to do is prepare the statement and execute, as such:

$stmt = $db->prepare ( "INSERT INTO $table $cols VALUES $rowVals" );
$stmt->execute ();

Tested with up to 2000 rows so far, and the execution time is dismal. Will run some more tests and will get back here in case I have something further to contribute.

Regards.

How to downgrade php from 7.1.1 to 5.6 in xampp 7.1.1?

It is very easy to do, all you need to do is 1) download 5.6 from [1]: https://sourceforge.net/projects/xampp/files/XAMPP%20Windows/5.6.36/, the run the setup and install in folder "xampp"

2) download 7.6 from [https://sourceforge.net/projects/xampp/files/XAMPP%20Windows/7.4.2/xampp-portable-windows-x64-7.4.2-0-VC15-installer.exe/download][1] and run the setup in "xampp2"

NOte: after that you now have separate xampp installed in your system. all you do now is to run each xampp as a separate entity. Alway quite the 5.6 if you want to run 7.6

Class Not Found: Empty Test Suite in IntelliJ

My fix for this issue was with folder names and paths.

My test were missing /java/ folder for some reason and IntelliJ didn't like that.

so from ../test/com/.. to ../test/java/com/..

and it is ok

How can I format the output of a bash command in neat columns

Try

xargs -n2  printf "%-20s%s\n"

or even

xargs printf "%-20s%s\n"

if input is not very large.

What is the difference between _tmain() and main() in C++?

the _T convention is used to indicate the program should use the character set defined for the application (Unicode, ASCII, MBCS, etc.). You can surround your strings with _T( ) to have them stored in the correct format.

 cout << _T( "There are " ) << argc << _T( " arguments:" ) << endl;

Error HRESULT E_FAIL has been returned from a call to a COM component VS2012 when debugging

The error occurred for me after I installed the latest Windows 10 SDK. I was getting the error while building a C++ project using SDK 8.1. In Project properties, I switch to latest 10 SDK. rebuild. That worked. Changed back to 8.1. Rebuild. No error.

jQuery: select an element's class and id at the same time?

Just to add that the answer that Alex provided worked for me, and not the one that is highlighted as an answer.

This one didn't work for me

$('#country.save') 

But this one did:

$('#country .save') 

so my conclusion is to use the space. Now I don't know if it's to the new version of jQuery that I'm using (1.5.1), but anyway hope this helps to anyone with similar problem that I've had.

edit: Full credit for explanation (in the comment to Alex's answer) goes to Felix Kling who says:

The space is the descendant selector, i.e. A B means "Match all elements that match B which are a descendant of elements matching A". AB means "select all element that match A and B". So it really depends on what you want to achieve. #country.save and #country .save are not equivalent.

formatFloat : convert float number to string

Try this

package main

import "fmt"
import "strconv"

func FloatToString(input_num float64) string {
    // to convert a float number to a string
    return strconv.FormatFloat(input_num, 'f', 6, 64)
}

func main() {
    fmt.Println(FloatToString(21312421.213123))
}

If you just want as many digits precision as possible, then the special precision -1 uses the smallest number of digits necessary such that ParseFloat will return f exactly. Eg

strconv.FormatFloat(input_num, 'f', -1, 64)

Personally I find fmt easier to use. (Playground link)

fmt.Printf("x = %.6f\n", 21312421.213123)

Or if you just want to convert the string

fmt.Sprintf("%.6f", 21312421.213123)

why does DateTime.ToString("dd/MM/yyyy") give me dd-MM-yyyy?

If you use MVC, tables, it works like this:

<td>@(((DateTime)detalle.fec).ToString("dd'/'MM'/'yyyy"))</td>

What does if [ $? -eq 0 ] mean for shell scripts?

It's checking the return value ($?) of grep. In this case it's comparing it to 0 (success).

Usually when you see something like this (checking the return value of grep) it's checking to see whether the particular string was detected. Although the redirect to /dev/null isn't necessary, the same thing can be accomplished using -q.

sys.argv[1] meaning in script

To pass arguments to your python script while running a script via command line

python create_thumbnail.py test1.jpg test2.jpg

here, script name - create_thumbnail.py, argument 1 - test1.jpg, argument 2 - test2.jpg

With in the create_thumbnail.py script i use

sys.argv[1:]

which give me the list of arguments i passed in command line as ['test1.jpg', 'test2.jpg']

StringUtils.isBlank() vs String.isEmpty()

StringUtils.isBlank() will also check for null, whereas this:

String foo = getvalue("foo");
if (foo.isEmpty())

will throw a NullPointerException if foo is null.

Get and Set Screen Resolution

In C# this is how to get the resolution Screen:

button click or form load:

string screenWidth = Screen.PrimaryScreen.Bounds.Width.ToString();
string screenHeight = Screen.PrimaryScreen.Bounds.Height.ToString();
Label1.Text = ("Resolution: " + screenWidth + "x" + screenHeight);

How can I solve a connection pool problem between ASP.NET and SQL Server?

This problem i had in my code. I will paste some example code i have over came below error. The timeout period elapsed prior to obtaining a connection from the pool. This may have occurred because all pooled connections were in use and max pool size was reached.

 String query = "insert into STATION2(ID,CITY,STATE,LAT_N,LONG_W) values('" + a1 + "','" + b1 + "','" + c1 + "','" + d1 + "','" + f1 + "')";
    //,'" + d1 + "','" + f1 + "','" + g1 + "'

    SqlConnection con = new SqlConnection(mycon);
    con.Open();
    SqlCommand cmd = new SqlCommand();
    cmd.CommandText = query;
    cmd.Connection = con;
    cmd.ExecuteNonQuery();
    **con.Close();**

You want to close the connection each and every time. Before that i didn't us the close connect due to this i got error. After adding close statement i have over came this error

Throw keyword in function's signature

The only practical effect of the throw specifier is that if something different from myExc is thrown by your function, std::unexpected will be called (instead of the normal unhandled exception mechanism).

To document the kind of exceptions that a function can throw, I typically do this:

bool
some_func() /* throw (myExc) */ {
}

Maven:Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:2.7:resources

In my case the targetPath was not having any value it was blank in the resources --> resource for the file directory with files that had issue. I had to update it to global as seen in the Code Sample 2 and re-run build to fix the issue.

Code Sample 1 (with issue)

<build>
    <resources>
        <resource>
            <directory>src/main/locale</directory>
            <filtering>true</filtering>
            <targetPath></targetPath>
            <includes>
                <include>*.xml</include>
                <include>*.config</include>
                <include>*.properties</include>
            </includes>
        </resource>
    </resources>

Code Sample 2 (fix applied)

<build>
    <resources>
        <resource>
            <directory>src/main/locale</directory>
            <filtering>true</filtering>
            <targetPath>global</targetPath>
            <includes>
                <include>*.xml</include>
                <include>*.config</include>
                <include>*.properties</include>
            </includes>
        </resource>
    </resources>

PostgreSQL Exception Handling

Use the DO statement, a new option in version 9.0:

DO LANGUAGE plpgsql
$$
BEGIN
CREATE TABLE "Logs"."Events"
    (
        EventId BIGSERIAL NOT NULL PRIMARY KEY,
        PrimaryKeyId bigint NOT NULL,
        EventDateTime date NOT NULL DEFAULT(now()),
        Action varchar(12) NOT NULL,
        UserId integer NOT NULL REFERENCES "Office"."Users"(UserId),
        PrincipalUserId varchar(50) NOT NULL DEFAULT(user)
    );

    CREATE TABLE "Logs"."EventDetails"
    (
        EventDetailId BIGSERIAL NOT NULL PRIMARY KEY,
        EventId bigint NOT NULL REFERENCES "Logs"."Events"(EventId),
        Resource varchar(64) NOT NULL,
        OldVal varchar(4000) NOT NULL,
        NewVal varchar(4000) NOT NULL
    );

    RAISE NOTICE 'Task completed sucessfully.';    
END;
$$;

Clear Cache in Android Application programmatically

The answer from dhams is correct (after having been edited several times), but as the many edits of the code shows, it is difficult to write correct and robust code for deleting a directory (with sub-dirs) yourself. So I strongly suggest using Apache Commons IO, or some other API that does this for you:

import org.apache.commons.io.FileUtils;

...

// Delete local cache dir (ignoring any errors):
FileUtils.deleteQuietly(context.getCacheDir());

PS: Also delete the directory returned by context.getExternalCacheDir() if you use that.

To be able to use Apache Commons IO, add this to your build.gradle file, in the dependencies part:

compile 'commons-io:commons-io:2.4'

Connecting to SQL Server using windows authentication

This worked for me:

in web.config file;

<add name="connectionstring name " connectionstring="server=SQLserver name; database= databasename; integrated security = true"/>

Apache: client denied by server configuration

Can you try changing "Allow from 127.0.0 192.168.1 ::1 localhost" to "Allow from all". If that fixes your problem, you need to be less restrict about where content can be requested from

how to add picasso library in android studio

Add the Picasso library in Dependency

dependencies {
       ...
       implementation 'com.squareup.picasso:picasso:2.71828'
       ...
    }

Sync The Project Create one imageview in Layout

<ImageView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/imageView"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true">
</ImageView>

Add the Internet permission in Manifest file

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

//Initialize ImageView

ImageView imageView = (ImageView) findViewById(R.id.imageView);

//Loading image from below url into imageView

Picasso.get()
   .load("YOUR IMAGE URL HERE")
   .into(imageView);

MySQL JDBC Driver 5.1.33 - Time Zone Issue

I am late, But If you are struggling through the following error and using datasource(javax.sql.DataSource):

The server time zone value 'CEST' is unrecognized or represents more than one time zone.

Set following line to get rid of the error:

MysqlDataSource dataSource = new MysqlDataSource();
dataSource.setServerTimezone("UTC");

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]

Creating a new empty branch for a new project

On base this answer from Hiery Nomus.

You can create a branch as an orphan:

git checkout --orphan <branchname>

This will create a new branch with no parents. Then, you can clear the working directory with:

git rm --cached -r .

And then you just commit branch with empty commit and then push

git commit -m <commit message> --allow-empty
git push origin <newbranch>

Quick Way to Implement Dictionary in C

The quickest way would be to use an already-existing implementation, like uthash.

And, if you really want to code it yourself, the algorithms from uthash can be examined and re-used. It's BSD-licensed so, other than the requirement to convey the copyright notice, you're pretty well unlimited in what you can do with it.

PHP Error: Cannot use object of type stdClass as array (array and object issues)

If you're iterating over an object instead of an array, you'll need to access the properties using:

$id = $blog->id;
$title = $blog->title;
$content = $blog->content;

That, or change your object to an array.

How to abort an interactive rebase if --abort doesn't work?

Try to follow the advice you see on the screen, and first reset your master's HEAD to the commit it expects.

git update-ref refs/heads/master b918ac16a33881ce00799bea63d9c23bf7022d67

Then, abort the rebase again.

Display alert message and redirect after click on accept

Combining CodeIgniter and JavaScript:

//for using the base_url() function
$this->load->helper('url');

echo "<script type='javascript/text'>";
echo "alert('There are no fields to generate a report');"
echo "window.location.href = '" . base_url() . "admin/ahm/panel';"
echo "</script>";

Note: The redirect() function automatically includes the base_url path that is why it wasn't required there.

How to get numbers after decimal point?

Just using simple operator division '/' and floor division '//' you can easily get the fraction part of any given float.

number = 5.55

result = (number/1) - (number//1)

print(result)

How do I detect a page refresh using jquery?

There are two events on client side as given below.

1. window.onbeforeunload (calls on Browser/tab Close & Page Load)

2. window.onload (calls on Page Load)

On server Side

public JsonResult TestAjax( string IsRefresh)
    {
        JsonResult result = new JsonResult();
        return result = Json("Called", JsonRequestBehavior.AllowGet);
    }

On Client Side

_x000D_
_x000D_
 <script type="text/javascript">_x000D_
    window.onbeforeunload = function (e) {_x000D_
        _x000D_
        $.ajax({_x000D_
            type: 'GET',_x000D_
            async: false,_x000D_
            url: '/Home/TestAjax',_x000D_
            data: { IsRefresh: 'Close' }_x000D_
        });_x000D_
    };_x000D_
_x000D_
    window.onload = function (e) {_x000D_
_x000D_
        $.ajax({_x000D_
            type: 'GET',_x000D_
            async: false,_x000D_
            url: '/Home/TestAjax',_x000D_
            data: {IsRefresh:'Load'}_x000D_
        });_x000D_
    };_x000D_
</script>
_x000D_
_x000D_
_x000D_

On Browser/Tab Close: if user close the Browser/tab, then window.onbeforeunload will fire and IsRefresh value on server side will be "Close".

On Refresh/Reload/F5: If user will refresh the page, first window.onbeforeunload will fire with IsRefresh value = "Close" and then window.onload will fire with IsRefresh value = "Load", so now you can determine at last that your page is refreshing.

Specifying colClasses in the read.csv

For multiple datetime columns with no header, and a lot of columns, say my datetime fields are in columns 36 and 38, and I want them read in as character fields:

data<-read.csv("test.csv", head=FALSE,   colClasses=c("V36"="character","V38"="character"))                        

Adding quotes to a string in VBScript

You have to use double double quotes to escape the double quotes (lol):

g = "abcd """ & a & """"

How to get Client location using Google Maps API v3?

A bit late but I got something similar that I'm busy building and here is the code to get current location - be sure to use local server to test.

Include relevant scripts from CDN:

    <script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&signed_in=true&callback=initMap">

HTML

<div id="map"></div>

CSS

html, body {
    height: 100%;
    margin: 0;
    padding: 0;
}
#map {
    height: 100%;
}

JS

var map = new google.maps.Map(document.getElementById('map'), {
    center: {lat: -34.397, lng: 150.644},
    zoom: 6
});
var infoWindow = new google.maps.InfoWindow({map: map});

// Try HTML5 geolocation.
if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(function(position) {
        var pos = {
            lat: position.coords.latitude,
            lng: position.coords.longitude
        };

        infoWindow.setPosition(pos);
        infoWindow.setContent('Location found.');
        map.setCenter(pos);
    }, function() {
        handleLocationError(true, infoWindow, map.getCenter());
    });
} else {
    // Browser doesn't support Geolocation
    handleLocationError(false, infoWindow, map.getCenter());
}

function handleLocationError(browserHasGeolocation, infoWindow, pos) {
    infoWindow.setPosition(pos);
    infoWindow.setContent(browserHasGeolocation ?
                          'Error: The Geolocation service failed.' :
                          'Error: Your browser doesn\'t support geolocation.');
}

DEMO

https://jsfiddle.net/ToreanJoel/4ythpy02/

Setting up FTP on Amazon Cloud Server

Jaminto did a great job of answering the question, but I recently went through the process myself and wanted to expand on Jaminto's answer.

I'm assuming that you already have an EC2 instance created and have associated an Elastic IP Address to it.


Step #1: Install vsftpd

SSH to your EC2 server. Type:

> sudo yum install vsftpd

This should install vsftpd.

Step #2: Open up the FTP ports on your EC2 instance

Next, you'll need to open up the FTP ports on your EC2 server. Log in to the AWS EC2 Management Console and select Security Groups from the navigation tree on the left. Select the security group assigned to your EC2 instance. Then select the Inbound tab, then click Edit:

enter image description here

Add two Custom TCP Rules with port ranges 20-21 and 1024-1048. For Source, you can select 'Anywhere'. If you decide to set Source to your own IP address, be aware that your IP address might change if it is being assigned via DHCP.

enter image description here



Step #3: Make updates to the vsftpd.conf file

Edit your vsftpd conf file by typing:

> sudo vi /etc/vsftpd/vsftpd.conf

Disable anonymous FTP by changing this line:

anonymous_enable=YES

to

anonymous_enable=NO

Then add the following lines to the bottom of the vsftpd.conf file:

pasv_enable=YES
pasv_min_port=1024
pasv_max_port=1048
pasv_address=<Public IP of your instance> 

Your vsftpd.conf file should look something like the following - except make sure to replace the pasv_address with your public facing IP address:

enter image description here

To save changes, press escape, then type :wq, then hit enter.



Step #4: Restart vsftpd

Restart vsftpd by typing:

> sudo /etc/init.d/vsftpd restart

You should see a message that looks like:

enter image description here


If this doesn't work, try:

> sudo /sbin/service vsftpd restart



Step #5: Create an FTP user

If you take a peek at /etc/vsftpd/user_list, you'll see the following:

# vsftpd userlist
# If userlist_deny=NO, only allow users in this file
# If userlist_deny=YES (default), never allow users in this file, and
# do not even prompt for a password.
# Note that the default vsftpd pam config also checks /etc/vsftpd/ftpusers
# for users that are denied.
root
bin
daemon
adm
lp
sync
shutdown
halt
mail
news
uucp
operator
games
nobody

This is basically saying, "Don't allow these users FTP access." vsftpd will allow FTP access to any user not on this list.

So, in order to create a new FTP account, you may need to create a new user on your server. (Or, if you already have a user account that's not listed in /etc/vsftpd/user_list, you can skip to the next step.)

Creating a new user on an EC2 instance is pretty simple. For example, to create the user 'bret', type:

> sudo adduser bret
> sudo passwd bret

Here's what it will look like:

enter image description here



Step #6: Restricting users to their home directories

At this point, your FTP users are not restricted to their home directories. That's not very secure, but we can fix it pretty easily.

Edit your vsftpd conf file again by typing:

> sudo vi /etc/vsftpd/vsftpd.conf

Un-comment out the line:

chroot_local_user=YES

It should look like this once you're done:

enter image description here

Restart the vsftpd server again like so:

> sudo /etc/init.d/vsftpd restart

All done!


Appendix A: Surviving a reboot

vsftpd doesn't automatically start when your server boots. If you're like me, that means that after rebooting your EC2 instance, you'll feel a moment of terror when FTP seems to be broken - but in reality, it's just not running!. Here's a handy way to fix that:

> sudo chkconfig --level 345 vsftpd on

Alternatively, if you are using redhat, another way to manage your services is by using this nifty graphic user interface to control which services should automatically start:

>  sudo ntsysv

enter image description here

Now vsftpd will automatically start up when your server boots up.


Appendix B: Changing a user's FTP home directory

* NOTE: Iman Sedighi has posted a more elegant solution for restricting users access to a specific directory. Please refer to his excellent solution posted as an answer *

You might want to create a user and restrict their FTP access to a specific folder, such as /var/www. In order to do this, you'll need to change the user's default home directory:

> sudo usermod -d /var/www/ username

In this specific example, it's typical to give the user permissions to the 'www' group, which is often associated with the /var/www folder:

> sudo usermod -a -G www username

Mailto links do nothing in Chrome but work in Firefox?

The usual <a href="mailto:[email protected]"></a> should work, but remember you must have a default email program set on your computer. For ex, I'm using Ubuntu 14.04 and the default email is thunderbird, which works fine.

Decreasing height of bootstrap 3.0 navbar

If you guys are generating your stylesheets with LESS/SASS and are importing Bootstrap there, I've found that overriding the @navbar-height variable lets your set the height of the navbar, which is originally defined in the variables.less file.

enter image description here

Align two divs horizontally side by side center to the page using bootstrap css

This should do the trick:

<div class="container">
    <div class="row">
        <div class="col-xs-6">
            ONE
        </div>
        <div class="col-xs-6">
            TWO
        </div>
    </div>
</div>

Have a read of the grid system section of the Bootstrap docs to familiarise yourself with how Bootstrap's grids work:

http://getbootstrap.com/css/#grid

Trigger standard HTML5 validation (form) without using submit button?

I think its simpler:

$('submit').click(function(e){
if (e.isValid())
   e.preventDefault();
//your code.
}

this will stop the submit until form is valid.

How can I get dictionary key as variable directly in Python (not by searching from value)?

What I sometimes do is I create another dictionary just to be able whatever I feel I need to access as string. Then I iterate over multiple dictionaries matching keys to build e.g. a table with first column as description.

dict_names = {'key1': 'Text 1', 'key2': 'Text 2'}
dict_values = {'key1': 0, 'key2': 1} 

for key, value in dict_names.items():
    print('{0} {1}'.format(dict_names[key], dict_values[key])

You can easily do for a huge amount of dictionaries to match data (I like the fact that with dictionary you can always refer to something well known as the key name)

yes I use dictionaries to store results of functions so I don't need to run these functions everytime I call them just only once and then access the results anytime.

EDIT: in my example the key name does not really matter (I personally like using the same key names as it is easier to go pick a single value from any of my matching dictionaries), just make sure the number of keys in each dictionary is the same

What does the "@" symbol do in Powershell?

PowerShell will actually treat any comma-separated list as an array:

"server1","server2"

So the @ is optional in those cases. However, for associative arrays, the @ is required:

@{"Key"="Value";"Key2"="Value2"}

Officially, @ is the "array operator." You can read more about it in the documentation that installed along with PowerShell, or in a book like "Windows PowerShell: TFM," which I co-authored.

mailto link with HTML body

Anybody can try the following (mailto function only accepts plaintext but here i show how to use HTML innertext properties and how to add an anchor as mailto body params):

//Create as many html elements you need.

const titleElement = document.createElement("DIV");
titleElement.innerHTML = this.shareInformation.title; // Just some string

//Here I create an <a> so I can use href property
const titleLinkElement = document.createElement("a");
titleLinkElement.href = this.shareInformation.link; // This is a url

...

let mail = document.createElement("a");

// Using es6 template literals add the html innerText property and anchor element created to mailto body parameter
mail.href = 
  `mailto:?subject=${titleElement.innerText}&body=${titleLinkElement}%0D%0A${abstractElement.innerText}`;
mail.click();

// Notice how I use ${titleLinkElement} that is an anchor element, so mailto uses its href and renders the url I needed

Received an invalid column length from the bcp client for colid 6

I know this post is old but I ran into this same issue and finally figured out a solution to determine which column was causing the problem and report it back as needed. I determined that colid returned in the SqlException is not zero based so you need to subtract 1 from it to get the value. After that it is used as the index of the _sortedColumnMappings ArrayList of the SqlBulkCopy instance not the index of the column mappings that were added to the SqlBulkCopy instance. One thing to note is that SqlBulkCopy will stop on the first error received so this may not be the only issue but at least helps to figure it out.

try
{
    bulkCopy.WriteToServer(importTable);
    sqlTran.Commit();
}    
catch (SqlException ex)
{
    if (ex.Message.Contains("Received an invalid column length from the bcp client for colid"))
    {
        string pattern = @"\d+";
        Match match = Regex.Match(ex.Message.ToString(), pattern);
        var index = Convert.ToInt32(match.Value) -1;

        FieldInfo fi = typeof(SqlBulkCopy).GetField("_sortedColumnMappings", BindingFlags.NonPublic | BindingFlags.Instance);
        var sortedColumns = fi.GetValue(bulkCopy);
        var items = (Object[])sortedColumns.GetType().GetField("_items", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(sortedColumns);

        FieldInfo itemdata = items[index].GetType().GetField("_metadata", BindingFlags.NonPublic | BindingFlags.Instance);
        var metadata = itemdata.GetValue(items[index]);

        var column = metadata.GetType().GetField("column", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance).GetValue(metadata);
        var length = metadata.GetType().GetField("length", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance).GetValue(metadata);
        throw new DataFormatException(String.Format("Column: {0} contains data with a length greater than: {1}", column, length));
    }

    throw;
}

ArrayAdapter in android to create simple listview

The TextView resource id it needs is for a TextView layout file, so it won't be in the same activity.

You can create it by going to File > New > XML > XML Layout File, and enter the widget type, which is 'TextView' in the root tag field.

Source: https://www.kompulsa.com/the-simplest-way-to-implement-an-android-listview/

Submitting form and pass data to controller method of type FileStreamResult

When in doubt, follow MVC conventions.

Create a viewModel if you haven't already that contains a property for JobID

public class Model
{
     public string JobId {get; set;}
     public IEnumerable<MyCurrentModel> myCurrentModel { get; set; }
     //...any other properties you may need
}

Strongly type your view

@model Fully.Qualified.Path.To.Model

Add a hidden field for JobId to the form

using (@Html.BeginForm("myMethod", "Home", FormMethod.Post))
{   
    //...    
    @Html.HiddenFor(m => m.JobId)
}

And accept the model as the parameter in your controller action:

[HttpPost]
public FileStreamResult myMethod(Model model)
{
    sting str = model.JobId;
}

ORDER BY using Criteria API

It's hard to know for sure without seeing the mappings (see @Juha's comment), but I think you want something like the following:

Criteria c = session.createCriteria(Cat.class);
Criteria c2 = c.createCriteria("mother");
Criteria c3 = c2.createCriteria("kind");
c3.addOrder(Order.asc("value"));
return c.list();

How do I position a div at the bottom center of the screen

If you aren't comfortable with using negative margins, check this out.

div {
  position: fixed;
  left: 50%;
  bottom: 20px;
  transform: translate(-50%, -50%);
  margin: 0 auto;
}
<div>
  Your Text
</div>

Especially useful when you don't know the width of the div.


align="center" has no effect.

Since you have position:absolute, I would recommend positioning it 50% from the left and then subtracting half of its width from its left margin.

#manipulate {
    position:absolute;
    width:300px;
    height:300px;
    background:#063;
    bottom:0px;
    right:25%;
    left:50%;
    margin-left:-150px;
}

How to create strings containing double quotes in Excel formulas?

I use a function for this (if the workbook already has VBA).

Function Quote(inputText As String) As String
  Quote = Chr(34) & inputText & Chr(34)
End Function

This is from Sue Mosher's book "Microsoft Outlook Programming". Then your formula would be:

="Maurice "&Quote("Rocket")&" Richard"

This is similar to what Dave DuPlantis posted.

Setting WPF image source in code

Simplest way:

var uriSource = new Uri("image path here");
image1.Source = new BitmapImage(uriSource);

How to perform Join between multiple tables in LINQ lambda

For joins, I strongly prefer query-syntax for all the details that are happily hidden (not the least of which are the transparent identifiers involved with the intermediate projections along the way that are apparent in the dot-syntax equivalent). However, you asked regarding Lambdas which I think you have everything you need - you just need to put it all together.

var categorizedProducts = product
    .Join(productcategory, p => p.Id, pc => pc.ProdId, (p, pc) => new { p, pc })
    .Join(category, ppc => ppc.pc.CatId, c => c.Id, (ppc, c) => new { ppc, c })
    .Select(m => new { 
        ProdId = m.ppc.p.Id, // or m.ppc.pc.ProdId
        CatId = m.c.CatId
        // other assignments
    });

If you need to, you can save the join into a local variable and reuse it later, however lacking other details to the contrary, I see no reason to introduce the local variable.

Also, you could throw the Select into the last lambda of the second Join (again, provided there are no other operations that depend on the join results) which would give:

var categorizedProducts = product
    .Join(productcategory, p => p.Id, pc => pc.ProdId, (p, pc) => new { p, pc })
    .Join(category, ppc => ppc.pc.CatId, c => c.Id, (ppc, c) => new {
        ProdId = ppc.p.Id, // or ppc.pc.ProdId
        CatId = c.CatId
        // other assignments
    });

...and making a last attempt to sell you on query syntax, this would look like this:

var categorizedProducts =
    from p in product
    join pc in productcategory on p.Id equals pc.ProdId
    join c in category on pc.CatId equals c.Id
    select new {
        ProdId = p.Id, // or pc.ProdId
        CatId = c.CatId
        // other assignments
    };

Your hands may be tied on whether query-syntax is available. I know some shops have such mandates - often based on the notion that query-syntax is somewhat more limited than dot-syntax. There are other reasons, like "why should I learn a second syntax if I can do everything and more in dot-syntax?" As this last part shows - there are details that query-syntax hides that can make it well worth embracing with the improvement to readability it brings: all those intermediate projections and identifiers you have to cook-up are happily not front-and-center-stage in the query-syntax version - they are background fluff. Off my soap-box now - anyhow, thanks for the question. :)

What static analysis tools are available for C#?

The tool NDepend is quoted as Quality Metric Tools but it is pretty much also a Code violation detection tool. Disclaimer: I am one of the developers of the tool

With NDepend, one can write Code Rule over LINQ Queries (what we call CQLinq). More than 200 CQLinq code rules are proposed by default. The strength of CQLinq is that it is straightforward to write a code rule, and get immediately results. Facilities are proposed to browse matched code elements. For example:

CQLinq code rule

Beside that, NDepend comes with many others static analysis like features. These include:

How to make a phone call programmatically?

If you end up with a SecurityException (and the call does not work), You should consider requesting the user permission to make a call as this is considered a dangerous permission:

ActivityCompat.requestPermissions(
    activity,
    new String[] {Manifest.permission.CALL_PHONE},
    1
);

Note this has nothing to do with the manifest permission (that you must have as well)

Difference between socket and websocket?

Regarding your question (b), be aware that the Websocket specification hasn't been finalised. According to the W3C:

Implementors should be aware that this specification is not stable.

Personally I regard Websockets to be waaay too bleeding edge to use at present. Though I'll probably find them useful in a year or so.

GnuPG: "decryption failed: secret key not available" error from gpg on Windows

You need to import not only your secret key, but also the corresponding public key, or you'll get this error.

Databound drop down list - initial value

I know this already has a chosen answer - but I wanted to toss in my two cents. I have a databound dropdown list:

<asp:DropDownList 
  id="country" 
  runat="server" 
  CssClass="selectOne" 
  DataSourceID="country_code" 
  DataTextField="Name" 
  DataValueField="CountryCode_PK"
></asp:DropDownList>
<asp:SqlDataSource 
  id="country_code" 
  runat="server" 
  ConnectionString="<%$ ConnectionStrings:DBConnectionString %>"
  SelectCommand="SELECT CountryCode_PK, CountryCode_PK + ' - ' + Name AS N'Name' FROM TBL_Country ORDER BY CountryCode_PK"
></asp:SqlDataSource>

In the codebehind, I have this - (which selects United States by default):

if (this.IsPostBack)
{
  //handle posted data
}
else 
{
  country.SelectedValue = "US";
}

The page initially loads based on the 'US' value rather than trying to worry about a selectedIndex (what if another item is added into the data table - I don't want to have to re-code)

How to use global variable in node.js?

May be following is better to avoid the if statement:

global.logger || (global.logger = require('my_logger'));

Entity Framework. Delete all rows in table

This works for me... EF v3.1.5

context.ModelName.RemoveRange(context.ModelName.ToList());
context.SaveChanges();

Specify the from user when sending email using the mail command

Most people need to change two values when trying to correctly forge the from address on an email. First is the from address and the second is the orig-to address. Many of the solutions offered online only change one of these values.

If as root, I try a simple mail command to send myself an email it might look like this. echo "test" | mail -s "a test" [email protected]

And the associated logs: Feb 6 09:02:51 myserver postfix/qmgr[28875]: B10322269D: from=<[email protected]>, size=437, nrcpt=1 (queue active) Feb 6 09:02:52 myserver postfix/smtp[19848]: B10322269D: to=<[email protected]>, relay=myMTA[x.x.x.x]:25, delay=0.34, delays=0.1/0/0.11/0.13, dsn=2.0.0, status=sent (250 Ok 0000014b5f678593-a0e399ef-a801-4655-ad6b-19864a220f38-000000)

Trying to change the from address with -- echo "test" | mail -s "a test" [email protected] -- [email protected]

This changes the orig-to value but not the from value: Feb 6 09:09:09 myserver postfix/qmgr[28875]: 6BD362269D: from=<[email protected]>, size=474, nrcpt=2 (queue active) Feb 6 09:09:09 myserver postfix/smtp[20505]: 6BD362269D: to=<me@noone>, orig_to=<[email protected]>, relay=myMTA[x.x.x.x]:25, delay=0.31, delays=0.06/0/0.09/0.15, dsn=2.0.0, status=sent (250 Ok 0000014b5f6d48e2-a98b70be-fb02-44e0-8eb3-e4f5b1820265-000000)

Next trying it with a -r and a -- to adjust the from and orig-to. echo "test" | mail -s "a test" -r [email protected] [email protected] -- [email protected]

And the logs: Feb 6 09:17:11 myserver postfix/qmgr[28875]: E3B972264C: from=<[email protected]>, size=459, nrcpt=2 (queue active) Feb 6 09:17:11 myserver postfix/smtp[21559]: E3B972264C: to=<[email protected]>, orig_to=<[email protected]>, relay=myMTA[x.x.x.x]:25, delay=1.1, delays=0.56/0.24/0.11/0.17, dsn=2.0.0, status=sent (250 Ok 0000014b5f74a2c0-c06709f0-4e8d-4d7e-9abf-dbcea2bee2ea-000000)

This is how it's working for me. Hope this helps someone.

Android - Best and safe way to stop thread

On Android the same rules apply as in a normal Java environment. In Java threads are not killed, but the stopping of a thread is done in a cooperative way. The thread is asked to terminate and the thread can then shutdown gracefully.

Often a volatile boolean field is used which the thread periodically checks and terminates when it is set to the corresponding value.

I would not use a boolean to check whether the thread should terminate. If you use volatile as a field modifier, this will work reliable, but if your code becomes more complex, for instead uses other blocking methods inside the while loop, it might happen, that your code will not terminate at all or at least takes longer as you might want.

Certain blocking library methods support interruption.

Every thread has already a boolean flag interrupted status and you should make use of it. It can be implemented like this:

public void run() {

   try {
      while(!Thread.currentThread().isInterrupted()) {
         // ...
      }
   } catch (InterruptedException consumed)
      /* Allow thread to exit */
   }

}

public void cancel() { interrupt(); }

Source code taken from Java Concurrency in Practice. Since the cancel() method is public you can let another thread invoke this method as you wanted.

There is also a poorly named static method interrupted which clears the interrupted status of the current thread.

Executing a batch script on Windows shutdown

Programatically this can be achieved with SCHTASKS:

SCHTASKS /Create /SC ONEVENT /mo "Event[System[(EventID=1074)]]" /EC Security /tn on_shutdown_normal /tr "c:\some.bat" 

SCHTASKS /Create /SC ONEVENT /mo "Event[System[(EventID=6006)]]" /EC Security /tn on_shutdown_6006 /tr "c:\some.bat" 

SCHTASKS /Create /SC ONEVENT /mo "Event[System[(EventID=6008)]]" /EC Security /tn on_shutdown_6008 /tr "c:\some.bat" 

Create view with primary key?

You may not be able to create a primary key (per say) but if your view is based on a table with a primary key and the key is included in the view, then the primary key will be reflected in the view also. Applications requiring a primary key may accept the view as it is the case with Lightswitch.

Convert date to another timezone in JavaScript

quick and dirty manual hour changer and return:

return new Date(new Date().setHours(new Date().getHours()+3)).getHours()

How to write a multiline command?

After trying almost every key on my keyboard:

C:\Users\Tim>cd ^
Mehr? Desktop

C:\Users\Tim\Desktop>

So it seems to be the ^ key.

Arrays.fill with multidimensional array in Java

Arrays.fill works only with one-dimensional array

Source of java.util.Arrays:

public static void fill(Object[] a, Object val) {
        int i = 0;

        for(int len = a.length; i < len; ++i) {
            a[i] = val;
        }

Use own loops for initialization array

How can I get a collection of keys in a JavaScript dictionary?

With a modern JavaScript engine you can use Object.keys(driversCounter).

Python 3 Building an array of bytes

what about simply constructing your frame from a standard list ?

frame = bytes([0xA2,0x01,0x02,0x03,0x04])

the bytes() constructor can build a byte frame from an iterable containing int values. an iterable is anything which implements the iterator protocol: an list, an iterator, an iterable object like what is returned by range()...

Does JSON syntax allow duplicate keys in an object?

In C# if you deserialise to a Dictionary<string, string> it takes the last key value pair:

string json = @"{""a"": ""x"", ""a"": ""y""}";
var d = JsonConvert.DeserializeObject<Dictionary<string, string>>(json);
// { "a" : "y" }

if you try to deserialise to

class Foo
{
    [JsonProperty("a")]
    public string Bar { get; set; }

    [JsonProperty("a")]
    public string Baz { get; set; }
}

var f = JsonConvert.DeserializeObject<Foo>(json);

you get a Newtonsoft.Json.JsonSerializationException exception.

How do you convert WSDLs to Java classes using Eclipse?

You need to do next in command line:

wsimport -keep -s (name of folder where you want to store generated code) urlToWsdl

for example:

wsimport -keep -s C://NewFolder https://www.blablabla.com

pip cannot install anything

This problem is most-likely caused by DNS setup: server cannot resolve the Domain Name, so cannot download the package.

Solution:

     sudo nano /etc/network/interface

add a line: dns-nameservers 8.8.8.8

save file and exit

     sudo ifdown eth0 && sudo ifup eth0

Then pip install should be working now.

Make XAMPP / Apache serve file outside of htdocs folder

You can relocate it by editing the DocumentRoot setting in XAMPP\apache\conf\httpd.conf.

It should currently be:

C:/xampp/htdocs

Change it to:

C:/projects/transitCalculator/trunk

Android Studio - Device is connected but 'offline'

In my case (same problem - that Nexus 5 is connected but with "offline" status) the problem was solved by "Invalidate caches and Restart" in Android Studio. Suppose that problem was in adb and restarting Android Studio causes to adb restart.

Python: SyntaxError: keyword can't be an expression

It's python source parser failure on sum.up=False named argument as sum.up is not valid argument name (you can't use dots -- only alphanumerics and underscores in argument names).

How do I run a batch script from within a batch script?

Here is example:

You have a.bat:

@echo off
if exist b.bat goto RUNB
goto END
:RUNB
b.bat
:END

and b.bat called conditionally from a.bat:

@echo off 
echo "This is b.bat"

How do I delete from multiple tables using INNER JOIN in SQL server

DELETE     TABLE1 LIN
FROM TABLE1 LIN
INNER JOIN TABLE2 LCS ON  CONDITION
WHERE CONDITION

Writing File to Temp Folder

System.IO.Path.GetTempPath()

The path specified by the TMP environment variable. The path specified by the TEMP environment variable. The path specified by the USERPROFILE environment variable. The Windows directory.

How to escape strings in SQL Server using PHP?

I have been using this as an alternative of mysql_real_escape_string():

function htmlsan($htmlsanitize){
    return $htmlsanitize = htmlspecialchars($htmlsanitize, ENT_QUOTES, 'UTF-8');
}
$data = "Whatever the value's is";
$data = stripslashes(htmlsan($data));

Unable to begin a distributed transaction

OK, so services are started, there is an ethernet path between them, name resolution works, linked servers work, and you disabled transaction authentication.

My gut says firewall issue, but a few things come to mind...

  1. Are the machines in the same domain? (yeah, shouldn't matter with disabled authentication)
  2. Are firewalls running on the the machines? DTC can be a bit of pain for firewalls as it uses a range of ports, see http://support.microsoft.com/kb/306843 For the time being, I would disable firewalls for the sake of identifying the problem
  3. What does DTC ping say? http://www.microsoft.com/download/en/details.aspx?id=2868
  4. What account is the SQL Service running as ?