Programs & Examples On #C api

Spring Boot REST service exception handling

I think ResponseEntityExceptionHandler meets your requirements. A sample piece of code for HTTP 400:

@ControllerAdvice
public class MyExceptionHandler extends ResponseEntityExceptionHandler {

  @ResponseStatus(value = HttpStatus.BAD_REQUEST)
  @ExceptionHandler({HttpMessageNotReadableException.class, MethodArgumentNotValidException.class,
      HttpRequestMethodNotSupportedException.class})
  public ResponseEntity<Object> badRequest(HttpServletRequest req, Exception exception) {
    // ...
  }
}

You can check this post

How does the Spring @ResponseBody annotation work?

@RequestBody annotation binds the HTTPRequest body to the domain object. Spring automatically deserializes incoming HTTP Request to object using HttpMessageConverters. HttpMessageConverter converts body of request to resolve the method argument depending on the content type of the request. Many examples how to use converters https://upcodein.com/search/jc/mg/ResponseBody/page/0

How to disable SSL certificate checking with Spring RestTemplate?

@Bean(name = "restTemplateByPassSSL")
public RestTemplate restTemplateByPassSSL()
        throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
    TrustStrategy acceptingTrustStrategy = (X509Certificate[] chain, String authType) -> true;
    HostnameVerifier hostnameVerifier = (s, sslSession) -> true;
    SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, acceptingTrustStrategy).build();
    SSLConnectionSocketFactory csf = new SSLConnectionSocketFactory(sslContext, hostnameVerifier);
    CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(csf).build();
    HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
    requestFactory.setHttpClient(httpClient);

    return new RestTemplate(requestFactory);
}

Sending GET request with Authentication headers using restTemplate

These days something like the following will suffice:

HttpHeaders headers = new HttpHeaders();
headers.setBearerAuth(accessToken);
restTemplate.exchange(RequestEntity.get(new URI(url)).headers(headers).build(), returnType);

Spring MVC: How to perform validation?

I would like to extend nice answer of Jerome Dalbert. I found very easy to write your own annotation validators in JSR-303 way. You are not limited to have "one field" validation. You can create your own annotation on type level and have complex validation (see examples below). I prefer this way because I don't need mix different types of validation (Spring and JSR-303) like Jerome do. Also this validators are "Spring aware" so you can use @Inject/@Autowire out of box.

Example of custom object validation:

@Target({ TYPE, ANNOTATION_TYPE })
@Retention(RUNTIME)
@Constraint(validatedBy = { YourCustomObjectValidator.class })
public @interface YourCustomObjectValid {

    String message() default "{YourCustomObjectValid.message}";

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};
}

public class YourCustomObjectValidator implements ConstraintValidator<YourCustomObjectValid, YourCustomObject> {

    @Override
    public void initialize(YourCustomObjectValid constraintAnnotation) { }

    @Override
    public boolean isValid(YourCustomObject value, ConstraintValidatorContext context) {

        // Validate your complex logic 

        // Mark field with error
        ConstraintViolationBuilder cvb = context.buildConstraintViolationWithTemplate(context.getDefaultConstraintMessageTemplate());
        cvb.addNode(someField).addConstraintViolation();

        return true;
    }
}

@YourCustomObjectValid
public YourCustomObject {
}

Example of generic fields equality:

import static java.lang.annotation.ElementType.ANNOTATION_TYPE;
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;

import javax.validation.Constraint;
import javax.validation.Payload;

@Target({ TYPE, ANNOTATION_TYPE })
@Retention(RUNTIME)
@Constraint(validatedBy = { FieldsEqualityValidator.class })
public @interface FieldsEquality {

    String message() default "{FieldsEquality.message}";

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};

    /**
     * Name of the first field that will be compared.
     * 
     * @return name
     */
    String firstFieldName();

    /**
     * Name of the second field that will be compared.
     * 
     * @return name
     */
    String secondFieldName();

    @Target({ TYPE, ANNOTATION_TYPE })
    @Retention(RUNTIME)
    public @interface List {
        FieldsEquality[] value();
    }
}




import java.lang.reflect.Field;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.ReflectionUtils;

public class FieldsEqualityValidator implements ConstraintValidator<FieldsEquality, Object> {

    private static final Logger log = LoggerFactory.getLogger(FieldsEqualityValidator.class);

    private String firstFieldName;
    private String secondFieldName;

    @Override
    public void initialize(FieldsEquality constraintAnnotation) {
        firstFieldName = constraintAnnotation.firstFieldName();
        secondFieldName = constraintAnnotation.secondFieldName();
    }

    @Override
    public boolean isValid(Object value, ConstraintValidatorContext context) {
        if (value == null)
            return true;

        try {
            Class<?> clazz = value.getClass();

            Field firstField = ReflectionUtils.findField(clazz, firstFieldName);
            firstField.setAccessible(true);
            Object first = firstField.get(value);

            Field secondField = ReflectionUtils.findField(clazz, secondFieldName);
            secondField.setAccessible(true);
            Object second = secondField.get(value);

            if (first != null && second != null && !first.equals(second)) {
                    ConstraintViolationBuilder cvb = context.buildConstraintViolationWithTemplate(context.getDefaultConstraintMessageTemplate());
          cvb.addNode(firstFieldName).addConstraintViolation();

          ConstraintViolationBuilder cvb = context.buildConstraintViolationWithTemplate(context.getDefaultConstraintMessageTemplate());
          cvb.addNode(someField).addConstraintViolation(secondFieldName);

                return false;
            }
        } catch (Exception e) {
            log.error("Cannot validate fileds equality in '" + value + "'!", e);
            return false;
        }

        return true;
    }
}

@FieldsEquality(firstFieldName = "password", secondFieldName = "confirmPassword")
public class NewUserForm {

    private String password;

    private String confirmPassword;

}

parsing JSONP $http.jsonp() response in angular.js

This was very helpful. Angular doesn't work exactly like JQuery. It has its own jsonp() method, which indeed requires "&callback=JSON_CALLBACK" at the end of the query string. Here's an example:

var librivoxSearch = angular.module('librivoxSearch', []);
librivoxSearch.controller('librivoxSearchController', function ($scope, $http) {
    $http.jsonp('http://librivox.org/api/feed/audiobooks/author/Melville?format=jsonp&callback=JSON_CALLBACK').success(function (data) {
        $scope.data = data;
    });
});

Then display or manipulate {{ data }} in your Angular template.

Role/Purpose of ContextLoaderListener in Spring?

Your understanding is correct. The ApplicationContext is where your Spring beans live. The purpose of the ContextLoaderListener is two-fold:

  1. to tie the lifecycle of the ApplicationContext to the lifecycle of the ServletContext and

  2. to automate the creation of the ApplicationContext, so you don't have to write explicit code to do create it - it's a convenience function.

Another convenient thing about the ContextLoaderListener is that it creates a WebApplicationContext and WebApplicationContext provides access to the ServletContext via ServletContextAware beans and the getServletContext method.

java.lang.UnsupportedClassVersionError Unsupported major.minor version 51.0

java.lang.UnsupportedClassVersionError happens because of a higher JDK during compile time and lower JDK during runtime.

Here's the list of versions:

Java SE 9 = 53,
Java SE 8 = 52,
Java SE 7 = 51,
Java SE 6.0 = 50,
Java SE 5.0 = 49,
JDK 1.4 = 48,
JDK 1.3 = 47,
JDK 1.2 = 46,
JDK 1.1 = 45

is python capable of running on multiple cores?

I converted the script to Python3 and ran it on my Raspberry Pi 3B+:

import time
import threading

def t():
        with open('/dev/urandom', 'rb') as f:
                for x in range(100):
                        f.read(4 * 65535)

if __name__ == '__main__':
    start_time = time.time()
    t()
    t()
    t()
    t()
    print("Sequential run time: %.2f seconds" % (time.time() - start_time))

    start_time = time.time()
    t1 = threading.Thread(target=t)
    t2 = threading.Thread(target=t)
    t3 = threading.Thread(target=t)
    t4 = threading.Thread(target=t)
    t1.start()
    t2.start()
    t3.start()
    t4.start()
    t1.join()
    t2.join()
    t3.join()
    t4.join()
    print("Parallel run time: %.2f seconds" % (time.time() - start_time))

python3 t.py

Sequential run time: 2.10 seconds
Parallel run time: 1.41 seconds

For me, running parallel was quicker.

What's the difference between @Component, @Repository & @Service annotations in Spring?

From Spring Documentation:

The @Repository annotation is a marker for any class that fulfils the role or stereotype of a repository (also known as Data Access Object or DAO). Among the uses of this marker is the automatic translation of exceptions, as described in Exception Translation.

Spring provides further stereotype annotations: @Component, @Service, and @Controller. @Component is a generic stereotype for any Spring-managed component. @Repository, @Service, and @Controller are specializations of @Component for more specific use cases (in the persistence, service, and presentation layers, respectively). Therefore, you can annotate your component classes with @Component, but, by annotating them with @Repository, @Service, or @Controller instead, your classes are more properly suited for processing by tools or associating with aspects.

For example, these stereotype annotations make ideal targets for pointcuts. @Repository, @Service, and @Controller can also carry additional semantics in future releases of the Spring Framework. Thus, if you are choosing between using @Component or @Service for your service layer, @Service is clearly the better choice. Similarly, as stated earlier, @Repository is already supported as a marker for automatic exception translation in your persistence layer.

Annotation Meaning
@Component generic stereotype for any Spring-managed component
@Repository stereotype for persistence layer
@Service stereotype for service layer
@Controller stereotype for presentation layer (spring-mvc)

Generating random strings with T-SQL

Heres something based on New Id.

with list as 
(
    select 1 as id,newid() as val
         union all
    select id + 1,NEWID()
    from    list   
    where   id + 1 < 10
) 
select ID,val from list
option (maxrecursion 0)

Table 'mysql.user' doesn't exist:ERROR

My solution was to run

mysql_upgrade -u root

Scenario: I updated the MySQL version on my Mac with 'homebrew upgrade'. Afterwards, some stuff worked, but other commands raised the error described in the question.

How to set timeout for a line of c# code

You can use the Task Parallel Library. To be more exact, you can use Task.Wait(TimeSpan):

using System.Threading.Tasks;

var task = Task.Run(() => SomeMethod(input));
if (task.Wait(TimeSpan.FromSeconds(10)))
    return task.Result;
else
    throw new Exception("Timed out");

how to get list of port which are in use on the server

There are a lot of options and tools. If you just want a list of listening ports and their owner processes try.

netstat -bano

How can I concatenate a string and a number in Python?

Since Python is a strongly typed language, concatenating a string and an integer as you may do in Perl makes no sense, because there's no defined way to "add" strings and numbers to each other.

Explicit is better than implicit.

...says "The Zen of Python", so you have to concatenate two string objects. You can do this by creating a string from the integer using the built-in str() function:

>>> "abc" + str(9)
'abc9'

Alternatively use Python's string formatting operations:

>>> 'abc%d' % 9
'abc9'

Perhaps better still, use str.format():

>>> 'abc{0}'.format(9)
'abc9'

The Zen also says:

There should be one-- and preferably only one --obvious way to do it.

Which is why I've given three options. It goes on to say...

Although that way may not be obvious at first unless you're Dutch.

How to implement a secure REST API with node.js

I just finished a sample app that does this in a pretty basic, but clear way. It uses mongoose with mongodb to store users and passport for auth management.

https://github.com/Khelldar/Angular-Express-Train-Seed

Why this line xmlns:android="http://schemas.android.com/apk/res/android" must be the first in the layout xml file?

In XML, element names are defined by the developer. This often results in a conflict when trying to mix XML documents from different XML applications. A user or an XML application will not know how to handle these differences. Name conflicts in XML can easily be avoided using a name prefix. When using prefixes in XML, a namespace for the prefix must be defined.The namespace can be defined by an xmlns attribute in the start tag of an element.The namespace declaration has the following syntax. xmlns:prefix="URI".

How can I scale the content of an iframe?

Followup to lxs's answer: I noticed a problem where having both the zoom and --webkit-transform tags at the same time seems to confound Chrome (version 15.0.874.15) by doing a double-zoom sort of effect. I was able to work around the issue by replacing zoom with -ms-zoom (targeted only at IE), leaving Chrome to make use of just the --webkit-transform tag, and that cleared things up.

How to fix Hibernate LazyInitializationException: failed to lazily initialize a collection of roles, could not initialize proxy - no Session

For those using JaVers, given an audited entity class, you may want to ignore the properties causing the LazyInitializationException exception (e.g. by using the @DiffIgnore annotation).

This tells the framework to ignore those properties when calculating the object differences, so it won't try to read from the DB the related objects outside the transaction scope (thus causing the exception).

Get file name from URI string in C#

The accepted answer is problematic for http urls. Moreover Uri.LocalPath does Windows specific conversions, and as someone pointed out leaves query strings in there. A better way is to use Uri.AbsolutePath

The correct way to do this for http urls is:

Uri uri = new Uri(hreflink);
string filename = System.IO.Path.GetFileName(uri.AbsolutePath);

php, mysql - Too many connections to database error

This can happen due to too many connection same time or many chat at same time. Also it can happen due too many session.

The best way to sort out this issue is restart MySQL.

service mysqld restart

or

service mysql restart

or

 /etc/init.d/mysqld restart

What is "Connect Timeout" in sql server connection string?

Gets the time to wait while trying to establish a connection before terminating the attempt and generating an error.

http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection.connectiontimeout%28v=vs.110%29.aspx

Drop-down menu that opens up/upward with pure css

If we are use chosen dropdown list, then we can use below css(No JS/JQuery require)

<select chosen="{width: '100%'}" ng- 
   model="modelName" class="form-control input- 
   sm"
   ng- 
   options="persons.persons as 
   persons.persons for persons in 
   jsonData"
   ng- 
   change="anyFunction(anyParam)" 
   required>
   <option value=""> </option>
</select>
<style>   
.chosen-container .chosen-drop {
    border-bottom: 0;
    border-top: 1px solid #aaa;
    top: auto;
    bottom: 40px;
}

.chosen-container.chosen-with-drop .chosen-single {
    border-top-left-radius: 0px;
    border-top-right-radius: 0px;

    border-bottom-left-radius: 5px;
    border-bottom-right-radius: 5px;

    background-image: none;
}

.chosen-container.chosen-with-drop .chosen-drop {
    border-bottom-left-radius: 0px;
    border-bottom-right-radius: 0px;

    border-top-left-radius: 5px;
    border-top-right-radius: 5px;

    box-shadow: none;

    margin-bottom: -16px;
}
</style>

How can I find non-ASCII characters in MySQL?

Try Using this query for searching special character records

SELECT *
FROM tableName
WHERE fieldName REGEXP '[^a-zA-Z0-9@:. \'\-`,\&]'

Laravel: How do I parse this json data in view blade?

Just Remove $ in to compact method ,
return view('page',compact('member'))

When creating a service with sc.exe how to pass in context parameters?

I found a way to use sc.

sc config binPath= "\"c:\path with spaces in it\service_executable.exe\" "

In other words, use \ to escape any "'s you want to survive the transit into the registry.

PHP JSON String, escape Double Quotes for JS output

I had challenge with users innocently entering € and some using double quotes to define their content. I tweaked a couple of answers from this page and others to finally define my small little work-around

$products = array($ofDirtyArray);
if($products !=null) {
    header("Content-type: application/json");
    header('Content-Type: charset=utf-8');
    array_walk_recursive($products, function(&$val) {
        $val = html_entity_decode(htmlentities($val, ENT_QUOTES, "UTF-8"));
    });
    echo json_encode($products,  JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_NUMERIC_CHECK);
}

I hope it helps someone/someone improves it.

Warning: X may be used uninitialized in this function

You get the warning because you did not assign a value to one, which is a pointer. This is undefined behavior.

You should declare it like this:

Vector* one = malloc(sizeof(Vector));

or like this:

Vector one;

in which case you need to replace -> operator with . like this:

one.a = 12;
one.b = 13;
one.c = -11;

Finally, in C99 and later you can use designated initializers:

Vector one = {
   .a = 12
,  .b = 13
,  .c = -11
};

Direct method from SQL command text to DataSet

Just finish it up.

string sqlCommand = "SELECT * FROM TABLE";
string connectionString = "blahblah";

DataSet ds = GetDataSet(sqlCommand, connectionString);
DataSet GetDataSet(string sqlCommand, string connectionString)
{
    DataSet ds = new DataSet();
    using (SqlCommand cmd = new SqlCommand(
        sqlCommand, new SqlConnection(connectionString)))
    {
        cmd.Connection.Open();
        DataTable table = new DataTable();
        table.Load(cmd.ExecuteReader());
        ds.Tables.Add(table);
    }
    return ds;
}

RichTextBox (WPF) does not have string property "Text"

There was a confusion between RichTextBox in System.Windows.Forms and in System.Windows.Control

I am using the one in the Control as I am using WPF. In there, there is no Text property, and in order to get a text, I should have used this line:

string myText = new TextRange(transcriberArea.Document.ContentStart, transcriberArea.Document.ContentEnd).Text; 

thanks

MySQL SELECT query string matching

You can use regular expressions like this:

SELECT * FROM pet WHERE name REGEXP 'Bob|Smith'; 

Assigning more than one class for one event

Have you tried this:

 function doSomething() {
     if ($(this).hasClass('clickedTag')){
         // code here
     } else {
         // and here
     }
 }

 $('.tag1, .tag2').click(doSomething);

How is TeamViewer so fast?

It sounds indeed like video streaming more than image streaming, as someone suggested. JPEG/PNG compression isn't targeted for these types of speeds, so forget them.

Imagine having a recording codec on your system that can realtime record an incoming video stream (your screen). A bit like Fraps perhaps. Then imagine a video playback codec on the other side (the remote client). As HD recorders can do it (record live and even playback live from the same HD), so should you, in the end. The HD surely can't deliver images quicker than you can read your display, so that isn't the bottleneck. The bottleneck are the video codecs. You'll find the encoder much more of a problem than the decoder, as all decoders are mostly free.

I'm not saying it's simple; I myself have used DirectShow to encode a video file, and it's not realtime by far. But given the right codec I'm convinced it can work.

Difference of two date time in sql server

Use This for DD:MM:SS:

SELECT CONVERT(VARCHAR(max), Datediff(dd, '2019-08-14 03:16:51.360', 
         '2019-08-15 05:45:37.610')) 
       + ':' 
       + CONVERT(CHAR(8), Dateadd(s, Datediff(s, '2019-08-14 03:16:51.360', 
         '2019-08-15 05:45:37.610'), '1900-1-1'), 8) 

How does the data-toggle attribute work? (What's its API?)

I think you are a bit confused on the purpose of custom data attributes. From the w3 spec

Custom data attributes are intended to store custom data private to the page or application, for which there are no more appropriate attributes or elements.

By itself an attribute of data-toggle=value is basically a key-value pair, in which the key is "data-toggle" and the value is "value".

In the context of Bootstrap, the custom data in the attribute is almost useless without the context that their JavaScript library includes for the data. If you look at the non-minified version of bootstrap.js then you can do a search for "data-toggle" and find how it is being used.

Here is an example of Bootstrap JavaScript code that I copied straight from the file regarding the use of "data-toggle".

  • Button Toggle

    Button.prototype.toggle = function () {
      var changed = true
      var $parent = this.$element.closest('[data-toggle="buttons"]')
    
      if ($parent.length) {
        var $input = this.$element.find('input')
        if ($input.prop('type') == 'radio') {
          if ($input.prop('checked') && this.$element.hasClass('active')) changed = false
          else $parent.find('.active').removeClass('active')
        }
        if (changed) $input.prop('checked', !this.$element.hasClass('active')).trigger('change')
      } else {
        this.$element.attr('aria-pressed', !this.$element.hasClass('active'))
      }
    
      if (changed) this.$element.toggleClass('active')
    }
    

The context that the code provides shows that Bootstrap is using the data-toggle attribute as a custom query selector to process the particular element.

From what I see these are the data-toggle options:

  • collapse
  • dropdown
  • modal
  • tab
  • pill
  • button(s)

You may want to look at the Bootstrap JavaScript documentation to get more specifics of what each do, but basically the data-toggle attribute toggles the element to active or not.

CSS rounded corners in IE8

http://fetchak.com/ie-css3/ works for IE 6+. Use this if css3pie doesn't work for you.

Get only the date in timestamp in mysql

$date= new DateTime($row['your_date']) ;  
echo $date->format('Y-m-d');

(grep) Regex to match non-ASCII characters?

To Validate Text Box Accept Ascii Only use this Pattern

[\x00-\x7F]+

Send a base64 image in HTML email

An alternative approach may be to embed images in the email using the cid method. (Basically including the image as an attachment, and then embedding it). In my experience, this approach seems to be well supported these days.

enter image description here

Source: https://www.campaignmonitor.com/blog/how-to/2008/08/embedding-images-revisited/

Image, saved to sdcard, doesn't appear in Android's Gallery app

there is an app in the emulator that says - ' Dev Tools'

click on that and select ' Media Scanning'.. all the images ll get scanned

Call apply-like function on each row of dataframe with multiple arguments from each row

New answer with dplyr package

If the function that you want to apply is vectorized, then you could use the mutate function from the dplyr package:

> library(dplyr)
> myf <- function(tens, ones) { 10 * tens + ones }
> x <- data.frame(hundreds = 7:9, tens = 1:3, ones = 4:6)
> mutate(x, value = myf(tens, ones))
  hundreds tens ones value
1        7    1    4    14
2        8    2    5    25
3        9    3    6    36

Old answer with plyr package

In my humble opinion, the tool best suited to the task is mdply from the plyr package.

Example:

> library(plyr)
> x <- data.frame(tens = 1:3, ones = 4:6)
> mdply(x, function(tens, ones) { 10 * tens + ones })
  tens ones V1
1    1    4 14
2    2    5 25
3    3    6 36

Unfortunately, as Bertjan Broeksema pointed out, this approach fails if you don't use all the columns of the data frame in the mdply call. For example,

> library(plyr)
> x <- data.frame(hundreds = 7:9, tens = 1:3, ones = 4:6)
> mdply(x, function(tens, ones) { 10 * tens + ones })
Error in (function (tens, ones)  : unused argument (hundreds = 7)

Hibernate Criteria for Dates

Why do you use Restrictions.like(...)?

You should use Restrictions.eq(...).

Note you can also use .le, .lt, .ge, .gt on date objects as comparison operators. LIKE operator is not appropriate for this case since LIKE is useful when you want to match results according to partial content of a column. Please see http://www.sql-tutorial.net/SQL-LIKE.asp for the reference.

For example if you have a name column with some people's full name, you can do where name like 'robert %' so that you will return all entries with name starting with 'robert ' (% can replace any character).

In your case you know the full content of the date you're trying to match so you shouldn't use LIKE but equality. I guess Hibernate doesn't give you any exception in this case, but anyway you will probably have the same problem with the Restrictions.eq(...).

Your date object you got with the code:

SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-YYYY");
String myDate = "17-04-2011";
Date date = formatter.parse(myDate);

This date object is equals to the 17-04-2011 at 0h, 0 minutes, 0 seconds and 0 nanoseconds.

This means that your entries in database must have exactly that date. What i mean is that if your database entry has a date "17-April-2011 19:20:23.707000000", then it won't be retrieved because you just ask for that date: "17-April-2011 00:00:00.0000000000".

If you want to retrieve all entries of your database from a given day, you will have to use the following code:

    SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-YYYY");
    String myDate = "17-04-2011";
    // Create date 17-04-2011 - 00h00
    Date minDate = formatter.parse(myDate);
    // Create date 18-04-2011 - 00h00 
    // -> We take the 1st date and add it 1 day in millisecond thanks to a useful and not so known class
    Date maxDate = new Date(minDate.getTime() + TimeUnit.DAYS.toMillis(1));
    Conjunction and = Restrictions.conjunction();
    // The order date must be >= 17-04-2011 - 00h00
    and.add( Restrictions.ge("orderDate", minDate) );
    // And the order date must be < 18-04-2011 - 00h00
    and.add( Restrictions.lt("orderDate", maxDate) ); 

What linux shell command returns a part of a string?

In bash you can try this:

stringZ=abcABC123ABCabc
#       0123456789.....
#       0-based indexing.

echo ${stringZ:0:2} # prints ab

More samples in The Linux Documentation Project

How to create relationships in MySQL

as ehogue said, put this in your CREATE TABLE

FOREIGN KEY (customer_id) REFERENCES customers(customer_id) 

alternatively, if you already have the table created, use an ALTER TABLE command:

ALTER TABLE `accounts`
  ADD CONSTRAINT `FK_myKey` FOREIGN KEY (`customer_id`) REFERENCES `customers` (`customer_id`) ON DELETE CASCADE ON UPDATE CASCADE;

One good way to start learning these commands is using the MySQL GUI Tools, which give you a more "visual" interface for working with your database. The real benefit to that (over Access's method), is that after designing your table via the GUI, it shows you the SQL it's going to run, and hence you can learn from that.

How to update gradle in android studio?

Step 1 (Use default gradle wrapper)

File?Settings?Build, Execution, Deployment?Build Tools?Gradle?Use default Gradle wrapper (recommended)

Android studio settings Gradle wrapper

Step 2 (Select desired gradle version)

File?Project Structure?Project

Android Studio project structure

The following table shows compatibility between Android plugin for Gradle and Gradle:

Compatibility table

Latest stable versions you can use with Android Studio 4.1.1 (November 2020):

Android Gradle Plugin version: 4.1.1
Gradle version: 6.5

Official links

How do you round a float to 2 decimal places in JRuby?

Edit

After getting feedback, It seems the original solution didn't work. That's why updated the answer as one of the suggestions.

def float_of_2_decimal(float_n) 
  float_n.to_d.round(2, :truncate).to_f
end

Other answers may work, if you want to have rounded numbers of 2 decimal places. But, If you want to have floating point numbers with first two decimal places without rounding, Those answers won't help.

So, to get a floating point number with first two decimal places, I used this technique. Doesn't work in some cases

def float_of_2_decimal(float_n)
  float_n.round(3).to_s[0..3].to_f
end

with 5.666666666666666666666666, it will return 5.66 instead of rounded 5.67. Hope it will help someone

MySQL error 1241: Operand should contain 1 column(s)

Another way to make the parser raise the same exception is the following incorrect clause.

SELECT r.name
FROM roles r
WHERE id IN ( SELECT role_id ,
                     system_user_id
                 FROM role_members m
                 WHERE r.id = m.role_id
                 AND m.system_user_id = intIdSystemUser
             )

The nested SELECT statement in the IN clause returns two columns, which the parser sees as operands, which is technically correct, since the id column matches values from but one column (role_id) in the result returned by the nested select statement, which is expected to return a list.

For sake of completeness, the correct syntax is as follows.

SELECT r.name
FROM roles r
WHERE id IN ( SELECT role_id
                 FROM role_members m
                 WHERE r.id = m.role_id
                 AND m.system_user_id = intIdSystemUser
             )

The stored procedure of which this query is a portion not only parsed, but returned the expected result.

How do I make a WinForms app go Full Screen

To the base question, the following will do the trick (hiding the taskbar)

private void Form1_Load(object sender, EventArgs e)
{
    this.TopMost = true;
    this.FormBorderStyle = FormBorderStyle.None;
    this.WindowState = FormWindowState.Maximized;
}

But, interestingly, if you swap those last two lines the Taskbar remains visible. I think the sequence of these actions will be hard to control with the properties window.

Stop on first error

Maybe you want set -e:

www.davidpashley.com/articles/writing-robust-shell-scripts.html#id2382181:

This tells bash that it should exit the script if any statement returns a non-true return value. The benefit of using -e is that it prevents errors snowballing into serious issues when they could have been caught earlier. Again, for readability you may want to use set -o errexit.

Is Constructor Overriding Possible?

Constructor looks like a method but name should be as class name and no return value.

Overriding means what we have declared in Super class, that exactly we have to declare in Sub class it is called Overriding. Super class name and Sub class names are different.

If you trying to write Super class Constructor in Sub class, then Sub class will treat that as a method not constructor because name should not match with Sub class name. And it will give an compilation error that methods does not have return value. So we should declare as void, then only it will compile.

Can I invoke an instance method on a Ruby module without including it?

After almost 9 years here's a generic solution:

module CreateModuleFunctions
  def self.included(base)
    base.instance_methods.each do |method|
      base.module_eval do
        module_function(method)
        public(method)
      end
    end
  end
end

RSpec.describe CreateModuleFunctions do
  context "when included into a Module" do
    it "makes the Module's methods invokable via the Module" do
      module ModuleIncluded
        def instance_method_1;end
        def instance_method_2;end

        include CreateModuleFunctions
      end

      expect { ModuleIncluded.instance_method_1 }.to_not raise_error
    end
  end
end

The unfortunate trick you need to apply is to include the module after the methods have been defined. Alternatively you may also include it after the context is defined as ModuleIncluded.send(:include, CreateModuleFunctions).

Or you can use it via the reflection_utils gem.

spec.add_dependency "reflection_utils", ">= 0.3.0"

require 'reflection_utils'
include ReflectionUtils::CreateModuleFunctions

Stored procedure - return identity as output parameter or scalar

I prefer to return the identity value as an output parameter. The result of the SP should indicate whether it succeeded or not. A value of 0 indicates the SP successfully completed, a non-zero value indicates an error. Also, if you ever need to make a change and return an additional value from the SP you don't need to make any changes other than adding an additional output parameter.

Better way to Format Currency Input editText?

Ok, here is a better way to deal with Currency formats, delete-backward keystroke. The code is based on @androidcurious' code above... But, deals with some problems related to backwards-deletion and some parse exceptions: http://miguelt.blogspot.ca/2013/01/textwatcher-for-currency-masksformatting.html [UPDATE] The previous solution had some problems... This is a better solutoin: http://miguelt.blogspot.ca/2013/02/update-textwatcher-for-currency.html And... here are the details:

This approach is better since it uses the conventional Android mechanisms. The idea is to format values after the user exists the View.

Define an InputFilter to restrict the numeric values – this is required in most cases because the screen is not large enough to accommodate long EditText views. This can be a static inner class or just another plain class:

/** Numeric range Filter. */
class NumericRangeFilter implements InputFilter {
    /** Maximum value. */
    private final double maximum;
    /** Minimum value. */
    private final double minimum;
    /** Creates a new filter between 0.00 and 999,999.99. */
    NumericRangeFilter() {
        this(0.00, 999999.99);
    }
    /** Creates a new filter.
     * @param p_min Minimum value.
     * @param p_max Maximum value. 
     */
    NumericRangeFilter(double p_min, double p_max) {
        maximum = p_max;
        minimum = p_min;
    }
    @Override
    public CharSequence filter(
            CharSequence p_source, int p_start,
            int p_end, Spanned p_dest, int p_dstart, int p_dend
    ) {
        try {
            String v_valueStr = p_dest.toString().concat(p_source.toString());
            double v_value = Double.parseDouble(v_valueStr);
            if (v_value<=maximum && v_value>=minimum) {
                // Returning null will make the EditText to accept more values.
                return null;
            }
        } catch (NumberFormatException p_ex) {
            // do nothing
        }
        // Value is out of range - return empty string.
        return "";
    }
}

Define a class (inner static or just a class) that will implement View.OnFocusChangeListener. Note that I'm using an Utils class - the implementation can be found at "Amounts, Taxes".

/** Used to format the amount views. */
class AmountOnFocusChangeListener implements View.OnFocusChangeListener {
    @Override
    public void onFocusChange(View p_view, boolean p_hasFocus) {
        // This listener will be attached to any view containing amounts.
        EditText v_amountView = (EditText)p_view;
        if (p_hasFocus) {
            // v_value is using a currency mask - transfor over to cents.
            String v_value = v_amountView.getText().toString();
            int v_cents = Utils.parseAmountToCents(v_value);
            // Now, format cents to an amount (without currency mask)
            v_value = Utils.formatCentsToAmount(v_cents);
            v_amountView.setText(v_value);
            // Select all so the user can overwrite the entire amount in one shot.
            v_amountView.selectAll();
        } else {
            // v_value is not using a currency mask - transfor over to cents.
            String v_value = v_amountView.getText().toString();
            int v_cents = Utils.parseAmountToCents(v_value);
            // Now, format cents to an amount (with currency mask)
            v_value = Utils.formatCentsToCurrency(v_cents);
            v_amountView.setText(v_value);
        }
    }
}

This class will remove the currency format when editing - relying on standard mechanisms. When the user exits, the currency format is re-applied.

It's better to define some static variables to minimize the number of instances:

   static final InputFilter[] FILTERS = new InputFilter[] {new NumericRangeFilter()};
   static final View.OnFocusChangeListener ON_FOCUS = new AmountOnFocusChangeListener();

Finally, within the onCreateView(...):

   EditText mAmountView = ....
   mAmountView.setFilters(FILTERS);
   mAmountView.setOnFocusChangeListener(ON_FOCUS);

You can reuse FILTERS and ON_FOCUS on any number of EditText views.

Here is the Utils class:

public class Utils {

   private static final NumberFormat FORMAT_CURRENCY = NumberFormat.getCurrencyInstance();
   /** Parses an amount into cents.
    * @param p_value Amount formatted using the default currency. 
    * @return Value as cents.
    */
   public static int parseAmountToCents(String p_value) {
       try {
           Number v_value = FORMAT_CURRENCY.parse(p_value);
           BigDecimal v_bigDec = new BigDecimal(v_value.doubleValue());
           v_bigDec = v_bigDec.setScale(2, BigDecimal.ROUND_HALF_UP);
           return v_bigDec.movePointRight(2).intValue();
       } catch (ParseException p_ex) {
           try {
               // p_value doesn't have a currency format.
               BigDecimal v_bigDec = new BigDecimal(p_value);
               v_bigDec = v_bigDec.setScale(2, BigDecimal.ROUND_HALF_UP);
               return v_bigDec.movePointRight(2).intValue();
           } catch (NumberFormatException p_ex1) {
               return -1;
           }
       }
   }
   /** Formats cents into a valid amount using the default currency.
    * @param p_value Value as cents 
    * @return Amount formatted using a currency.
    */
   public static String formatCentsToAmount(int p_value) {
       BigDecimal v_bigDec = new BigDecimal(p_value);
       v_bigDec = v_bigDec.setScale(2, BigDecimal.ROUND_HALF_UP);
       v_bigDec = v_bigDec.movePointLeft(2);
       String v_currency = FORMAT_CURRENCY.format(v_bigDec.doubleValue());
       return v_currency.replace(FORMAT_CURRENCY.getCurrency().getSymbol(), "").replace(",", "");
   }
   /** Formats cents into a valid amount using the default currency.
    * @param p_value Value as cents 
    * @return Amount formatted using a currency.
    */
   public static String formatCentsToCurrency(int p_value) {
       BigDecimal v_bigDec = new BigDecimal(p_value);
       v_bigDec = v_bigDec.setScale(2, BigDecimal.ROUND_HALF_UP);
       v_bigDec = v_bigDec.movePointLeft(2);
       return FORMAT_CURRENCY.format(v_bigDec.doubleValue());
   }

}

Convert special characters to HTML in Javascript

public static string HtmlEncode (string text)
{
    string result;
    using (StringWriter sw = new StringWriter())
    {
        var x = new HtmlTextWriter(sw);
        x.WriteEncodedText(text);
        result = sw.ToString();
    }
    return result;

}

WPF Application that only has a tray icon

I recently had this same problem. Unfortunately, NotifyIcon is only a Windows.Forms control at the moment, if you want to use it you are going to have to include that part of the framework. I guess that depends how much of a WPF purist you are.

If you want a quick and easy way of getting started check out this WPF NotifyIcon control on the Code Project which does not rely on the WinForms NotifyIcon at all. A more recent version seems to be available on the author's website and as a NuGet package. This seems like the best and cleanest way to me so far.

  • Rich ToolTips rather than text
  • WPF context menus and popups
  • Command support and routed events
  • Flexible data binding
  • Rich balloon messages rather than the default messages provides by the OS

Check it out. It comes with an amazing sample app too, very easy to use, and you can have great looking Windows Live Messenger style WPF popups, tooltips, and context menus. Perfect for displaying an RSS feed, I am using it for a similar purpose.

How do I import a .bak file into Microsoft SQL Server 2012?

Not sure why they removed the option to just right click on the database and restore like you could in SQL Server Management Studio 2008 and earlier, but as mentioned above you can restore from a .BAK file with:

RESTORE DATABASE YourDB FROM DISK = 'D:BackUpYourBaackUpFile.bak' WITH REPLACE

But you will want WITH REPLACE instead of WITH RESTORE if your moving it from one server to another.

Freeze the top row for an html table only (Fixed Table Header Scrolling)

I know this has several answers, but none of these really helped me. I found [this article][1] which explains why my sticky wasn't operating as expected.

Basically, you cannot use position: sticky; on <thead> or <tr> elements. However, they can be used on <th>.

The minimum code I needed to make it work is as follows:

table {
  text-align: left;
  position: relative;
}

th {
  background: white;
  position: sticky;
  top: 0;
}

With the table set to relative the <th> can be set to sticky, with the top at 0 [1]: https://css-tricks.com/position-sticky-and-table-headers/

NOTE: It's necessary to wrap the table with a div with max-height:

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

where:

#managerTable {
    max-height: 500px;
    overflow: auto;
}

Compare two DataFrames and output their differences side-by-side

A function that finds asymmetrical difference between two data frames is implemented below: (Based on set difference for pandas) GIST: https://gist.github.com/oneryalcin/68cf25f536a25e65f0b3c84f9c118e03

def diff_df(df1, df2, how="left"):
    """
      Find Difference of rows for given two dataframes
      this function is not symmetric, means
            diff(x, y) != diff(y, x)
      however
            diff(x, y, how='left') == diff(y, x, how='right')

      Ref: https://stackoverflow.com/questions/18180763/set-difference-for-pandas/40209800#40209800
    """
    if (df1.columns != df2.columns).any():
        raise ValueError("Two dataframe columns must match")

    if df1.equals(df2):
        return None
    elif how == 'right':
        return pd.concat([df2, df1, df1]).drop_duplicates(keep=False)
    elif how == 'left':
        return pd.concat([df1, df2, df2]).drop_duplicates(keep=False)
    else:
        raise ValueError('how parameter supports only "left" or "right keywords"')

Example:

df1 = pd.DataFrame(d1)
Out[1]: 
                Comment  Name  isEnrolled  score
0  He was late to class  Jack        True   2.17
1             Graduated  Nick       False   1.11
2                         Zoe        True   4.12


df2 = pd.DataFrame(d2)

Out[2]: 
                Comment  Name  isEnrolled  score
0  He was late to class  Jack        True   2.17
1           On vacation   Zoe        True   4.12

diff_df(df1, df2)
Out[3]: 
     Comment  Name  isEnrolled  score
1  Graduated  Nick       False   1.11
2              Zoe        True   4.12

diff_df(df2, df1)
Out[4]: 
       Comment Name  isEnrolled  score
1  On vacation  Zoe        True   4.12

# This gives the same result as above
diff_df(df1, df2, how='right')
Out[22]: 
       Comment Name  isEnrolled  score
1  On vacation  Zoe        True   4.12

How to make an inline element appear on new line, or block element not occupy the whole line?

Even though the question is quite fuzzy and the HTML snippet is quite limited, I suppose

.feature_desc {
    display: block;
}
.feature_desc:before {
    content: "";
    display: block;
}

might give you want you want to achieve without the <br/> element. Though it would help to see your CSS applied to these elements.

NOTE. The example above doesn't work in IE7 though.

SQLite - getting number of rows in a database

In SQL, NULL = NULL is false, you usually have to use IS NULL:

SELECT CASE WHEN MAX(id) IS NULL THEN 0 ELSE (MAX(id) + 1) END FROM words

But, if you want the number of rows, you should just use count(id) since your solution will give 10 if your rows are (0,1,3,5,9) where it should give 5.

If you can guarantee you will always ids from 0 to N, max(id)+1 may be faster depending on the index implementation (it may be faster to traverse the right side of a balanced tree rather than traversing the whole tree, counting.

But that's very implementation-specific and I would advise against relying on it, not least because it locks your performance to a specific DBMS.

ggplot with 2 y axes on each side and different scales

It's not possible in ggplot2 because I believe plots with separate y scales (not y-scales that are transformations of each other) are fundamentally flawed. Some problems:

  • The are not invertible: given a point on the plot space, you can not uniquely map it back to a point in the data space.

  • They are relatively hard to read correctly compared to other options. See A Study on Dual-Scale Data Charts by Petra Isenberg, Anastasia Bezerianos, Pierre Dragicevic, and Jean-Daniel Fekete for details.

  • They are easily manipulated to mislead: there is no unique way to specify the relative scales of the axes, leaving them open to manipulation. Two examples from the Junkcharts blog: one, two

  • They are arbitrary: why have only 2 scales, not 3, 4 or ten?

You also might want to read Stephen Few's lengthy discussion on the topic Dual-Scaled Axes in Graphs Are They Ever the Best Solution?.

Convert DataSet to List

Use the code below:

using Newtonsoft.Json;
string JSONString = string.Empty;
JSONString = JsonConvert.SerializeObject(ds.Tables[0]);

How to add Google Maps Autocomplete search box?

Just copy and paste the sameple code below.

<!DOCTYPE html>
<html>
    <head>
        <script src="https://maps.googleapis.com/maps/api/jsvv=3.exp&sensor=false&libraries=places"></script>
    </head>
    <body>
        <label for="locationTextField">Location</label>
        <input id="locationTextField" type="text" size="50">

        <script>
            function init() {
                var input = document.getElementById('locationTextField');
                var autocomplete = new google.maps.places.Autocomplete(input);
            }

            google.maps.event.addDomListener(window, 'load', init);
        </script>
    </body>
</html>

Well formatted code can be found from this link. http://jon.kim/how-to-add-google-maps-autocomplete-search-box/

Perl read line by line

If you had use strict turned on, you would have found out that $++foo doesn't make any sense.

Here's how to do it:

use strict;
use warnings;

my $file = 'SnPmaster.txt';
open my $info, $file or die "Could not open $file: $!";

while( my $line = <$info>)  {   
    print $line;    
    last if $. == 2;
}

close $info;

This takes advantage of the special variable $. which keeps track of the line number in the current file. (See perlvar)

If you want to use a counter instead, use

my $count = 0;
while( my $line = <$info>)  {   
    print $line;    
    last if ++$count == 2;
}

How to get href value using jQuery?

It works... Tested in IE8 (don't forget to allow javascript to run if you're testing the file from your computer) and chrome.

Login credentials not working with Gmail SMTP

I had already enabled "Allow less secure apps" and my SMPT python program was working perfectly!

But next day it stared giving me "Bad Credentials error (SMTPAuthenticationError: (535, b'5.7.8 Username and Password not accepted)". I was using the exact same credentials as before and the less secure apps option was also enabled..!

Changed my password again but that also did not help.

Still not working? If you still get the SMTPAuthenticationError but now the code is 534, its because the location is unknown. Follow this link:

https://accounts.google.com/DisplayUnlockCaptcha

Click continue and this should give you 10 minutes for registering your new app. So proceed to doing another login attempt now and it should work.

Note: Had to try multipe times to get this option enabled. Once enabled, I tried connecting after 30mins and it worked..!!!

Hope this helps.

Why is Thread.Sleep so harmful

Sleep is used in cases where independent program(s) that you have no control over may sometimes use a commonly used resource (say, a file), that your program needs to access when it runs, and when the resource is in use by these other programs your program is blocked from using it. In this case, where you access the resource in your code, you put your access of the resource in a try-catch (to catch the exception when you can't access the resource), and you put this in a while loop. If the resource is free, the sleep never gets called. But if the resource is blocked, then you sleep for an appropriate amount of time, and attempt to access the resource again (this why you're looping). However, bear in mind that you must put some kind of limiter on the loop, so it's not a potentially infinite loop. You can set your limiting condition to be N number of attempts (this is what I usually use), or check the system clock, add a fixed amount of time to get a time limit, and quit attempting access if you hit the time limit.

Regex using javascript to return just numbers

As per @Syntle's answer, if you have only non numeric characters you'll get an Uncaught TypeError: Cannot read property 'join' of null.

This will prevent errors if no matches are found and return an empty string:

('something'.match( /\d+/g )||[]).join('')

How do I debug a stand-alone VBScript script?

This is for future readers. I found that the simplest method for me was to use Visual Studio -> Tools -> External Tools. More details in this answer.

Easier to use and good debugging tools.

how to configure lombok in eclipse luna

Step 1: Goto https://projectlombok.org/download and click on 1.18.2

Step 2: Place your jar file in java installation path in my case it is C:\Program Files\Java\jdk-10.0.1\lib

step 3: Open your Eclipse IDE folder where you have in your PC.

Step 4: Add the place where I added then open your IDE it will open without any errors.

-startup
plugins/org.eclipse.equinox.launcher_1.5.0.v20180512-1130.jar
--launcher.library
plugins/org.eclipse.equinox.launcher.win32.win32.x86_64_1.1.700.v20180518-1200
-product
org.eclipse.epp.package.jee.product
-showsplash
org.eclipse.epp.package.common
--launcher.defaultAction
openFile
--launcher.defaultAction
openFile
--launcher.appendVmargs
-vmargs
-Dosgi.requiredJavaVersion=1.8
-javaagent:C:\Program Files\Java\jdk-10.0.1\lib\lombok.jar
-Xbootclasspath/a:C:\Program Files\Java\jdk-10.0.1\lib\lombok.jar
[email protected]/eclipse-workspace
-XX:+UseG1GC
-XX:+UseStringDeduplication
--add-modules=ALL-SYSTEM
-Dosgi.requiredJavaVersion=1.8
-Dosgi.dataAreaRequiresExplicitInit=true
-Xms256m
-Xmx1024m
--add-modules=ALL-SYSTEM

How do you display JavaScript datetime in 12 hour AM/PM format?

_x000D_
_x000D_
function formatTime( d = new Date(), ampm = true ) 
{
    var hour = d.getHours();
    
    if ( ampm )
    {
        var a = ( hour >= 12 ) ? 'PM' : 'AM';
        hour = hour % 12;
        hour = hour ? hour : 12; // the hour '0' should be '12'  
    }

    var hour    = checkDigit(hour);  
    var minute  = checkDigit(d.getMinutes());
    var second  = checkDigit(d.getSeconds());
  
    // https://stackoverflow.com/questions/1408289/how-can-i-do-string-interpolation-in-javascript
    return ( ampm ) ? `${hour}:${minute}:${second} ${a}` : `${hour}:${minute}:${second}`;
}

function checkDigit(t)
{
  return ( t < 10 ) ? `0${t}` : t;
}

document.querySelector("#time1").innerHTML = formatTime();
document.querySelector("#time2").innerHTML = formatTime( new Date(), false );
_x000D_
<p>ampm true:   <span id="time1"></span> (default)</p>
<p>ampm false:  <span id="time2"></span></p>
_x000D_
_x000D_
_x000D_

Reading CSV file and storing values into an array

You can use Microsoft.VisualBasic.FileIO.TextFieldParser dll in C# for better performance

get below code example from above article

static void Main()
{
    string csv_file_path=@"C:\Users\Administrator\Desktop\test.csv";

    DataTable csvData = GetDataTabletFromCSVFile(csv_file_path);

    Console.WriteLine("Rows count:" + csvData.Rows.Count);

    Console.ReadLine();
}


private static DataTable GetDataTabletFromCSVFile(string csv_file_path)
{
    DataTable csvData = new DataTable();

    try
    {

    using(TextFieldParser csvReader = new TextFieldParser(csv_file_path))
        {
            csvReader.SetDelimiters(new string[] { "," });
            csvReader.HasFieldsEnclosedInQuotes = true;
            string[] colFields = csvReader.ReadFields();
            foreach (string column in colFields)
            {
                DataColumn datecolumn = new DataColumn(column);
                datecolumn.AllowDBNull = true;
                csvData.Columns.Add(datecolumn);
            }

            while (!csvReader.EndOfData)
            {
                string[] fieldData = csvReader.ReadFields();
                //Making empty value as null
                for (int i = 0; i < fieldData.Length; i++)
                {
                    if (fieldData[i] == "")
                    {
                        fieldData[i] = null;
                    }
                }
                csvData.Rows.Add(fieldData);
            }
        }
    }
    catch (Exception ex)
    {
    }
    return csvData;
}

Why does this AttributeError in python occur?

This happens because the scipy module doesn't have any attribute named sparse. That attribute only gets defined when you import scipy.sparse.

Submodules don't automatically get imported when you just import scipy; you need to import them explicitly. The same holds for most packages, although a package can choose to import its own submodules if it wants to. (For example, if scipy/__init__.py included a statement import scipy.sparse, then the sparse submodule would be imported whenever you import scipy.)

Failed to load resource: the server responded with a status of 404 (Not Found) error in server

Use your browser's network inspector (F12) to see when the browser is requesting the bgbody.png image and what absolute path it's using and why the server is returning a 404 response.

...assuming that bgbody.png actually exists :)

Is your CSS in a stylesheet file or in a <style> block in a page? If it's in a stylesheet then the relative path must be relative to the CSS stylesheet (not the document that references it). If it's in a page then it must be relative to the current resource path. If you're using non-filesystem-based resource paths (i.e. using URL rewriting or URL routing) then this will cause problems and it's best to always use absolute paths.

Going by your relative path it looks like you store your images separately from your stylesheets. I don't think this is a good idea - I support storing images and other resources, like fonts, in the same directory as the stylesheet itself, as it simplifies paths and is also a more logical filesystem arrangement.

What is the purpose of Node.js module.exports and how do you use it?

the refer link is like this:

exports = module.exports = function(){
    //....
}

the properties of exports or module.exports ,such as functions or variables , will be exposed outside

there is something you must pay more attention : don't override exports .

why ?

because exports just the reference of module.exports , you can add the properties onto the exports ,but if you override the exports , the reference link will be broken .

good example :

exports.name = 'william';

exports.getName = function(){
   console.log(this.name);
}

bad example :

exports = 'william';

exports = function(){
     //...
}

If you just want to exposed only one function or variable , like this:

// test.js
var name = 'william';

module.exports = function(){
    console.log(name);
}   

// index.js
var test = require('./test');
test();

this module only exposed one function and the property of name is private for the outside .

How to add a ScrollBar to a Stackpanel

For horizontally oriented StackPanel, explicitly putting both the scrollbar visibilities worked for me to get the horizontal scrollbar.

    <ScrollViewer VerticalScrollBarVisibility="Hidden" HorizontalScrollBarVisibility="Auto" >
        <StackPanel Orientation="Horizontal" />
    </ScrollViewer>

Two column div layout with fluid left and fixed right column

CSS:

#sidebar {float: right; width: 200px; background: #eee;}
#content {overflow: hidden; background: #dad;}

HTML:

<div id="sidebar">I'm 200px wide</div>
<div id="content"> I take up the remaining space <br> and I don't wrap under the right column</div>

The above should work, you can put that code in wrapper if you want the give it width and center it too, overflow:hidden on the column without a width is the key to getting it to contain, vertically, as in not wrap around the side columns (can be left or right)

IE6 might need zoom:1 set on the #content div too if you need it's support

How to only get file name with Linux 'find'?

If you want to run some action against the filename only, using basename can be tough.

For example this:

find ~/clang+llvm-3.3/bin/ -type f -exec echo basename {} \; 

will just echo basename /my/found/path. Not what we want if we want to execute on the filename.

But you can then xargs the output. for example to kill the files in a dir based on names in another dir:

cd dirIwantToRMin;
find ~/clang+llvm-3.3/bin/ -type f -exec basename {} \; | xargs rm

LINQ select one field from list of DTO objects to array

This is very simple in LinQ... You can use the select statement to get an Enumerable of properties of the objects.

var mySkus = myLines.Select(x => x.Sku);

Or if you want it as an Array just do...

var mySkus = myLines.Select(x => x.Sku).ToArray();

How to check if mod_rewrite is enabled in php?

For IIS heros and heroins:

No need to look for mod_rewrite. Just install Rewrite 2 module and then import .htaccess files.

How to get relative path of a file in visual studio?

Omit the "~\":

var path = @"FolderIcon\Folder.ico";

~\ doesn't mean anything in terms of the file system. The only place I've seen that correctly used is in a web app, where ASP.NET replaces the tilde with the absolute path to the root of the application.

You can typically assume the paths are relative to the folder where the EXE is located. Also, make sure that the image is specified as "content" and "copy if newer"/"copy always" in the properties tab in Visual Studio.

How do I remove blank elements from an array?

Here is what works for me:

[1, "", 2, "hello", nil].reject(&:blank?)

output:

[1, 2, "hello"]

How to download an entire directory and subdirectories using wget?

You may use this in shell:

wget -r --no-parent http://abc.tamu.edu/projects/tzivi/repository/revisions/2/raw/tzivi/

The Parameters are:

-r     //recursive Download

and

--no-parent // Don´t download something from the parent directory

If you don't want to download the entire content, you may use:

-l1 just download the directory (tzivi in your case)

-l2 download the directory and all level 1 subfolders ('tzivi/something' but not 'tivizi/somthing/foo')  

And so on. If you insert no -l option, wget will use -l 5 automatically.

If you insert a -l 0 you´ll download the whole Internet, because wget will follow every link it finds.

How to Consolidate Data from Multiple Excel Columns All into One Column

Here is how you do it with some simple Excel formulae, and no fancy VBA needed. The trick is to use the OFFSET formula. Please see this example spreadsheet:

https://docs.google.com/spreadsheet/ccc?key=0AuSyDFZlcRtHdGJOSnFwREotRzFfM28tWElpZ1FaR2c&usp=sharing#gid=0

C - determine if a number is prime

OK, so forget about C. Suppose I give you a number and ask you to determine if it's prime. How do you do it? Write down the steps clearly, then worry about translating them into code.

Once you have the algorithm determined, it will be much easier for you to figure out how to write a program, and for others to help you with it.

edit: Here's the C# code you posted:

static bool IsPrime(int number) {
    for (int i = 2; i < number; i++) {
        if (number % i == 0 && i != number) return false;
    }
    return true;
}

This is very nearly valid C as is; there's no bool type in C, and no true or false, so you need to modify it a little bit (edit: Kristopher Johnson correctly points out that C99 added the stdbool.h header). Since some people don't have access to a C99 environment (but you should use one!), let's make that very minor change:

int IsPrime(int number) {
    int i;
    for (i=2; i<number; i++) {
        if (number % i == 0 && i != number) return 0;
    }
    return 1;
}

This is a perfectly valid C program that does what you want. We can improve it a little bit without too much effort. First, note that i is always less than number, so the check that i != number always succeeds; we can get rid of it.

Also, you don't actually need to try divisors all the way up to number - 1; you can stop checking when you reach sqrt(number). Since sqrt is a floating-point operation and that brings a whole pile of subtleties, we won't actually compute sqrt(number). Instead, we can just check that i*i <= number:

int IsPrime(int number) {
    int i;
    for (i=2; i*i<=number; i++) {
        if (number % i == 0) return 0;
    }
    return 1;
}

One last thing, though; there was a small bug in your original algorithm! If number is negative, or zero, or one, this function will claim that the number is prime. You likely want to handle that properly, and you may want to make number be unsigned, since you're more likely to care about positive values only:

int IsPrime(unsigned int number) {
    if (number <= 1) return 0; // zero and one are not prime
    unsigned int i;
    for (i=2; i*i<=number; i++) {
        if (number % i == 0) return 0;
    }
    return 1;
}

This definitely isn't the fastest way to check if a number is prime, but it works, and it's pretty straightforward. We barely had to modify your code at all!

Convert this string to datetime

The Problem is with your code formatting,

inorder to use strtotime() You should replace '06/Oct/2011:19:00:02' with 06/10/2011 19:00:02 and date('d/M/Y:H:i:s', $date); with date('d/M/Y H:i:s', $date);. Note the spaces in between.

So the final code looks like this

$s = '06/10/2011 19:00:02';
$date = strtotime($s);
echo date('d/M/Y H:i:s', $date);

How can I use Oracle SQL developer to run stored procedures?

There are two possibilities, both from Quest Software, TOAD & SQL Navigator:

Here is the TOAD Freeware download: http://www.toadworld.com/Downloads/FreewareandTrials/ToadforOracleFreeware/tabid/558/Default.aspx

And the SQL Navigator (trial version): http://www.quest.com/sql-navigator/software-downloads.aspx

Maven Installation OSX Error Unsupported major.minor version 51.0

In Eclipse, you don't need to change JAVA_HOME, you just need to change the run configuration for Maven to something above 1.6 (even if your project is on Java 6, Maven shouldn't be). Right-click the project, choose Maven Build or Run As > Run Configurations and set the correct JDK version.

How to implement swipe gestures for mobile devices?

Shameless plug I know, but you might want to consider a jQuery plugin that I wrote:

https://github.com/benmajor/jQuery-Mobile-Events

It does not require jQuery Mobile, only jQuery.

How to center an image horizontally and align it to the bottom of the container?

.image_block    {
    width: 175px;
    height: 175px;
    position: relative;
}

.image_block a  {
    width: 100%;
    text-align: center;
    position: absolute;
    bottom: 0px;
}

.image_block img    {
/*  nothing specific  */
}

explanation: an element positioned absolutely will be relative to the closest parent which has a non-static positioning. i'm assuming you're happy with how your .image_block displays, so we can leave the relative positioning there.

as such, the <a> element will be positioned relative to the .image_block, which will give us the bottom alignment. then, we text-align: center the <a> element, and give it a 100% width so that it is the size of .image_block.

the <img> within <a> will then center appropriately.

How to detect when a youtube video finishes playing?

What you may want to do is include a script on all pages that does the following ... 1. find the youtube-iframe : searching for it by width and height by title or by finding www.youtube.com in its source. You can do that by ... - looping through the window.frames by a for-in loop and then filter out by the properties

  1. inject jscript in the iframe of the current page adding the onYoutubePlayerReady must-include-function http://shazwazza.com/post/Injecting-JavaScript-into-other-frames.aspx

  2. Add the event listeners etc..

Hope this helps

How can I tell jackson to ignore a property for which I don't have control over the source code?

One other possibility is, if you want to ignore all unknown properties, you can configure the mapper as follows:

mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

Hibernate: ids for this class must be manually assigned before calling save()

Assign primary key in hibernate

Make sure that the attribute is primary key and Auto Incrementable in the database. Then map it into the data class with the annotation with @GeneratedValue annotation using IDENTITY.

@Entity
@Table(name = "client")
data class Client(
        @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id") private val id: Int? = null
)

GL

Source

Create a Bitmap/Drawable from file path

Well, using the static Drawable.createFromPath(String pathName) seems a bit more straightforward to me than decoding it yourself... :-)

If your mImg is a simple ImageView, you don't even need it, use mImg.setImageUri(Uri uri) directly.

What is the format specifier for unsigned short int?

From the Linux manual page:

h      A  following  integer conversion corresponds to a short int or unsigned short int argument, or a fol-
       lowing n conversion corresponds to a pointer to a short int argument.

So to print an unsigned short integer, the format string should be "%hu".

Is there a better way to do optional function parameters in JavaScript?

I tried some options mentioned in here and performance tested them. At this moment the logicalor seems to be the fastest. Although this is subject of change over time (different JavaScript engine versions).

These are my results (Microsoft Edge 20.10240.16384.0):

Function executed            Operations/sec     Statistics
TypeofFunction('test');          92,169,505     ±1.55%   9% slower
SwitchFuntion('test');            2,904,685     ±2.91%  97% slower
ObjectFunction({param1: 'test'});   924,753     ±1.71%  99% slower
LogicalOrFunction('test');      101,205,173     ±0.92%     fastest
TypeofFunction2('test');         35,636,836     ±0.59%  65% slower

This performance test can be easily replicated on: http://jsperf.com/optional-parameters-typeof-vs-switch/2

This is the code of the test:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script>
    Benchmark.prototype.setup = function() {
        function TypeofFunction(param1, optParam1, optParam2, optParam3) {
            optParam1 = (typeof optParam1 === "undefined") ? "Some default" : optParam1;
            optParam2 = (typeof optParam2 === "undefined") ? "Another default" : optParam2;
            optParam3 = (typeof optParam3 === "undefined") ? "Some other default" : optParam3;
        }

        function TypeofFunction2(param1, optParam1, optParam2, optParam3) {
            optParam1 = defaultValue(optParam1, "Some default");
            optParam2 = defaultValue(optParam2, "Another default");
            optParam3 = defaultValue(optParam3, "Some other default");
        }

        function defaultValue(variable, defaultValue) {
            return (typeof variable !== 'undefined') ? (variable) : (defaultValue);
        }

        function SwitchFuntion(param1, optParam1, optParam2, optParam3) {
            switch (arguments.length - 1) { // <-- 1 is number of required arguments
                case 0:
                    optParam1 = 'Some default';
                case 1:
                    optParam2 = 'Another default';
                case 2:
                    optParam3 = 'Some other default';
            }
        }

        function ObjectFunction(args) {
            var defaults = {
                optParam1: 'Some default',
                optParam2: 'Another default',
                optParam3: 'Some other default'
            }
            args = $.extend({}, defaults, args);
        }

        function LogicalOrFunction(param1, optParam1, optParam2, optParam3) {
            optParam1 || (optParam1 = 'Some default');
            optParam2 || (optParam1 = 'Another default');
            optParam3 || (optParam1 = 'Some other default');
        }
    };
</script>

How do I detect whether a Python variable is a function?

In Python3 I came up with type (f) == type (lambda x:x) which yields True if f is a function and False if it is not. But I think I prefer isinstance (f, types.FunctionType), which feels less ad hoc. I wanted to do type (f) is function, but that doesn't work.

Best way to implement multi-language/globalization in large .NET project

Most opensource projects use GetText for this purpose. I don't know how and if it's ever been used on a .Net project before.

Post order traversal of binary tree without recursion

I have not added the node class as its not particularly relevant or any test cases, leaving those as an excercise for the reader etc.

void postOrderTraversal(node* root)
{
    if(root == NULL)
        return;

    stack<node*> st;
    st.push(root);

    //store most recent 'visited' node
    node* prev=root;

    while(st.size() > 0)
    {
        node* top = st.top();
        if((top->left == NULL && top->right == NULL))
        {
            prev = top;
            cerr<<top->val<<" ";
            st.pop();
            continue;
        }
        else
        {
            //we can check if we are going back up the tree if the current
            //node has a left or right child that was previously outputted
            if((top->left == prev) || (top->right== prev))
            {
                prev = top;
                cerr<<top->val<<" ";
                st.pop();
                continue;
            }

            if(top->right != NULL)
                st.push(top->right);

            if(top->left != NULL)
                st.push(top->left);
        }
    }
    cerr<<endl;
}

running time O(n) - all nodes need to be visited AND space O(n) - for the stack, worst case tree is a single line linked list

How to make Scrollable Table with fixed headers using CSS

What you want to do is separate the content of the table from the header of the table. You want only the <th> elements to be scrolled. You can easily define this separation in HTML with the <tbody> and the <thead> elements.
Now the header and the body of the table are still connected to each other, they will still have the same width (and same scroll properties). Now to let them not 'work' as a table anymore you can set the display: block. This way <thead> and <tbody> are separated.

table tbody, table thead
{
    display: block;
}

Now you can set the scroll to the body of the table:

table tbody 
{
   overflow: auto;
   height: 100px;
}

And last, because the <thead> doesn't share the same width as the body anymore, you should set a static width to the header of the table:

th
{
    width: 72px;
}

You should also set a static width for <td>. This solves the issue of the unaligned columns.

td
{
    width: 72px;
}


Note that you are also missing some HTML elements. Every row should be in a <tr> element, that includes the header row:

<tr>
     <th>head1</th>
     <th>head2</th>
     <th>head3</th>
     <th>head4</th>
</tr>

I hope this is what you meant.

jsFiddle

Addendum

If you would like to have more control over the column widths, have them to vary in width between each other, and course keep the header and body columns aligned, you can use the following example:

    table th:nth-child(1), td:nth-child(1) { min-width: 50px;  max-width: 50px; }
    table th:nth-child(2), td:nth-child(2) { min-width: 100px; max-width: 100px; }
    table th:nth-child(3), td:nth-child(3) { min-width: 150px; max-width: 150px; }
    table th:nth-child(4), td:nth-child(4) { min-width: 200px; max-width: 200px; }

Parenthesis/Brackets Matching using Stack algorithm

public static boolean isValidExpression(String expression) {
    Map<Character, Character> openClosePair = new HashMap<Character, Character>();
    openClosePair.put(')', '(');
    openClosePair.put('}', '{');
    openClosePair.put(']', '[');        
    Stack<Character> stack = new Stack<Character>();
    for(char ch : expression.toCharArray()) {
        if(openClosePair.containsKey(ch)) {
            if(stack.pop() != openClosePair.get(ch)) {
                return false;
            }
        } else if(openClosePair.values().contains(ch)) {
            stack.push(ch); 
        }
    }
    return stack.isEmpty();
}

Android 6.0 Marshmallow. Cannot write to SD Card

Android changed how permissions work with Android 6.0 that's the reason for your errors. You have to actually request and check if the permission was granted by user to use. So permissions in manifest file will only work for api below 21. Check this link for a snippet of how permissions are requested in api23 http://android-developers.blogspot.nl/2015/09/google-play-services-81-and-android-60.html?m=1

Code:-

If (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE) !=
                PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, STORAGE_PERMISSION_RC);
            return;
        }`


` @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == STORAGE_PERMISSION_RC) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                //permission granted  start reading
            } else {
                Toast.makeText(this, "No permission to read external storage.", Toast.LENGTH_SHORT).show();
            }
        }
    }
}

CSS Vertical align does not work with float

You need to set line-height.

<div style="border: 1px solid red;">
<span style="font-size: 38px; vertical-align:middle; float:left; line-height: 38px">Hejsan</span>
<span style="font-size: 13px; vertical-align:middle; float:right; line-height: 38px">svejsan</span>
<div style="clear: both;"></div>

http://jsfiddle.net/VBR5J/

Get a particular cell value from HTML table using JavaScript

Just simply.. #sometime when larger table we can't add the id to each tr

     <table>
        <tr>
            <td>some text</td>
            <td>something</td>
        </tr>
        <tr>
            <td>Hello</td>
            <td>Hel</td>
        </tr>
    </table>

    <script>
        var cell = document.getElementsByTagName("td"); 
        var i = 0;
        while(cell[i] != undefined){
            alert(cell[i].innerHTML); //do some alert for test
            i++;
            }//end while
    </script>

IntelliJ IDEA shows errors when using Spring's @Autowired annotation

Got the same error here!

It seems the Intellij cannot verify if the class implementation is a @Service or @Component.

Solve it just changing from Error to Warning(Pressing Alt + Enter).

python location on mac osx

run the following code in a .py file:

import sys

print(sys.version)
print(sys.executable)

store return json value in input hidden field

Although I have seen the suggested methods used and working, I think that setting the value of an hidden field only using the JSON.stringify breaks the HTML...

Here I'll explain what I mean:

<input type="hidden" value="{"name":"John"}">

As you can see the first double quote after the open chain bracket could be interpreted by some browsers as:

<input type="hidden" value="{" rubbish >

So for a better approach to this I would suggest to use the encodeURIComponent function. Together with the JSON.stringify we shold have something like the following:

> encodeURIComponent(JSON.stringify({"name":"John"}))
> "%7B%22name%22%3A%22John%22%7D"

Now that value can be safely stored in an input hidden type like so:

<input type="hidden" value="%7B%22name%22%3A%22John%22%7D">

or (even better) using the data- attribute of the HTML element manipulated by the script that will consume the data, like so:

<div id="something" data-json="%7B%22name%22%3A%22John%22%7D"></div>

Now to read the data back we can do something like:

> var data = JSON.parse(decodeURIComponent(div.getAttribute("data-json")))
> console.log(data)
> Object {name: "John"}

Remove pattern from string with gsub

The following code works on your example :

gsub(".*_", "", a)

How do I set up IntelliJ IDEA for Android applications?

Once I have followed all these steps, I start to receive error messages in all android classes calls like:

Cannot resolve Android Classes

I revolved that including android.jar in the SDKs Platform Settings:

SKDs Classpath

Hive cast string to date dd-MM-yyyy

AFAIK you must reformat your String in ISO format to be able to cast it as a Date:

cast(concat(substr(STR_DMY,7,4), '-',
            substr(STR_DMY,1,2), '-',
            substr(STR_DMY,4,2)
           )
     as date
     ) as DT

To display a Date as a String with specific format, then it's the other way around, unless you have Hive 1.2+ and can use date_format()

=> did you check the documentation by the way?

What to use now Google News API is deprecated?

Looks like you might have until the end of 2013 before they officially close it down. http://groups.google.com/group/google-ajax-search-api/browse_thread/thread/6aaa1b3529620610/d70f8eec3684e431?lnk=gst&q=news+api#d70f8eec3684e431

Also, it sounds like they are building a replacement... but it's going to cost you.

I'd say, go to a different service. I think bing has a news API.

You might enjoy (or not) reading: http://news.ycombinator.com/item?id=1864625

How to close a thread from within?

How about sys.exit() from the module sys.

If sys.exit() is executed from within a thread it will close that thread only.

This answer here talks about that: Why does sys.exit() not exit when called inside a thread in Python?

What is SaaS, PaaS and IaaS? With examples

Following link gives very good explanation on SaaS, PaaS and Iaas.. http://opensourceforgeeks.blogspot.in/2015/01/difference-between-saas-paas-and-iaas.html

Just some brief:


IaaS, here vendor provides infra to user where an user gets hardware/virtualization infra, storage and Networking infra.

PaaS, here vendor provides platform to user where an user gets all required things for their work like OS, Database, Execution Environment along with IaaS provided environment. So pass is platform + IaaS.

SaaS seems to be quite wide area where vendor provides almost everything from infra to platform to software. So SaaS is Iaas+PaaS along with different softwares like ms office, virtual box etc..

Angularjs loading screen on ajax request

I built on @DavidLin's answer a little to simplify it - removing any dependency on jQuery in the directive. I can confirm this works as I use it in a production application

function AjaxLoadingOverlay($http) {

    return {
        restrict: 'A',
        link: function ($scope, $element, $attributes) {

            $scope.loadingOverlay = false;

            $scope.isLoading = function () {
                return $http.pendingRequests.length > 0;
            };

            $scope.$watch($scope.isLoading, function (isLoading) {
                $scope.loadingOverlay = isLoading;
            });
        }
    };
}   

I use a ng-show instead of a jQuery call to hide/show the <div>.

Here's the <div> which I placed just below the opening <body> tag:

<div ajax-loading-overlay class="loading-overlay" ng-show="loadingOverlay">
    <img src="Resources/Images/LoadingAnimation.gif" />
</div>

And here's the CSS that provides the overlay to block UI while a $http call is being made:

.loading-overlay {
    position: fixed;
    z-index: 999;
    height: 2em;
    width: 2em;
    overflow: show;
    margin: auto;
    top: 0;
    left: 0;
    bottom: 0;
    right: 0;
}

.loading-overlay:before {
    content: '';
    display: block;
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0,0,0,0.3);
}

/* :not(:required) hides these rules from IE9 and below */
.loading-overlay:not(:required) {
    font: 0/0 a;
    color: transparent;
    text-shadow: none;
    background-color: transparent;
    border: 0;
}

CSS credit goes to @Steve Seeger's - his post: https://stackoverflow.com/a/35470281/335545

How to put attributes via XElement

Add XAttribute in the constructor of the XElement, like

new XElement("Conn", new XAttribute("Server", comboBox1.Text));

You can also add multiple attributes or elements via the constructor

new XElement("Conn", new XAttribute("Server", comboBox1.Text), new XAttribute("Database", combobox2.Text));

or you can use the Add-Method of the XElement to add attributes

XElement element = new XElement("Conn");
XAttribute attribute = new XAttribute("Server", comboBox1.Text);
element.Add(attribute);

Continuous Integration vs. Continuous Delivery vs. Continuous Deployment

Continuous Integration

I Agree with your university's definition. Continuous Integration is a strategy for how a developer can integrate code to the mainline continuously - as opposed to frequently.

You might claim that it's merely a branching strategy in your version control system.

It has to do with the size of the tasks you assign to a developer; If a task is estimated to take 4-5 man-days then the developer will have no incitement to deliver anything for the next 4-5 days, because he's not done with anything - yet.

So size matters:

small task = continuous integration
big task   = frequent integration

The ideal task size is not bigger than a day's work. This way a developer will naturally have at least one integration per day.

Continuous Delivery

There are basically three schools within Continuous Delivery:

Continuous Delivery is a natural extension of Continuous Integration

This school, looks at the Addison-Wesley "Martin Fowler" signature series and makes the assumption that since the 2007 release was called "Continuous Integration" and the one that followed in 2011 was called "Continuous Delivery" they are probably volume 1+2 of the same conceptual idea that has to do with continuous something.

Continuous Delivery has to do with Agile Software Development

This school takes off-set in the idea that Continuous Delivery is all about being able to support the principles in the agile movement, not just as a conceptual idea or a letter of intent but for real - in real life.

Taking offset in the first principle in the Agile Manifesto where the term "continuous delivery" is actually used for the first time:

Our highest priority is to satisfy the customer through early and continuous delivery of valuable software.

This school claims that "Continuous Delivery" is a paradigm that embraces everything required to implement an automated verification of your "definition of done".

This school accepts that "Continuous Delivery" and the buzz word or megatrend "DevOps" are flip sides of the same coin, in the sense that they both try to embrace or encapsulate this new paradigm or approach and not just a technique.

Continuous Delivery is a synonym to Continuous Deployment

The third school advocates that Continuous Deployment and Continuous Delivery can be used interchangeably to mean the same thing.

When something is ready in the hands of the developers, it's immediately delivered to the end-users, which in most cases will mean that it should be deployed to the production environment. Hence "Deploy" and "Deliver" means the same.

Which school to join

Your university clearly joined the first school and claims that we're referring to volume 1+2 of the same publication series. My opinion is that this is a misuse of the term Continuous Delivery.

I personally advocate for the understanding that Continuous Delivery is related to implementing a real-life support for the ideas and concepts stated by the agile movement. So I joined the school that says the term embraces a whole paradigm - like "DevOps".

The school that uses delivery as a synonym to deploy is mostly advocated by tool vendors who create deployment consoles, trying to get a bit of hype from the more widespread use of the term Continuous Delivery.

Continuous Deployment

The focus on Continuous Deployment is mostly relevant in domains where the end user's access to software updates relies on the update of some centralized source for this information and where this centralized source is not always easy to update because it's monolithic or has (too) high coherence by nature (web, SOA, Databases etc.).

For a lot of domains that produces software where there is no centralized source of information (devices, consumer products, client installations etc.) or where the centralized source for information is easy to update (app stores artifact management systems, Open Source repositories etc.), there is almost no hype about the term Continuous Deployment at all. They just deploy; it's not a big thing - it's not a pain that requires special focus.

The fact that Continuous Deployment is not something that is generically interesting to everyone is also an argument that the school that claims that "delivery" and "deploy" are synonyms got it all wrong. Because Continuous Delivery actually makes perfectly good sense to everyone - even if you are doing embedded software in devices or releasing Open Source plugins for a framework.

Your university's definition that Continuous Deployment is a natural next step of Continuous Delivery implicitly assumes that every delivery that is QA'ed should go become available to the end-users immediately, is closer to the definition that my tribe use to describe the term "Continous Release", which, in turn, is another concept that doesn't generically makes sense to everyone either.

A release can be a very strategic or political thing and there is no reason to assume that everybody would want to do this all the time (unless they are an online bookstore a streaming service type of company). Nevertheless, companies that don't blindly release everything all the time may have any number of reasons why they would want to be masters of deployment anyway, so they too do Continuous Deployment. Not of release to production, but of release-candidates to production-like environments.

Again I believe your university got it wrong. They are mistaking "Continuous Deployment" for "Continuous Release".

Continuous deployment is simply the discipline of continuously being able to move the result of a development process to a production-like environment where functional testing can be executed in full scale.

The Continuous Delivery Storyline

In the picture it all comes alive:

enter image description here

The Continuous Integration process is the first two actions in the state-transition diagram. which - if successful - kicks off the Continuous Delivery pipeline that implements the definition of done. Deployment is just one of the many actions that will have to be done continuously in this pipeline. Ideally, the process is automated from the point where the developer commits to the VCS to the point where the pipeline has confirmed that we have a valid release candidate.

How to find the Windows version from the PowerShell command line

Using Windows Powershell, it possible to get the data you need in the following way

Caption:

(Get-WmiObject -class Win32_OperatingSystem).Caption

ReleaseId:

(Get-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion" -Name ReleaseId).ReleaseId

version:

(Get-CimInstance Win32_OperatingSystem).version

How to make rounded percentages add up to 100%

If you really must round them, there are already very good suggestions here (largest remainder, least relative error, and so on).

There is also already one good reason not to round (you'll get at least one number that "looks better" but is "wrong"), and how to solve that (warn your readers) and that is what I do.

Let me add on the "wrong" number part.

Suppose you have three events/entitys/... with some percentages that you approximate as:

DAY 1
who |  real | app
----|-------|------
  A | 33.34 |  34
  B | 33.33 |  33
  C | 33.33 |  33

Later on the values change slightly, to

DAY 2
who |  real | app
----|-------|------
  A | 33.35 |  33
  B | 33.36 |  34
  C | 33.29 |  33

The first table has the already mentioned problem of having a "wrong" number: 33.34 is closer to 33 than to 34.

But now you have a bigger error. Comparing day 2 to day 1, the real percentage value for A increased, by 0.01%, but the approximation shows a decrease by 1%.

That is a qualitative error, probably quite worse that the initial quantitative error.

One could devise a approximation for the whole set but, you may have to publish data on day one, thus you'll not know about day two. So, unless you really, really, must approximate, you probably better not.

Convert string to Python class object?

You could do something like:

globals()[class_name]

Java - How to create new Entry (key, value)

org.apache.commons.lang3.tuple.Pair implements java.util.Map.Entry and can also be used standalone.

Also as others mentioned Guava's com.google.common.collect.Maps.immutableEntry(K, V) does the trick.

I prefer Pair for its fluent Pair.of(L, R) syntax.

Submit form using AJAX and jQuery

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

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

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

} );

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

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

Get the last three chars from any string - Java

This method would be helpful :

String rightPart(String text,int length)
{
    if (text.length()<length) return text;
    String raw = "";
    for (int i = 1; i <= length; i++) {
        raw += text.toCharArray()[text.length()-i];
    }
    return new StringBuilder(raw).reverse().toString();
}

PHP syntax question: What does the question mark and colon mean?

It's the ternary form of the if-else operator. The above statement basically reads like this:

if ($add_review) then {
    return FALSE; //$add_review evaluated as True
} else {
    return $arg //$add_review evaluated as False
}

See here for more details on ternary op in PHP: http://www.addedbytes.com/php/ternary-conditionals/

jQuery/JavaScript to replace broken images

You can use GitHub's own fetch for this:

Frontend: https://github.com/github/fetch
or for Backend, a Node.js version: https://github.com/bitinn/node-fetch

fetch(url)
  .then(function(res) {
    if (res.status == '200') {
      return image;
    } else {
      return placeholder;
    }
  }

Edit: This method is going to replace XHR and supposedly already has been in Chrome. To anyone reading this in the future, you may not need the aforementioned library included.

What is the best way to repeatedly execute a function every x seconds?

If you want a non-blocking way to execute your function periodically, instead of a blocking infinite loop I'd use a threaded timer. This way your code can keep running and perform other tasks and still have your function called every n seconds. I use this technique a lot for printing progress info on long, CPU/Disk/Network intensive tasks.

Here's the code I've posted in a similar question, with start() and stop() control:

from threading import Timer

class RepeatedTimer(object):
    def __init__(self, interval, function, *args, **kwargs):
        self._timer     = None
        self.interval   = interval
        self.function   = function
        self.args       = args
        self.kwargs     = kwargs
        self.is_running = False
        self.start()

    def _run(self):
        self.is_running = False
        self.start()
        self.function(*self.args, **self.kwargs)

    def start(self):
        if not self.is_running:
            self._timer = Timer(self.interval, self._run)
            self._timer.start()
            self.is_running = True

    def stop(self):
        self._timer.cancel()
        self.is_running = False

Usage:

from time import sleep

def hello(name):
    print "Hello %s!" % name

print "starting..."
rt = RepeatedTimer(1, hello, "World") # it auto-starts, no need of rt.start()
try:
    sleep(5) # your long-running job goes here...
finally:
    rt.stop() # better in a try/finally block to make sure the program ends!

Features:

  • Standard library only, no external dependencies
  • start() and stop() are safe to call multiple times even if the timer has already started/stopped
  • function to be called can have positional and named arguments
  • You can change interval anytime, it will be effective after next run. Same for args, kwargs and even function!

Leaflet changing Marker color

You can also use the Google Charts API to get icons (just change 'abcdef' with the hexadecimal color you want:

Examples:

What does value & 0xff do in Java?

It sets result to the (unsigned) value resulting from putting the 8 bits of value in the lowest 8 bits of result.

The reason something like this is necessary is that byte is a signed type in Java. If you just wrote:

int result = value;

then result would end up with the value ff ff ff fe instead of 00 00 00 fe. A further subtlety is that the & is defined to operate only on int values1, so what happens is:

  1. value is promoted to an int (ff ff ff fe).
  2. 0xff is an int literal (00 00 00 ff).
  3. The & is applied to yield the desired value for result.

(The point is that conversion to int happens before the & operator is applied.)

1Well, not quite. The & operator works on long values as well, if either operand is a long. But not on byte. See the Java Language Specification, sections 15.22.1 and 5.6.2.

$(this).attr("id") not working

Because of the way the function is called (i.e. as a simple call to a function variable), this is the global object (for which window is an alias in browsers). Use the obj parameter instead.

Also, creating a jQuery object and the using its attr() method for obtaining an element ID is inefficient and unnecessary. Just use the element's id property, which works in all browsers.

function showHideOther(obj){ 
    var sel = obj.options[obj.selectedIndex].value;
    var ID = obj.id;

    if (sel == 'other') { 
        $(obj).html("<input type='text' name='" + ID + "' id='" + ID + "' />");
    } else {
        $(obj).css({'display' : 'none'});
    }
}

List View Filter Android

Add an EditText on top of your listview in its .xml layout file. And in your activity/fragment..

lv = (ListView) findViewById(R.id.list_view);
    inputSearch = (EditText) findViewById(R.id.inputSearch);

// Adding items to listview
adapter = new ArrayAdapter<String>(this, R.layout.list_item, R.id.product_name,    products);
lv.setAdapter(adapter);       
inputSearch.addTextChangedListener(new TextWatcher() {

    @Override
    public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
        // When user changed the Text
        MainActivity.this.adapter.getFilter().filter(cs);
    }

    @Override
    public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) { }

    @Override
    public void afterTextChanged(Editable arg0) {}
});

The basic here is to add an OnTextChangeListener to your edit text and inside its callback method apply filter to your listview's adapter.

EDIT

To get filter to your custom BaseAdapter you"ll need to implement Filterable interface.

class CustomAdapter extends BaseAdapter implements Filterable {

    public View getView(){
    ...
    }
    public Integer getCount()
    {
    ...
    }

    @Override
    public Filter getFilter() {

        Filter filter = new Filter() {

            @SuppressWarnings("unchecked")
            @Override
            protected void publishResults(CharSequence constraint, FilterResults results) {

                arrayListNames = (List<String>) results.values;
                notifyDataSetChanged();
            }

            @Override
            protected FilterResults performFiltering(CharSequence constraint) {

                FilterResults results = new FilterResults();
                ArrayList<String> FilteredArrayNames = new ArrayList<String>();

                // perform your search here using the searchConstraint String.

                constraint = constraint.toString().toLowerCase();
                for (int i = 0; i < mDatabaseOfNames.size(); i++) {
                    String dataNames = mDatabaseOfNames.get(i);
                    if (dataNames.toLowerCase().startsWith(constraint.toString()))  {
                        FilteredArrayNames.add(dataNames);
                    }
                }

                results.count = FilteredArrayNames.size();
                results.values = FilteredArrayNames;
                Log.e("VALUES", results.values.toString());

                return results;
            }
        };

        return filter;
    }
}

Inside performFiltering() you need to do actual comparison of the search query to values in your database. It will pass its result to publishResults() method.

Batch File: ( was unexpected at this time

you need double quotes in all your three if statements, eg.:

IF "%a%"=="2" (

@echo OFF &SETLOCAL ENABLEDELAYEDEXPANSION
cls
title ~USB Wizard~
echo What do you want to do?
echo 1.Enable/Disable USB Storage Devices.
echo 2.Enable/Disable Writing Data onto USB Storage.
echo 3.~Yet to come~.


set "a=%globalparam1%"
goto :aCheck
:aPrompt
set /p "a=Enter Choice: "
:aCheck
if "%a%"=="" goto :aPrompt
echo %a%

IF "%a%"=="2" (
    title USB WRITE LOCK
    echo What do you want to do?
    echo 1.Apply USB Write Protection
    echo 2.Remove USB Write Protection
    ::param1
    set "param1=%globalparam2%"
    goto :param1Check
    :param1Prompt
    set /p "param1=Enter Choice: "
    :param1Check
    if "!param1!"=="" goto :param1Prompt

    if "!param1!"=="1" (
         REG ADD HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\StorageDevicePolicies\ /v WriteProtect /t REG_DWORD /d 00000001
         USB Write is Locked!
    )
    if "!param1!"=="2" (
         REG ADD HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\StorageDevicePolicies\ /v WriteProtect /t REG_DWORD /d 00000000
         USB Write is Unlocked!
    )
)
pause

How to TryParse for Enum value?

There is not a TryParse because the Enum's type is not known until runtime. A TryParse that follows the same methodology as say the Date.TryParse method would throw an implicit conversion error on the ByRef parameter.

I suggest doing something like this:

//1 line call to get value
MyEnums enumValue = (Sections)EnumValue(typeof(Sections), myEnumTextValue, MyEnums.SomeEnumDefault);

//Put this somewhere where you can reuse
public static object EnumValue(System.Type enumType, string value, object NotDefinedReplacement)
{
    if (Enum.IsDefined(enumType, value)) {
        return Enum.Parse(enumType, value);
    } else {
        return Enum.Parse(enumType, NotDefinedReplacement);
    }
}

Warning comparison between pointer and integer

In this line ...

if (*message == "\0") {

... as you can see in the warning ...

warning: comparison between pointer and integer
      ('int' and 'char *')

... you are actually comparing an int with a char *, or more specifically, an int with an address to a char.

To fix this, use one of the following:

if(*message == '\0') ...
if(message[0] == '\0') ...
if(!*message) ...

On a side note, if you'd like to compare strings you should use strcmp or strncmp, found in string.h.

Windows CMD command for accessing usb?

Try this batch :

@echo off
Title List of connected external devices by Hackoo
Mode con cols=100 lines=20 & Color 9E
wmic LOGICALDISK where driveType=2 get deviceID > wmic.txt
for /f "skip=1" %%b IN ('type wmic.txt') DO (echo %%b & pause & Dir %%b)
Del wmic.txt
pause

dropdownlist set selected value in MVC3 Razor

I drilled down the formation of the drop down list instead of using @Html.DropDownList(). This is useful if you have to set the value of the dropdown list at runtime in razor instead of controller:

<select id="NewsCategoriesID" name="NewsCategoriesID">
    @foreach (SelectListItem option in ViewBag.NewsCategoriesID)
    {
        <option value="@option.Value" @(option.Value == ViewBag.ValueToSet ? "selected='selected'" : "")>@option.Text</option>

    }
</select>

ASP.NET MVC How to pass JSON object from View to Controller as Parameter

You say "I am not using a forms to manipulate the data." But you are doing a POST. Therefore, you are, in fact, using a form, even if it's empty.

$.ajax's dataType tells jQuery what type the server will return, not what you are passing. POST can only pass a form. jQuery will convert data to key/value pairs and pass it as a query string. From the docs:

Data to be sent to the server. It is converted to a query string, if not already a string. It's appended to the url for GET-requests. See processData option to prevent this automatic processing. Object must be Key/Value pairs. If value is an Array, jQuery serializes multiple values with same key i.e. {foo:["bar1", "bar2"]} becomes '&foo=bar1&foo=bar2'.

Therefore:

  1. You aren't passing JSON to the server. You're passing JSON to jQuery.
  2. Model binding happens in the same way it happens in any other case.

Why are elementwise additions much faster in separate loops than in a combined loop?

The first loop alternates writing in each variable. The second and third ones only make small jumps of element size.

Try writing two parallel lines of 20 crosses with a pen and paper separated by 20 cm. Try once finishing one and then the other line and try another time by writting a cross in each line alternately.

Removing the textarea border in HTML

Add this to your <head>:

<style type="text/css">
    textarea { border: none; }
</style>

Or do it directly on the textarea:

<textarea style="border: none"></textarea>

How to use regex in String.contains() method in Java

As of Java 11 one can use Pattern#asMatchPredicate which returns Predicate<String>.

String string = "stores%store%product";
String regex = "stores.*store.*product.*";
Predicate<String> matchesRegex = Pattern.compile(regex).asMatchPredicate();

boolean match = matchesRegex.test(string);                   // true

The method enables chaining with other String predicates, which is the main advantage of this method as long as the Predicate offers and, or and negate methods.

String string = "stores$store$product";
String regex = "stores.*store.*product.*";

Predicate<String> matchesRegex = Pattern.compile(regex).asMatchPredicate();
Predicate<String> hasLength = s -> s.length() > 20;

boolean match = hasLength.and(matchesRegex).test(string);    // false

Change route params without reloading in Angular 2

Using location.go(url) is the way to go, but instead of hardcoding the url , consider generating it using router.createUrlTree().

Given that you want to do the following router call: this.router.navigate([{param: 1}], {relativeTo: this.activatedRoute}) but without reloading the component, it can be rewritten as:

const url = this.router.createUrlTree([], {relativeTo: this.activatedRoute, queryParams: {param: 1}}).toString()

 this.location.go(url);

What's the difference between Invoke() and BeginInvoke()

Do you mean Delegate.Invoke/BeginInvoke or Control.Invoke/BeginInvoke?

  • Delegate.Invoke: Executes synchronously, on the same thread.
  • Delegate.BeginInvoke: Executes asynchronously, on a threadpool thread.
  • Control.Invoke: Executes on the UI thread, but calling thread waits for completion before continuing.
  • Control.BeginInvoke: Executes on the UI thread, and calling thread doesn't wait for completion.

Tim's answer mentions when you might want to use BeginInvoke - although it was mostly geared towards Delegate.BeginInvoke, I suspect.

For Windows Forms apps, I would suggest that you should usually use BeginInvoke. That way you don't need to worry about deadlock, for example - but you need to understand that the UI may not have been updated by the time you next look at it! In particular, you shouldn't modify data which the UI thread might be about to use for display purposes. For example, if you have a Person with FirstName and LastName properties, and you did:

person.FirstName = "Kevin"; // person is a shared reference
person.LastName = "Spacey";
control.BeginInvoke(UpdateName);
person.FirstName = "Keyser";
person.LastName = "Soze";

Then the UI may well end up displaying "Keyser Spacey". (There's an outside chance it could display "Kevin Soze" but only through the weirdness of the memory model.)

Unless you have this sort of issue, however, Control.BeginInvoke is easier to get right, and will avoid your background thread from having to wait for no good reason. Note that the Windows Forms team has guaranteed that you can use Control.BeginInvoke in a "fire and forget" manner - i.e. without ever calling EndInvoke. This is not true of async calls in general: normally every BeginXXX should have a corresponding EndXXX call, usually in the callback.

Moving Panel in Visual Studio Code to right side

As of October 2018 (version 1.29) the button in @mvvijesh's answer no longer exists.

You now have 2 options. Right click the panel's toolbar (nowhere else on the panel will work) and choose "move panel right/bottom":

Or choose "View: Toggle Panel Position" from the command palette.

Source: VSCode update notes: https://code.visualstudio.com/updates/v1_29#_panel-position-button-to-context-menu

Reporting Services permissions on SQL Server R2 SSRS

This did the trick for me. http://thecodeattic.wordpress.com/category/ssrs/. Go down to step 35 to see the error you are getting. Paraphrasing:

Once you're able to log in to YourServer/Reports as an administrator, click Home in the top-right corner, then Folder Settings and New Role Assignment. Enter your user name and check a box for each role you want to grant yourself. Finally, click OK. You should now be able to browse folders without launching your browser with elevated privileges.

Don't forget to set the security at the site level **AND ** at the folder level. I hope that helps.

Rick

How to use [DllImport("")] in C#?

You can't declare an extern local method inside of a method, or any other method with an attribute. Move your DLL import into the class:

using System.Runtime.InteropServices;


public class WindowHandling
{
    [DllImport("User32.dll")]
    public static extern int SetForegroundWindow(IntPtr point);

    public void ActivateTargetApplication(string processName, List<string> barcodesList)
    {
        Process p = Process.Start("notepad++.exe");
        p.WaitForInputIdle();
        IntPtr h = p.MainWindowHandle;
        SetForegroundWindow(h);
        SendKeys.SendWait("k");
        IntPtr processFoundWindow = p.MainWindowHandle;
    }
}

How can I control the speed that bootstrap carousel slides in items?

If using the ngCarousel module, edit the interval variable in the file @ng-bootstrap/ng-bootstrap/carousel-config.js like so:

var NgbCarouselConfig = /** @class */ (function () {
function NgbCarouselConfig() {
    this.interval = 10000;
    this.wrap = true;
    ...
}
...

How to drop all tables from a database with one SQL query?

I Know this question is very old but every Time i need this code .. by the way if you have tables and views and Functions and PROCEDURES you can delete it all by this Script .. so why i post this Script ?? because if u delete all tables you will need to delete all views and if you have Functions and PROCEDURES you need to delete it too
i Hope it will help someone

DECLARE @sql NVARCHAR(max)=''

 SELECT @sql += ' Drop table ' + QUOTENAME(TABLE_SCHEMA) + '.'+ QUOTENAME(TABLE_NAME) 
+ '; '
FROM   INFORMATION_SCHEMA.TABLES
WHERE  TABLE_TYPE = 'BASE TABLE'

Exec Sp_executesql @sql


 DECLARE @sql VARCHAR(MAX) = ''
    , @crlf VARCHAR(2) = CHAR(13) + CHAR(10) ;

 SELECT @sql = @sql + 'DROP VIEW ' + QUOTENAME(SCHEMA_NAME(schema_id)) + '.' + 
 QUOTENAME(v.name) +';' + @crlf
 FROM   sys.views v

 PRINT @sql;
 EXEC(@sql);

 declare @procName varchar(500)
 declare cur cursor 

 for select [name] from sys.objects where type = 'p'
 open cur
 fetch next from cur into @procName
 while @@fetch_status = 0
 begin
  exec('drop procedure [' + @procName + ']')
fetch next from cur into @procName
 end
  close cur
  deallocate cur

  Declare @sql NVARCHAR(MAX) = N'';

    SELECT @sql = @sql + N' DROP FUNCTION ' 
               + QUOTENAME(SCHEMA_NAME(schema_id)) 
               + N'.' + QUOTENAME(name)
    FROM sys.objects
  WHERE type_desc LIKE '%FUNCTION%';

   Exec sp_executesql @sql
  GO

Remove Null Value from String array in java

This is the code that I use to remove null values from an array which does not use array lists.

String[] array = {"abc", "def", null, "g", null}; // Your array
String[] refinedArray = new String[array.length]; // A temporary placeholder array
int count = -1;
for(String s : array) {
    if(s != null) { // Skips over null values. Add "|| "".equals(s)" if you want to exclude empty strings
        refinedArray[++count] = s; // Increments count and sets a value in the refined array
    }
}

// Returns an array with the same data but refits it to a new length
array = Arrays.copyOf(refinedArray, count + 1);

Angular 2 Dropdown Options Default Value

If you assign the default value to selectedWorkout and use [ngValue] (which allows to use objects as value - otherwise only string is supported) then it should just do what you want:

<select class="form-control" name="sel" 
    [(ngModel)]="selectedWorkout" 
    (ngModelChange)="updateWorkout($event)">
  <option *ngFor="let workout of workouts" [ngValue]="workout">
    {{workout.name}}
  </option>
</select>

Ensure that the value you assign to selectedWorkout is the same instance than the one used in workouts. Another object instance even with the same properties and values won't be recognized. Only object identity is checked.

update

Angular added support for compareWith, that makes it easier to set the default value when [ngValue] is used (for object values)

From the docs https://angular.io/api/forms/SelectControlValueAccessor

<select [compareWith]="compareFn"  [(ngModel)]="selectedCountries">
    <option *ngFor="let country of countries" [ngValue]="country">
        {{country.name}}
    </option>
</select>
compareFn(c1: Country, c2: Country): boolean {
    return c1 && c2 ? c1.id === c2.id : c1 === c2;
}

This way a different (new) object instance can be set as default value and compareFn is used to figure out if they should be considered equal (for example if the id property is the same.

how to remove empty strings from list, then remove duplicate values from a list

dtList  = dtList.Where(s => !string.IsNullOrWhiteSpace(s)).Distinct().ToList()

I assumed empty string and whitespace are like null. If not you can use IsNullOrEmpty (allow whitespace), or s != null

How do I write a for loop in bash

if you're intereased only in bash the "for(( ... ))" solution presented above is the best, but if you want something POSIX SH compliant that will work on all unices you'll have to use "expr" and "while", and that's because "(())" or "seq" or "i=i+1" are not that portable among various shells

Correct way to initialize empty slice

The two alternative you gave are semantically identical, but using make([]int, 0) will result in an internal call to runtime.makeslice (Go 1.14).

You also have the option to leave it with a nil value:

var myslice []int

As written in the Golang.org blog:

a nil slice is functionally equivalent to a zero-length slice, even though it points to nothing. It has length zero and can be appended to, with allocation.

A nil slice will however json.Marshal() into "null" whereas an empty slice will marshal into "[]", as pointed out by @farwayer.

None of the above options will cause any allocation, as pointed out by @ArmanOrdookhani.

Difference between string object and string literal

The long answer is available here, so I'll give you the short one.

When you do this:

String str = "abc";

You are calling the intern() method on String. This method references an internal pool of String objects. If the String you called intern() on already resides in the pool, then a reference to that String is assigned to str. If not, then the new String is placed in the pool, and a reference to it is then assigned to str.

Given the following code:

String str = "abc";
String str2 = "abc";
boolean identity = str == str2;

When you check for object identity by doing == (you are literally asking: do these two references point to the same object?), you get true.

However, you don't need to intern() Strings. You can force the creation on a new Object on the Heap by doing this:

String str = new String("abc");
String str2 = new String("abc");
boolean identity = str == str2;

In this instance, str and str2 are references to different Objects, neither of which have been interned, so that when you test for Object identity using ==, you will get false.

In terms of good coding practice: do not use == to check for String equality, use .equals() instead.

Retrieve column names from java.sql.ResultSet

import java.sql.*;

public class JdbcGetColumnNames {

    public static void main(String args[]) {
        Connection con = null;
        Statement st = null;
        ResultSet rs = null;

        try {
            Class.forName("com.mysql.jdbc.Driver");
            con = DriverManager.getConnection(
                    "jdbc:mysql://localhost:3306/komal", "root", "root");

            st = con.createStatement();

            String sql = "select * from person";
            rs = st.executeQuery(sql);
            ResultSetMetaData metaData = rs.getMetaData();

            int rowCount = metaData.getColumnCount();

            System.out.println("Table Name : " + metaData.getTableName(2));
            System.out.println("Field  \tDataType");

            for (int i = 0; i < rowCount; i++) {
                System.out.print(metaData.getColumnName(i + 1) + "  \t");
                System.out.println(metaData.getColumnTypeName(i + 1));
            }
        } catch (Exception e) {
            System.out.println(e);
        }
    }
}

Table Name : person Field DataType id VARCHAR cname VARCHAR dob DATE

Apply function to pandas groupby

As of Pandas version 0.22, there exists also an alternative to apply: pipe, which can be considerably faster than using apply (you can also check this question for more differences between the two functionalities).

For your example:

df = pd.DataFrame({"my_label": ['A','B','A','C','D','D','E']})

  my_label
0        A
1        B
2        A
3        C
4        D
5        D
6        E

The apply version

df.groupby('my_label').apply(lambda grp: grp.count() / df.shape[0])

gives

          my_label
my_label          
A         0.285714
B         0.142857
C         0.142857
D         0.285714
E         0.142857

and the pipe version

df.groupby('my_label').pipe(lambda grp: grp.size() / grp.size().sum())

yields

my_label
A    0.285714
B    0.142857
C    0.142857
D    0.285714
E    0.142857

So the values are identical, however, the timings differ quite a lot (at least for this small dataframe):

%timeit df.groupby('my_label').apply(lambda grp: grp.count() / df.shape[0])
100 loops, best of 3: 5.52 ms per loop

and

%timeit df.groupby('my_label').pipe(lambda grp: grp.size() / grp.size().sum())
1000 loops, best of 3: 843 µs per loop

Wrapping it into a function is then also straightforward:

def get_perc(grp_obj):
    gr_size = grp_obj.size()
    return gr_size / gr_size.sum()

Now you can call

df.groupby('my_label').pipe(get_perc)

yielding

my_label
A    0.285714
B    0.142857
C    0.142857
D    0.285714
E    0.142857

However, for this particular case, you do not even need a groupby, but you can just use value_counts like this:

df['my_label'].value_counts(sort=False) / df.shape[0]

yielding

A    0.285714
C    0.142857
B    0.142857
E    0.142857
D    0.285714
Name: my_label, dtype: float64

For this small dataframe it is quite fast

%timeit df['my_label'].value_counts(sort=False) / df.shape[0]
1000 loops, best of 3: 770 µs per loop

As pointed out by @anmol, the last statement can also be simplified to

df['my_label'].value_counts(sort=False, normalize=True)

Convert java.util.Date to String

Convert a Date to a String using DateFormat#format method:

String pattern = "MM/dd/yyyy HH:mm:ss";

// Create an instance of SimpleDateFormat used for formatting 
// the string representation of date according to the chosen pattern
DateFormat df = new SimpleDateFormat(pattern);

// Get the today date using Calendar object.
Date today = Calendar.getInstance().getTime();        
// Using DateFormat format method we can create a string 
// representation of a date with the defined format.
String todayAsString = df.format(today);

// Print the result!
System.out.println("Today is: " + todayAsString);

From http://www.kodejava.org/examples/86.html

Java: Clear the console

This will work if you are doing this in Bluej or any other similar software.

System.out.print('\u000C');

Why does a base64 encoded string have an = sign at the end

It serves as padding.

A more complete answer is that a base64 encoded string doesn't always end with a =, it will only end with one or two = if they are required to pad the string out to the proper length.

Retrieve the position (X,Y) of an HTML element relative to the browser window

To retrieve the position relative to the page efficiently, and without using a recursive function: (includes IE also)

var element = document.getElementById('elementId'); //replace elementId with your element's Id.
var rect = element.getBoundingClientRect();
var elementLeft,elementTop; //x and y
var scrollTop = document.documentElement.scrollTop?
                document.documentElement.scrollTop:document.body.scrollTop;
var scrollLeft = document.documentElement.scrollLeft?                   
                 document.documentElement.scrollLeft:document.body.scrollLeft;
elementTop = rect.top+scrollTop;
elementLeft = rect.left+scrollLeft;

java.net.UnknownHostException: Invalid hostname for server: local

What the exception is really saying is that there is no known server with the name "local". My guess is that you're trying to connect to your local computer. Try with the hostname "localhost" instead, or perhaps 127.0.0.1 or ::1 (the last one is IPv6).

From the javadocs:

Thrown to indicate that the IP address of a host could not be determined.

127.0.0.1or ::1 or "localhost" should always be the loopback interface, so if that doesn't work I'd be really surprised.

If there really is a server called "local" on your network - examine your DNS settings or add it to your hosts file.

JPA : How to convert a native query result set to POJO class collection

Use DTO Design Pattern. It was used in EJB 2.0. Entity was container managed. DTO Design Pattern is used to solve this problem. But, it might be use now, when the application is developed Server Side and Client Side separately.DTO is used when Server side doesn't want to pass/return Entity with annotation to Client Side.

DTO Example :

PersonEntity.java

@Entity
public class PersonEntity {
    @Id
    private String id;
    private String address;

    public PersonEntity(){

    }
    public PersonEntity(String id, String address) {
        this.id = id;
        this.address = address;
    }
    //getter and setter

}

PersonDTO.java

public class PersonDTO {
    private String id;
    private String address;

    public PersonDTO() {
    }
    public PersonDTO(String id, String address) {
        this.id = id;
        this.address = address;
    }

    //getter and setter 
}

DTOBuilder.java

public class DTOBuilder() {
    public static PersonDTO buildPersonDTO(PersonEntity person) {
        return new PersonDTO(person.getId(). person.getAddress());
    }
}

EntityBuilder.java <-- it mide be need

public class EntityBuilder() {
    public static PersonEntity buildPersonEntity(PersonDTO person) {
        return new PersonEntity(person.getId(). person.getAddress());
    }
}

How to add text at the end of each line in Vim?

ex mode is easiest:

:%s/$/,

: - enter command mode
% - for every line
s/ - substitute
$ - the end of the line
/ - and change it to
, - a comma

Jenkins not executing jobs (pending - waiting for next executor)

  • go to Jenkins -> Manage Jenkins -> Manage Nodes
  • examine the "master" node.(Click on configure icon)

In my case No of executors was set to 0. Increased it and issue got fixed.

Creating instance list of different objects

If you can't be more specific than Object with your instances, then use:

List<Object> employees = new ArrayList<Object>();

Otherwise be as specific as you can:

List<? extends SpecificType> employees = new ArrayList<? extends SpecificType>();

Using Python String Formatting with Lists

You should take a look to the format method of python. You could then define your formatting string like this :

>>> s = '{0} BLAH BLAH {1} BLAH {2} BLAH BLIH BLEH'
>>> x = ['1', '2', '3']
>>> print s.format(*x)
'1 BLAH BLAH 2 BLAH 3 BLAH BLIH BLEH'

Get key and value of object in JavaScript?

for (var i in a) {
   console.log(a[i],i)
}

Finding smallest value in an array most efficiently

If you're developing some kind of your own array abstraction, you can get O(1) if you store smallest added value in additional attribute and compare it every time a new item is put into array.

It should look something like this:

class MyArray
{
public:
    MyArray() : m_minValue(INT_MAX) {}

    void add(int newValue)
    {
        if (newValue < m_minValue) m_minValue = newValue;
        list.push_back( newValue );
    }

    int min()
    {
        return m_minValue;
    }

private:
    int m_minValue;
    std::list m_list;
}

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

You could use IIF statement like in the next example:

SELECT
   IIF(test_expression, value_if_true, value_if_false) AS FIELD_NAME
FROM
   TABLE_NAME

Difference between Grunt, NPM and Bower ( package.json vs bower.json )

Update for mid 2016:

The things are changing so fast that if it's late 2017 this answer might not be up to date anymore!

Beginners can quickly get lost in choice of build tools and workflows, but what's most up to date in 2016 is not using Bower, Grunt or Gulp at all! With help of Webpack you can do everything directly in NPM!

Don't get me wrong people use other workflows and I still use GULP in my legacy project(but slowly moving out of it), but this is how it's done in the best companies and developers working in this workflow make a LOT of money!

Look at this template it's a very up-to-date setup consisting of a mixture of the best and the latest technologies: https://github.com/coryhouse/react-slingshot

  • Webpack
  • NPM as a build tool (no Gulp, Grunt or Bower)
  • React with Redux
  • ESLint
  • the list is long. Go and explore!

Your questions:

When I want to add a package (and check in the dependency into git), where does it belong - into package.json or into bower.json

  • Everything belongs in package.json now

  • Dependencies required for build are in "devDependencies" i.e. npm install require-dir --save-dev (--save-dev updates your package.json by adding an entry to devDependencies)

  • Dependencies required for your application during runtime are in "dependencies" i.e. npm install lodash --save (--save updates your package.json by adding an entry to dependencies)

If that is the case, when should I ever install packages explicitly like that without adding them to the file that manages dependencies (apart from installing command line tools globally)?

Always. Just because of comfort. When you add a flag (--save-dev or --save) the file that manages deps (package.json) gets updated automatically. Don't waste time by editing dependencies in it manually. Shortcut for npm install --save-dev package-name is npm i -D package-name and shortcut for npm install --save package-name is npm i -S package-name

The import javax.persistence cannot be resolved

If you are using Hibernate as a JPA implementation and you are not using Maven/Gradle, the easier way is to download whole bundle instead of jar file one by one.

Go http://hibernate.org/orm/downloads/ and download the latest library, extract the jar from the required folder.

how to bypass Access-Control-Allow-Origin?

It's a really bad idea to use *, which leaves you wide open to cross site scripting. You basically want your own domain all of the time, scoped to your current SSL settings, and optionally additional domains. You also want them all to be sent as one header. The following will always authorize your own domain in the same SSL scope as the current page, and can optionally also include any number of additional domains. It will send them all as one header, and overwrite the previous one(s) if something else already sent them to avoid any chance of the browser grumbling about multiple access control headers being sent.

class CorsAccessControl
{
    private $allowed = array();

    /**
     * Always adds your own domain with the current ssl settings.
     */
    public function __construct()
    {
        // Add your own domain, with respect to the current SSL settings.
        $this->allowed[] = 'http'
            . ( ( array_key_exists( 'HTTPS', $_SERVER )
                && $_SERVER['HTTPS'] 
                && strtolower( $_SERVER['HTTPS'] ) !== 'off' ) 
                    ? 's' 
                    : null )
            . '://' . $_SERVER['HTTP_HOST'];
    }

    /**
     * Optionally add additional domains. Each is only added one time.
     */
    public function add($domain)
    {
        if ( !in_array( $domain, $this->allowed )
        {
            $this->allowed[] = $domain;
        }
    /**
     * Send 'em all as one header so no browsers grumble about it.
     */
    public function send()
    {
        $domains = implode( ', ', $this->allowed );
        header( 'Access-Control-Allow-Origin: ' . $domains, true ); // We want to send them all as one shot, so replace should be true here.
    }
}

Usage:

$cors = new CorsAccessControl();

// If you are only authorizing your own domain:
$cors->send();

// If you are authorizing multiple domains:
foreach ($domains as $domain)
{
    $cors->add($domain);
}
$cors->send();

You get the idea.

How to leave space in HTML

Either use literal non-breaking space symbol (yes, you can copy/paste it), HTML entity, or, if you're dealing with big pre-formatted block, use white-space CSS property.

open program minimized via command prompt

Try:

start  "" "C:\Program Files (x86)\Microsoft Office\Office12\WINWORD.EXE" --new-window/min

I had the same problem, but I was trying to open chrome.exe maximized. If I put the /min anywhere else in the command line, like before or after the empty title, it was ignored.

How to upsert (update or insert) in SQL Server 2005

You can use @@ROWCOUNT to check whether row should be inserted or updated:

update table1 
set name = 'val2', itemname = 'val3', itemcatName = 'val4', itemQty = 'val5'
where id = 'val1'
if @@ROWCOUNT = 0
insert into table1(id, name, itemname, itemcatName, itemQty)
values('val1', 'val2', 'val3', 'val4', 'val5')

in this case if update fails, the new row will be inserted

How to secure phpMyAdmin

One of my concerns with phpMyAdmin was that by default, all MySQL users can access the db. If DB's root password is compromised, someone can wreck havoc on the db. I wanted to find a way to avoid that by restricting which MySQL user can login to phpMyAdmin.

I have found using AllowDeny configuration in PhpMyAdmin to be very useful. http://wiki.phpmyadmin.net/pma/Config#AllowDeny_.28rules.29

AllowDeny lets you configure access to phpMyAdmin in a similar way to Apache. If you set the 'order' to explicit, it will only grant access to users defined in 'rules' section. In the rules, section you restrict MySql users who can access use the phpMyAdmin.

$cfg['Servers'][$i]['AllowDeny']['order'] = 'explicit'
$cfg['Servers'][$i]['AllowDeny']['rules'] = array('pma-user from all')

Now you have limited access to the user named pma-user in MySQL, you can grant limited privilege to that user.

grant select on db_name.some_table to 'pma-user'@'app-server'

The matching wildcard is strict, but no declaration can be found for element 'context:component-scan

I was having issues with

Caused by: org.xml.sax.SAXParseException: cvc-complex-type.2.4.c: The matching wildcard is strict, but no declaration can be found for element 'security:http'

and for me I had to add the spring-security-config jar to the classpath

http://docs.spring.io/spring-security/site/docs/3.1.x/reference/ns-config.html

EDIT:

It might be that you have the correct dependency in your pom.

But...

If you are using multiple spring dependencies and assembling into a single jar then the META-INF/spring.schemas is probably being overwritten by the spring.schemas of another of your spring dependencies.

(Extract that file from your assembled jar and you'll understand)

Spring schemas is just a bunch of lines that look like this:

http\://www.springframework.org/schema/p=org.springframework.beans.factory.xml.SimplePropertyNamespaceHandler
http\://www.springframework.org/schema/beans/spring-beans-3.0.xsd=org/springframework/beans/factory/xml/spring-beans-3.0.xsd

But if another dependency overwrites that file, then the definition will be retrieved from http, and if you have a firewall/proxy it will fail to get it.

One solution is to append spring.schemas and spring.handlers into a single file.

Check:

Idea to avoid that spring.handlers/spring.schemas get overwritten when merging multiple spring dependencies in a single jar

set the iframe height automatically

If you a framework like Bootstrap you can make any iframe video responsive by using this snippet:

<div class="embed-responsive embed-responsive-16by9">
    <iframe class="embed-responsive-item" src="vid.mp4" allowfullscreen></iframe>
</div>

Copying PostgreSQL database to another server


Dump your database : pg_dump database_name_name > backup.sql


Import your database back: psql db_name < backup.sql

How to modify list entries during for loop?

No you wouldn't alter the "content" of the list, if you could mutate strings that way. But in Python they are not mutable. Any string operation returns a new string.

If you had a list of objects you knew were mutable, you could do this as long as you don't change the actual contents of the list.

Thus you will need to do a map of some sort. If you use a generator expression it [the operation] will be done as you iterate and you will save memory.

Insert php variable in a href

You could try:

<a href="<?php echo $directory ?>">The link to the file</a>

Or for PHP 5.4+ (<?= is the PHP short echo tag):

<a href="<?= $directory ?>">The link to the file</a>

But your path is relative to the server, don't forget that.

Register .NET Framework 4.5 in IIS 7.5

For Windows 8 and Windows Server 2012 use dism /online /enable-feature /featurename:IIS-ASPNET45 As administrative command prompt.

Excel function to make SQL-like queries on worksheet data?

If you can save the workbook then you have the option to use ADO and Jet/ACE to treat the workbook as a database, and execute SQL against the sheet.

The MSDN information on how to hit Excel using ADO can be found here.

Java swing application, close one window and open another when button is clicked

Here is an example:

enter image description here

enter image description here

StartupWindow.java

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;


public class StartupWindow extends JFrame implements ActionListener
{
    private JButton btn;

    public StartupWindow()
    {
        super("Simple GUI");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        btn = new JButton("Open the other JFrame!");
        btn.addActionListener(this);
        btn.setActionCommand("Open");
        add(btn);
        pack();

    }

    @Override
    public void actionPerformed(ActionEvent e)
    {
        String cmd = e.getActionCommand();

        if(cmd.equals("Open"))
        {
            dispose();
            new AnotherJFrame();
        }
    }

    public static void main(String[] args)
    {
        SwingUtilities.invokeLater(new Runnable(){

            @Override
            public void run()
            {
                new StartupWindow().setVisible(true);
            }

        });
    }
}

AnotherJFrame.java

import javax.swing.JFrame;
import javax.swing.JLabel;

public class AnotherJFrame extends JFrame
{
    public AnotherJFrame()
    {
        super("Another GUI");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        add(new JLabel("Empty JFrame"));
        pack();
        setVisible(true);
    }
}

Setting width as a percentage using jQuery

Here is an alternative that worked for me:

$('div#somediv').css({'width': '70%'});

How to quickly and conveniently disable all console.log statements in my code?

I have used winston logger earlier.

Nowadays I am using below simpler code from experience:

  1. Set the environment variable from cmd/ command line (on Windows):

    cmd
    setx LOG_LEVEL info
    

Or, you could have a variable in your code if you like, but above is better.

  1. Restart cmd/ command line, or, IDE/ editor like Netbeans

  2. Have below like code:

    console.debug = console.log;   // define debug function
    console.silly = console.log;   // define silly function
    
    switch (process.env.LOG_LEVEL) {
        case 'debug':
        case 'silly':
            // print everything
            break;
    
        case 'dir':
        case 'log':
            console.debug = function () {};
            console.silly = function () {};
            break;
    
        case 'info':
            console.debug = function () {};
            console.silly = function () {};
            console.dir = function () {};
            console.log = function () {};
            break;
    
        case 'trace':   // similar to error, both may print stack trace/ frames
        case 'warn':    // since warn() function is an alias for error()
        case 'error':
            console.debug = function () {};
            console.silly = function () {};
            console.dir = function () {};
            console.log = function () {};
            console.info = function () {};
            break;
    }
    
  3. Now use all console.* as below:

    console.error(' this is a error message '); // will print
    console.warn(' this is a warn message '); // will print
    console.trace(' this is a trace message '); // will print
    console.info(' this is a info message '); // will print, LOG_LEVEL is set to this
    
    console.log(' this is a log message '); // will NOT print
    console.dir(' this is a dir message '); // will NOT print
    console.silly(' this is a silly message '); // will NOT print
    console.debug(' this is a debug message '); // will NOT print
    

Now, based on your LOG_LEVEL settings made in the point 1 (like, setx LOG_LEVEL log and restart command line), some of the above will print, others won't print

Hope that helped.

"Thinking in AngularJS" if I have a jQuery background?

To describe the "paradigm shift", I think a short answer can suffice.

AngularJS changes the way you find elements

In jQuery, you typically use selectors to find elements, and then wire them up:
$('#id .class').click(doStuff);

In AngularJS, you use directives to mark the elements directly, to wire them up:
<a ng-click="doStuff()">

AngularJS doesn't need (or want) you to find elements using selectors - the primary difference between AngularJS's jqLite versus full-blown jQuery is that jqLite does not support selectors.

So when people say "don't include jQuery at all", it's mainly because they don't want you to use selectors; they want you to learn to use directives instead. Direct, not select!

How to get an enum value from a string value in Java?

If you don't want to write your own utility use Google's library:

Enums.getIfPresent(Blah.class, "A")

Unlike the built in java function it let's you check if A is present in Blah and doesn't throw an exception.

How to run a Runnable thread in Android at defined intervals?

Kotlin with Coroutines

In Kotlin, using coroutines you can do the following:

CoroutineScope(Dispatchers.Main).launch { // Main, because UI is changed
    ticker(delayMillis = 1000, initialDelayMillis = 1000).consumeEach {
        tv.append("Hello World")
    }
}

Try it out here!

java.lang.OutOfMemoryError: Java heap space

If you want to increase your heap space, you can use java -Xms<initial heap size> -Xmx<maximum heap size> on the command line. By default, the values are based on the JRE version and system configuration. You can find out more about the VM options on the Java website.

However, I would recommend profiling your application to find out why your heap size is being eaten. NetBeans has a very good profiler included with it. I believe it uses the jvisualvm under the hood. With a profiler, you can try to find where many objects are being created, when objects get garbage collected, and more.

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

New location for mysql config file is

/etc/mysql/mysql.conf.d/mysqld.cnf

disable a hyperlink using jQuery

The disabled attribute isn't valid on all HTML elements I believe, see the MSDN article. That and the proper value for disabled is simply "disabled". Your best approach is to bind a click function that returns false.

Javascript change font color

Html code

<div id="coloredBy">
    Colored By Santa
</div>

javascript code

document.getElementById("coloredBy").style.color = colorCode; // red or #ffffff

I think this is very easy to use

Cannot start session without errors in phpMyAdmin

Login fails if session folder in not writeable. To check that, create a PHP file in your web directory with:

<?php
$sessionPath = 'undefined';

if (!($sessionPath = ini_get('session.save_path'))) {
    $sessionPath = isset($_ENV['TMP']) ? $_ENV['TMP'] : sys_get_temp_dir();
}

if (!is_writeable($sessionPath)) {
    echo 'Session directory "'. $sessionPath . '"" is not writeable';
} else {
    echo 'Session directory: "' . $sessionPath . '" is writeable';
}

If session folder is not writeable do either

sudo setfacl -R -m u:www-data:rwx <session directory> or chmod 777 <session directory> -

Remove all special characters from a string

Update

The solution below has a "SEO friendlier" version:

function hyphenize($string) {
    $dict = array(
        "I'm"      => "I am",
        "thier"    => "their",
        // Add your own replacements here
    );
    return strtolower(
        preg_replace(
          array( '#[\\s-]+#', '#[^A-Za-z0-9. -]+#' ),
          array( '-', '' ),
          // the full cleanString() can be downloaded from http://www.unexpectedit.com/php/php-clean-string-of-utf8-chars-convert-to-similar-ascii-char
          cleanString(
              str_replace( // preg_replace can be used to support more complicated replacements
                  array_keys($dict),
                  array_values($dict),
                  urldecode($string)
              )
          )
        )
    );
}

function cleanString($text) {
    $utf8 = array(
        '/[áàâãªä]/u'   =>   'a',
        '/[ÁÀÂÃÄ]/u'    =>   'A',
        '/[ÍÌÎÏ]/u'     =>   'I',
        '/[íìîï]/u'     =>   'i',
        '/[éèêë]/u'     =>   'e',
        '/[ÉÈÊË]/u'     =>   'E',
        '/[óòôõºö]/u'   =>   'o',
        '/[ÓÒÔÕÖ]/u'    =>   'O',
        '/[úùûü]/u'     =>   'u',
        '/[ÚÙÛÜ]/u'     =>   'U',
        '/ç/'           =>   'c',
        '/Ç/'           =>   'C',
        '/ñ/'           =>   'n',
        '/Ñ/'           =>   'N',
        '/–/'           =>   '-', // UTF-8 hyphen to "normal" hyphen
        '/[’‘‹›‚]/u'    =>   ' ', // Literally a single quote
        '/[“”«»„]/u'    =>   ' ', // Double quote
        '/ /'           =>   ' ', // nonbreaking space (equiv. to 0x160)
    );
    return preg_replace(array_keys($utf8), array_values($utf8), $text);
}

The rationale for the above functions (which I find way inefficient - the one below is better) is that a service that shall not be named apparently ran spelling checks and keyword recognition on the URLs.

After losing a long time on a customer's paranoias, I found out they were not imagining things after all -- their SEO experts [I am definitely not one] reported that, say, converting "Viaggi Economy Perù" to viaggi-economy-peru "behaved better" than viaggi-economy-per (the previous "cleaning" removed UTF8 characters; Bogotà became bogot, Medellìn became medelln and so on).

There were also some common misspellings that seemed to influence the results, and the only explanation that made sense to me is that our URL were being unpacked, the words singled out, and used to drive God knows what ranking algorithms. And those algorithms apparently had been fed with UTF8-cleaned strings, so that "Perù" became "Peru" instead of "Per". "Per" did not match and sort of took it in the neck.

In order to both keep UTF8 characters and replace some misspellings, the faster function below became the more accurate (?) function above. $dict needs to be hand tailored, of course.

Previous answer

A simple approach:

// Remove all characters except A-Z, a-z, 0-9, dots, hyphens and spaces
// Note that the hyphen must go last not to be confused with a range (A-Z)
// and the dot, NOT being special (I know. My life was a lie), is NOT escaped

$str = preg_replace('/[^A-Za-z0-9. -]/', '', $str);

// Replace sequences of spaces with hyphen
$str = preg_replace('/  */', '-', $str);

// The above means "a space, followed by a space repeated zero or more times"
// (should be equivalent to / +/)

// You may also want to try this alternative:
$str = preg_replace('/\\s+/', '-', $str);

// where \s+ means "zero or more whitespaces" (a space is not necessarily the
// same as a whitespace) just to be sure and include everything

Note that you might have to first urldecode() the URL, since %20 and + both are actually spaces - I mean, if you have "Never%20gonna%20give%20you%20up" you want it to become Never-gonna-give-you-up, not Never20gonna20give20you20up . You might not need it, but I thought I'd mention the possibility.

So the finished function along with test cases:

function hyphenize($string) {
    return 
    ## strtolower(
          preg_replace(
            array('#[\\s-]+#', '#[^A-Za-z0-9. -]+#'),
            array('-', ''),
        ##     cleanString(
              urldecode($string)
        ##     )
        )
    ## )
    ;
}

print implode("\n", array_map(
    function($s) {
            return $s . ' becomes ' . hyphenize($s);
    },
    array(
    'Never%20gonna%20give%20you%20up',
    "I'm not the man I was",
    "'Légeresse', dit sa majesté",
    )));


Never%20gonna%20give%20you%20up    becomes  never-gonna-give-you-up
I'm not the man I was              becomes  im-not-the-man-I-was
'Légeresse', dit sa majesté        becomes  legeresse-dit-sa-majeste

To handle UTF-8 I used a cleanString implementation found online (link broken since, but a stripped down copy with all the not-too-esoteric UTF8 characters is at the beginning of the answer; it's also easy to add more characters to it if you need) that converts UTF8 characters to normal characters, thus preserving the word "look" as much as possible. It could be simplified and wrapped inside the function here for performance.

The function above also implements converting to lowercase - but that's a taste. The code to do so has been commented out.

How to get single value from this multi-dimensional PHP array

Look at the keys and indentation in your print_r:

echo $myarray[0]['email'];

echo $myarray[0]['gender'];

...etc

Can an html element have multiple ids?

That's interesting, but as far as I know the answer is a firm no. I don't see why you need a nested ID, since you'll usually cross it with another element that has the same nested ID. If you don't there's no point, if you do there's still very little point.

Swift convert unix time to date and time

Here is a working Swift 3 solution from one of my apps.

/**
 * 
 * Convert unix time to human readable time. Return empty string if unixtime     
 * argument is 0. Note that EMPTY_STRING = ""
 *
 * @param unixdate the time in unix format, e.g. 1482505225
 * @param timezone the user's time zone, e.g. EST, PST
 * @return the date and time converted into human readable String format
 *
 **/

private func getDate(unixdate: Int, timezone: String) -> String {
    if unixdate == 0 {return EMPTY_STRING}
    let date = NSDate(timeIntervalSince1970: TimeInterval(unixdate))
    let dayTimePeriodFormatter = DateFormatter()
    dayTimePeriodFormatter.dateFormat = "MMM dd YYYY hh:mm a"
    dayTimePeriodFormatter.timeZone = NSTimeZone(name: timezone) as TimeZone!
    let dateString = dayTimePeriodFormatter.string(from: date as Date)
    return "Updated: \(dateString)"
}

Prevent row names to be written to file when using write.csv

write.csv(t, "t.csv", row.names=FALSE)

From ?write.csv:

row.names: either a logical value indicating whether the row names of
          ‘x’ are to be written along with ‘x’, or a character vector
          of row names to be written.

what's the differences between r and rb in fopen

You should use "r" for opening text files. Different operating systems have slightly different ways of storing text, and this will perform the correct translations so that you don't need to know about the idiosyncracies of the local operating system. For example, you will know that newlines will always appear as a simple "\n", regardless of where the code runs.

You should use "rb" if you're opening non-text files, because in this case, the translations are not appropriate.

'No database provider has been configured for this DbContext' on SignInManager.PasswordSignInAsync

Override constructor of DbContext Try this :-

public DataContext(DbContextOptions<DataContext> option):base(option) {}

MySQL Great Circle Distance (Haversine formula)

From Google Code FAQ - Creating a Store Locator with PHP, MySQL & Google Maps:

Here's the SQL statement that will find the closest 20 locations that are within a radius of 25 miles to the 37, -122 coordinate. It calculates the distance based on the latitude/longitude of that row and the target latitude/longitude, and then asks for only rows where the distance value is less than 25, orders the whole query by distance, and limits it to 20 results. To search by kilometers instead of miles, replace 3959 with 6371.

SELECT id, ( 3959 * acos( cos( radians(37) ) * cos( radians( lat ) ) 
* cos( radians( lng ) - radians(-122) ) + sin( radians(37) ) * sin(radians(lat)) ) ) AS distance 
FROM markers 
HAVING distance < 25 
ORDER BY distance 
LIMIT 0 , 20;

How can I encode a string to Base64 in Swift?

After thorough research I found the solution

Encoding

    let plainData = (plainString as NSString).dataUsingEncoding(NSUTF8StringEncoding)
    let base64String =plainData.base64EncodedStringWithOptions(NSDataBase64EncodingOptions.fromRaw(0)!)
    println(base64String) // bXkgcGxhbmkgdGV4dA==

Decoding

    let decodedData = NSData(base64EncodedString: base64String, options:NSDataBase64DecodingOptions.fromRaw(0)!)
    let decodedString = NSString(data: decodedData, encoding: NSUTF8StringEncoding)    
    println(decodedString) // my plain data

More on this http://creativecoefficient.net/swift/encoding-and-decoding-base64/

Case-Insensitive List Search

You can use StringComparer:

    var list = new List<string>();
    list.Add("cat");
    list.Add("dog");
    list.Add("moth");

    if (list.Contains("MOTH", StringComparer.OrdinalIgnoreCase))
    {
        Console.WriteLine("found");
    }

jQuery - What are differences between $(document).ready and $(window).load?

The Difference between $(document).ready() and $(window).load() functions is that the code included inside $(window).load() will run once the entire page(images, iframes, stylesheets,etc) are loaded whereas the document ready event fires before all images,iframes etc. are loaded, but after the whole DOM itself is ready.


$(document).ready(function(){

}) 

and

$(function(){

});

and

jQuery(document).ready(function(){

});

There are not difference between the above 3 codes.

They are equivalent,but you may face conflict if any other JavaScript Frameworks uses the same dollar symbol $ as a shortcut name.

jQuery.noConflict();
jQuery.ready(function($){
 //Code using $ as alias to jQuery
});

How to print / echo environment variables?

The syntax

variable=value command

is often used to set an environment variables for a specific process. However, you must understand which process gets what variable and who interprets it. As an example, using two shells:

a=5
# variable expansion by the current shell:
a=3 bash -c "echo $a"
# variable expansion by the second shell:
a=3 bash -c 'echo $a'

The result will be 5 for the first echo and 3 for the second.

array filter in python?

If the order is not important, you should use set.difference. However, if you want to retain order, a simple list comprehension is all it takes.

result = [a for a in A if a not in subset_of_A]

EDIT: As delnan says, performance will be substantially improved if subset_of_A is an actual set, since checking for membership in a set is O(1) as compared to O(n) for a list.

A = [6, 7, 8, 9, 10, 11, 12]
subset_of_A = set([6, 9, 12]) # the subset of A

result = [a for a in A if a not in subset_of_A]

How do I dump the data of some SQLite3 tables?

According to the SQLite documentation for the Command Line Shell For SQLite you can export an SQLite table (or part of a table) as CSV, simply by setting the "mode" to "csv" and then run a query to extract the desired rows of the table:

sqlite> .header on
sqlite> .mode csv
sqlite> .once c:/work/dataout.csv
sqlite> SELECT * FROM tab1;
sqlite> .exit

Then use the ".import" command to import CSV (comma separated value) data into an SQLite table:

sqlite> .mode csv
sqlite> .import C:/work/dataout.csv tab1
sqlite> .exit

Please read the further documentation about the two cases to consider: (1) Table "tab1" does not previously exist and (2) table "tab1" does already exist.

Dynamic loading of images in WPF

In code to load resource in the executing assembly where my image 'Freq.png' was in the folder "Icons" and defined as "Resource".

        this.Icon = new BitmapImage(new Uri(@"pack://application:,,,/" 
             + Assembly.GetExecutingAssembly().GetName().Name 
             + ";component/" 
             + "Icons/Freq.png", UriKind.Absolute)); 

I also made a function if anybody would like it...

/// <summary>
/// Load a resource WPF-BitmapImage (png, bmp, ...) from embedded resource defined as 'Resource' not as 'Embedded resource'.
/// </summary>
/// <param name="pathInApplication">Path without starting slash</param>
/// <param name="assembly">Usually 'Assembly.GetExecutingAssembly()'. If not mentionned, I will use the calling assembly</param>
/// <returns></returns>
public static BitmapImage LoadBitmapFromResource(string pathInApplication, Assembly assembly = null)
{
    if (assembly == null)
    {
        assembly = Assembly.GetCallingAssembly();
    }

    if (pathInApplication[0] == '/')
    {
        pathInApplication = pathInApplication.Substring(1);
    }
    return new BitmapImage(new Uri(@"pack://application:,,,/" + assembly.GetName().Name + ";component/" + pathInApplication, UriKind.Absolute)); 
}

Usage:

        this.Icon = ResourceHelper.LoadBitmapFromResource("Icons/Freq.png");

How to read a file byte by byte in Python and how to print a bytelist as a binary?

Late to the party, but this may help anyone looking for a quick solution:

you can use bin(ord('b')).replace('b', '')bin() it gives you the binary representation with a 'b' after the last bit, you have to remove it. Also ord() gives you the ASCII number to the char or 8-bit/1 Byte coded character.

Cheers

Flutter: Trying to bottom-center an item in a Column, but it keeps left-aligning

Widget _bottom() {
    return Column(
      mainAxisAlignment: MainAxisAlignment.start,
      children: [
        Expanded(
          child: Container(
            color: Colors.amberAccent,
            width: double.infinity,
            child: SingleChildScrollView(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.start,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: new List<int>.generate(50, (index) => index + 1)
                    .map((item) {
                  return Text(
                    item.toString(),
                    style: TextStyle(fontSize: 20),
                  );
                }).toList(),
              ),
            ),
          ),
        ),
        Container(
          color: Colors.blue,
          child: Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Text(
                'BoTToM',
                textAlign: TextAlign.center,
                style: TextStyle(fontSize: 33),
              ),
            ],
          ),
        ),
      ],
    );
  }