Programs & Examples On #Sesame

Sesame was the old name of the Eclipse RDF4J Java framework for storing, querying and inferencing for RDF. It can be deployed as a web server or used as a Java library. Features include several query languages (SeRQL and SPARQL), inferencing support, and scalable persistence in an RDF database.

Maven compile: package does not exist

You have to add the following dependency to your build:

<dependency>
    <groupId>org.openrdf.sesame</groupId>
    <artifactId>sesame-rio-api</artifactId>
    <version>2.7.2</version>
</dependency>

Furthermore i would suggest to take a deep look into the documentation about how to use the lib.

A full list of all the new/popular databases and their uses?

I doubt I'd use it in a mission-critical system, but Derby has always been very interesting to me.

How to check if object has any properties in JavaScript?

You can use the built in Object.keys method to get a list of keys on an object and test its length.

var x = {};
// some code where value of x changes and than you want to check whether it is null or some object with values

if(Object.keys(x).length){
 // Your code here if x has some properties  
}

How can I get city name from a latitude and longitude point?

In case if you don't want to use google geocoding API than you can refer to few other Free APIs for the development purpose. for example i used [mapquest] API in order to get the location name.

you can fetch location name easily by implementing this following function

_x000D_
_x000D_
 const fetchLocationName = async (lat,lng) => {
    await fetch(
      'https://www.mapquestapi.com/geocoding/v1/reverse?key=API-Key&location='+lat+'%2C'+lng+'&outFormat=json&thumbMaps=false',
    )
      .then((response) => response.json())
      .then((responseJson) => {
        console.log(
          'ADDRESS GEOCODE is BACK!! => ' + JSON.stringify(responseJson),
        );
      });
  };
_x000D_
_x000D_
_x000D_

How to know the git username and email saved during configuration?

Considering what @Robert said, I tried to play around with the config command and it seems that there is a direct way to know both the name and email.

To know the username, type:

git config user.name

To know the email, type:

git config user.email

These two output just the name and email respectively and one doesn't need to look through the whole list. Comes in handy.

Find nearest latitude/longitude with an SQL query

Try this, it show the nearest points to provided coordinates (within 50 km). It works perfectly:

SELECT m.name,
    m.lat, m.lon,
    p.distance_unit
             * DEGREES(ACOS(COS(RADIANS(p.latpoint))
             * COS(RADIANS(m.lat))
             * COS(RADIANS(p.longpoint) - RADIANS(m.lon))
             + SIN(RADIANS(p.latpoint))
             * SIN(RADIANS(m.lat)))) AS distance_in_km
FROM <table_name> AS m
JOIN (
      SELECT <userLat> AS latpoint, <userLon> AS longpoint,
             50.0 AS radius, 111.045 AS distance_unit
     ) AS p ON 1=1
WHERE m.lat
BETWEEN p.latpoint  - (p.radius / p.distance_unit)
    AND p.latpoint  + (p.radius / p.distance_unit)
    AND m.lon BETWEEN p.longpoint - (p.radius / (p.distance_unit * COS(RADIANS(p.latpoint))))
    AND p.longpoint + (p.radius / (p.distance_unit * COS(RADIANS(p.latpoint))))
ORDER BY distance_in_km

Just change <table_name>. <userLat> and <userLon>

You can read more about this solution here: http://www.plumislandmedia.net/mysql/haversine-mysql-nearest-loc/

How do I fix the Visual Studio compile error, "mismatch between processor architecture"?

I've had a similar problem before, specifically when adding a test solution to an existing x64 solution, like SharePoint. In my case, it seems to have to do with the fact that certain project templates are added as certain platforms by default.

Here's the solution that often works for me: set everything to the correct platform in the Configuration Manager (the active configuration drop-down, says Debug normally, is a good way to get to it) and project platform (in project properties), then build, then set everything back to AnyCPU. Sometimes I have to remove and re-add some dependencies (DLLs in each project's Properties) and sometimes the "Run tests in 32 bit or 64 bit process" (double-click Local.testsettings and go to Hosts) has to be changed.

It seems to me that this is just setting something then setting it back, but there's probably more going on behind the scenes that I'm not seeing. It's worked fairly consistently for me in the past though.

Pandas DataFrame column to list

You can use pandas.Series.tolist

e.g.:

import pandas as pd
df = pd.DataFrame({'a':[1,2,3], 'b':[4,5,6]})

Run:

>>> df['a'].tolist()

You will get

>>> [1, 2, 3]

how to pass this element to javascript onclick function and add a class to that clicked element

Try like

<script>
function Data(string)
{      
  $('.filter').removeClass('active');
  $(this).parent('.filter').addClass('active') ;
} 
</script>

For the class selector you need to use . before the classname.And you need to add the class for the parent. Bec you are clicking on anchor tag not the filter.

Javascript : calling function from another file

Why don't you take a look to this answer

Including javascript files inside javascript files

In short you can load the script file with AJAX or put a script tag on the HTML to include it( before the script that uses the functions of the other script). The link I posted is a great answer and has multiple examples and explanations of both methods.

Rails DateTime.now without Time

If you're happy to require 'active_support/core_ext', then you can use

DateTime.now.midnight # => Sat, 19 Nov 2011 00:00:00 -0800

Removing carriage return and new-line from the end of a string in c#

This is what I got to work for me.

s.Replace("\r","").Replace("\n","")

Best practice when adding whitespace in JSX

I have been trying to think of a good convention to use when placing text next to components on different lines, and found a couple good options:

<p>
    Hello {
        <span>World</span>
    }!
</p>

or

<p>
    Hello {}
    <span>World</span>
    {} again!
</p>

Each of these produces clean html without additional &nbsp; or other extraneous markup. It creates fewer text nodes than using {' '}, and allows using of html entities where {' hello &amp; goodbye '} does not.

how to return a char array from a function in C

Lazy notes in comments.

#include <stdio.h>
// for malloc
#include <stdlib.h>

// you need the prototype
char *substring(int i,int j,char *ch);


int main(void /* std compliance */)
{
  int i=0,j=2;
  char s[]="String";
  char *test;
  // s points to the first char, S
  // *s "is" the first char, S
  test=substring(i,j,s); // so s only is ok
  // if test == NULL, failed, give up
  printf("%s",test);
  free(test); // you should free it
  return 0;
}


char *substring(int i,int j,char *ch)
{
  int k=0;
  // avoid calc same things several time
  int n = j-i+1; 
  char *ch1;
  // you can omit casting - and sizeof(char) := 1
  ch1=malloc(n*sizeof(char));
  // if (!ch1) error...; return NULL;

  // any kind of check missing:
  // are i, j ok? 
  // is n > 0... ch[i] is "inside" the string?...
  while(k<n)
    {   
      ch1[k]=ch[i];
      i++;k++;
    }   

  return ch1;
}

How to display HTML <FORM> as inline element?

<form> cannot go inside <p>, no. The browser is going to abruptly close your <p> element when it hits the opening <form> tag as it tries to handle what it thinks is an unclosed paragraph element:

<p>Read this sentence 
 </p><form style='display:inline;'>

How to set some xlim and ylim in Seaborn lmplot facetgrid

The lmplot function returns a FacetGrid instance. This object has a method called set, to which you can pass key=value pairs and they will be set on each Axes object in the grid.

Secondly, you can set only one side of an Axes limit in matplotlib by passing None for the value you want to remain as the default.

Putting these together, we have:

g = sns.lmplot('X', 'Y', df, col='Z', sharex=False, sharey=False)
g.set(ylim=(0, None))

enter image description here

Spark - repartition() vs coalesce()

repartition - it's recommended to use it while increasing the number of partitions, because it involve shuffling of all the data.

coalesce - it's is recommended to use it while reducing the number of partitions. For example if you have 3 partitions and you want to reduce it to 2, coalesce will move the 3rd partition data to partition 1 and 2. Partition 1 and 2 will remains in the same container. On the other hand, repartition will shuffle data in all the partitions, therefore the network usage between the executors will be high and it will impacts the performance.

coalesce performs better than repartition while reducing the number of partitions.

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

Here's my imperative version of mkdirp for nodejs.

function mkdirSyncP(location) {
    let normalizedPath = path.normalize(location);
    let parsedPathObj = path.parse(normalizedPath);
    let curDir = parsedPathObj.root;
    let folders = parsedPathObj.dir.split(path.sep);
    folders.push(parsedPathObj.base);
    for(let part of folders) {
        curDir = path.join(curDir, part);
        if (!fs.existsSync(curDir)) {
            fs.mkdirSync(curDir);
        }
    }
}

Why should C++ programmers minimize use of 'new'?

new() shouldn't be used as little as possible. It should be used as carefully as possible. And it should be used as often as necessary as dictated by pragmatism.

Allocation of objects on the stack, relying on their implicit destruction, is a simple model. If the required scope of an object fits that model then there's no need to use new(), with the associated delete() and checking of NULL pointers. In the case where you have lots of short-lived objects allocation on the stack should reduce the problems of heap fragmentation.

However, if the lifetime of your object needs to extend beyond the current scope then new() is the right answer. Just make sure that you pay attention to when and how you call delete() and the possibilities of NULL pointers, using deleted objects and all of the other gotchas that come with the use of pointers.

Create HTTP post request and receive response using C# console application

Insted of using System.Net.WebClient I would recommend to have a look on System.Net.Http.HttpClient which was introduced with net 4.5 and makes your life much easier.

Also microsoft recommends to use the HttpClient on this article

http://msdn.microsoft.com/en-us/library/system.net.webclient(VS.90).aspx

An example could look like this:

var client = new HttpClient();
var content = new MultipartFormDataContent
{
     { new StringContent("myUserId"), "userid"},
     { new StringContent("myFileName"), "filename"},
     { new StringContent("myPassword"), "password"},
     { new StringContent("myType"), "type"}
};

var responseMessage = await client.PostAsync("some url", content);        
var stream = await responseMessage.Content.ReadAsStreamAsync();

Send POST parameters with MultipartFormData using Alamofire, in iOS Swift

In Alamofire 4 it is important to add the body data before you add the file data!

let parameters = [String: String]()
[...]
self.manager.upload(
    multipartFormData: { multipartFormData in
        for (key, value) in parameters {
            multipartFormData.append(value.data(using: .utf8)!, withName: key)
        }
        multipartFormData.append(imageData, withName: "user", fileName: "user.jpg", mimeType: "image/jpeg")
    },
    to: path,
    [...]
)

How to loop through elements of forms with JavaScript?

Es5 forEach:

Array.prototype.forEach.call(form.elements, function (inpt) {
       if(inpt.name === name) {
             inpt.parentNode.removeChild(inpt);
       }
});

Otherwise the lovely for:

var input;
for(var i = 0; i < form.elements.length; i++) {
     input = form.elements[i];

      // ok my nice work with input, also you have the index with i (in foreach too you can get the index as second parameter (foreach is a wrapper around for, that offer a function to be called at each iteration.
}

CSS 3 slide-in from left transition

USE THIS FOR RIGHT TO LEFT SLIDING :

HTML:

   <div class="nav ">
       <ul>
        <li><a href="#">HOME</a></li>
        <li><a href="#">ABOUT</a></li>
        <li><a href="#">SERVICES</a></li>
        <li><a href="#">CONTACT</a></li>
       </ul>
   </div>

CSS:

/*nav*/
.nav{
    position: fixed;
    right:0;
    top: 70px;
    width: 250px;
    height: calc(100vh - 70px);
    background-color: #333;
    transform: translateX(100%);
    transition: transform 0.3s ease-in-out;

}
.nav-view{
    transform: translateX(0);
}
.nav ul{
    margin: 0;
    padding: 0;
}
.nav ul li{
    margin: 0;
    padding: 0;
    list-style-type: none;
}
.nav ul li a{
    color: #fff;
    display: block;
    padding: 10px;
    border-bottom: solid 1px rgba(255,255,255,0.4);
    text-decoration: none;
}

JS:

  $(document).ready(function(){
  $('a#click-a').click(function(){
    $('.nav').toggleClass('nav-view');
  });
});

Could not open input file: artisan

After installing composer, you need to create the project:

composer create-project laravel/laravel /path/to/tour/project

You can see the documentation, for your php version the lastest Laravel you can install is 5.0.

Now days here is the lastest version and require > php7.0. Here is the documentation.

Installing pip packages to $HOME folder

I would use virtualenv at your HOME directory.

$ sudo easy_install -U virtualenv
$ cd ~
$ virtualenv .
$ bin/pip ...

You could then also alter ~/.(login|profile|bash_profile), whichever is right for your shell to add ~/bin to your PATH and then that pip|python|easy_install would be the one used by default.

Setting Icon for wpf application (VS 08)

@742's answer works pretty well, but as outlined in the comments when running from the VS debugger the generic icon is still shown.

If you want to have your icon even when you're pressing F5, you can add in the Main Window:

<Window x:Class="myClass"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Icon="./Resources/Icon/myIcon.png">

where you indicate the path to your icon (the icon can be *.png, *.ico.)

(Note you will still need to set the Application Icon or it'll still be the default in Explorer).

How can I set NODE_ENV=production on Windows?

In case you are using GITBASH terminal "set NODE_ENV=production" will not work, what can you do is type "export NODE_ENV=production"

SLF4J: Class path contains multiple SLF4J bindings

Just use only required dependency, not all :))). For me, for normal work of logging process you need this dependency exclude others from pom.xml

<dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-api</artifactId>
        <version>1.7.5</version>
    </dependency>

    <dependency>
        <groupId>ch.qos.logback</groupId>
        <artifactId>logback-classic</artifactId>
        <version>1.1.8</version>
    </dependency>

    <dependency>
        <groupId>ch.qos.logback</groupId>
        <artifactId>logback-core</artifactId>
        <version>1.1.8</version>
    </dependency>

Alter user defined type in SQL Server

I ran into this issue with custom types in stored procedures, and solved it with the script below. I didn't fully understand the scripts above, and I follow the rule of "if you don't know what it does, don't do it".

In a nutshell, I rename the old type, and create a new one with the original type name. Then, I tell SQL Server to refresh its details about each stored procedure using the custom type. You have to do this, as everything is still "compiled" with reference to the old type, even with the rename. In this case, the type I needed to change was "PrizeType". I hope this helps. I'm looking for feedback, too, so I learn :)

Note that you may need to go to Programmability > Types > [Appropriate User Type] and delete the object. I found that DROP TYPE doesn't appear to always drop the type even after using the statement.

/* Rename the UDDT you want to replace to another name */ 
exec sp_rename 'PrizeType', 'PrizeTypeOld', 'USERDATATYPE';

/* Add the updated UDDT with the new definition */ 
CREATE TYPE [dbo].[PrizeType] AS TABLE(
    [Type] [nvarchar](50) NOT NULL,
    [Description] [nvarchar](max) NOT NULL,
    [ImageUrl] [varchar](max) NULL
);

/* We need to force stored procedures to refresh with the new type... let's take care of that. */
/* Get a cursor over a list of all the stored procedures that may use this and refresh them */
declare sprocs cursor
  local static read_only forward_only
for
    select specific_name from information_schema.routines where routine_type = 'PROCEDURE'

declare @sprocName varchar(max)

open sprocs
fetch next from sprocs into @sprocName
while @@fetch_status = 0
begin
    print 'Updating ' + @sprocName;
    exec sp_refreshsqlmodule @sprocName
    fetch next from sprocs into @sprocName
end
close sprocs
deallocate sprocs

/* Drop the old type, now that everything's been re-assigned; must do this last */
drop type PrizeTypeOld;

How to use If Statement in Where Clause in SQL?

SELECT *
  FROM Customer
 WHERE (I.IsClose=@ISClose OR @ISClose is NULL)  
   AND (C.FirstName like '%'+@ClientName+'%' or @ClientName is NULL )    
   AND (isnull(@Value,1) <> 2
        OR I.RecurringCharge = @Total
        OR @Total is NULL )    
   AND (isnull(@Value,2) <> 3
        OR I.RecurringCharge like '%'+cast(@Total as varchar(50))+'%'
        OR @Total is NULL )

Basically, your condition was

if (@Value=2)
   TEST FOR => (I.RecurringCharge=@Total  or @Total is NULL )    

flipped around,

AND (isnull(@Value,1) <> 2                -- A
        OR I.RecurringCharge = @Total    -- B
        OR @Total is NULL )              -- C

When (A) is true, i.e. @Value is not 2, [A or B or C] will become TRUE regardless of B and C results. B and C are in reality only checked when @Value = 2, which is the original intention.

Convert JSON String to Pretty Print JSON output using Jackson

For Jackson 1.9, We can use the following code for pretty print.

ObjectMapper objectMapper = new ObjectMapper();
objectMapper.enable(SerializationConfig.Feature.INDENT_OUTPUT);

Fetch: reject promise and catch the error if status is not OK?

Thanks for the help everyone, rejecting the promise in .catch() solved my issue:

export function fetchVehicle(id) {
    return dispatch => {
        return dispatch({
            type: 'FETCH_VEHICLE',
            payload: fetch(`http://swapi.co/api/vehicles/${id}/`)
                .then(status)
                .then(res => res.json())    
                .catch(error => {
                    return Promise.reject()
                })
            });
    };
}


function status(res) {
    if (!res.ok) {
        throw new Error(res.statusText);
    }
    return res;
}

Is there a good JavaScript minifier?

JavaScript Minifier gives a good API you can use programatically:

curl -X POST -s --data-urlencode 'input=$(function() { alert("Hello, World!"); });' http://javascript-minifier.com/raw

Or by uploading a file and redirecting to a new file:

curl -X POST -s --data-urlencode '[email protected]' http://javascript-minifier.com/raw > ready.min.js

Hope that helps.

Spring get current ApplicationContext

Another way is to inject applicationContext through servlet.

This is an example of how to inject dependencies when using Spring web services.

<servlet>
        <servlet-name>my-soap-ws</servlet-name>
        <servlet-class>org.springframework.ws.transport.http.MessageDispatcherServlet</servlet-class>
        <init-param>
            <param-name>transformWsdlLocations</param-name>
            <param-value>false</param-value>
        </init-param>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:my-applicationContext.xml</param-value>
        </init-param>
        <load-on-startup>5</load-on-startup>

</servlet>

Alternate way is to add application Context in your web.xml as shown below

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>
        /WEB-INF/classes/my-another-applicationContext.xml
        classpath:my-second-context.xml
    </param-value>
</context-param>

Basically you are trying to tell servlet that it should look for beans defined in these context files.

JavaScript: Upload file

Unless you're trying to upload the file using ajax, just submit the form to /upload/image.

<form enctype="multipart/form-data" action="/upload/image" method="post">
    <input id="image-file" type="file" />
</form>

If you do want to upload the image in the background (e.g. without submitting the whole form), you can use ajax:

Hide Twitter Bootstrap nav collapse on click

_x000D_
_x000D_
$('.nav a').click(function () {_x000D_
    $('.navbar-collapse').collapse('hide');_x000D_
});
_x000D_
_x000D_
_x000D_

How to format time since xxx e.g. “4 minutes ago” similar to Stack Exchange sites

This will show you past and previous time formats like '2 days ago' '10 minutes from now' and you can pass it either a Date object, a numeric timestamp or a date string

_x000D_
_x000D_
function time_ago(time) {_x000D_
_x000D_
  switch (typeof time) {_x000D_
    case 'number':_x000D_
      break;_x000D_
    case 'string':_x000D_
      time = +new Date(time);_x000D_
      break;_x000D_
    case 'object':_x000D_
      if (time.constructor === Date) time = time.getTime();_x000D_
      break;_x000D_
    default:_x000D_
      time = +new Date();_x000D_
  }_x000D_
  var time_formats = [_x000D_
    [60, 'seconds', 1], // 60_x000D_
    [120, '1 minute ago', '1 minute from now'], // 60*2_x000D_
    [3600, 'minutes', 60], // 60*60, 60_x000D_
    [7200, '1 hour ago', '1 hour from now'], // 60*60*2_x000D_
    [86400, 'hours', 3600], // 60*60*24, 60*60_x000D_
    [172800, 'Yesterday', 'Tomorrow'], // 60*60*24*2_x000D_
    [604800, 'days', 86400], // 60*60*24*7, 60*60*24_x000D_
    [1209600, 'Last week', 'Next week'], // 60*60*24*7*4*2_x000D_
    [2419200, 'weeks', 604800], // 60*60*24*7*4, 60*60*24*7_x000D_
    [4838400, 'Last month', 'Next month'], // 60*60*24*7*4*2_x000D_
    [29030400, 'months', 2419200], // 60*60*24*7*4*12, 60*60*24*7*4_x000D_
    [58060800, 'Last year', 'Next year'], // 60*60*24*7*4*12*2_x000D_
    [2903040000, 'years', 29030400], // 60*60*24*7*4*12*100, 60*60*24*7*4*12_x000D_
    [5806080000, 'Last century', 'Next century'], // 60*60*24*7*4*12*100*2_x000D_
    [58060800000, 'centuries', 2903040000] // 60*60*24*7*4*12*100*20, 60*60*24*7*4*12*100_x000D_
  ];_x000D_
  var seconds = (+new Date() - time) / 1000,_x000D_
    token = 'ago',_x000D_
    list_choice = 1;_x000D_
_x000D_
  if (seconds == 0) {_x000D_
    return 'Just now'_x000D_
  }_x000D_
  if (seconds < 0) {_x000D_
    seconds = Math.abs(seconds);_x000D_
    token = 'from now';_x000D_
    list_choice = 2;_x000D_
  }_x000D_
  var i = 0,_x000D_
    format;_x000D_
  while (format = time_formats[i++])_x000D_
    if (seconds < format[0]) {_x000D_
      if (typeof format[2] == 'string')_x000D_
        return format[list_choice];_x000D_
      else_x000D_
        return Math.floor(seconds / format[2]) + ' ' + format[1] + ' ' + token;_x000D_
    }_x000D_
  return time;_x000D_
}_x000D_
_x000D_
var aDay = 24 * 60 * 60 * 1000;_x000D_
console.log(time_ago(new Date(Date.now() - aDay)));_x000D_
console.log(time_ago(new Date(Date.now() - aDay * 2)));
_x000D_
_x000D_
_x000D_

Full-screen iframe with a height of 100%

You can can call a function which will calculate the iframe's body hieght when the iframe is loaded:

<script type="text/javascript">
    function iframeloaded(){
       var lastHeight = 0, curHeight = 0, $frame = $('iframe:eq(0)');
       curHeight = $frame.contents().find('body').height();
       if ( curHeight != lastHeight ) {
           $frame.css('height', (lastHeight = curHeight) + 'px' );
       }
    }
</script>

<iframe onload="iframeloaded()" src=...>

What causes and what are the differences between NoClassDefFoundError and ClassNotFoundException?

Given the Class loader sussystem actions:

http://www.artima.com/insidejvm/ed2/images/fig7-1.gif

This is an article that helped me a lot to understand the difference: http://docs.oracle.com/javase/specs/jvms/se7/html/jvms-5.html

If an error occurs during class loading, then an instance of a subclass of LinkageError must be thrown at a point in the program that (directly or indirectly) uses the class or interface being loaded.

If the Java Virtual Machine ever attempts to load a class C during verification (§5.4.1) or resolution (§5.4.3) (but not initialization (§5.5)), and the class loader that is used to initiate loading of C throws an instance of ClassNotFoundException, then the Java Virtual Machine must throw an instance of NoClassDefFoundError whose cause is the instance of ClassNotFoundException.

So a ClassNotFoundException is a root cause of NoClassDefFoundError.
And a NoClassDefFoundError is a special case of type loading error, that occurs at Linking step.

SQL Server stored procedure Nullable parameter

You can/should set your parameter to value to DBNull.Value;

if (variable == "")
{
     cmd.Parameters.Add("@Param", SqlDbType.VarChar, 500).Value = DBNull.Value;
}
else
{
     cmd.Parameters.Add("@Param", SqlDbType.VarChar, 500).Value = variable;
}

Or you can leave your server side set to null and not pass the param at all.

What is recursion and when should I use it?

Actually the better recursive solution for factorial should be:

int factorial_accumulate(int n, int accum) {
    return (n < 2 ? accum : factorial_accumulate(n - 1, n * accum));
}

int factorial(int n) {
    return factorial_accumulate(n, 1);
}

Because this version is Tail Recursive

Rails: select unique values from a column

This works too.

Model.pluck("DISTINCT rating")

Enable & Disable a Div and its elements in Javascript

You should be able to set these via the attr() or prop() functions in jQuery as shown below:

jQuery (< 1.7):

// This will disable just the div
$("#dcacl").attr('disabled','disabled');

or

// This will disable everything contained in the div
$("#dcacl").children().attr("disabled","disabled");

jQuery (>= 1.7):

// This will disable just the div
$("#dcacl").prop('disabled',true);

or

// This will disable everything contained in the div
$("#dcacl").children().prop('disabled',true);

or

//  disable ALL descendants of the DIV
$("#dcacl *").prop('disabled',true);

Javascript:

// This will disable just the div
document.getElementById("dcalc").disabled = true;

or

// This will disable all the children of the div
var nodes = document.getElementById("dcalc").getElementsByTagName('*');
for(var i = 0; i < nodes.length; i++){
     nodes[i].disabled = true;
}

Find row in datatable with specific id

You can use LINQ to DataSet/DataTable

var rows = dt.AsEnumerable()
               .Where(r=> r.Field<int>("ID") == 5);

Since each row has a unique ID, you should use Single/SingleOrDefault which would throw exception if you get multiple records back.

DataRow dr = dt.AsEnumerable()
               .SingleOrDefault(r=> r.Field<int>("ID") == 5);

(Substitute int for the type of your ID field)

How do I find out if the GPS of an Android device is enabled

In your LocationListener, implement onProviderEnabled and onProviderDisabled event handlers. When you call requestLocationUpdates(...), if GPS is disabled on the phone, onProviderDisabled will be called; if user enables GPS, onProviderEnabled will be called.

Why is there no SortedList in Java?

For any newcomers, as of April 2015, Android now has a SortedList class in the support library, designed specifically to work with RecyclerView. Here's the blog post about it.

How to properly create an SVN tag from trunk?

svn copy http://URL/svn/trukSource http://URL/svn/tagDestination -m "Test tag code" 
  $error[0].Exception | Select-object Data

All you have to do change URL path. This command will create new dir "tagDestination". The second line will be let know you the full error details if any occur. Create svn env variable if not created. Can check (Cmd:- set, Powershell:- Get-ChildItem Env:) Default path is "C:\Program Files\TortoiseSVN\bin\TortoiseProc.exe"

Interface or an Abstract Class: which one to use?

Just wanted to add an example of when you may need to use both. I am currently writing a file handler bound to a database model in a general purpose ERP solution.

  • I have multiple abstract classes which handle the standard crud and also some specialty functionality like conversion and streaming for different categories of files.
  • The file access interface defines a common set of methods which are needed to get, store and delete a file.

This way, I get to have multiple templates for different files and a common set of interface methods with clear distinction. The interface gives the correct analogy to the access methods rather than what would have been with a base abstract class.

Further down the line when I will make adapters for different file storage services, this implementation will allow the interface to be used elsewhere in totally different contexts.

Cannot read property 'push' of undefined when combining arrays

In most cases you have to initialize the array,

let list: number[] = [];

nodemon not found in npm

npx nodemon (app.js) worked for me and nodemon (app.js) did not.

I updated node.js to the latest version and now both are working.

Equivalent to AssemblyInfo in dotnet core/csproj

I want to extend this topic/answers with the following. As someone mentioned, this auto-generated AssemblyInfo can be an obstacle for the external tools. In my case, using FinalBuilder, I had an issue that AssemblyInfo wasn't getting updated by build action. Apparently, FinalBuilder relies on ~proj file to find location of the AssemblyInfo. I thought, it was looking anywhere under project folder. No. So, changing this

<PropertyGroup>
   <GenerateAssemblyInfo>false</GenerateAssemblyInfo>
</PropertyGroup> 

did only half the job, it allowed custom assembly info if built by VS IDE/MS Build. But I needed FinalBuilder do it too without manual manipulations to assembly info file. I needed to satisfy all programs, MSBuild/VS and FinalBuilder.

I solved this by adding an entry to the existing ItemGroup

<ItemGroup>
   <Compile Remove="Common\**" />
   <Content Remove="Common\**" />
   <EmbeddedResource Remove="Common\**" />
   <None Remove="Common\**" />
   <!-- new added item -->
   <None Include="Properties\AssemblyInfo.cs" />
</ItemGroup>

Now, having this item, FinalBuilder finds location of AssemblyInfo and modifies the file. While action None allows MSBuild/DevEnv ignore this entry and no longer report an error based on Compile action that usually comes with Assembly Info entry in proj files.

C:\Program Files\dotnet\sdk\2.0.2\Sdks\Microsoft.NET.Sdk\build\Microsoft.NET.Sdk.DefaultItems.targets(263,5): error : Duplicate 'Compile' items were included. The .NET SDK includes 'Compile' items from your project directory by default. You can either remove these items from your project file, or set the 'EnableDefaultCompileItems' property to 'false' if you want to explicitly include them in your project file. For more information, see https://aka.ms/sdkimplicititems. The duplicate items were: 'AssemblyInfo.cs'

How do operator.itemgetter() and sort() work?

Answer for Python beginners

In simpler words:

  1. The key= parameter of sort requires a key function (to be applied to be objects to be sorted) rather than a single key value and
  2. that is just what operator.itemgetter(1) will give you: A function that grabs the first item from a list-like object.

(More precisely those are callables, not functions, but that is a difference that can often be ignored.)

awk - concatenate two string variable and assign to a third

Could use sprintf to accomplish this:

awk '{str = sprintf("%s %s", $1, $2)} END {print str}' file

Injecting @Autowired private field during testing

Sometimes you can refactor your @Component to use constructor or setter based injection to setup your testcase (you can and still rely on @Autowired). Now, you can create your test entirely without a mocking framework by implementing test stubs instead (e.g. Martin Fowler's MailServiceStub):

@Component
public class MyLauncher {

    private MyService myService;

    @Autowired
    MyLauncher(MyService myService) {
        this.myService = myService;
    }

    // other methods
}

public class MyServiceStub implements MyService {
    // ...
}

public class MyLauncherTest
    private MyLauncher myLauncher;
    private MyServiceStub myServiceStub;

    @Before
    public void setUp() {
        myServiceStub = new MyServiceStub();
        myLauncher = new MyLauncher(myServiceStub);
    }

    @Test
    public void someTest() {

    }
}

This technique especially useful if the test and the class under test is located in the same package because then you can use the default, package-private access modifier to prevent other classes from accessing it. Note that you can still have your production code in src/main/java but your tests in src/main/test directories.


If you like Mockito then you will appreciate the MockitoJUnitRunner. It allows you to do "magic" things like @Manuel showed you:

@RunWith(MockitoJUnitRunner.class)
public class MyLauncherTest
    @InjectMocks
    private MyLauncher myLauncher; // no need to call the constructor

    @Mock
    private MyService myService;

    @Test
    public void someTest() {

    }
}

Alternatively, you can use the default JUnit runner and call the MockitoAnnotations.initMocks() in a setUp() method to let Mockito initialize the annotated values. You can find more information in the javadoc of @InjectMocks and in a blog post that I have written.

Copy/Paste/Calculate Visible Cells from One Column of a Filtered Table

I've found this to work very well. It uses the .range property of the .autofilter object, which seems to be a rather obscure, but very handy, feature:

Sub copyfiltered()
    ' Copies the visible columns
    ' and the selected rows in an autofilter
    '
    ' Assumes that the filter was previously applied
    '
    Dim wsIn As Worksheet
    Dim wsOut As Worksheet

    Set wsIn = Worksheets("Sheet1")
    Set wsOut = Worksheets("Sheet2")

    ' Hide the columns you don't want to copy
    wsIn.Range("B:B,D:D").EntireColumn.Hidden = True

    'Copy the filtered rows from wsIn and and paste in wsOut
    wsIn.AutoFilter.Range.Copy Destination:=wsOut.Range("A1")
End Sub

How can I remove the "No file chosen" tooltip from a file input in Chrome?

It works for me!

input[type="file"]{
  font-size: 0px;
}

Then, you can use different kind of styles such as width, height or other properties in order to create your own input file.

Apply formula to the entire column

It looks like some of the other answers have become outdated, but for me this worked:

  1. Click on the cell with the text/formula to copy
  2. Shift+Click on the last cell to copy to
  3. Ctrl + Enter

(Note that this replaces text if the destination cells aren't empty)

Disable color change of anchor tag when visited

If you use some pre-processor like SASS, you can use @extend feature:

a:visited {
  @extend a;
}

As a result you will see automatically-added a:visited selector for every style with a selector, so be carefully with it, because your style-table may be increase in size very much.

As a compromise you can add @extend only in those block wich you really need.

How to delete an element from a Slice in Golang

This is how you Delete From a slice the idiomatic way. You don't need to build a function it is built into the append. Try it here https://play.golang.org/p/QMXn9-6gU5P

z := []int{9, 8, 7, 6, 5, 3, 2, 1, 0}
fmt.Println(z)  //will print Answer [9 8 7 6 5 3 2 1 0]

z = append(z[:2], z[4:]...)
fmt.Println(z)   //will print Answer [9 8 5 3 2 1 0]

How to get the current user's Active Directory details in C#

If you're using .NET 3.5 SP1+ the better way to do this is to take a look at the

System.DirectoryServices.AccountManagement namespace.

It has methods to find people and you can pretty much pass in any username format you want and then returns back most of the basic information you would need. If you need help on loading the more complex objects and properties check out the source code for http://umanage.codeplex.com its got it all.

Brent

Page vs Window in WPF?

Page Control can be contained in Window Control but vice versa is not possible

You can use Page control within the Window control using NavigationWindow and Frame controls. Window is the root control that must be used to hold/host other controls (e.g. Button) as container. Page is a control which can be hosted in other container controls like NavigationWindow or Frame. Page control has its own goal to serve like other controls (e.g. Button). Page is to create browser like applications. So if you host Page in NavigationWindow, you will get the navigation implementation built-in. Pages are intended for use in Navigation applications (usually with Back and Forward buttons, e.g. Internet Explorer).

WPF provides support for browser style navigation inside standalone application using Page class. User can create multiple pages, navigate between those pages along with data.There are multiple ways available to Navigate through one page to another page.

How do I add button on each row in datatable?

take a look here... this was very helpfull to me https://datatables.net/examples/ajax/null_data_source.html

$(document).ready(function() {
    var table = $('#example').DataTable( {
        "ajax": "data/arrays.txt",
        "columnDefs": [ {
        "targets": -1,
        "data": null,
        "defaultContent": "<button>Click!</button>"
    } ]
} );

$('#example tbody').on( 'click', 'button', function () {
    var data = table.row( $(this).parents('tr') ).data();
    alert( data[0] +"'s salary is: "+ data[ 5 ] );
    } );
} );

Getting list of Facebook friends with latest API

Getting the friends like @nfvs describes is a good way. It outputs a multi-dimensional array with all friends with attributes id and name (ordered by id). You can see the friends photos like this:

foreach ($friends as $key=>$value) {
    echo count($value) . ' Friends';
    echo '<hr />';
    echo '<ul id="friends">';
    foreach ($value as $fkey=>$fvalue) {
        echo '<li><img src="https://graph.facebook.com/' . $fvalue->id . '/picture" title="' . $fvalue->name . '"/></li>';
    }
    echo '</ul>';
}

Pass row number as variable in excel sheet

An alternative is to use OFFSET:

Assuming the column value is stored in B1, you can use the following

C1 = OFFSET(A1, 0, B1 - 1)

This works by:

a) taking a base cell (A1)
b) adding 0 to the row (keeping it as A)
c) adding (A5 - 1) to the column

You can also use another value instead of 0 if you want to change the row value too.

Dictionary with list of strings as value

A simpler way of doing it is:

var dictionary = list.GroupBy(it => it.Key).ToDictionary(dict => dict.Key, dict => dict.Select(item => item.value).ToList());

What is SOA "in plain english"?

Depends on who you are!

If you're an business owner, SOA is a solution to increase your incomes and business agility. If you're an entreprise architect, SOA is a way to draw nice and clean piece of software on a blank canvas. If you're an architect SOA is the solution to design loosely coupled services over an integration platform, to just plug services into outlets. If you're a developper SOA is a programming paradigm where a service is in the center of the design and the code.

You should read 100-SOA-Questions [pdf]

Cheers

IF...THEN...ELSE using XML

<IF>
    <CONDITIONS>
        <CONDITION field="time" from="5pm" to="9pm"></CONDITION>
    </CONDITIONS>
    <RESULTS><...some actions defined.../></RESULTS>
    <ELSE>
        <RESULTS><...some other actions defined.../></RESULTS>        
    </ELSE>
</IF>

Here's my take on it. This will allow you to have multiple conditions.

Python send POST with header

If we want to add custom HTTP headers to a POST request, we must pass them through a dictionary to the headers parameter.

Here is an example with a non-empty body and headers:

import requests
import json

url = 'https://somedomain.com'
body = {'name': 'Maryja'}
headers = {'content-type': 'application/json'}

r = requests.post(url, data=json.dumps(body), headers=headers)

Source

Adding a column to a dataframe in R

Even if that's a 7 years old question, people new to R should consider using the data.table, package.

A data.table is a data.frame so all you can do for/to a data.frame you can also do. But many think are ORDERS of magnitude faster with data.table.

vec <- 1:10
library(data.table)
DT <- data.table(start=c(1,3,5,7), end=c(2,6,7,9))
DT[,new:=apply(DT,1,function(row) mean(vec[ row[1] : row[2] ] ))]

Difference between & and && in Java?

& is bitwise AND operator comparing bits of each operand.
For example,

int a = 4;
int b = 7;
System.out.println(a & b); // prints 4
//meaning in an 32 bit system
// 00000000 00000000 00000000 00000100
// 00000000 00000000 00000000 00000111
// ===================================
// 00000000 00000000 00000000 00000100


&& is logical AND operator comparing boolean values of operands only. It takes two operands indicating a boolean value and makes a lazy evaluation on them.

Download and install an ipa from self hosted url on iOS

NSURL *url = [NSURL URLWithString:@"itms-services://?action=download-manifest&amp;url=https://xxxxxx.com/rest/images/apps/ipa/dev/xyz.plist"]];
[[UIApplication sharedApplication] openURL:url];

openUrl method was deprecated.

[[UIApplication sharedApplication] openURL: url options:@{} completionHandler:nil];

This method latest openUrl method and it will display prompt dialog.The dialog will show

xxxxxx.com would like to install "YOUR_APP_NAME"

this messages. If you click the "install" button application will close and ipa will download.

How to add two edit text fields in an alert dialog

 LayoutInflater factory = LayoutInflater.from(this);
final View textEntryView = factory.inflate(R.layout.text_entry, null);
//text_entry is an Layout XML file containing two text field to display in alert dialog
final EditText input1 = (EditText) textEntryView.findViewById(R.id.EditText1);
final EditText input2 = (EditText) textEntryView.findViewById(R.id.EditText2);             
input1.setText("DefaultValue", TextView.BufferType.EDITABLE);
input2.setText("DefaultValue", TextView.BufferType.EDITABLE);
final AlertDialog.Builder alert = new AlertDialog.Builder(this);

alert.setIcon(R.drawable.icon)
     .setTitle("Enter the Text:")
     .setView(textEntryView)
     .setPositiveButton("Save", 
         new DialogInterface.OnClickListener() {
             public void onClick(DialogInterface dialog, int whichButton) {
                    Log.i("AlertDialog","TextEntry 1 Entered "+input1.getText().toString());
                    Log.i("AlertDialog","TextEntry 2 Entered "+input2.getText().toString());
                    /* User clicked OK so do some stuff */
             }
         })
     .setNegativeButton("Cancel",
         new DialogInterface.OnClickListener() {
             public void onClick(DialogInterface dialog,
                    int whichButton) {
             }
         });
alert.show();

HRESULT: 0x80131040: The located assembly's manifest definition does not match the assembly reference

Just another case here. I had this error from Managed Debugging Assistant on the first time deserializing a XML file into objects under VS2010/.NET 4. A DLL containing classes for the objects is generated in a post-build event (usual Microsoft style stuff). Worked very well for several projects in same solution, problem appeared when doing that in one more of the projects. Error text:

BindingFailure was detected Message: The assembly with display name MyProjectName.XmlSerializers' failed to load in the 'LoadFrom' binding context of the AppDomain with ID 1. The cause of the failure was: System.IO.FileLoadException: Could not load file or assembly MyProjectName.XmlSerializers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)

Since some answers here suggested a platform mismatch, I noticed that 3 projects and the solution had "mixed platforms" configuration selected, and 3 projects were compiled for x86 instead of AnyCPU. I have no platform-specific code (though some vendor-provided DLLs rely on a few x86 libraries). I replaced all occurrences of x86 into AnyCPU with this:

for a in $( egrep '(x86|AnyCPU)' */*.csproj *.sln -l  ) ; do echo $a ; sed -i 's/x86/AnyCPU/' $a ; done

Then the project would build but all options to run or debug code would be greyed out. Restarting VS would not help.

I reverted with git the references to the x86-library, just in case, but kept AnyCPU for all the code I compile.

Following F5 or Start Debugging Button is Greyed Out for Winform application? I unloaded and reloaded the starting project (it was also the one where the initial problem appeared in the first place).

After that, everything fell back into place: the program works without the initial error.

See http://www.catb.org/jargon/html/R/rain-dance.html , http://www.catb.org/jargon/html/V/voodoo-programming.html or http://www.catb.org/jargon/html/I/incantation.html and links there.

MySQL Sum() multiple columns

Another way of doing this is by generating the select query. Play with this fiddle.

SELECT CONCAT('SELECT ', group_concat(`COLUMN_NAME` SEPARATOR '+'), ' FROM scorecard') 
FROM  `INFORMATION_SCHEMA`.`COLUMNS` 
WHERE `TABLE_SCHEMA` = (select database()) 
AND   `TABLE_NAME`   = 'scorecard'
AND   `COLUMN_NAME` LIKE 'mark%';

The query above will generate another query that will do the selecting for you.

  1. Run the above query.
  2. Get the result and run that resulting query.

Sample result:

SELECT mark1+mark2+mark3 FROM scorecard

You won't have to manually add all the columns anymore.

Facebook share button and custom text

You have several options:

  1. Use the standard FB Share button and set text via Open Graph API and meta tags on your page.
  2. Instead of Share, use FB.ui's stream.publish method, which let's you control the URL, title, caption, description and thumbnail at run-time.
  3. Or use http://www.facebook.com/sharer.php with appropriate parameters.

How to refresh Android listview?

After deleting data from list view, you have to call refreshDrawableState(). Here is the example:

final DatabaseHelper db = new DatabaseHelper (ActivityName.this);

db.open();

db.deleteContact(arg3);

mListView.refreshDrawableState();

db.close();

and deleteContact method in DatabaseHelper class will be somewhat looks like

public boolean deleteContact(long rowId) {

   return db.delete(TABLE_NAME, BaseColumns._ID + "=" + rowId, null) > 0;

}

Global variables in c#.net

You can create a variable with an application scope

How to change default timezone for Active Record in Rails?

In my case (Rails 5), I ended up adding these 2 lines in my app/config/environments/development.rb

config.time_zone = "Melbourne"
config.active_record.default_timezone = :local

That's it! And to make sure that Melbourne was read correctly, I ran the command in my terminal:

bundle exec rake time:zones:all

and Melbourne was listing in the timezone I'm in!

Format number as percent in MS SQL Server

In SQL Server 2012 and later, there is the FORMAT() function. You can pass it a 'P' parameter for percentage. For example:

SELECT FORMAT((37.0/38.0),'P') as [Percentage] -- 97.37 %

To support percentage decimal precision, you can use P0 for no decimals (whole-numbers) or P3 for 3 decimals (97.368%).

SELECT FORMAT((37.0/38.0),'P0') as [WholeNumberPercentage] -- 97 %
SELECT FORMAT((37.0/38.0),'P3') as [ThreeDecimalsPercentage] -- 97.368 %

Array Index Out of Bounds Exception (Java)

for ( i = 0; i < total.length; i++ ); // remove this
{
    if (total[i]!=0)
        System.out.println( "Letter" + (char)( 'a' + i) + " count =" + total[i]);
}

The for loop loops until i=26 (where 26 is total.length) and then your if is executed, going over the bounds of the array. Remove the ; at the end of the for loop.

Open fancybox from function

The answers seems a bit over complicated. I hope I didn't misunderstand the question.

If you simply want to open a fancy box from a click to an "A" tag. Just set your html to

<a id="my_fancybox" href="#contentdiv">click me</a>

The contents of your box will be inside of a div with id "contentdiv" and in your javascript you can initialize fancybox like this:

$('#my_fancybox').fancybox({
    'autoScale': true,
    'transitionIn': 'elastic',
    'transitionOut': 'elastic',
    'speedIn': 500,
    'speedOut': 300,
    'autoDimensions': true,
    'centerOnScroll': true,
});

This will show a fancybox containing "contentdiv" when your anchor tag is clicked.

How do you make Vim unhighlight what you searched for?

Append the following line to the end of your .vimrc to prevent highlighting altogether:

set nohlsearch

How to return a dictionary | Python

What's going on is that you're returning right after the first line of the file doesn't match the id you're looking for. You have to do this:

def query(id):
    for line in file:
        table = {}
        (table["ID"],table["name"],table["city"]) = line.split(";")
        if id == int(table["ID"]):
             file.close()
             return table
    # ID not found; close file and return empty dict
    file.close()
    return {}

How to install SimpleJson Package for Python

If you have Python 2.6 installed then you already have simplejson - just import json; it's the same thing.

How to hide a div after some time period?

In older versions of jquery you'll have to do it the "javascript way" using settimeout

setTimeout( function(){$('div').hide();} , 4000);

or

setTimeout( "$('div').hide();", 4000);

Recently with jquery 1.4 this solution has been added:

$("div").delay(4000).hide();

Of course replace "div" by the correct element using a valid jquery selector and call the function when the document is ready.

Spring Boot Configure and Use Two DataSources

Here is the Complete solution

#First Datasource (DB1)
db1.datasource.url: url
db1.datasource.username:user
db1.datasource.password:password

#Second Datasource (DB2)
db2.datasource.url:url
db2.datasource.username:user
db2.datasource.password:password

Since we are going to get access two different databases (db1, db2), we need to configure each data source configuration separately like:

public class DB1_DataSource {
@Autowired
private Environment env;
@Bean
@Primary
public LocalContainerEntityManagerFactoryBean db1EntityManager() {
    LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
    em.setDataSource(db1Datasource());
    em.setPersistenceUnitName("db1EntityManager");
    HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
    em.setJpaVendorAdapter(vendorAdapter);
    HashMap<string, object=""> properties = new HashMap<>();
    properties.put("hibernate.dialect",
            env.getProperty("hibernate.dialect"));
    properties.put("hibernate.show-sql",
            env.getProperty("jdbc.show-sql"));
    em.setJpaPropertyMap(properties);
    return em;
}

@Primary
@Bean
public DataSource db1Datasource() {

    DriverManagerDataSource dataSource
            = new DriverManagerDataSource();
    dataSource.setDriverClassName(
            env.getProperty("jdbc.driver-class-name"));
    dataSource.setUrl(env.getProperty("db1.datasource.url"));
    dataSource.setUsername(env.getProperty("db1.datasource.username"));
    dataSource.setPassword(env.getProperty("db1.datasource.password"));

    return dataSource;
}

@Primary
@Bean
public PlatformTransactionManager db1TransactionManager() {

    JpaTransactionManager transactionManager
            = new JpaTransactionManager();
    transactionManager.setEntityManagerFactory(
            db1EntityManager().getObject());
    return transactionManager;
}
}

Second Datasource :

public class DB2_DataSource {

@Autowired
private Environment env;

@Bean
public LocalContainerEntityManagerFactoryBean db2EntityManager() {
    LocalContainerEntityManagerFactoryBean em
            = new LocalContainerEntityManagerFactoryBean();
    em.setDataSource(db2Datasource());
    em.setPersistenceUnitName("db2EntityManager");
    HibernateJpaVendorAdapter vendorAdapter
            = new HibernateJpaVendorAdapter();
    em.setJpaVendorAdapter(vendorAdapter);
    HashMap<string, object=""> properties = new HashMap<>();
    properties.put("hibernate.dialect",
            env.getProperty("hibernate.dialect"));
    properties.put("hibernate.show-sql",
            env.getProperty("jdbc.show-sql"));
    em.setJpaPropertyMap(properties);
    return em;
}

@Bean
public DataSource db2Datasource() {
    DriverManagerDataSource dataSource
            = new DriverManagerDataSource();
    dataSource.setDriverClassName(
            env.getProperty("jdbc.driver-class-name"));
    dataSource.setUrl(env.getProperty("db2.datasource.url"));
    dataSource.setUsername(env.getProperty("db2.datasource.username"));
    dataSource.setPassword(env.getProperty("db2.datasource.password"));

    return dataSource;
}

@Bean
public PlatformTransactionManager db2TransactionManager() {
    JpaTransactionManager transactionManager
            = new JpaTransactionManager();
    transactionManager.setEntityManagerFactory(
            db2EntityManager().getObject());
    return transactionManager;
}
}

Here you can find the complete Example on my blog : Spring Boot with Multiple DataSource Configuration

Tools to search for strings inside files without indexing

Original Answer

Windows Grep does this really well.

Edit: Windows Grep is no longer being maintained or made available by the developer. An alternate download link is here: Windows Grep - alternate

Current Answer

Visual Studio Code has excellent search and replace capabilities across files. It is extremely fast, supports regex and live preview before replacement.

enter image description here

How do I decrease the size of my sql server log file?

  • Perform a full backup of your database. Don't skip this. Really.
  • Change the backup method of your database to "Simple"
  • Open a query window and enter "checkpoint" and execute
  • Perform another backup of the database
  • Change the backup method of your database back to "Full" (or whatever it was, if it wasn't already Simple)
  • Perform a final full backup of the database.
  • Run below queries one by one
    1. USE Database_Name
    2. select name,recovery_model_desc from sys.databases
    3. ALTER DATABASE Database_Name SET RECOVERY simple
    4. DBCC SHRINKFILE (Database_Name_log , 1)

Is there a SELECT ... INTO OUTFILE equivalent in SQL Server Management Studio?

In SQL Management Studio you can:

  1. Right click on the result set grid, select 'Save Result As...' and save in.

  2. On a tool bar toggle 'Result to Text' button. This will prompt for file name on each query run.

If you need to automate it, use bcp tool.

Completely uninstall PostgreSQL 9.0.4 from Mac OSX Lion?

homebrew Installer

Assuming you installed PostgreSQL with homebrew as referenced in check status of postgresql server Mac OS X and how to start postgresql server on mac os x: you can use the brew uninstall postgresql command.

EnterpriseDB Installer

If you used the EnterpriseDB installer then see the other answer in this thread.

The EnterpriseDB installer is what you get if you follow "download" links from the main Postgres web site. The Postgres team releases only source code, so the EnterpriseDB.com company builds installers as a courtesy to the community.

Postgres.app

You may have also used Postgres.app.

This double-clickable Mac app contains the Postgres engine.

Microsoft Azure: How to create sub directory in a blob container

I needed to do this from Jenkins pipeline, so, needed to upload files to specific folder name but not to the root container folder. I use --destination-path that can be folder or folder1/folder2

az storage blob upload-batch --account-name $AZURE_STORAGE_ACCOUNT --destination ${CONTAINER_NAME} --destination-path ${VERSION_FOLDER} --source ${BUILD_FOLDER} --account-key $ACCESS_KEY

hope this help to someone

How to send push notification to web browser?

So here I am answering my own question. I have got answers to all my queries from people who have build push notification services in the past.

Update (May 2018): Here is a comprehensive and a very well written doc on web push notification from Google.

Answer to the original questions asked 3 years ago:

  1. Can we use GCM/APNS to send push notification to all Web Browsers including Firefox & Safari?

Answer: Google has deprecated GCM as of April 2018. You can now use Firebase Cloud Messaging (FCM). This supports all platforms including web browsers.

  1. If not via GCM can we have our own back-end to do the same?

Answer: Yes, push notification can be sent from our own back-end. Support for the same has come to all major browsers.

Check this codelab from Google to better understand the implementation.

Some Tutorials:

  • Implementing push notification in Django Here.
  • Using flask to send push notification Here & Here.
  • Sending push notifcaiton from Nodejs Here
  • Sending push notification using php Here & Here
  • Sending push notification from Wordpress. Here & Here
  • Sending push notification from Drupal. Here

Implementing own backend in various programming languages.:

Further Readings: - - Documentation from Firefox website can be read here. - A very good overview of Web Push by Google can be found here. - An FAQ answering most common confusions and questions.

Are there any free services to do the same? There are some companies that provide a similar solution in free, freemium and paid models. Am listing few below:

  1. https://onesignal.com/ (Free | Support all platforms)
  2. https://firebase.google.com/products/cloud-messaging/ (Free)
  3. https://clevertap.com/ (Has free plan)
  4. https://goroost.com/

Note: When choosing a free service remember to read the TOS. Free services often work by collecting user data for various purposes including analytics.

Apart from that, you need to have HTTPS to send push notifications. However, you can get https freely via letsencrypt.org

How to run DOS/CMD/Command Prompt commands from VB.NET?

You could try this method:

Public Class MyUtilities
    Shared Sub RunCommandCom(command as String, arguments as String, permanent as Boolean) 
        Dim p as Process = new Process() 
        Dim pi as ProcessStartInfo = new ProcessStartInfo() 
        pi.Arguments = " " + if(permanent = true, "/K" , "/C") + " " + command + " " + arguments 
        pi.FileName = "cmd.exe" 
        p.StartInfo = pi 
        p.Start() 
    End Sub
End Class

call, for example, in this way:

MyUtilities.RunCommandCom("DIR", "/W", true)

EDIT: For the multiple command on one line the key are the & | && and || command connectors

  • A & B → execute command A, then execute command B.
  • A | B → execute command A, and redirect all it's output into the input of command B.
  • A && B → execute command A, evaluate the errorlevel after running Command A, and if the exit code (errorlevel) is 0, only then execute command B.
  • A || B → execute Command A, evaluate the exit code of this command and if it's anything but 0, only then execute command B.

Background service with location listener in android

Background location service. It will be restarted even after killing the app.

MainActivity.java

public class MainActivity extends AppCompatActivity {
    AlarmManager alarmManager;
    Button stop;
    PendingIntent pendingIntent;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        if (alarmManager == null) {
            alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
            Intent intent = new Intent(this, AlarmReceive.class);
            pendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0);
            alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 30000,
                    pendingIntent);
        }
    }
}

BookingTrackingService.java

public class BookingTrackingService extends Service implements LocationListener {

    private static final String TAG = "BookingTrackingService";
    private Context context;
    boolean isGPSEnable = false;
    boolean isNetworkEnable = false;
    double latitude, longitude;
    LocationManager locationManager;
    Location location;
    private Handler mHandler = new Handler();
    private Timer mTimer = null;
    long notify_interval = 30000;

    public double track_lat = 0.0;
    public double track_lng = 0.0;
    public static String str_receiver = "servicetutorial.service.receiver";
    Intent intent;

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();

        mTimer = new Timer();
        mTimer.schedule(new TimerTaskToGetLocation(), 5, notify_interval);
        intent = new Intent(str_receiver);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        this.context = this;


        return START_NOT_STICKY;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.e(TAG, "onDestroy <<");
        if (mTimer != null) {
            mTimer.cancel();
        }
    }

    private void trackLocation() {
        Log.e(TAG, "trackLocation");
        String TAG_TRACK_LOCATION = "trackLocation";
        Map<String, String> params = new HashMap<>();
        params.put("latitude", "" + track_lat);
        params.put("longitude", "" + track_lng);

        Log.e(TAG, "param_track_location >> " + params.toString());

        stopSelf();
        mTimer.cancel();

    }

    @Override
    public void onLocationChanged(Location location) {

    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {

    }

    @Override
    public void onProviderEnabled(String provider) {

    }

    @Override
    public void onProviderDisabled(String provider) {

    }

    /******************************/

    private void fn_getlocation() {
        locationManager = (LocationManager) getApplicationContext().getSystemService(LOCATION_SERVICE);
        isGPSEnable = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        isNetworkEnable = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);

        if (!isGPSEnable && !isNetworkEnable) {
            Log.e(TAG, "CAN'T GET LOCATION");
            stopSelf();
        } else {
            if (isNetworkEnable) {
                location = null;
                locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000, 0, this);
                if (locationManager != null) {
                    location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                    if (location != null) {

                        Log.e(TAG, "isNetworkEnable latitude" + location.getLatitude() + "\nlongitude" + location.getLongitude() + "");
                        latitude = location.getLatitude();
                        longitude = location.getLongitude();
                        track_lat = latitude;
                        track_lng = longitude;
//                        fn_update(location);
                    }
                }
            }

            if (isGPSEnable) {
                location = null;
                locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 0, this);
                if (locationManager != null) {
                    location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
                    if (location != null) {
                        Log.e(TAG, "isGPSEnable latitude" + location.getLatitude() + "\nlongitude" + location.getLongitude() + "");
                        latitude = location.getLatitude();
                        longitude = location.getLongitude();
                        track_lat = latitude;
                        track_lng = longitude;
//                        fn_update(location);
                    }
                }
            }

            Log.e(TAG, "START SERVICE");
            trackLocation();

        }
    }

    private class TimerTaskToGetLocation extends TimerTask {
        @Override
        public void run() {

            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    fn_getlocation();
                }
            });

        }
    }

//    private void fn_update(Location location) {
//
//        intent.putExtra("latutide", location.getLatitude() + "");
//        intent.putExtra("longitude", location.getLongitude() + "");
//        sendBroadcast(intent);
//    }
}

AlarmReceive.java (BroadcastReceiver)

public class AlarmReceive extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        Log.e("Service_call_"  , "You are in AlarmReceive class.");
        Intent background = new Intent(context, BookingTrackingService.class);
//        Intent background = new Intent(context, GoogleService.class);
        Log.e("AlarmReceive ","testing called broadcast called");
        context.startService(background);
    }
}

AndroidManifest.xml

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

 <service
            android:name=".ServiceAndBroadcast.BookingTrackingService"
            android:enabled="true" />

        <receiver
            android:name=".ServiceAndBroadcast.AlarmReceive"
            android:exported="false">
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED" />
            </intent-filter>
        </receiver>

How do I base64 encode a string efficiently using Excel VBA?

As Mark C points out, you can use the MSXML Base64 encoding functionality as described here.

I prefer late binding because it's easier to deploy, so here's the same function that will work without any VBA references:

Function EncodeBase64(text As String) As String
  Dim arrData() As Byte
  arrData = StrConv(text, vbFromUnicode)

  Dim objXML As Variant
  Dim objNode As Variant

  Set objXML = CreateObject("MSXML2.DOMDocument")
  Set objNode = objXML.createElement("b64")

  objNode.dataType = "bin.base64"
  objNode.nodeTypedValue = arrData
  EncodeBase64 = objNode.text

  Set objNode = Nothing
  Set objXML = Nothing
End Function

Error #2032: Stream Error

Just to clarify my comment (it's illegible in a single line)

I think the best answer is the comment by Mike Chambers in this link (http://www.judahfrangipane.com/blog/2007/02/15/error-2032-stream-error/) by Hunter McMillen.

A note from Mike Chambers:

If you run into this using URLLoader, listen for the:

flash.events.HTTPStatusEvent.HTTP_STATUS

and in AIR :

flash.events.HTTPStatusEvent.HTTP_RESPONSE_STATUS

It should give you some more information (such as the status code being returned from the server).

Is there an equivalent method to C's scanf in Java?

Not an equivalent, but you can use a Scanner and a pattern to parse lines with three non-negative numbers separated by spaces, for example:

71 5796 2489
88 1136 5298
42 420 842

Here's the code using findAll:

new Scanner(System.in).findAll("(\\d+) (\\d+) (\\d+)")
        .forEach(result -> {
            int fst = Integer.parseInt(result.group(1));
            int snd = Integer.parseInt(result.group(2));
            int third = Integer.parseInt(result.group(3));
            int sum = fst + snd + third;
            System.out.printf("%d + %d + %d = %d", fst, snd, third, sum);
        });

Mips how to store user input string

# This code works fine in QtSpim simulator

.data
    buffer: .space 20
    str1:  .asciiz "Enter string"
    str2:  .asciiz "You wrote:\n"

.text

main:
    la $a0, str1    # Load and print string asking for string
    li $v0, 4
    syscall

    li $v0, 8       # take in input

    la $a0, buffer  # load byte space into address
    li $a1, 20      # allot the byte space for string

    move $t0, $a0   # save string to t0
    syscall

    la $a0, str2    # load and print "you wrote" string
    li $v0, 4
    syscall

    la $a0, buffer  # reload byte space to primary address
    move $a0, $t0   # primary address = t0 address (load pointer)
    li $v0, 4       # print string
    syscall

    li $v0, 10      # end program
    syscall

Nested lists python

I think you want to access list values and their indices simultaneously and separately:

l = [[2,2,2],[3,3,3],[4,4,4],[5,5,5]]
l_len = len(l)
l_item_len = len(l[0])
for i in range(l_len):
    for j in range(l_item_len):
        print(f'List[{i}][{j}] : {l[i][j]}'  )

Lost connection to MySQL server at 'reading initial communication packet', system error: 0

I just set up mysql on a windows box. I got the OP's error when trying to connect with the Navicat MySql client on the same box. I had to specify 127.0.0.1 as the host, and that got it.

localhost, or the servers actual ip address both did not work.

Repository Pattern Step by Step Explanation

As a summary, I would describe the wider impact of the repository pattern. It allows all of your code to use objects without having to know how the objects are persisted. All of the knowledge of persistence, including mapping from tables to objects, is safely contained in the repository.

Very often, you will find SQL queries scattered in the codebase and when you come to add a column to a table you have to search code files to try and find usages of a table. The impact of the change is far-reaching.

With the repository pattern, you would only need to change one object and one repository. The impact is very small.

Perhaps it would help to think about why you would use the repository pattern. Here are some reasons:

  • You have a single place to make changes to your data access

  • You have a single place responsible for a set of tables (usually)

  • It is easy to replace a repository with a fake implementation for testing - so you don't need to have a database available to your unit tests

There are other benefits too, for example, if you were using MySQL and wanted to switch to SQL Server - but I have never actually seen this in practice!

How to run python script on terminal (ubuntu)?

Set the PATH as below:


In the csh shell - type setenv PATH "$PATH:/usr/local/bin/python" and press Enter.

In the bash shell (Linux) - type export PATH="$PATH:/usr/local/bin/python" and press Enter.

In the sh or ksh shell - type PATH="$PATH:/usr/local/bin/python" and press Enter.

Note - /usr/local/bin/python is the path of the Python directory


now run as below:

-bash-4.2$ python test.py

Hello, Python!

Set background image on grid in WPF using C#

In order to avoid path problem, you can simply try this, just keep background image in images folder and add this code

<Grid>
  <Grid.Background>
    <ImageBrush Stretch="Fill" ImageSource="..\Images\background.jpg"
                AlignmentY="Top" AlignmentX="Center"/>
  </Grid.Background>
</Grid>

Change text color with Javascript?

Try below code:

$(document).ready(function(){
$('#about').css({'background-color':'black'});    
});

http://jsfiddle.net/jPCFC/

How to avoid variable substitution in Oracle SQL Developer with 'trinidad & tobago'

In SQL*Plus putting SET DEFINE ? at the top of the script will normally solve this. Might work for Oracle SQL Developer as well.

Set height of <div> = to height of another <div> through .css

You would certainly benefit from using a responsive framework for your project. It would save you a good amount of headaches. However, seeing the structure of your HTML I would do the following:

Please check the example: http://jsfiddle.net/xLA4q/

HTML:

<div class="nav-content-wrapper">
 <div class="left-nav">asdasdasd ads asd ads asd ad asdasd ad ad a ad</div>
 <div class="content">asd as dad ads ads ads ad ads das ad sad</div>
</div>

CSS:

.nav-content-wrapper{position:relative; overflow:auto; display:block;height:300px;}
.left-nav{float:left;width:30%;height:inherit;}
.content{float:left;width:70%;height:inherit;}

Tkinter example code for multiple windows, why won't buttons load correctly?

You need to specify the master for the second button. Otherwise it will get packed onto the first window. This is needed not only for Button, but also for other widgets and non-gui objects such as StringVar.

Quick fix: add the frame new as the first argument to your Button in Demo2.

Possibly better: Currently you have Demo2 inheriting from tk.Frame but I think this makes more sense if you change Demo2 to be something like this,

class Demo2(tk.Toplevel):     
    def __init__(self):
        tk.Toplevel.__init__(self)
        self.title("Demo 2")
        self.button = tk.Button(self, text="Button 2", # specified self as master
                                width=25, command=self.close_window)
        self.button.pack()

    def close_window(self):
        self.destroy()

Just as a suggestion, you should only import tkinter once. Pick one of your first two import statements.

AngularJS: How do I manually set input to $valid in controller?

The answers above didn't help me solve my problem. After a long search I bumped into this partial solution.

I've finally solved my problem with this code to set the input field manually to ng-invalid (to set to ng-valid set it to 'true'):

$scope.myForm.inputName.$setValidity('required', false);

How to pass parameters to a Script tag?

it is a very old thread, I know but this might help too if somebody gets here once they search for a solution.

Basically I used the document.currentScript to get the element from where my code is running and I filter using the name of the variable I am looking for. I did it extending currentScript with a method called "get", so we will be able to fetch the value inside that script by using:

document.currentScript.get('get_variable_name');

In this way we can use standard URI to retrieve the variables without adding special attributes.

This is the final code

document.currentScript.get = function(variable) {
    if(variable=(new RegExp('[?&]'+encodeURIComponent(variable)+'=([^&]*)')).exec(this.src))
    return decodeURIComponent(variable[1]);
};

I was forgetting about IE :) It could not be that easier... Well I did not mention that document.currentScript is a HTML5 property. It has not been included for different versions of IE (I tested until IE11, and it was not there yet). For IE compatibility, I added this portion to the code:

document.currentScript = document.currentScript || (function() {
  var scripts = document.getElementsByTagName('script');
  return scripts[scripts.length - 1];
})();

What we are doing here is to define some alternative code for IE, which returns the current script object, which is required in the solution to extract parameters from the src property. This is not the perfect solution for IE since there are some limitations; If the script is loaded asynchronously. Newer browsers should include ".currentScript" property.

I hope it helps.

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

There is nothing in JDK to do this.

  static String[] suffixes =
  //    0     1     2     3     4     5     6     7     8     9
     { "th", "st", "nd", "rd", "th", "th", "th", "th", "th", "th",
  //    10    11    12    13    14    15    16    17    18    19
       "th", "th", "th", "th", "th", "th", "th", "th", "th", "th",
  //    20    21    22    23    24    25    26    27    28    29
       "th", "st", "nd", "rd", "th", "th", "th", "th", "th", "th",
  //    30    31
       "th", "st" };

 Date date = new Date();
 SimpleDateFormat formatDayOfMonth  = new SimpleDateFormat("d");
 int day = Integer.parseInt(formatDateOfMonth.format(date));
 String dayStr = day + suffixes[day];

Or using Calendar:

 Calendar c = Calendar.getInstance();
 c.setTime(date);
 int day = c.get(Calendar.DAY_OF_MONTH);
 String dayStr = day + suffixes[day];

Per comments by @thorbjørn-ravn-andersen, a table like this can be helpful when localizing:

  static String[] suffixes =
     {  "0th",  "1st",  "2nd",  "3rd",  "4th",  "5th",  "6th",  "7th",  "8th",  "9th",
       "10th", "11th", "12th", "13th", "14th", "15th", "16th", "17th", "18th", "19th",
       "20th", "21st", "22nd", "23rd", "24th", "25th", "26th", "27th", "28th", "29th",
       "30th", "31st" };

How to preserve aspect ratio when scaling image using one (CSS) dimension in IE6?

The only way to do explicit scaling in CSS is to use tricks such as found here.

IE6 only, you could also use filters (check out PNGFix). But applying them automatically to the page will need javascript, though that javascript could be embedded in the CSS file.

If you are going to require javascript, then you might want to just have javascript fill in the missing value for the height by inspecting the image once the content has loaded. (Sorry I do not have a reference for this technique).

Finally, and pardon me for this soapbox, you might want to eschew IE6 support in this matter. You could add _width: auto after your width: 75px rule, so that IE6 at least renders the image reasonably, even if it is the wrong size.

I recommend the last solution simply because IE6 is on the way out: 20% and going down almost a percent a month. Also, I note that your site is recreational and in the UK. Both of these help the demographic lean to be away from IE6: IE6 usage drops nearly 40% during weekends (no citation sorry), and UK has a much lower IE6 demographic (again no citation, sorry).

Good luck!

When to use React "componentDidUpdate" method?

I have used componentDidUpdate() in highchart.

Here is a simple example of this component.

import React, { PropTypes, Component } from 'react';
window.Highcharts = require('highcharts');

export default class Chartline extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      chart: ''
    };
  }

  public componentDidUpdate() {
    // console.log(this.props.candidate, 'this.props.candidate')
    if (this.props.category) {
      const category = this.props.category ? this.props.category : {};
      console.log('category', category);
      window.Highcharts.chart('jobcontainer_' + category._id, {
        title: {
          text: ''
        },
        plotOptions: {
          series: {
            cursor: 'pointer'
          }
        },
        chart: {
          defaultSeriesType: 'spline'
        },
        xAxis: {
          // categories: candidate.dateArr,
          categories: ['Day1', 'Day2', 'Day3', 'Day4', 'Day5', 'Day6', 'Day7'],
          showEmpty: true
        },
        labels: {
          style: {
            color: 'white',
            fontSize: '25px',
            fontFamily: 'SF UI Text'
          }
        },
        series: [
          {
            name: 'Low',
            color: '#9B260A',
            data: category.lowcount
          },
          {
            name: 'High',
            color: '#0E5AAB',
            data: category.highcount
          },
          {
            name: 'Average',
            color: '#12B499',
            data: category.averagecount
          }
        ]
      });
    }
  }
  public render() {
    const category = this.props.category ? this.props.category : {};
    console.log('render category', category);
    return <div id={'jobcontainer_' + category._id} style={{ maxWidth: '400px', height: '180px' }} />;
  }
}

How to split a string of space separated numbers into integers?

Here is my answer for python 3.

some_string = "2 3 8 61 "

list(map(int, some_string.strip().split()))

Windows Batch: How to add Host-Entries?

I am adding this answer in case someone else would like to store the host entry set in a txt file formatted like the normal host file. This looks for a TAB delimiter. This is based off of the answers from @Rashy and @that0n3guy. The differences can be noticed around the FOR command.

@echo off
TITLE Modifying your HOSTS file
ECHO.

:: BatchGotAdmin
:-------------------------------------
REM  --> Check for permissions
>nul 2>&1 "%SYSTEMROOT%\system32\cacls.exe" "%SYSTEMROOT%\system32\config\system"

REM --> If error flag set, we do not have admin.
if '%errorlevel%' NEQ '0' (
    echo Requesting administrative privileges...
    goto UACPrompt
) else ( goto gotAdmin )

:UACPrompt
    echo Set UAC = CreateObject^("Shell.Application"^) > "%temp%\getadmin.vbs"
    set params = %*:"="
    echo UAC.ShellExecute "cmd.exe", "/c %~s0 %params%", "", "runas", 1 >> "%temp%\getadmin.vbs"

    "%temp%\getadmin.vbs"
    del "%temp%\getadmin.vbs"
    exit /B

:gotAdmin
    pushd "%CD%"
    CD /D "%~dp0"
:--------------------------------------

:LOOP
SET Choice=
SET /P Choice="Do you want to modify HOSTS file ? (Y/N)"

IF NOT '%Choice%'=='' SET Choice=%Choice:~0,1%

ECHO.
IF /I '%Choice%'=='Y' GOTO ACCEPTED
IF /I '%Choice%'=='N' GOTO REJECTED
ECHO Please type Y (for Yes) or N (for No) to proceed!
ECHO.
GOTO Loop


:REJECTED
ECHO Your HOSTS file was left unchanged.
ECHO Finished.
GOTO END


:ACCEPTED
setlocal enabledelayedexpansion
::Create your list of host domains
for /F "tokens=1,2 delims=  " %%A in (%WINDIR%\System32\drivers\etc\storedhosts.txt) do (
    SET _host=%%B
    SET _ip=%%A
    SET NEWLINE=^& echo.
    ECHO Adding !_ip!       !_host!
    REM REM ::strip out this specific line and store in tmp file
    type %WINDIR%\System32\drivers\etc\hosts | findstr /v !_host! > tmp.txt
    REM REM ::re-add the line to it
    ECHO %NEWLINE%^!_ip!        !_host! >> tmp.txt
    REM ::overwrite host file
    copy /b/v/y tmp.txt %WINDIR%\System32\drivers\etc\hosts
    del tmp.txt 
)

ipconfig /flushdns
ECHO.
ECHO.
ECHO Finished, you may close this window now.
GOTO END

:END
ECHO.
PAUSE
EXIT

Example "storedhosts.txt" (tab delimited)

127.0.0.1   mysite.com
168.1.64.2  yoursite.com
192.1.0.1   internalsite.com

jQuery - how to write 'if not equal to' (opposite of ==)

!=

For example,

if ("apple" != "orange")
  // true, the string "apple" is not equal to the string "orange"

Means not. See also the logical operators list. Also, when you see triple characters, it's a type sensitive comparison. (e.g. if (1 === '1') [not equal])

How to print Two-Dimensional Array like table

For traversing through a 2D array, I think the following for loop can be used.

        for(int a[]: twoDm)
        {
            System.out.println(Arrays.toString(a));
        }
if you don't want the commas you can string replace
if you want this to be performant you should loop through a[] and then print it.

Assigning a variable NaN in python without numpy

A more consistent (and less opaque) way to generate inf and -inf is to again use float():

>> positive_inf = float('inf')
>> positive_inf
inf
>> negative_inf = float('-inf')
>> negative_inf
-inf

Note that the size of a float varies depending on the architecture, so it probably best to avoid using magic numbers like 9e999, even if that is likely to work.

import sys
sys.float_info
sys.float_info(max=1.7976931348623157e+308,
               max_exp=1024, max_10_exp=308,
               min=2.2250738585072014e-308, min_exp=-1021,
               min_10_exp=-307, dig=15, mant_dig=53,
               epsilon=2.220446049250313e-16, radix=2, rounds=1)

How can I make a JUnit test wait?

You could also use the CountDownLatch object like explained here.

how to make a new line in a jupyter markdown cell

"We usually put ' (space)' after the first sentence before a new line, but it doesn't work in Jupyter."

That inspired me to try using two spaces instead of just one - and it worked!!

(Of course, that functionality could possibly have been introduced between when the question was asked in January 2017, and when my answer was posted in March 2018.)

Laravel: getting a a single value from a MySQL query

Using query builder, get the single column value such as groupName

  $groupName = DB::table('users')->where('username', $username)->pluck('groupName');

For Laravel 5.1

 $groupName=DB::table('users')->where('username', $username)->value('groupName');

Or, Using user model, get the single column value

 $groupName = User::where('username', $username)->pluck('groupName');

Or, get the first row and then split for getting single column value

 $data = User::where('username', $username)->first();
 if($data)
   $groupName=$data->groupName;

Assign a variable inside a Block to a variable outside a Block

To assign a variable inside block which outside of block always use __block specifier before that variable your code should be like this:-

__block Person *aPerson = nil;

Download and save PDF file with Python requests module

You should use response.content in this case:

with open('/tmp/metadata.pdf', 'wb') as f:
    f.write(response.content)

From the document:

You can also access the response body as bytes, for non-text requests:

>>> r.content
b'[{"repository":{"open_issues":0,"url":"https://github.com/...

So that means: response.text return the output as a string object, use it when you're downloading a text file. Such as HTML file, etc.

And response.content return the output as bytes object, use it when you're downloading a binary file. Such as PDF file, audio file, image, etc.


You can also use response.raw instead. However, use it when the file which you're about to download is large. Below is a basic example which you can also find in the document:

import requests

url = 'http://www.hrecos.org//images/Data/forweb/HRTVBSH.Metadata.pdf'
r = requests.get(url, stream=True)

with open('/tmp/metadata.pdf', 'wb') as fd:
    for chunk in r.iter_content(chunk_size):
        fd.write(chunk)

chunk_size is the chunk size which you want to use. If you set it as 2000, then requests will download that file the first 2000 bytes, write them into the file, and do this again, again and again, unless it finished.

So this can save your RAM. But I'd prefer use response.content instead in this case since your file is small. As you can see use response.raw is complex.


Relates:

pros and cons between os.path.exists vs os.path.isdir

Most of the time, it is the same.

But, path can exist physically whereas path.exists() returns False. This is the case if os.stat() returns False for this file.

If path exists physically, then path.isdir() will always return True. This does not depend on platform.

Call Activity method from adapter

Yes you can.

In the adapter Add a new Field :

private Context mContext;

In the adapter Constructor add the following code :

public AdapterName(......, Context context) {
  //your code.
  this.mContext = context;
}

In the getView(...) of Adapter:

Button btn = (Button) convertView.findViewById(yourButtonId);
btn.setOnClickListener(new Button.OnClickListener() {
  @Override
  public void onClick(View v) {
    if (mContext instanceof YourActivityName) {
      ((YourActivityName)mContext).yourDesiredMethod();
    }
  }
});

replace with your own class names where you see your code, your activity etc.

If you need to use this same adapter for more than one activity then :

Create an Interface

public interface IMethodCaller {
    void yourDesiredMethod();
}

Implement this interface in activities you require to have this method calling functionality.

Then in Adapter getView(), call like:

Button btn = (Button) convertView.findViewById(yourButtonId);
btn.setOnClickListener(new Button.OnClickListener() {
    @Override
    public void onClick(View v) {
        if (mContext instanceof IMethodCaller) {
            ((IMethodCaller) mContext).yourDesiredMethod();
        }
    }
});

You are done. If you need to use this adapter for activities which does not require this calling mechanism, the code will not execute (If check fails).

delete map[key] in go?

delete(sessions, "anykey")

These days, nothing will crash.

Adding value labels on a matplotlib bar chart

Building off the above (great!) answer, we can also make a horizontal bar plot with just a few adjustments:

# Bring some raw data.
frequencies = [6, -16, 75, 160, 244, 260, 145, 73, 16, 4, 1]

freq_series = pd.Series(frequencies)

y_labels = [108300.0, 110540.0, 112780.0, 115020.0, 117260.0, 119500.0, 
            121740.0, 123980.0, 126220.0, 128460.0, 130700.0]

# Plot the figure.
plt.figure(figsize=(12, 8))
ax = freq_series.plot(kind='barh')
ax.set_title('Amount Frequency')
ax.set_xlabel('Frequency')
ax.set_ylabel('Amount ($)')
ax.set_yticklabels(y_labels)
ax.set_xlim(-40, 300) # expand xlim to make labels easier to read

rects = ax.patches

# For each bar: Place a label
for rect in rects:
    # Get X and Y placement of label from rect.
    x_value = rect.get_width()
    y_value = rect.get_y() + rect.get_height() / 2

    # Number of points between bar and label. Change to your liking.
    space = 5
    # Vertical alignment for positive values
    ha = 'left'

    # If value of bar is negative: Place label left of bar
    if x_value < 0:
        # Invert space to place label to the left
        space *= -1
        # Horizontally align label at right
        ha = 'right'

    # Use X value as label and format number with one decimal place
    label = "{:.1f}".format(x_value)

    # Create annotation
    plt.annotate(
        label,                      # Use `label` as label
        (x_value, y_value),         # Place label at end of the bar
        xytext=(space, 0),          # Horizontally shift label by `space`
        textcoords="offset points", # Interpret `xytext` as offset in points
        va='center',                # Vertically center label
        ha=ha)                      # Horizontally align label differently for
                                    # positive and negative values.

plt.savefig("image.png")

horizontal bar plot with annotations

JPA eager fetch does not join

to join you can do multiple things (using eclipselink)

  • in jpql you can do left join fetch

  • in named query you can specify query hint

  • in TypedQuery you can say something like

    query.setHint("eclipselink.join-fetch", "e.projects.milestones");

  • there is also batch fetch hint

    query.setHint("eclipselink.batch", "e.address");

see

http://java-persistence-performance.blogspot.com/2010/08/batch-fetching-optimizing-object-graph.html

How to convert datetime to timestamp using C#/.NET (ignoring current timezone)

Find timestamp from DateTime:

private long ConvertToTimestamp(DateTime value)
{
    TimeZoneInfo NYTimeZone = TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time");
    DateTime NyTime = TimeZoneInfo.ConvertTime(value, NYTimeZone);
    TimeZone localZone = TimeZone.CurrentTimeZone;
    System.Globalization.DaylightTime dst = localZone.GetDaylightChanges(NyTime.Year);
    NyTime = NyTime.AddHours(-1);
    DateTime epoch = new DateTime(1970, 1, 1, 0, 0, 0, 0).ToLocalTime();
    TimeSpan span = (NyTime - epoch);
    return (long)Convert.ToDouble(span.TotalSeconds);
}

How to tag an older commit in Git?

Building upon the answers of the others, here is a one-liner solution that sets the tag date to when it actually happened, uses annotated tag and requires no git checkout:

tag="v0.1.3" commit="8f33a878" bash -c 'GIT_COMMITTER_DATE="$(git show --format=%aD $commit)" git tag -a $tag -m $tag $commit'
git push --tags origin master

where tag is set to the desired tag string, and commit to the commit hash.

How can I create a temp file with a specific extension with .NET?

How about:

Path.Combine(Path.GetTempPath(), DateTime.Now.Ticks.ToString() + "_" + Guid.NewGuid().ToString() + ".csv")

It is highly improbable that the computer will generate the same Guid at the same instant of time. The only weakness i see here is the performance impact DateTime.Now.Ticks will add.

Float and double datatype in Java

This example illustrates how to extract the sign (the leftmost bit), exponent (the 8 following bits) and mantissa (the 23 rightmost bits) from a float in Java.

int bits = Float.floatToIntBits(-0.005f);
int sign = bits >>> 31;
int exp = (bits >>> 23 & ((1 << 8) - 1)) - ((1 << 7) - 1);
int mantissa = bits & ((1 << 23) - 1);
System.out.println(sign + " " + exp + " " + mantissa + " " +
  Float.intBitsToFloat((sign << 31) | (exp + ((1 << 7) - 1)) << 23 | mantissa));

The same approach can be used for double’s (11 bit exponent and 52 bit mantissa).

long bits = Double.doubleToLongBits(-0.005);
long sign = bits >>> 63;
long exp = (bits >>> 52 & ((1 << 11) - 1)) - ((1 << 10) - 1);
long mantissa = bits & ((1L << 52) - 1);
System.out.println(sign + " " + exp + " " + mantissa + " " +
  Double.longBitsToDouble((sign << 63) | (exp + ((1 << 10) - 1)) << 52 | mantissa));

Credit: http://s-j.github.io/java-float/

Why use $_SERVER['PHP_SELF'] instead of ""

When you insert ANY variable into HTML, unless you want the browser to interpret the variable itself as HTML, it's best to use htmlspecialchars() on it. Among other things, it prevents hackers from inserting arbitrary HTML in your page.

The value of $_SERVER['PHP_SELF'] is taken directly from the URL entered in the browser. Therefore if you use it without htmlspecialchars(), you're allowing hackers to directly manipulate the output of your code.

For example, if I e-mail you a link to http://example.com/"><script>malicious_code_here()</script><span class=" and you have <form action="<?php echo $_SERVER['PHP_SELF'] ?>">, the output will be:

<form action="http://example.com/"><script>malicious_code_here()</script><span class="">

My script will run, and you will be none the wiser. If you were logged in, I may have stolen your cookies, or scraped confidential info from your page.

However, if you used <form action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']) ?>">, the output would be:

<form action="http://example.com/&quot;&gt;&lt;script&gt;cookie_stealing_code()&lt;/script&gt;&lt;span class=&quot;">

When you submitted the form, you'd have a weird URL, but at least my evil script did not run.

On the other hand, if you used <form action="">, then the output would be the same no matter what I added to my link. This is the option I would recommend.

Using multiple delimiters in awk

I see many perfect answers are up on the board, but still would like to upload my piece of code too,

awk -F"/" '{print $3 " " $5 " " $7}' sam | sed 's/ cat.* =//g'

ValueError: invalid literal for int () with base 10

As Lattyware said, there is a difference between Python2 & Python3 that leads to this error:

With Python2, int(str(5/2)) gives you 2. With Python3, the same gives you: ValueError: invalid literal for int() with base 10: '2.5'

If you need to convert some string that could contain float instead of int, you should always use the following ugly formula:

int(float(myStr))

As float('3.0') and float('3') give you 3.0, but int('3.0') gives you the error.

Getting results between two dates in PostgreSQL

You have to use the date part fetching method:

SELECT * FROM testbed WHERE start_date  ::date >= to_date('2012-09-08' ,'YYYY-MM-DD') and date::date <= to_date('2012-10-09' ,'YYYY-MM-DD')

What does 'x packages are looking for funding' mean when running `npm install`?

You can skip fund using:

npm install --no-fund YOUR PACKAGE NAME

For example :

npm install --no-fund core-js

Return HTML content as a string, given URL. Javascript Function

In some websites, XMLHttpRequest may send you something like <script src="#"></srcipt>. In that case, try using a HTML document like the script under:

<html>
  <body>
    <iframe src="website.com"></iframe>
    <script src="your_JS"></script>
  </body>
</html>

Now you can use JS to get some text out of the HTML, such as getElementbyId.

But this may not work for some websites with cross-domain blocking.

Change select box option background color

If you really want to style the within a , consider switching to a Javascript/CSS based drop down such as http://getbootstrap.com/2.3.2/components.html#dropdowns or https://silviomoreto.github.io/bootstrap-select/examples/. This because browsers such as IE do not allow styling of options within elements. Chrome/OSX also has this problem - you cannot style options.

However a warning is attached to that approach. These types of menus work very differently on mobile platforms because native elements aren't used. They can have annoying quirks on desktop as well. My advice is 1) don't write your own and 2) find a library that's been really well tested.

Detecting real time window size changes in Angular 4

If you'd like you components to remain easily testable you should wrap the global window object in an Angular Service:

import { Injectable } from '@angular/core';

@Injectable()
export class WindowService {

  get windowRef() {
    return window;
  }

}

You can then inject it like any other service:

constructor(
    private windowService: WindowService
) { }

And consume...

  ngOnInit() {
      const width= this.windowService.windowRef.innerWidth;
  }

How to declare a vector of zeros in R

You have several options

integer(3)
numeric(3)
rep(0, 3)
rep(0L, 3)

Should I use Vagrant or Docker for creating an isolated environment?

With Vagrant now you can have Docker as a provider. http://docs.vagrantup.com/v2/docker/. Docker provider can be used instead of VirtualBox or VMware.

Please note that you can also use Docker for provisioning with Vagrant. This is very different than using Docker as a provider. http://docs.vagrantup.com/v2/provisioning/docker.html

This means you can replace Chef or Puppet with Docker. You can use combinations like Docker as provider (VM) with Chef as provisioner. Or you can use VirtualBox as provider and Docker as provisioner.

How to get margin value of a div in plain JavaScript?

Also, you can create your own outerHeight for HTML elements. I don't know if it works in IE, but it works in Chrome. Perhaps, you can enhance the code below using currentStyle, suggested in the answer above.

Object.defineProperty(Element.prototype, 'outerHeight', {
    'get': function(){
        var height = this.clientHeight;
        var computedStyle = window.getComputedStyle(this); 
        height += parseInt(computedStyle.marginTop, 10);
        height += parseInt(computedStyle.marginBottom, 10);
        height += parseInt(computedStyle.borderTopWidth, 10);
        height += parseInt(computedStyle.borderBottomWidth, 10);
        return height;
    }
});

This piece of code allow you to do something like this:

document.getElementById('foo').outerHeight

According to caniuse.com, getComputedStyle is supported by main browsers (IE, Chrome, Firefox).

Bootstrap 3 with remote Modal

Regarding the remote option for modals, from the docs:

If a remote URL is provided, content will be loaded via jQuery's load method and injected into the root of the modal element.

That means your remote file should provide the complete modal structure, not just what you want to display on the body.

Bootstrap 3.1 Update:

In v3.1 the above behavior was changed and now the remote content is loaded into .modal-content

See this Demo fiddle

Boostrap 3.3 Update:

This option is deprecated since v3.3.0 and has been removed in v4. We recommend instead using client-side templating or a data binding framework, or calling jQuery.load yourself.

VIM Disable Automatic Newline At End Of File

Add the following command to your .vimrc to turn of the end-of-line option:

autocmd FileType php setlocal noeol binary fileformat=dos

However, PHP itself will ignore that last end-of-line - it shouldn't be an issue. I am almost certain that in your case there is something else which is adding the last newline character, or possibly there is a mixup with windows/unix line ending types (\n or \r\n, etc).

Update:

An alternative solution might be to just add this line to your .vimrc:

set fileformats+=dos

How to break out from foreach loop in javascript

Use a for loop instead of .forEach()

var myObj = [{"a": "1","b": null},{"a": "2","b": 5}]
var result = false

for(var call of myObj) {
    console.log(call)
    
    var a = call['a'], b = call['b']
     
    if(a == null || b == null) {
        result = false
        break
    }
}

IBOutlet and IBAction

An Outlet is a link from code to UI. If you want to show or hide an UI element, if you want to get the text of a textfield or enable or disable an element (or a hundred other things) you have to define an outlet of that object in the sources and link that outlet through the “interface object” to the UI element. After that you can use the outlet just like any other variable in your coding.

IBAction – a special method triggered by user-interface objects. Interface Builder recognizes them.

@interface Controller
{
  IBOutlet id textField; // links to TextField UI object
}

- (IBAction)doAction:(id)sender; // e.g. called when button pushed

For further information please refer Apple Docs

Lambda function in list comprehensions

The first one

f = lambda x: x*x
[f(x) for x in range(10)]

runs f() for each value in the range so it does f(x) for each value

the second one

[lambda x: x*x for x in range(10)]

runs the lambda for each value in the list, so it generates all of those functions.

How do I get the file name from a String containing the Absolute file path?

You can use FileInfo object to get all information of your file.

    FileInfo f = new FileInfo(@"C:\Hello\AnotherFolder\The File Name.PDF");
    MessageBox.Show(f.Name);
    MessageBox.Show(f.FullName);
    MessageBox.Show(f.Extension );
    MessageBox.Show(f.DirectoryName);

syntaxerror: unexpected character after line continuation character in python

You need to quote that filename:

f = open("D\\python\\HW\\2_1 - Copy.cp", "r")

Otherwise the bare backslash after the D is interpreted as a line-continuation character, and should be followed by a newline. This is used to extend long expressions over multiple lines, for readability:

print "This is a long",\
      "line of text",\
      "that I'm printing."

Also, you shouldn't have semicolons (;) at the end of your statements in Python.

Clearing an input text field in Angular2

HTML

<input type="text" [(ngModel)]="obj.mobile" name="mobile" id="mobile" class="form-control" placeholder="Mobile/E-mail" />

TS

onClickClear(){
   this.obj.mobile= undefined;
}

How to send a POST request with BODY in swift

Here is how I created Http POST request with swift that needs parameters with Json encoding and with headers.

Created API Client BKCAPIClient as a shared instance which will include all types of requests such as POST, GET, PUT, DELETE etc.

func postRequest(url:String, params:Parameters?, headers:HTTPHeaders?, completion:@escaping (_ responseData:Result<Any>?, _ error:Error?)->Void){
    Alamofire.request(url, method: .post, parameters: params, encoding: JSONEncoding.default, headers: headers).responseJSON {
        response in
        guard response.result.isSuccess,
            (response.result.value != nil) else {
                debugPrint("Error while fetching data: \(String(describing: response.result.error))")
                completion(nil,response.result.error)
                return
        }
        completion(response.result,nil)
    }
}

Created Operation class that contains all data needed for particular request and also contains parsing logic inside completion block.

func requestAccountOperation(completion: @escaping ( (_ result:Any?, _ error:Error?) -> Void)){
    BKCApiClient.shared.postRequest(url: BKCConstants().bkcUrl, params: self.parametrs(), headers: self.headers()) { (result, error) in
        if(error != nil){
            //Parse and save to DB/Singletons.
        }
        completion(result, error)
    }
}
func parametrs()->Parameters{
    return ["userid”:”xnmtyrdx”,”bcode":"HDF"] as Parameters
}
func headers()->HTTPHeaders{
    return ["Authorization": "Basic bXl1c2VyOm15cGFzcw",
            "Content-Type": "application/json"] as HTTPHeaders
}

Call API In any View Controller where we need this data

func callToAPIOperation(){
let accOperation: AccountRequestOperation = AccountRequestOperation()
accOperation.requestAccountOperation{(result, error) in

}}

How to format a floating number to fixed width in Python

This will print 76.66:

print("Number: ", f"{76.663254: .2f}")

Python, how to check if a result set is empty?

I had issues with rowcount always returning -1 no matter what solution I tried.

I found the following a good replacement to check for a null result.

c.execute("SELECT * FROM users WHERE id=?", (id_num,))
row = c.fetchone()
if row == None:
   print("There are no results for this query")

Adding up BigDecimals using Streams

If you don't mind a third party dependency, there is a class named Collectors2 in Eclipse Collections which contains methods returning Collectors for summing and summarizing BigDecimal and BigInteger. These methods take a Function as a parameter so you can extract a BigDecimal or BigInteger value from an object.

List<BigDecimal> list = mList(
        BigDecimal.valueOf(0.1),
        BigDecimal.valueOf(1.1),
        BigDecimal.valueOf(2.1),
        BigDecimal.valueOf(0.1));

BigDecimal sum =
        list.stream().collect(Collectors2.summingBigDecimal(e -> e));
Assert.assertEquals(BigDecimal.valueOf(3.4), sum);

BigDecimalSummaryStatistics statistics =
        list.stream().collect(Collectors2.summarizingBigDecimal(e -> e));
Assert.assertEquals(BigDecimal.valueOf(3.4), statistics.getSum());
Assert.assertEquals(BigDecimal.valueOf(0.1), statistics.getMin());
Assert.assertEquals(BigDecimal.valueOf(2.1), statistics.getMax());
Assert.assertEquals(BigDecimal.valueOf(0.85), statistics.getAverage());

Note: I am a committer for Eclipse Collections.

saving a file (from stream) to disk using c#

I have to quote Jon (the master of c#) Skeet:

Well, the easiest way would be to open a file stream and then use:

byte[] data = memoryStream.ToArray(); fileStream.Write(data, 0, data.Length);

That's relatively inefficient though, as it involves copying the buffer. It's fine for small streams, but for huge amounts of data you should consider using:

fileStream.Write(memoryStream.GetBuffer(), 0, memoryStream.Position);

Java 6 Unsupported major.minor version 51.0

add jdk8 or higher version at JAVA_HOME and path.

add JAVA_HOME add C:\ProgramFiles\Java\jdk1.8.0_201

For Path =>

add %MAVEN_HOME%\bin

and finally restart your pc.

How to exclude particular class name in CSS selector?

One way is to use the multiple class selector (no space as that is the descendant selector):

_x000D_
_x000D_
.reMode_hover:not(.reMode_selected):hover _x000D_
{_x000D_
   background-color: #f0ac00;_x000D_
}
_x000D_
<a href="" title="Design" class="reMode_design  reMode_hover">_x000D_
    <span>Design</span>_x000D_
</a>_x000D_
_x000D_
<a href="" title="Design" _x000D_
 class="reMode_design  reMode_hover reMode_selected">_x000D_
    <span>Design</span>_x000D_
</a>
_x000D_
_x000D_
_x000D_

laravel the requested url was not found on this server

I have faced the same problem in cPanel and I fixed my problem to add in .htaccess file below these line

# Handle Front Controller...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]

How do I find out which process is locking a file using .NET?

This works for DLLs locked by other processes. This routine will not find out for example that a text file is locked by a word process.

C#:

using System.Management; 
using System.IO;   

static class Module1 
{ 
static internal ArrayList myProcessArray = new ArrayList(); 
private static Process myProcess; 

public static void Main() 
{ 

    string strFile = "c:\\windows\\system32\\msi.dll"; 
    ArrayList a = getFileProcesses(strFile); 
    foreach (Process p in a) { 
        Debug.Print(p.ProcessName); 
    } 
} 


private static ArrayList getFileProcesses(string strFile) 
{ 
    myProcessArray.Clear(); 
    Process[] processes = Process.GetProcesses; 
    int i = 0; 
    for (i = 0; i <= processes.GetUpperBound(0) - 1; i++) { 
        myProcess = processes(i); 
        if (!myProcess.HasExited) { 
            try { 
                ProcessModuleCollection modules = myProcess.Modules; 
                int j = 0; 
                for (j = 0; j <= modules.Count - 1; j++) { 
                    if ((modules.Item(j).FileName.ToLower.CompareTo(strFile.ToLower) == 0)) { 
                        myProcessArray.Add(myProcess); 
                        break; // TODO: might not be correct. Was : Exit For 
                    } 
                } 
            } 
            catch (Exception exception) { 
            } 
            //MsgBox(("Error : " & exception.Message)) 
        } 
    } 
    return myProcessArray; 
} 
} 

VB.Net:

Imports System.Management
Imports System.IO

Module Module1
Friend myProcessArray As New ArrayList
Private myProcess As Process

Sub Main()

    Dim strFile As String = "c:\windows\system32\msi.dll"
    Dim a As ArrayList = getFileProcesses(strFile)
    For Each p As Process In a
        Debug.Print(p.ProcessName)
    Next
End Sub


Private Function getFileProcesses(ByVal strFile As String) As ArrayList
    myProcessArray.Clear()
    Dim processes As Process() = Process.GetProcesses
    Dim i As Integer
    For i = 0 To processes.GetUpperBound(0) - 1
        myProcess = processes(i)
        If Not myProcess.HasExited Then
            Try
                Dim modules As ProcessModuleCollection = myProcess.Modules
                Dim j As Integer
                For j = 0 To modules.Count - 1
                    If (modules.Item(j).FileName.ToLower.CompareTo(strFile.ToLower) = 0) Then
                        myProcessArray.Add(myProcess)
                        Exit For
                    End If
                Next j
            Catch exception As Exception
                'MsgBox(("Error : " & exception.Message))
            End Try
        End If
    Next i
    Return myProcessArray
End Function
End Module

Change color and appearance of drop down arrow

Not easily done I am afraid. The problem is Css cannot replace the arrow in a select as this is rendered by the browser. But you can build a new control from div and input elements and Javascript to perform the same function as the select.

Try looking at some of the autocomplete plugins for Jquery for example.

Otherwise there is some info on the select element here:

http://www.devarticles.com/c/a/Web-Style-Sheets/Taming-the-Select/

angularjs make a simple countdown

var timer_seconds_counter = 120;
$scope.countDown = function() {
      timer_seconds_counter--;
      timer_object = $timeout($scope.countDown, 1000);
      $scope.timer = parseInt(timer_seconds_counter / 60) ? parseInt(timer_seconds_counter / 60) : '00';
      if ((timer_seconds_counter % 60) < 10) {
        $scope.timer += ':' + ((timer_seconds_counter % 60) ? '0' + (timer_seconds_counter % 60) : '00');
      } else {
        $scope.timer += ':' + ((timer_seconds_counter % 60) ? (timer_seconds_counter % 60) : '00');
      }
      $scope.timer += ' minutes'
      if (timer_seconds_counter === 0) {
        timer_seconds_counter = 30;
        $timeout.cancel(timer_object);
        $scope.timer = '2:00 minutes';
      }
    }

How to pass a variable from Activity to Fragment, and pass it back?

Public variable declarations in classes is the easiest way:

On target class:

public class MyFragment extends Fragment {
    public MyCallerFragment caller; // Declare the caller var
...
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
           Bundle savedInstanceState) {
        // Do what you want with the vars
        caller.str = "I changed your value!";
        caller.i = 9999;
        ...
        return inflater.inflate(R.layout.my_fragment, container, false);
    }
...
}

On caller class:

public class MyCallerFragment extends Fragment {
    public Integer i; // Declared public var
    public String str; // Declared public var
        ...
            FragmentManager fragmentManager = getParentFragmentManager();
            FragmentTransaction transaction = fragmentManager.beginTransaction();

            myFragment = new MyFragment();
            myFragment.caller = this;
            transaction.replace(R.id.nav_host_fragment, myFragment)
                    .addToBackStack(null).commit();
        ...
}

If you want to use the main activity it is easy too:

On main activity class:

public class MainActivity extends AppCompatActivity {
    public String str; // Declare public var
    public EditText myEditText; // You can declare public elements too.
                                // Taking care that you have it assigned
                                // correctly.
...
}

On called class:

public class MyFragment extends Fragment {
    private MainActivity main; // Declare the activity var
...
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
           Bundle savedInstanceState) {
        // Assign the main activity var
        main = (MainActivity) getActivity();

        // Do what you want with the vars
        main.str = "I changed your value!";
        main.myEditText.setText("Wow I can modify the EditText too!");
        ...
        return inflater.inflate(R.layout.my_fragment, container, false);
    }
...
}

Note: Take care when using events (onClick, onChanged, etc) because you can be on a "fighting" situation where more than one assign a variable. The result will be that the variable sometimes does not will change or will return to the last value magically.

For more combinations use your creativity. :)

Return string Input with parse.string

You don't need to parse the string, it's defined as a string already.

Just do:

    private static String getStringInput (String prompt) {
     String input = EZJ.getUserInput(prompt);
     return input;
    }

Install sbt on ubuntu

The simplest way of installing SBT on ubuntu is the deb package provided by Typesafe.

Run the following shell commands:

  1. wget http://apt.typesafe.com/repo-deb-build-0002.deb
  2. sudo dpkg -i repo-deb-build-0002.deb
  3. sudo apt-get update
  4. sudo apt-get install sbt

And you're done !

Should C# or C++ be chosen for learning Games Programming (consoles)?

I think that C++.

Because c# needs additional instalation for C# runtime which only absorbs space on a disk. And C# is of course a bit slower.

Webview load html from assets directory

Download source code from here (Open html file from assets android)

activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:layout_width="match_parent"
 android:background="#FFFFFF"
 android:layout_height="match_parent">

<WebView
 android:layout_width="match_parent"
 android:id="@+id/webview"
 android:layout_height="match_parent"
 android:layout_margin="10dp"></WebView>
</RelativeLayout>

MainActivity.java

package com.deepshikha.htmlfromassets;
 import android.app.ProgressDialog;
 import android.support.v7.app.AppCompatActivity;
 import android.os.Bundle;
 import android.webkit.WebView;
 import android.webkit.WebViewClient;

public class MainActivity extends AppCompatActivity {

WebView webview;
 ProgressDialog progressDialog;

@Override
 protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_main);
 init();
 }

private void init(){
 webview = (WebView)findViewById(R.id.webview);
 webview.loadUrl("file:///android_asset/download.html");
 webview.requestFocus();

progressDialog = new ProgressDialog(MainActivity.this);
 progressDialog.setMessage("Loading");
 progressDialog.setCancelable(false);
 progressDialog.show();

webview.setWebViewClient(new WebViewClient() {

public void onPageFinished(WebView view, String url) {
 try {
 progressDialog.dismiss();
 } catch (Exception e) {
 e.printStackTrace();
 }
 }
 });
 }
 }

mvn command not found in OSX Mavrerick

Here is what worked for me.

First of all I checked if M2_HOME variable is set env | grep M2_HOME. I've got nothing.

I knew I had Maven installed in the folder "/usr/local/apache-maven-3.2.2", so executing the following 3 steps solved the problem for me:

  1. Set M2_HOME env variable

M2_HOME=/usr/local/apache-maven-3.2.2

  1. Set M2 env variable

M2=$M2_HOME/bin

  1. Update the PATH

export PATH=$M2:$PATH

As mentioned above you can save that sequence in the .bash_profile file if you want it to be executed automatically.

Extract a part of the filepath (a directory) in Python

import os

directory = os.path.abspath('\\') # root directory
print(directory) # e.g. 'C:\'

directory = os.path.abspath('.') # current directory
print(directory) # e.g. 'C:\Users\User\Desktop'

parent_directory, directory_name = os.path.split(directory)
print(directory_name) # e.g. 'Desktop'
parent_parent_directory, parent_directory_name = os.path.split(parent_directory)
print(parent_directory_name) # e.g. 'User'

This should also do the trick.

What does the "at" (@) symbol do in Python?

If you are referring to some code in a python notebook which is using Numpy library, then @ operator means Matrix Multiplication. For example:

import numpy as np
def forward(xi, W1, b1, W2, b2):
    z1 = W1 @ xi + b1
    a1 = sigma(z1)
    z2 = W2 @ a1 + b2
    return z2, a1

What is difference between monolithic and micro kernel?

In the spectrum of kernel designs the two extreme points are monolithic kernels and microkernels.

The (classical) Linux kernel for instance is a monolithic kernel (and so is every commercial OS to date as well - though they might claim otherwise);

In that its code is a single C file giving rise to a single process that implements all of the above services.
To exemplify the encapsulation of the Linux kernel we remark that the Linux kernel does not even have access to any of the standard C libraries. Indeed the Linux kernel cannot use rudimentary C library functions such as printf. Instead it implements its own printing function (called prints).

This seclusion of the Linux kernel and self-containment provide Linux kernel with its main advantage: the kernel resides in a single address space1 enabling all features to communicate in the fastest way possible without resorting to any type of message passing. In particular, a monolithic kernel implements all of the device drivers of the system.

This however is the main drawback of a monolithic kernel: introduction of any new unsupported hardware requires a rewrite of the kernel (in the relevant parts), recompilation of it, and re-installing the entire OS.
More importantly, if any device driver crashes the entire kernel suffers as a result. This un-modular approach to hardware additions and hardware crashes is the main argument for supporting the other extreme design approach for kernels. A microkernel is in a sense a minimalistic kernel that houses only the very basic of OS services (like process management and file system management). In a microkernel the device drivers lie outside of the kernel allowing for addition and removal of device drivers while the OS is running and require no alternations of the kernel.

Is there any way to call a function periodically in JavaScript?

Since you want the function to be executed periodically, use setInterval

How do I use variables in Oracle SQL Developer?

In sql developer define properties by default "ON". If it is "OFF" any case, use below steps.

set define on; define batchNo='123'; update TABLE_NAME SET IND1 = 'Y', IND2 = 'Y' WHERE BATCH_NO = '&batchNo';

Git push error: Unable to unlink old (Permission denied)

sudo chmod -R ug+w .;

This command would fix the issue. It gives write permissions to the folder.

Permission denied when launch python script via bash

I'm a Ubuntu user and I had the same issue, when I was trying to run python script through a bash script while files were located in a NTFS partition (even with su didn't work) then I've moved it home (ext4) then it worked.

How could I use requests in asyncio?

Requests does not currently support asyncio and there are no plans to provide such support. It's likely that you could implement a custom "Transport Adapter" (as discussed here) that knows how to use asyncio.

If I find myself with some time it's something I might actually look into, but I can't promise anything.

How do I change TextView Value inside Java Code?

First we need to find a Button:

Button mButton = (Button) findViewById(R.id.my_button);

After that, you must implement View.OnClickListener and there you should find the TextView and execute the method setText:

mButton.setOnClickListener(new View.OnClickListener {
    public void onClick(View v) {
        final TextView mTextView = (TextView) findViewById(R.id.my_text_view);
        mTextView.setText("Some Text");
    }
});

Displaying a 3D model in JavaScript/HTML5

I have not played with 3D yet, but I know a good place for ressources on 3D for HTML5.

http://www.html5rocks.com/en/gaming

And here is a tutorial on how to create your 3D models with the Three.js Framework.

http://www.html5rocks.com/en/tutorials/three/intro/

This may help you. Good luck.

What's wrong with nullable columns in composite primary keys?

NULL == NULL -> false (at least in DBMSs)

So you wouldn't be able to retrieve any relationships using a NULL value even with additional columns with real values.

How to pass the button value into my onclick event function?

You can do like this.

<input type="button" value="mybutton1" onclick="dosomething(this)">

function dosomething(element){
    alert("value is "+element.value); //you can print any value like id,class,value,innerHTML etc.
};

How do I fix "Expected to return a value at the end of arrow function" warning?

A map() creates an array, so a return is expected for all code paths (if/elses).

If you don't want an array or to return data, use forEach instead.

How/when to generate Gradle wrapper files?

This is the command to use to tell Gradle to upgrade the wrapper such that it will grab the distribution versions of libraries that includes source code:

./gradlew wrapper --gradle-version <version> --distribution-type all

Specifying the distribution-type with "all" will make sure Gradle downloads source files for use by your development environment.

Pros:

  • IDEs will have immediate access to source code. For example, Intellij IDEA won't prompt you to update your build scripts to include the source distro (because this command already did that)

Cons:

  • Longer/Bigger build process because it's downloading source code. This is a waste of time/space on a build or CI server where the source code is not necessary.

Please comment or provide another answer if you know of any command line option to tell Gradle not to download sources on a build server.

Maven dependency for Servlet 3.0 API?

Just for newcomers.

<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>3.1.0</version>
    <scope>provided</scope>
</dependency>

Inserting multiple rows in a single SQL query?

If you are inserting into a single table, you can write your query like this (maybe only in MySQL):

INSERT INTO table1 (First, Last)
VALUES
    ('Fred', 'Smith'),
    ('John', 'Smith'),
    ('Michael', 'Smith'),
    ('Robert', 'Smith');

Is it possible to serialize and deserialize a class in C++?

I recommend using boost serialization as described by other posters. Here is a good detailed tutorial on how to use it which complements the boost tutorials nicely: http://www.ocoudert.com/blog/2011/07/09/a-practical-guide-to-c-serialization/

Log4j: How to configure simplest possible file logging?

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">

<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/" debug="false">

   <appender name="fileAppender" class="org.apache.log4j.RollingFileAppender">
      <param name="Threshold" value="INFO" />
      <param name="File" value="sample.log"/>
      <layout class="org.apache.log4j.PatternLayout">
         <param name="ConversionPattern" value="%d %-5p  [%c{1}] %m %n" />
      </layout>
   </appender>

  <root> 
    <priority value ="debug" /> 
    <appender-ref ref="fileAppender" /> 
  </root> 

</log4j:configuration>

Log4j can be a bit confusing. So lets try to understand what is going on in this file: In log4j you have two basic constructs appenders and loggers.

Appenders define how and where things are appended. Will it be logged to a file, to the console, to a database, etc.? In this case you are specifying that log statements directed to fileAppender will be put in the file sample.log using the pattern specified in the layout tags. You could just as easily create a appender for the console or the database. Where the console appender would specify things like the layout on the screen and the database appender would have connection details and table names.

Loggers respond to logging events as they bubble up. If an event catches the interest of a specific logger it will invoke its attached appenders. In the example below you have only one logger the root logger - which responds to all logging events by default. In addition to the root logger you can specify more specific loggers that respond to events from specific packages. These loggers can have their own appenders specified using the appender-ref tags or will otherwise inherit the appenders from the root logger. Using more specific loggers allows you to fine tune the logging level on specific packages or to direct certain packages to other appenders.

So what this file is saying is:

  1. Create a fileAppender that logs to file sample.log
  2. Attach that appender to the root logger.
  3. The root logger will respond to any events at least as detailed as 'debug' level
  4. The appender is configured to only log events that are at least as detailed as 'info'

The net out is that if you have a logger.debug("blah blah") in your code it will get ignored. A logger.info("Blah blah"); will output to sample.log.

The snippet below could be added to the file above with the log4j tags. This logger would inherit the appenders from <root> but would limit the all logging events from the package org.springframework to those logged at level info or above.

  <!-- Example Package level Logger -->
    <logger name="org.springframework">
        <level value="info"/>
    </logger>   

convert big endian to little endian in C [without using provided func]

Here's a fairly generic version; I haven't compiled it, so there are probably typos, but you should get the idea,

void SwapBytes(void *pv, size_t n)
{
    assert(n > 0);

    char *p = pv;
    size_t lo, hi;
    for(lo=0, hi=n-1; hi>lo; lo++, hi--)
    {
        char tmp=p[lo];
        p[lo] = p[hi];
        p[hi] = tmp;
    }
}
#define SWAP(x) SwapBytes(&x, sizeof(x));

NB: This is not optimised for speed or space. It is intended to be clear (easy to debug) and portable.

Update 2018-04-04 Added the assert() to trap the invalid case of n == 0, as spotted by commenter @chux.

How do you force Visual Studio to regenerate the .designer files for aspx/ascx files?

Just to add to the long list of answers here - I've just run into this issue in VS2010 (SP1) with an .aspx file. I tried adding and removing standard ASP controls (which has worked in the past) but in the end, I had to remove one of the runat=server lines from an existing control (and save) to force the designer file to regenerate.

ARM compilation error, VFP registers used by executable, not object file

I have found on an arm hardfloat system where glibc binutils and gcc were crosscompiled, using gcc gives the same error.

It is solved by exporting-mfloat-abi=hard to flags, then gcc compiles without errors.

Fastest way of finding differences between two files in unix?

You could also try to include md5-hash-sums or similar do determine whether there are any differences at all. Then, only compare files which have different hashes...

Loop through files in a directory using PowerShell

Other answers are great, I just want to add... a different approach usable in PowerShell: Install GNUWin32 utils and use grep to view the lines / redirect the output to file http://gnuwin32.sourceforge.net/

This overwrites the new file every time:

grep "step[49]" logIn.log > logOut.log 

This appends the log output, in case you overwrite the logIn file and want to keep the data:

grep "step[49]" logIn.log >> logOut.log 

Note: to be able to use GNUWin32 utils globally you have to add the bin folder to your system path.

How to redirect output of an already running process

I collected some information on the internet and prepared the script that requires no external tool: See my response here. Hope it's helpful.

"document.getElementByClass is not a function"

I tried

Document.getElementsByClassName('option0')

Which resulted in the error: Uncaught TypeError: Document.getElementsByClass is not a function

After that I tried:

document.getElementsByClassName('option0')

And it works!

C# - How to get Program Files (x86) on Windows 64 bit

Note, however, that the ProgramFiles(x86) environment variable is only available if your application is running 64-bit.

If your application is running 32-bit, you can just use the ProgramFiles environment variable whose value will actually be "Program Files (x86)".

What's the difference between including files with JSP include directive, JSP include action and using JSP Tag Files?

All three template options - <%@include>, <jsp:include> and <%@tag> are valid, and all three cover different use cases.

With <@include>, the JSP parser in-lines the content of the included file into the JSP before compilation (similar to a C #include). You'd use this option with simple, static content: for example, if you wanted to include header, footer, or navigation elements into every page in your web-app. The included content becomes part of the compiled JSP and there's no extra cost at runtime.

<jsp:include> (and JSTL's <c:import>, which is similar and even more powerful) are best suited to dynamic content. Use these when you need to include content from another URL, local or remote; when the resource you're including is itself dynamic; or when the included content uses variables or bean definitions that conflict with the including page. <c:import> also allows you to store the included text in a variable, which you can further manipulate or reuse. Both these incur an additional runtime cost for the dispatch: this is minimal, but you need to be aware that the dynamic include is not "free".

Use tag files when you want to create reusable user interface components. If you have a List of Widgets, say, and you want to iterate over the Widgets and display properties of each (in a table, or in a form), you'd create a tag. Tags can take arguments, using <%@tag attribute> and these arguments can be either mandatory or optional - somewhat like method parameters.

Tag files are a simpler, JSP-based mechanism of writing tag libraries, which (pre JSP 2.0) you had to write using Java code. It's a lot cleaner to write JSP tag files when there's a lot of rendering to do in the tag: you don't need to mix Java and HTML code as you'd have to do if you wrote your tags in Java.

Including a css file in a blade template?

if your css file in public/css use :

<link rel="stylesheet" type="text/css" href="{{ asset('css/style.css') }}" >

if your css file in another folder in public use :

 <link rel="stylesheet" type="text/css" href="{{ asset('path/css/style.css') }}" >

Everytime I run gulp anything, I get a assertion error. - Task function must be specified

Try replacing your last line of gulpfile.js

gulp.task('default', ['server', 'watch']);

with

gulp.task('default', gulp.series('server', 'watch'));