Programs & Examples On #Nntool

How to install and use "make" in Windows?

I could suggest a step by step approach.

  1. Visit GNUwin
  2. Download the Setup Program
  3. Follow the instructions and install GNUWin. You should pay attention to the directory where your application is being installed. (You will need it later1)
  4. Follow these instructions and add make to your environment variables. As I told you before, now it is time to know where your application was installed. FYI: The default directory is C:\Program Files (x86)\GnuWin32\.
  5. Now, update the PATH to include the bin directory of the newly installed program. A typical example of what one might add to the path is: ...;C:\Program Files (x86)\GnuWin32\bin

Jquery resizing image

$(function() {
    $('.story-small img').each(function() {
        var maxWidth = 100; // Max width for the image
        var maxHeight = 100;    // Max height for the image
        var width = $(this).width();    // Current image width
        var height = $(this).height();  // Current image height
        // Check if the current width is larger than the max
        if(width>height && width>maxWidth)
        {
            ratio = maxWidth / width;   // get ratio for scaling image
            $(this).css("width", maxWidth); // Set new width
            $(this).css("height", height * ratio); // Scale height based on ratio
        }
        else if(height>width && height>maxHeight)
        {
            ratio = maxHeight / height; // get ratio for scaling image
            $(this).css("height", maxHeight);   // Set new height
            $(this).css("width", width * ratio);    // Scale width based on ratio
        }
    });
});

Convert SQL Server result set into string

Test this:

 DECLARE @result NVARCHAR(MAX)

 SELECT @result = STUFF(
                        (   SELECT ',' + CONVERT(NVARCHAR(20), StudentId) 
                            FROM Student 
                            WHERE condition = abc 
                            FOR xml path('')
                        )
                        , 1
                        , 1
                        , '')

Multiple inputs with same name through POST in php

In your html you can pass in an array for the name i.e

<input type="text" name="address[]" /> 

This way php will receive an array of addresses.

Get timezone from DateTime

Generally the practice would be to pass data as a DateTime with a "timezone" of UTC and then pass a TimeZoneInfo object and when you are ready to display the data, you use the TimeZoneInfo object to convert the UTC DateTime.

The other option is to set the DateTime with the current timezone, and then make sure the "timezone" is unknown for the DateTime object, then make sure the DateTime is again passed with a TimeZoneInfo that indicates the TimeZone of the DateTime passed.

As others have indicated here, it would be nice if Microsoft got on top of this and created one nice object to do it all, but for now you have to deal with two objects.

Correct way to use Modernizr to detect IE?

Detecting CSS 3D transforms

Modernizr can detect CSS 3D transforms, yeah. The truthiness of Modernizr.csstransforms3d will tell you if the browser supports them.

The above link lets you select which tests to include in a Modernizr build, and the option you're looking for is available there.


Detecting IE specifically

Alternatively, as user356990 answered, you can use conditional comments if you're searching for IE and IE alone. Rather than creating a global variable, you can use HTML5 Boilerplate's <html> conditional comments trick to assign a class:

<!--[if lt IE 7]>      <html class="no-js lt-ie9 lt-ie8 lt-ie7"> <![endif]-->
<!--[if IE 7]>         <html class="no-js lt-ie9 lt-ie8"> <![endif]-->
<!--[if IE 8]>         <html class="no-js lt-ie9"> <![endif]-->
<!--[if gt IE 8]><!--> <html class="no-js"> <!--<![endif]-->

If you already have jQuery initialised, you can just check with $('html').hasClass('lt-ie9'). If you need to check which IE version you're in so you can conditionally load either jQuery 1.x or 2.x, you can do something like this:

myChecks.ltIE9 = (function(){
    var htmlElemClasses = document.querySelector('html').className.split(' ');
    if (!htmlElemClasses){return false;}
    for (var i = 0; i < htmlElemClasses.length; i += 1 ){
      var klass = htmlElemClasses[i];
      if (klass === 'lt-ie9'){
        return true;
      }
    }
    return false;
}());

N.B. IE conditional comments are only supported up to IE9 inclusive. From IE10 onwards, Microsoft encourages using feature detection rather than browser detection.


Whichever method you choose, you'd then test with

if ( myChecks.ltIE9 || Modernizr.csstransforms3d ){
    // iframe or flash fallback
} 

Don't take that || literally, of course.

How to create a unique index on a NULL column?

It is possible to use filter predicates to specify which rows to include in the index.

From the documentation:

WHERE <filter_predicate> Creates a filtered index by specifying which rows to include in the index. The filtered index must be a nonclustered index on a table. Creates filtered statistics for the data rows in the filtered index.

Example:

CREATE TABLE Table1 (
  NullableCol int NULL
)

CREATE UNIQUE INDEX IX_Table1 ON Table1 (NullableCol) WHERE NullableCol IS NOT NULL;

The controller for path was not found or does not implement IController

In another scenario just I would like to add is In my scenario, the name space was different for controller as it was mistake of copying controller from another project.

C++ pass an array by reference

Like the other answer says, put the & after the *.

This brings up an interesting point that can be confusing sometimes: types should be read from right to left. For example, this is (starting from the rightmost *) a pointer to a constant pointer to an int.

int * const *x;

What you wrote would therefore be a pointer to a reference, which is not possible.

Error resolving template "index", template might not exist or might not be accessible by any of the configured Template Resolvers

Check for the name of the

templates

folder. it should be templates not template(without s).

nuget 'packages' element is not declared warning

None of the answers will solve your problem permanently. If you go to the path of adding XSD (From Xml menu, select "Create schema"), you will end up having problems with the package manager as it will clean up your packages.config file when you add a new package.

The best solution is just ignore by closing the file when you don't use it.

Django download a file

You missed underscore in argument document_root. But it's bad idea to use serve in production. Use something like this instead:

import os
from django.conf import settings
from django.http import HttpResponse, Http404

def download(request, path):
    file_path = os.path.join(settings.MEDIA_ROOT, path)
    if os.path.exists(file_path):
        with open(file_path, 'rb') as fh:
            response = HttpResponse(fh.read(), content_type="application/vnd.ms-excel")
            response['Content-Disposition'] = 'inline; filename=' + os.path.basename(file_path)
            return response
    raise Http404

How do I make my ArrayList Thread-Safe? Another approach to problem in Java?

Whenever you want to use ant thread safe version of ant collection object,take help of java.util.concurrent.* package. It has almost all concurrent version of unsynchronized collection objects. eg: for ArrayList, you have java.util.concurrent.CopyOnWriteArrayList

You can do Collections.synchronizedCollection(any collection object),but remember this classical synchr. technique is expensive and comes with performence overhead. java.util.concurrent.* package is less expensive and manage the performance in better way by using mechanisms like

copy-on-write,compare-and-swap,Lock,snapshot iterators,etc.

So,Prefer something from java.util.concurrent.* package

What are good grep tools for Windows?

Cygwin includes grep. All the GNU tools amd Unix stuff works great on Windows if you install Cygwin.

http://www.cygwin.com/

CSS: Responsive way to center a fluid div (without px width) while limiting the maximum width?

This might sound really simplistic...

But this will center the div inside the div, exactly in the center in relation to left and right margin or parent container, but you can adjust percentage symmetrically on left and right.

margin-right: 10%;
margin-left: 10%;

Then you can adjust % to make it as wide as you want it.

Why check both isset() and !empty()

It is not necessary.

No warning is generated if the variable does not exist. That means empty() is essentially the concise equivalent to !isset($var) || $var == false.

php.net

Get battery level and state in Android

Based on official android docs, you can use this method in a Helper or Util class to get current battery percentage:

Java version:

public static int getBatteryPercentage(Context context) {

    if (Build.VERSION.SDK_INT >= 21) {

         BatteryManager bm = (BatteryManager) context.getSystemService(BATTERY_SERVICE);
         return bm.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY);

    } else {

         IntentFilter iFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
         Intent batteryStatus = context.registerReceiver(null, iFilter);

         int level = batteryStatus != null ? batteryStatus.getIntExtra(BatteryManager.EXTRA_LEVEL, -1) : -1;
         int scale = batteryStatus != null ? batteryStatus.getIntExtra(BatteryManager.EXTRA_SCALE, -1) : -1;

         double batteryPct = level / (double) scale;

         return (int) (batteryPct * 100);
   }
}

Kotlin version:

fun getBatteryPercentage(context: Context): Int {
    return if (Build.VERSION.SDK_INT >= 21) {
        val bm = context.getSystemService(BATTERY_SERVICE) as BatteryManager
        bm.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY)
    
    } else {
        val iFilter = IntentFilter(Intent.ACTION_BATTERY_CHANGED)
        val batteryStatus: Intent = context.registerReceiver(null, iFilter)
        val level = batteryStatus?.getIntExtra(BatteryManager.EXTRA_LEVEL, -1)
        val scale = batteryStatus?.getIntExtra(BatteryManager.EXTRA_SCALE, -1)
        val batteryPct = level / scale.toDouble()
        (batteryPct * 100).toInt()
    }
}

Xcode 6.1 - How to uninstall command line tools?

If you installed the command line tools separately, delete them using:

sudo rm -rf /Library/Developer/CommandLineTools

file_get_contents(): SSL operation failed with code 1, Failed to enable crypto

If your PHP version is 5, try installing cURL by typing the following command in the terminal:

sudo apt-get install php5-curl

Definition of "downstream" and "upstream"

When you read in git tag man page:

One important aspect of git is it is distributed, and being distributed largely means there is no inherent "upstream" or "downstream" in the system.

, that simply means there is no absolute upstream repo or downstream repo.
Those notions are always relative between two repos and depends on the way data flows:

If "yourRepo" has declared "otherRepo" as a remote one, then:

  • you are pulling from upstream "otherRepo" ("otherRepo" is "upstream from you", and you are "downstream for otherRepo").
  • you are pushing to upstream ("otherRepo" is still "upstream", where the information now goes back to).

Note the "from" and "for": you are not just "downstream", you are "downstream from/for", hence the relative aspect.


The DVCS (Distributed Version Control System) twist is: you have no idea what downstream actually is, beside your own repo relative to the remote repos you have declared.

  • you know what upstream is (the repos you are pulling from or pushing to)
  • you don't know what downstream is made of (the other repos pulling from or pushing to your repo).

Basically:

In term of "flow of data", your repo is at the bottom ("downstream") of a flow coming from upstream repos ("pull from") and going back to (the same or other) upstream repos ("push to").


You can see an illustration in the git-rebase man page with the paragraph "RECOVERING FROM UPSTREAM REBASE":

It means you are pulling from an "upstream" repo where a rebase took place, and you (the "downstream" repo) is stuck with the consequence (lots of duplicate commits, because the branch rebased upstream recreated the commits of the same branch you have locally).

That is bad because for one "upstream" repo, there can be many downstream repos (i.e. repos pulling from the upstream one, with the rebased branch), all of them having potentially to deal with the duplicate commits.

Again, with the "flow of data" analogy, in a DVCS, one bad command "upstream" can have a "ripple effect" downstream.


Note: this is not limited to data.
It also applies to parameters, as git commands (like the "porcelain" ones) often call internally other git commands (the "plumbing" ones). See rev-parse man page:

Many git porcelainish commands take mixture of flags (i.e. parameters that begin with a dash '-') and parameters meant for the underlying git rev-list command they use internally and flags and parameters for the other commands they use downstream of git rev-list. This command is used to distinguish between them.

What is special about /dev/tty?

The 'c' means it's a character special file.

Maven fails to find local artifact

The local Maven repo tracks where artifacts originally came from using a file named "_maven.repositories" in the artifact directory. After removing it, the build worked. This answer fixed the problem for me.

How do you remove duplicates from a list whilst preserving order?

In Python 3.7 and above, dictionaries are guaranteed to remember their key insertion order. The answer to this question summarizes the current state of affairs.

The OrderedDict solution thus becomes obsolete and without any import statements we can simply issue:

>>> lst = [1, 2, 1, 3, 3, 2, 4]
>>> list(dict.fromkeys(lst))
[1, 2, 3, 4]

Javascript: Call a function after specific time period

Timeout:

setTimeout(() => {
   console.log('Hello Timeout!')
}, 3000);

Interval:

setInterval(() => {
   console.log('Hello Interval!')
}, 2000);

Center text in table cell

I would recommend using CSS for this. You should create a CSS rule to enforce the centering, for example:

.ui-helper-center {
    text-align: center;
}

And then add the ui-helper-center class to the table cells for which you wish to control the alignment:

<td class="ui-helper-center">Content</td>

EDIT: Since this answer was accepted, I felt obligated to edit out the parts that caused a flame-war in the comments, and to not promote poor and outdated practices.

See Gabe's answer for how to include the CSS rule into your page.

Test only if variable is not null in if statement

I don't believe the expression is sensical as it is.

Elvis means "if truthy, use the value, else use this other thing."

Your "other thing" is a closure, and the value is status != null, neither of which would seem to be what you want. If status is null, Elvis says true. If it's not, you get an extra layer of closure.

Why can't you just use:

(it.description == desc) && ((status == null) || (it.status == status))

Even if that didn't work, all you need is the closure to return the appropriate value, right? There's no need to create two separate find calls, just use an intermediate variable.

Can local storage ever be considered secure?

This is a really interesting article here. I'm considering implementing JS encryption for offering security when using local storage. It's absolutely clear that this will only offer protection if the device is stolen (and is implemented correctly). It won't offer protection against keyloggers etc. However this is not a JS issue as the keylogger threat is a problem of all applications, regardless of their execution platform (browser, native). As to the article "JavaScript Crypto Considered Harmful" referenced in the first answer, I have one criticism; it states "You could use SSL/TLS to solve this problem, but that's expensive and complicated". I think this is a very ambitious claim (and possibly rather biased). Yes, SSL has a cost, but if you look at the cost of developing native applications for multiple OS, rather than web-based due to this issue alone, the cost of SSL becomes insignificant.

My conclusion - There is a place for client-side encryption code, however as with all applications the developers must recognise it's limitations and implement if suitable for their needs, and ensuring there are ways of mitigating it's risks.

Spring Boot: Is it possible to use external application.properties files in arbitrary directories with a fat jar?

I managed to load an application.properties file in external path while using -jar option.

The key was PropertiesLauncher.

To use PropertiesLauncher, pom.xml file must be changed like this:

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
            <configuration>  <!-- added -->
                <layout>ZIP</layout> <!-- to use PropertiesLaunchar -->
            </configuration>
        </plugin>
    </plugins>
</build>

For this, I referenced the following StackOverflow question: spring boot properties launcher unable to use . BTW, In Spring Boot Maven Plugin document(http://docs.spring.io/spring-boot/docs/1.1.7.RELEASE/maven-plugin/repackage-mojo.html), there is no mention that specifying ZIP triggers that PropertiesLauncher is used. (Perhaps in another document?)

After the jar file had been built, I could see that the PropertiesLauncher is used by inspecting Main-Class property in META-INF/MENIFEST.MF in the jar.

Now, I can run the jar as follows(in Windows):

java -Dloader.path=file:///C:/My/External/Dir,MyApp-0.0.1-SNAPSHOT.jar -jar MyApp-0.0.1-SNAPSHOT.jar

Note that the application jar file is included in loader.path.

Now an application.properties file in C:\My\External\Dir\config is loaded.

As a bonus, any file (for example, static html file) in that directory can also be accessed by the jar since it's in the loader path.

As for the non-jar (expanded) version mentioned in UPDATE 2, maybe there was a classpath order problem.

MySQL - Select the last inserted row easiest way

You can use ORDER BY ID DESC, but it's WAY faster if you go that way:

SELECT * FROM bugs WHERE ID = (SELECT MAX(ID) FROM bugs WHERE user = 'me')

In case that you have a huge table, it could make a significant difference.

EDIT

You can even set a variable in case you need it more than once (or if you think it is easier to read).

SELECT @bug_id := MAX(ID) FROM bugs WHERE user = 'me';
SELECT * FROM bugs WHERE ID = @bug_id;

How to use external ".js" files

This is the way to include an external javascript file to you HTML markup.

<script type="text/javascript" src="/js/external-javascript.js"></script>

Where external-javascript.js is the external file to be included. Make sure the path and the file name are correct while you including it.

<a href="javascript:showCountry('countryCode')">countryCode</a>

The above mentioned method is correct for anchor tags and will work perfectly. But for other elements you should specify the event explicitly.

Example:

<select name="users" onChange="showUser(this.value)">

Thanks, XmindZ

webpack: Module not found: Error: Can't resolve (with relative path)

Just ran into this... I have a common library shared among multiple transpiled products. I was using symlinks with brunch to handle sharing things between the projects. When moving to webpack, this stopped working.

What did get things working was using webpack configuration to turn off symlink resolving.

i.e. adding this in webpack.config.js:

module.exports = {
  //...
  resolve: {
    symlinks: false
  }
};

as documented here:

https://webpack.js.org/configuration/resolve/#resolvesymlinks

How to make Git "forget" about a file that was tracked but is now in .gitignore?

If anyone having hard time on Windows and you wanna ignore entire folder, 'cd' to desired the 'folder' and do 'Git Bash Here'.

git ls-files -z | xargs -0 git update-index --assume-unchanged

How to change the default message of the required field in the popover of form-control in bootstrap?

Combination of Mritunjay and Bartu's answers are full answer to this question. I copying the full example.

<input class="form-control" type="email"  required="" placeholder="username"
 oninvalid="this.setCustomValidity('Please Enter valid email')"
 oninput="setCustomValidity('')"></input>

Here,

this.setCustomValidity('Please Enter valid email')" - Display the custom message on invalidated of the field

oninput="setCustomValidity('')" - Remove the invalidate message on validated filed.

ErrorActionPreference and ErrorAction SilentlyContinue for Get-PSSessionConfiguration

A solution for me:

$old_ErrorActionPreference = $ErrorActionPreference
$ErrorActionPreference = 'SilentlyContinue'
if((Get-PSSessionConfiguration -Name "MyShellUri" -ErrorAction SilentlyContinue) -eq $null) {
   WriteTraceForTrans "The session configuration MyShellUri is already unregistered."
}
else {        
   #Unregister-PSSessionConfiguration -Name "MyShellUri" -Force -ErrorAction Ignore
}
$ErrorActionPreference = $old_ErrorActionPreference 

Or use try-catch

try { 

(Get-PSSessionConfiguration -Name "MyShellUri" -ErrorAction SilentlyContinue)

} 
catch {

}

How to validate a form with multiple checkboxes to have atleast one checked

if (
  document.forms["form"]["mon"].checked==false &&
  document.forms["form"]["tues"].checked==false &&
  document.forms["form"]["wed"].checked==false &&
  document.forms["form"]["thrs"].checked==false &&
  document.forms["form"]["fri"].checked==false
) {
  alert("Select at least One Day into Five Days");
  return false; 
}

Is there a Google Keep API?

I have been waiting to see if Google would open a Keep API. When I discovered Google Tasks, and saw that it had an Android app, web app, and API, I converted over to Tasks. This may not directly answer your question, but it is my solution to the Keep API problem.

Tasks doesn't have a reminder alarm exactly like Keep. I can live without that if I also connect with the Calendar API.

https://developers.google.com/google-apps/tasks/

Get css top value as number not as string?

A jQuery plugin based on M4N's answer

jQuery.fn.cssNumber = function(prop){
    var v = parseInt(this.css(prop),10);
    return isNaN(v) ? 0 : v;
};

So then you just use this method to get number values

$("#logo").cssNumber("top")

How to test an Internet connection with bash?

For the fastest result, ping a DNS server:

ping -c1 "8.8.8.8" &>"/dev/null"

if [[ "${?}" -ne 0 ]]; then
    echo "offline"
elif [[ "${#args[@]}" -eq 0 ]]; then
    echo "online"
fi

Available as a standalone command: linkStatus

What process is listening on a certain port on Solaris?

Most probly sun's administrative server.. It's usually bundled along with sun's directory and a few other webmin-ish stuff that is in the default installation

html "data-" attribute as javascript parameter

you might use default parameters in your function and then just pass the entire dataset itself, since the dataset is already a DOMStringMap Object

<div data-uid="aaa" data-name="bbb" data-value="ccc"
onclick="fun(this.dataset)">

<script>
const fun = ({uid:'ddd', name:'eee', value:'fff', other:'default'} = {}) { 
    // 
}
</script>

that way, you can deal with any data-values that got set in the html tag, or use defaults if they weren't set - that kind of thing

maybe not in this situation, but in others, it might be advantageous to put all your preferences in a single data-attribute

<div data-all='{"uid":"aaa","name":"bbb","value":"ccc"}'
onclick="fun(JSON.parse(this.dataset.all))">

there are probably more terse ways of doing that, if you already know certain things about the order of the data

<div data-all="aaa,bbb,ccc" onclick="fun(this.dataset.all.split(','))">

internal/modules/cjs/loader.js:582 throw err

I was facing same problem.. I downgraded webpack-dev-server to 2.5.1 version. Now everything is working fine .

Manually adding a Userscript to Google Chrome

This parameter is is working for me:

--enable-easy-off-store-extension-install

Do the following:

  1. Right click on your "Chrome" icon.
  2. Choose properties
  3. At the end of your target line, place these parameters: --enable-easy-off-store-extension-install
  4. It should look like: chrome.exe --enable-easy-off-store-extension-install
  5. Start Chrome by double-clicking on the icon

Better way to sum a property value in an array

I know that this question has an accepted answer but I thought I'd chip in with an alternative which uses array.reduce, seeing that summing an array is the canonical example for reduce:

$scope.sum = function(items, prop){
    return items.reduce( function(a, b){
        return a + b[prop];
    }, 0);
};

$scope.travelerTotal = $scope.sum($scope.traveler, 'Amount');

Fiddle

How to checkout in Git by date?

To those who prefer a pipe to command substitution

git rev-list -n1 --before=2013-7-4 master | xargs git checkout

Location of WSDL.exe

You'll get it as part of a Visual Studio install (if you included the SDK), or in a standalone SDK install. It'll live somewhere like C:\program files\Microsoft Visual Studio 8\SDK\v2.0\Bin

If you don't already have it, you can download the .NET SDKs from
http://msdn.microsoft.com/en-us/netframework/aa569263.aspx

How do I format a date in Jinja2?

If you are dealing with a lower level time object (I often just use integers), and don't want to write a custom filter for whatever reason, an approach I use is to pass the strftime function into the template as a variable, where it can be called where you need it.

For example:

import time
context={
    'now':int(time.time()),
    'strftime':time.strftime }  # Note there are no brackets () after strftime
                                # This means we are passing in a function, 
                                # not the result of a function.

self.response.write(jinja2.render_template('sometemplate.html', **context))

Which can then be used within sometemplate.html:

<html>
    <body>
        <p>The time is {{ strftime('%H:%M%:%S',now) }}, and 5 seconds ago it was {{ strftime('%H:%M%:%S',now-5) }}.
    </body>
</html>

Clearing NSUserDefaults

Did you try using -removeObjectForKey?

 [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"defunctPreference"];

Pandas : compute mean or std (standard deviation) over entire dataframe

You could convert the dataframe to be a single column with stack (this changes the shape from 5x3 to 15x1) and then take the standard deviation:

df.stack().std()         # pandas default degrees of freedom is one

Alternatively, you can use values to convert from a pandas dataframe to a numpy array before taking the standard deviation:

df.values.std(ddof=1)    # numpy default degrees of freedom is zero

Unlike pandas, numpy will give the standard deviation of the entire array by default, so there is no need to reshape before taking the standard deviation.

A couple of additional notes:

  • The numpy approach here is a bit faster than the pandas one, which is generally true when you have the option to accomplish the same thing with either numpy or pandas. The speed difference will depend on the size of your data, but numpy was roughly 10x faster when I tested a few different sized dataframes on my laptop (numpy version 1.15.4 and pandas version 0.23.4).

  • The numpy and pandas approaches here will not give exactly the same answers, but will be extremely close (identical at several digits of precision). The discrepancy is due to slight differences in implementation behind the scenes that affect how the floating point values get rounded.

How to change pivot table data source in Excel?

right click on the pivot table in excel choose wizard click 'back' click 'get data...' in the query window File - Table Definition

then you can create a new or choose a different connection

Difference between spring @Controller and @RestController annotation

@Controller returns View. @RestController returns ResponseBody.

iPhone app signing: A valid signing identity matching this profile could not be found in your keychain

Just a note with Xcode 4: in the organizer there are two different sections in the left pane:

  1. Library > Provisioning profiles

  2. Devices > your device > Provisioning profiles

I was always puttings my provisioning profiles into 2. and even after cleaning and installing properly it was not working. Then I discovered 1. and finally I found the refresh button. If you select 'Automatic device provisioning' in 1. and click on refresh, then everything got validated (no yellow warning in 2. anymore).

How can I change the current URL?

Hmm, I would use

window.location = 'http://localhost/index.html#?options=go_here';

I'm not exactly sure if that is what you mean.

Aesthetics must either be length one, or the same length as the dataProblems

Similar to @joran's answer. Reshape the df so that the prices for each product are in different columns:

xx <- reshape(df, idvar=c("skew","version","color"),
              v.names="price", timevar="product", direction="wide")

xx will have columns price.p1, ... price.p4, so:

ggp <- ggplot(xx,aes(x=price.p1, y=price.p3, color=factor(skew))) +
       geom_point(shape=19, size=5)
ggp + facet_grid(color~version)

gives the result from your image.

Making an svg image object clickable with onclick, avoiding absolute positioning

I wrapped the 'svg' tag in 'a' tag and put the onClick event in the 'a' tag

Cannot implicitly convert type from Task<>

You need to make TestGetMethod async too and attach await in front of GetIdList(); will unwrap the task to List<int>, So if your helper function is returning Task make sure you have await as you are calling the function async too.

public Task<List<int>> TestGetMethod()
{
    return GetIdList();
}    

async Task<List<int>> GetIdList()
{
    using (HttpClient proxy = new HttpClient())
    {
        string response = await proxy.GetStringAsync("www.test.com");
        List<int> idList = JsonConvert.DeserializeObject<List<int>>();
        return idList;
    }
}

Another option

public async void TestGetMethod(List<int> results)
{
    results = await GetIdList(); // await will unwrap the List<int>
}

align right in a table cell with CSS

What worked for me now is:

CSS:

.right {
  text-align: right;
  margin-right: 1em;
}

.left {
  text-align: left;
  margin-left: 1em;
}

HTML:

<table width="100%">
  <tbody>
    <tr>
      <td class="left">
        <input id="abort" type="submit" name="abort" value="Back">
        <input id="save" type="submit" name="save" value="Save">
      </td>
      <td class="right">
        <input id="delegate" type="submit" name="delegate" value="Delegate">
        <input id="unassign" type="submit" name="unassign" value="Unassign">
        <input id="complete" type="submit" name="complete" value="Complete">
      </td>
    </tr>
  </tbody>
</table>

See the following fiddle:

http://jsfiddle.net/Joysn/3u3SD/

HTML not loading CSS file

Well I too had the exactly same question. And everything was okay with my CSS link. Why html was not loading the CSS file was due to its position (as in my case).

Well I had my custom CSS defined in the wrong place and that is why the webpage was not accessing it. Then I started to test and place the CSS link to different place and voila it worked for me.

I had read somewhere that we should place custom CSS right after Bootstrap CSS so I did but then it was not loading it. So I changed the position and it worked.

Hope this helps.

Thanks!

How can you get the Manifest Version number from the App's (Layout) XML variables?

You can use the versionName in XML resources, such as activity layouts. First create a string resource in the app/build.gradle with the following snippet in the android node:

applicationVariants.all { variant ->
    variant.resValue "string", "versionName", variant.versionName
}

So the whole build.gradle file contents may look like this:

apply plugin: 'com.android.application'

android {
    compileSdkVersion 23
    buildToolsVersion '24.0.0 rc3'
    defaultConfig {
        applicationId 'com.example.myapplication'
        minSdkVersion 15
        targetSdkVersion 23
        versionCode 17
        versionName '0.2.3'
        jackOptions {
            enabled true
        }
    }
    applicationVariants.all { variant ->
        variant.resValue "string", "versionName", variant.versionName
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    productFlavors {
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
} 

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.3.0'
    compile 'com.android.support:design:23.3.0'
    compile 'com.android.support:support-v4:23.3.0'
}

Then you can use @string/versionName in the XML. Android Studio will mark it red, but the app will compile without issues. For example, this may be used like this in app/src/main/res/xml/preferences.xml:

<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">

    <PreferenceCategory
        android:title="About"
        android:key="pref_key_about">

        <Preference
            android:key="pref_about_build"
            android:title="Build version"
            android:summary="@string/versionName" />

    </PreferenceCategory>


</PreferenceScreen>

jQuery dialog popup

Your problem is on the call for the dialog

If you dont initialize the dialog, you don't have to pass "open" for it to show:

$("#dialog").dialog();

Also, this code needs to be on a $(document).ready(); function or be below the elements for it to work.

Color picker utility (color pipette) in Ubuntu

I recommend GPick:

sudo apt-get install gpick

Applications -> Graphics -> GPick

It has many more features than gcolor2 but is still extremely simple to use: click on one of the hex swatches, move your mouse around the screen over the colours you want to pick, then press the Space bar to add to your swatch list.

If that doesn't work, another way is to click-and-drag from the centre of the hexagon and release your mouse over the pixel that you want to sample. Then immediately hit Space to copy that color into the next swatch in rotation.

It also has a traditional colour picker (like gcolor2) in the bottom right-hand corner of the window to allow you to pick individual colours with magnification.

Shell script to delete directories older than n days

OR

rm -rf `find /path/to/base/dir/* -type d -mtime +10`

Updated, faster version of it:

find /path/to/base/dir/* -mtime +10 -print0 | xargs -0 rm -f

Maximum Length of Command Line String

In Windows 10, it's still 8191 characters...at least on my machine.

It just cuts off any text after 8191 characters. Well, actually, I got 8196 characters, and after 8196, then it just won't let me type any more.

Here's a script that will test how long of a statement you can use. Well, assuming you have gawk/awk installed.

echo rem this is a test of how long of a line that a .cmd script can generate >testbat.bat
gawk 'BEGIN {printf "echo -----";for (i=10;i^<=100000;i +=10) printf "%%06d----",i;print;print "pause";}' >>testbat.bat
testbat.bat

The type or namespace name 'DbContext' could not be found

I had to first uninstall EntityFramework(Uninstall-package EntityFramework (not case sensitive apparently)), then install it again(Install-package EntityFramework), via the PM Console

CSS How to set div height 100% minus nPx

great one... now i have stopped using % he he he... except for the main container as shown below:

<div id="divContainer">
    <div id="divHeader">
    </div>
    <div id="divContentArea">
        <div id="divContentLeft">
        </div>
        <div id="divContentRight">
        </div>
    </div>
    <div id="divFooter">
    </div>
</div>

and here is the css:

#divContainer {
    width: 100%;
    height: 100%;
}
#divHeader {
    position: absolute;
    left: 0px;
    top: 0px;
    right: 0px;
    height: 28px;
}
#divContentArea {
    position: absolute;
    left: 0px;
    top: 30px;
    right: 0px;
    bottom: 30px;
}
#divContentLeft {
    position: absolute;
    top: 0px;
    left: 0px;
    width: 250px;
    bottom: 0px;
}
#divContentRight {
    position: absolute;
    top: 0px;
    left: 254px;
    right: 0px;
    bottom: 0px;
}
#divFooter {
    position: absolute;
    height: 28px;
    left: 0px;
    bottom: 0px;
    right: 0px;
}

i tested this in all known browsers and is working fine. Are there any drawbacks using this way?

Postman Chrome: What is the difference between form-data, x-www-form-urlencoded and raw

Here are some supplemental examples to see the raw text that Postman passes in the request. You can see this by opening the Postman console:

enter image description here

form-data

Header

content-type: multipart/form-data; boundary=--------------------------590299136414163472038474

Body

key1=value1key2=value2

x-www-form-urlencoded

Header

Content-Type: application/x-www-form-urlencoded

Body

key1=value1&key2=value2

Raw text/plain

Header

Content-Type: text/plain

Body

This is some text.

Raw json

Header

Content-Type: application/json

Body

{"key1":"value1","key2":"value2"}

Java2D: Increase the line width

You should use setStroke to set a stroke of the Graphics2D object.

The example at http://www.java2s.com gives you some code examples.

The following code produces the image below:

import java.awt.*;
import java.awt.geom.Line2D;
import javax.swing.*;

public class FrameTest {
    public static void main(String[] args) {
        JFrame jf = new JFrame("Demo");
        Container cp = jf.getContentPane();
        cp.add(new JComponent() {
            public void paintComponent(Graphics g) {
                Graphics2D g2 = (Graphics2D) g;
                g2.setStroke(new BasicStroke(10));
                g2.draw(new Line2D.Float(30, 20, 80, 90));
            }
        });
        jf.setSize(300, 200);
        jf.setVisible(true);
    }
}

enter image description here

(Note that the setStroke method is not available in the Graphics object. You have to cast it to a Graphics2D object.)


This post has been rewritten as an article here.

Remove duplicates from a List<T> in C#

Installing the MoreLINQ package via Nuget, you can easily distinct object list by a property

IEnumerable<Catalogue> distinctCatalogues = catalogues.DistinctBy(c => c.CatalogueCode); 

Adding to the classpath on OSX

If your shell is tcsh or csh, you can set it in /etc/profile. Open terminal, "vim /etc/profile" and add the following line:

setenv CLASSPATH (insert your classpath here)

Calling C++ class methods via a function pointer

I don't think anyone has explained here that one issue is that you need "member pointers" rather than normal function pointers.

Member pointers to functions are not simply function pointers. In implementation terms, the compiler cannot use a simple function address because, in general, you don't know the address to call until you know which object to dereference for (think virtual functions). You also need to know the object in order to provide the this implicit parameter, of course.

Having said that you need them, now I'll say that you really need to avoid them. Seriously, member pointers are a pain. It is much more sane to look at object-oriented design patterns that achieve the same goal, or to use a boost::function or whatever as mentioned above - assuming you get to make that choice, that is.

If you are supplying that function pointer to existing code, so you really need a simple function pointer, you should write a function as a static member of the class. A static member function doesn't understand this, so you'll need to pass the object in as an explicit parameter. There was once a not-that-unusual idiom along these lines for working with old C code that needs function pointers

class myclass
{
  public:
    virtual void myrealmethod () = 0;

    static void myfunction (myclass *p);
}

void myclass::myfunction (myclass *p)
{
  p->myrealmethod ();
}

Since myfunction is really just a normal function (scope issues aside), a function pointer can be found in the normal C way.

EDIT - this kind of method is called a "class method" or a "static member function". The main difference from a non-member function is that, if you reference it from outside the class, you must specify the scope using the :: scope resolution operator. For example, to get the function pointer, use &myclass::myfunction and to call it use myclass::myfunction (arg);.

This kind of thing is fairly common when using the old Win32 APIs, which were originally designed for C rather than C++. Of course in that case, the parameter is normally LPARAM or similar rather than a pointer, and some casting is needed.

How to turn off gcc compiler optimization to enable buffer overflow

That's a good problem. In order to solve that problem you will also have to disable ASLR otherwise the address of g() will be unpredictable.

Disable ASLR:

sudo bash -c 'echo 0 > /proc/sys/kernel/randomize_va_space'

Disable canaries:

gcc overflow.c -o overflow -fno-stack-protector

After canaries and ASLR are disabled it should be a straight forward attack like the ones described in Smashing the Stack for Fun and Profit

Here is a list of security features used in ubuntu: https://wiki.ubuntu.com/Security/Features You don't have to worry about NX bits, the address of g() will always be in a executable region of memory because it is within the TEXT memory segment. NX bits only come into play if you are trying to execute shellcode on the stack or heap, which is not required for this assignment.

Now go and clobber that EIP!

How can I compare two time strings in the format HH:MM:SS?

As Felix Kling said in the comments, provided your times are based on a 24 hour clock (and they should be if there's no AM/PM) and provided they are always in the format HH:MM:SS you can do a direct string comparison:

var str1 = "10:20:45",
    str2 = "05:10:10";

if (str1 > str2)
    alert("Time 1 is later than time 2");
else
    alert("Time 2 is later than time 1");

make: *** No rule to make target `all'. Stop

Your makefile should ideally be named makefile, not make. Note that you can call your makefile anything you like, but as you found, you then need the -f option with make to specify the name of the makefile. Using the default name of makefile just makes life easier.

Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation

To install the prerequisites for GPU support in TensorFlow 2.1:

  1. Install your latest GPU drivers.
  2. Install CUDA 10.1.
    • If the CUDA installer reports "you are installing an older driver version", you may wish to choose a custom installation and deselect some components. Indeed, note that software bundled with CUDA including GeForce Experience, PhysX, a Display Driver, and Visual Studio integration are not required by TensorFlow.
    • Also note that TensorFlow requires a specific version of the CUDA Toolkit unless you build from source; for TensorFlow 2.1 and 2.2, this is currently version 10.1.
  3. Install cuDNN.
    1. Download cuDNN v7.6.4 for CUDA 10.1. This will require you to sign up to the NVIDIA Developer Program.
    2. Unzip to a suitable location and add the bin directory to your PATH.
  4. Install tensorflow by pip install tensorflow.
  5. You may need to restart your PC.

python capitalize first letter only

You can replace the first letter (preceded by a digit) of each word using regex:

re.sub(r'(\d\w)', lambda w: w.group().upper(), '1bob 5sandy')

output:
 1Bob 5Sandy

How do you clear Apache Maven's cache?

As some answers have pointed out, sometimes you really want to delete the local repository entirely, for example, there might be some artifacts that can't be purged as they are not anymore referenced by the pom.

If you want to have this deletion embedded in a maven phase, as for example clean you can use the maven-clean-plugin and access the repository through the settings, for example:

 <plugin>
    <inherited>false</inherited>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-antrun-plugin</artifactId>
    <version>1.1</version>
    <executions>
        <execution>
            <phase>clean</phase>
            <goals>
                <goal>run</goal>
            </goals>
            <configuration>
                <tasks>
                    <echo>Base clean is attached to deleting local maven cache</echo>
                    <echo>${settings.localRepository}</echo>
                </tasks>
            </configuration>
        </execution>
    </executions>
</plugin>

<plugin>
    <inherited>false</inherited>
    <artifactId>maven-clean-plugin</artifactId>
    <version>3.1.0</version>
    <configuration>
        <filesets>
            <fileset>
                <directory>${settings.localRepository}</directory>
            </fileset>
        </filesets>
    </configuration>
</plugin>

How to compare LocalDate instances Java 8

LocalDate ld ....;
LocalDateTime ldtime ...;

ld.isEqual(LocalDate.from(ldtime));

How to delete an instantiated object Python?

What do you mean by delete? In Python, removing a reference (or a name) can be done with the del keyword, but if there are other names to the same object that object will not be deleted.

--> test = 3
--> print(test)
3
--> del test
--> print(test)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'test' is not defined

compared to:

--> test = 5
--> other is test  # check that both name refer to the exact same object
True
--> del test       # gets rid of test, but the object is still referenced by other
--> print(other)
5

Need to ZIP an entire directory using Node.js

Adm-zip has problems just compressing an existing archive https://github.com/cthackers/adm-zip/issues/64 as well as corruption with compressing binary files.

I've also ran into compression corruption issues with node-zip https://github.com/daraosn/node-zip/issues/4

node-archiver is the only one that seems to work well to compress but it doesn't have any uncompress functionality.

How to change the current URL in javascript?

Even it is not a good way of doing what you want try this hint: var url = MUST BE A NUMER FIRST

function nextImage (){
url = url + 1;  
location.href='http://mywebsite.com/' + url+'.html';
}

What's the best way to store Phone number in Django models

Validation is easy, text them a little code to type in. A CharField is a great way to store it. I wouldn't worry too much about canonicalizing phone numbers.

What is a wrapper class?

To make a wrapper class well being is not a easy job. To understand a wrapper class how it is designed by some others is also not a easy job. Because it is idea, not code. Only when you understand the idea, you can understand wrapper.

Encoding Javascript Object to Json string

Unless the variable k is defined, that's probably what's causing your trouble. Something like this will do what you want:

var new_tweets = { };

new_tweets.k = { };

new_tweets.k.tweet_id = 98745521;
new_tweets.k.user_id = 54875;

new_tweets.k.data = { };

new_tweets.k.data.in_reply_to_screen_name = 'other_user';
new_tweets.k.data.text = 'tweet text';

// Will create the JSON string you're looking for.
var json = JSON.stringify(new_tweets);

You can also do it all at once:

var new_tweets = {
  k: {
    tweet_id: 98745521,
    user_id: 54875,
    data: {
      in_reply_to_screen_name: 'other_user',
      text: 'tweet_text'
    }
  }
}

C# Reflection: How to get class reference from string?

Bit late for reply but this should do the trick

Type myType = Type.GetType("AssemblyQualifiedName");

your assembly qualified name should be like this

"Boom.Bam.Class, Boom.Bam, Version=1.0.0.262, Culture=neutral, PublicKeyToken=e16dba1a3c4385bd"

What should I do when 'svn cleanup' fails?

I solved this problem by copying some colleague's .svn directory into mine and then updating my working copy. It was a nice, quick and clean solution.

Send Email Intent

With Kotlin, works with Gmail :

val i = Intent(Intent.ACTION_SENDTO).apply {
    type = "text/html"
    data = Uri.parse("mailto:")
    putExtra(Intent.EXTRA_EMAIL, arrayOf(email))
    putExtra(Intent.EXTRA_SUBJECT, subject)
    putExtra(Intent.EXTRA_TITLE, subject)
}
if (packageManager != null && i.resolveActivity(packageManager) != null) {
    startActivity(i)
}

If anyone find a solution to display the message too...

Excel SUMIF between dates

To SUMIFS between dates, use the following:

=SUMIFS(B:B,A:A,">="&DATE(2012,1,1),A:A,"<"&DATE(2012,6,1))

Violation of PRIMARY KEY constraint. Cannot insert duplicate key in object

To prevent inserting a record that exist already. I'd check if the ID value exists in the database. For the example of a Table created with an IDENTITY PRIMARY KEY:

CREATE TABLE [dbo].[Persons] (    
    ID INT IDENTITY(1,1) PRIMARY KEY,
    LastName VARCHAR(40) NOT NULL,
    FirstName VARCHAR(40)
);

When JANE DOE and JOE BROWN already exist in the database.

SET IDENTITY_INSERT [dbo].[Persons] OFF;
INSERT INTO [dbo].[Persons] (FirstName,LastName)
VALUES ('JANE','DOE'); 
INSERT INTO Persons (FirstName,LastName) 
VALUES ('JOE','BROWN');

DATABASE OUTPUT of TABLE [dbo].[Persons] will be:

ID    LastName   FirstName
1     DOE        Jane
2     BROWN      JOE

I'd check if i should update an existing record or insert a new one. As the following JAVA example:

int NewID = 1;
boolean IdAlreadyExist = false;
// Using SQL database connection
// STEP 1: Set property
System.setProperty("java.net.preferIPv4Stack", "true");
// STEP 2: Register JDBC driver
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
// STEP 3: Open a connection
try (Connection conn1 = DriverManager.getConnection(DB_URL, USER,pwd) {
    conn1.setAutoCommit(true);
    String Select = "select * from Persons where  ID = " + ID;
    Statement st1 = conn1.createStatement();
    ResultSet rs1 = st1.executeQuery(Select);
    // iterate through the java resultset
    while (rs1.next()) {
        int ID = rs1.getInt("ID");
        if (NewID==ID) {
            IdAlreadyExist = true;
        }

    }
    conn1.close();
} catch (SQLException e1) {
    System.out.println(e1);
}
if (IdAlreadyExist==false) {
    //Insert new record code here
} else {
    //Update existing record code here
}

How can I truncate a datetime in SQL Server?

For SQL Server 2008 only

CAST(@SomeDateTime AS Date) 

Then cast it back to datetime if you want

CAST(CAST(@SomeDateTime AS Date) As datetime)

The difference between fork(), vfork(), exec() and clone()

  1. fork() - creates a new child process, which is a complete copy of the parent process. Child and parent processes use different virtual address spaces, which is initially populated by the same memory pages. Then, as both processes are executed, the virtual address spaces begin to differ more and more, because the operating system performs a lazy copying of memory pages that are being written by either of these two processes and assigns an independent copies of the modified pages of memory for each process. This technique is called Copy-On-Write (COW).
  2. vfork() - creates a new child process, which is a "quick" copy of the parent process. In contrast to the system call fork(), child and parent processes share the same virtual address space. NOTE! Using the same virtual address space, both the parent and child use the same stack, the stack pointer and the instruction pointer, as in the case of the classic fork()! To prevent unwanted interference between parent and child, which use the same stack, execution of the parent process is frozen until the child will call either exec() (create a new virtual address space and a transition to a different stack) or _exit() (termination of the process execution). vfork() is the optimization of fork() for "fork-and-exec" model. It can be performed 4-5 times faster than the fork(), because unlike the fork() (even with COW kept in the mind), implementation of vfork() system call does not include the creation of a new address space (the allocation and setting up of new page directories).
  3. clone() - creates a new child process. Various parameters of this system call, specify which parts of the parent process must be copied into the child process and which parts will be shared between them. As a result, this system call can be used to create all kinds of execution entities, starting from threads and finishing by completely independent processes. In fact, clone() system call is the base which is used for the implementation of pthread_create() and all the family of the fork() system calls.
  4. exec() - resets all the memory of the process, loads and parses specified executable binary, sets up new stack and passes control to the entry point of the loaded executable. This system call never return control to the caller and serves for loading of a new program to the already existing process. This system call with fork() system call together form a classical UNIX process management model called "fork-and-exec".

Decoding base64 in batch

Here's a batch file, called base64encode.bat, that encodes base64.

@echo off
if not "%1" == "" goto :arg1exists
echo usage: base64encode input-file [output-file]
goto :eof
:arg1exists
set base64out=%2
if "%base64out%" == "" set base64out=con 
(
  set base64tmp=base64.tmp
  certutil -encode "%1" %base64tmp% > nul
  findstr /v /c:- %base64tmp%
  erase %base64tmp%
) > %base64out%

How to save password when using Subversion from the console

To add to Heath's answer: It looks like Subversion 1.6 disabled storing passwords by default if it can't store them in encrypted form. You can allow storing unencrypted passwords by explicitly setting password-stores = (that is, to the empty value) in ~/.subversion/config.

To check which password store subversion uses, look in ~/.subversion/auth/svn.simple. This contains several files, each a hash table with a simple key/value encoding. The svn:realmstring in each file identifies which realm that file is for. If the file has

K 8
passtype
V 6
simple

then it stores the password in plain text somewhere in that file, in a K 8 password entry. Else, it tries to use one of the configured password-stores.

Xcode is not currently available from the Software Update server

I know this is an old post but I also ran into this problem today. I found out that when I executed sudo softwareupdate -l the Command Line Tools were listed as an update, so I installed them using sudo softwareupdate -i -a.

How to split a string and assign it to variables

Golang does not support implicit unpacking of an slice (unlike python) and that is the reason this would not work. Like the examples given above, we would need to workaround it.

One side note:

The implicit unpacking happens for variadic functions in go:

func varParamFunc(params ...int) {

}

varParamFunc(slice1...)

Create new XML file and write data to it?

DOMDocument is a great choice. It's a module specifically designed for creating and manipulating XML documents. You can create a document from scratch, or open existing documents (or strings) and navigate and modify their structures.

$xml = new DOMDocument();
$xml_album = $xml->createElement("Album");
$xml_track = $xml->createElement("Track");
$xml_album->appendChild( $xml_track );
$xml->appendChild( $xml_album );

$xml->save("/tmp/test.xml");

To re-open and write:

$xml = new DOMDocument();
$xml->load('/tmp/test.xml');
$nodes = $xml->getElementsByTagName('Album') ;
if ($nodes->length > 0) {
   //insert some stuff using appendChild()
}

//re-save
$xml->save("/tmp/test.xml");

How do I calculate someone's age in Java?

/**
 * Compute from string date in the format of yyyy-MM-dd HH:mm:ss the age of a person.
 * @author Yaron Ronen
 * @date 04/06/2012  
 */
private int computeAge(String sDate)
{
    // Initial variables.
    Date dbDate = null;
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");      

    // Parse sDate.
    try
    {
        dbDate = (Date)dateFormat.parse(sDate);
    }
    catch(ParseException e)
    {
        Log.e("MyApplication","Can not compute age from date:"+sDate,e);
        return ILLEGAL_DATE; // Const = -2
    }

    // Compute age.
    long timeDiff = System.currentTimeMillis() - dbDate.getTime();      
    int age = (int)(timeDiff / MILLI_SECONDS_YEAR);  // MILLI_SECONDS_YEAR = 31558464000L;

    return age; 
}

how to read System environment variable in Spring applicationContext

Using Spring EL you can eis example write as follows

<bean id="myBean" class="path.to.my.BeanClass">
    <!-- can be overridden with -Dtest.target.host=http://whatever.com -->
    <constructor-arg value="#{systemProperties['test.target.host'] ?: 'http://localhost:18888'}"/>
</bean>

Can I change the fill color of an svg path with CSS?

you put this css for svg circle.

svg:hover circle{
    fill: #F6831D;
    stroke-dashoffset: 0;
    stroke-dasharray: 700;
    stroke-width: 2;
}

Difference between Python's Generators and Iterators

I am writing specifically for Python newbies in a very simple way, though deep down Python does so many things.

Let’s start with the very basic:

Consider a list,

l = [1,2,3]

Let’s write an equivalent function:

def f():
    return [1,2,3]

o/p of print(l): [1,2,3] & o/p of print(f()) : [1,2,3]

Let’s make list l iterable: In python list is always iterable that means you can apply iterator whenever you want.

Let’s apply iterator on list:

iter_l = iter(l) # iterator applied explicitly

Let’s make a function iterable, i.e. write an equivalent generator function. In python as soon as you introduce the keyword yield; it becomes a generator function and iterator will be applied implicitly.

Note: Every generator is always iterable with implicit iterator applied and here implicit iterator is the crux So the generator function will be:

def f():
  yield 1 
  yield 2
  yield 3

iter_f = f() # which is iter(f) as iterator is already applied implicitly

So if you have observed, as soon as you made function f a generator, it is already iter(f)

Now,

l is the list, after applying iterator method "iter" it becomes, iter(l)

f is already iter(f), after applying iterator method "iter" it becomes, iter(iter(f)), which is again iter(f)

It's kinda you are casting int to int(x) which is already int and it will remain int(x).

For example o/p of :

print(type(iter(iter(l))))

is

<class 'list_iterator'>

Never forget this is Python and not C or C++

Hence the conclusion from above explanation is:

list l ~= iter(l)

generator function f == iter(f)

What is the default stack size, can it grow, how does it work with garbage collection?

As you say, local variables and references are stored on the stack. When a method returns, the stack pointer is simply moved back to where it was before the method started, that is, all local data is "removed from the stack". Therefore, there is no garbage collection needed on the stack, that only happens in the heap.

To answer your specific questions:

  • See this question on how to increase the stack size.
  • You can limit the stack growth by:
    • grouping many local variables in an object: that object will be stored in the heap and only the reference is stored on the stack
    • limit the number of nested function calls (typically by not using recursion)
  • For windows, the default stack size is 320k for 32bit and 1024k for 64bit, see this link.

Read a text file using Node.js?

I am posting a complete example which I finally got working. Here I am reading in a file rooms/rooms.txt from a script rooms/rooms.js

var fs = require('fs');
var path = require('path');
var readStream = fs.createReadStream(path.join(__dirname, '../rooms') + '/rooms.txt', 'utf8');
let data = ''
readStream.on('data', function(chunk) {
    data += chunk;
}).on('end', function() {
    console.log(data);
});

How do I split a string into an array of characters?

The split() method in javascript accepts two parameters: a separator and a limit. The separator specifies the character to use for splitting the string. If you don't specify a separator, the entire string is returned, non-separated. But, if you specify the empty string as a separator, the string is split between each character.

Therefore:

s.split('')

will have the effect you seek.

More information here

Checking if type == list in python

You should try using isinstance()

if isinstance(object, list):
       ## DO what you want

In your case

if isinstance(tmpDict[key], list):
      ## DO SOMETHING

To elaborate:

x = [1,2,3]
if type(x) == list():
    print "This wont work"
if type(x) == list:                  ## one of the way to see if it's list
    print "this will work"           
if type(x) == type(list()):
    print "lets see if this works"
if isinstance(x, list):              ## most preferred way to check if it's list
    print "This should work just fine"

The difference between isinstance() and type() though both seems to do the same job is that isinstance() checks for subclasses in addition, while type() doesn’t.

How to find a Java Memory Leak

NetBeans has a built-in profiler.

RecyclerView vs. ListView

I worked a little with RecyclerView and still prefer ListView.

  1. Sure, both of them use ViewHolders, so this is not an advantage.

  2. A RecyclerView is more difficult in coding.

  3. A RecyclerView doesn't contain a header and footer, so it's a minus.

  4. A ListView doesn't require to make a ViewHolder. In cases where you want to have a list with sections or subheaders it would be a good idea to make independent items (without a ViewHolder), it's easier and doesn't require separate classes.

What is the best way to create and populate a numbers table?

Here is a short and fast in-memory solution that I came up with utilizing the Table Valued Constructors introduced in SQL Server 2008:

It will return 1,000,000 rows, however you can either add/remove CROSS JOINs, or use TOP clause to modify this.

;WITH v AS (SELECT * FROM (VALUES(0),(0),(0),(0),(0),(0),(0),(0),(0),(0)) v(z))

SELECT N FROM (SELECT ROW_NUMBER() OVER (ORDER BY v1.z)-1 N FROM v v1 
    CROSS JOIN v v2 CROSS JOIN v v3 CROSS JOIN v v4 CROSS JOIN v v5 CROSS JOIN v v6) Nums

Note that this could be quickly calculated on the fly, or (even better) stored in a permanent table (just add an INTO clause after the SELECT N segment) with a primary key on the N field for improved efficiency.

How to compile a 32-bit binary on a 64-bit linux machine with gcc/cmake

For any complex application, I suggest to use an lxc container. lxc containers are 'something in the middle between a chroot on steroids and a full fledged virtual machine'.

For example, here's a way to build 32-bit wine using lxc on an Ubuntu Trusty system:

sudo apt-get install lxc lxc-templates
sudo lxc-create -t ubuntu -n my32bitbox -- --bindhome $LOGNAME -a i386 --release trusty
sudo lxc-start -n my32bitbox
# login as yourself
sudo sh -c "sed s/deb/deb-src/ /etc/apt/sources.list >> /etc/apt/sources.list"
sudo apt-get install devscripts
sudo apt-get build-dep wine1.7
apt-get source wine1.7
cd wine1.7-*
debuild -eDEB_BUILD_OPTIONS="parallel=8" -i -us -uc -b
shutdown -h now   # to exit the container

Here is the wiki page about how to build 32-bit wine on a 64-bit host using lxc.

SQLException: No suitable driver found for jdbc:derby://localhost:1527

I just bumped into this problem, tried all above suggestions but still failed. Without repeat what have been suggested above, here are the things I (you) may be missing: In case you are using maven, likely you'll state the dependencies i.e:

<groupId>org.apache.derby</groupId>
<artifactId>derbyclient</artifactId>
<version>10.10.1.1</version>

Please be careful with the version. It must be compatible with the server instance you are running.

I solved my case by giving up on what maven dependencies provided and manually adding external jar from "%JAVA_HOME%\db\lib", the same source of my running server. In this case I'm testing using my Local.

So if you're testing with remote server instance, look for the derbyclient.jar that come with server package.

onActivityResult is not being called in Fragment

FOR NESTED FRAGMENTS (for example, when using a ViewPager)

In your main activity:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
}

In your main top level fragment(ViewPager fragment):

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    YourFragment frag = (YourFragment) getChildFragmentManager().getFragments().get(viewPager.getCurrentItem());
    frag.yourMethod(data);  // Method for callback in YourFragment
    super.onActivityResult(requestCode, resultCode, data);
}

In YourFragment (nested fragment):

public void yourMethod(Intent data){
    // Do whatever you want with your data
}

How do I use DrawerLayout to display over the ActionBar/Toolbar and under the status bar?

Try with this:

<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/drawer_layout"
android:fitsSystemWindows="true">


<FrameLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <!--Main layout and ads-->
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <FrameLayout
            android:id="@+id/ll_main_hero"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="1">

        </FrameLayout>

        <FrameLayout
            android:id="@+id/ll_ads"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <View
                android:layout_width="320dp"
                android:layout_height="50dp"
                android:layout_gravity="center"
                android:background="#ff00ff" />
        </FrameLayout>


    </LinearLayout>

    <!--Toolbar-->
    <android.support.v7.widget.Toolbar
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/toolbar"
        android:elevation="4dp" />
</FrameLayout>


<!--left-->
<ListView
    android:layout_width="240dp"
    android:layout_height="match_parent"
    android:layout_gravity="start"
    android:choiceMode="singleChoice"
    android:divider="@null"
    android:background="@mipmap/layer_image"
    android:id="@+id/left_drawer"></ListView>

<!--right-->
<FrameLayout
    android:layout_width="240dp"
    android:layout_height="match_parent"
    android:layout_gravity="right"
    android:background="@mipmap/layer_image">

    <ImageView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:src="@mipmap/ken2"
        android:scaleType="centerCrop" />
</FrameLayout>

style :

<style name="ts_theme_overlay" parent="Theme.AppCompat.Light.NoActionBar">
    <item name="colorPrimary">@color/red_A700</item>
    <item name="colorPrimaryDark">@color/red1</item>
    <item name="android:windowBackground">@color/blue_A400</item>
</style>

Main Activity extends ActionBarActivity

toolBar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolBar);

Now you can onCreateOptionsMenu like as normal ActionBar with ToolBar.

This is my Layout

  • TOP: Left Drawer - Right Drawer
    • MID: ToolBar (ActionBar)
    • BOTTOM: ListFragment

Hope you understand !have fun !

How to determine if a type implements an interface with C# reflection

Modifying Jeff's answer for optimal performance (thanks to performance test by Pierre Arnaud):

var type = typeof(MyType);
var implementsInterface = typeof(IMyInterface).IsAssignableFrom(type) && type.IsClass;

To find all types that implement an interface in a given Assembly:

var implementations = typeof(TypeInTargetAssembly).Assembly.GetTypes()
                          .Where(t => typeof(IMyInterface).IsAssignableFrom(t) && t.IsClass);

DLL load failed error when importing cv2

Please Remember if you want to install python package/libraries for windows,

you should always consider Python unofficial Binaries

Step 1:

Search for your package, download dependent version 2.7 or 3.6 you can find it under Downloads/your_package_version.whl its called python wheel

Step 2:

Now install using pip,

pip install ~/Downloads/your_packae_ver.whl

this will install without any error.

Copy a file list as text from Windows Explorer

If you paste the listing into your word processor instead of Notepad, (since each file name is in quotation marks with the full path name), you can highlight all the stuff you don't want on the first file, then use Find and Replace to replace every occurrence of that with nothing. Same with the ending quote (").

It makes a nice clean list of file names.

Connect to SQL Server 2012 Database with C# (Visual Studio 2012)

Note to under

connetionString =@"server=XXX;Trusted_Connection=yes;database=yourDB;";

Note: XXX = . OR .\SQLEXPRESS OR .\MSSQLSERVER OR (local)\SQLEXPRESS OR (localdb)\v11.0 &...

you can replace 'server' with 'Data Source'

too you can replace 'database' with 'Initial Catalog'

Sample:

 connetionString =@"server=.\SQLEXPRESS;Trusted_Connection=yes;Initial Catalog=books;";

"R cannot be resolved to a variable"?

Check your AndroidManifest.xml file, see if the package name is correct. If you copied an example it is likely this is wrong and the source of your problem.

How do I concatenate strings and variables in PowerShell?

These answers all seem very complicated. If you are using this in a PowerShell script you can simply do this:

$name = 'Slim Shady'
Write-Host 'My name is'$name

It will output

My name is Slim Shady

Note how a space is put between the words for you

What is the OR operator in an IF statement

The conditional or operator is ||:

if (expr1 || expr2) {do stuff}

if (title == "User greeting" || title == "User name") {do stuff}

The conditional (the OR) and it's parts are boolean expressions.

MSDN lists the C# operators in precedence order here http://msdn.microsoft.com/en-us/library/6a71f45d.aspx . And the MSDN page for boolean expressions is http://msdn.microsoft.com/en-us/library/dya2szfk.aspx .

If you are just starting to learn programming, you should read up on Conditional Statements from an introductory text or tutorial. This one seems to cover most of the basics: http://www.functionx.com/csharp/Lesson10.htm .

TypeScript add Object to array with push

class PushObjects {
    testMethod(): Array<number> { 
        //declaration and initialisation of array onject
        var objs: number[] = [1,2,3,4,5,7];
        //push the elements into the array object
        objs.push(100);
        //pop the elements from the array
        objs.pop();
        return objs;
    }   
}

let pushObj = new PushObjects();
//create the button element from the dom object 
let btn = document.createElement('button');
//set the text value of the button
btn.textContent = "Click here";
//button click event
btn.onclick = function () { 

    alert(pushObj.testMethod());

} 

document.body.appendChild(btn);

How do I reload a page without a POSTDATA warning in Javascript?

I had some problems with anchor/hash-urls (including #) not reloading using the solution from Rex...

So I finally ended up by removing the hash part:

window.location = window.location.href.split("#")[0];

How to break out of a loop from inside a switch?

It amazes me how simple this is considering the depth of explanations... Here's all you need...

bool imLoopin = true;

while(imLoopin) {

    switch(msg->state) {

        case MSGTYPE: // ... 
            break;

        // ... more stuff ...

        case DONE:
            imLoopin = false;
            break;

    }

}

LOL!! Really! That's all you need! One extra variable!

How to decode encrypted wordpress admin password?

just edit wp_user table with your phpmyadmin, and choose MD5 on Function field then input your new password, save it (go button). enter image description here

Handling a Menu Item Click Event - Android

Replace Your onOptionsItemSelected as:

  @Override
          public boolean onOptionsItemSelected(MenuItem item) {
            switch (item.getItemId()) {
              case OK_MENU_ITEM:
                 startActivity(new Intent(DashboardActivity.this, SettingActivity.class));
                 break;

            // You can handle other cases Here.
              default: 
                 super.onOptionsItemSelected(item);
            }
          }

Here, I want to navigate from DashboardActivity to SettingActivity.

bootstrap button shows blue outline when clicked

very simple :

.btn {outline: none;}

Best way to remove items from a collection

For a simple List structure the most efficient way seems to be using the Predicate RemoveAll implementation.

Eg.

 workSpace.RoleAssignments.RemoveAll(x =>x.Member.Name == shortName);

The reasons are:

  1. The Predicate/Linq RemoveAll method is implemented in List and has access to the internal array storing the actual data. It will shift the data and resize the internal array.
  2. The RemoveAt method implementation is quite slow, and will copy the entire underlying array of data into a new array. This means reverse iteration is useless for List

If you are stuck implementing this in a the pre c# 3.0 era. You have 2 options.

  • The easily maintainable option. Copy all the matching items into a new list and and swap the underlying list.

Eg.

List<int> list2 = new List<int>() ; 
foreach (int i in GetList())
{
    if (!(i % 2 == 0))
    {
        list2.Add(i);
    }
}
list2 = list2;

Or

  • The tricky slightly faster option, which involves shifting all the data in the list down when it does not match and then resizing the array.

If you are removing stuff really frequently from a list, perhaps another structure like a HashTable (.net 1.1) or a Dictionary (.net 2.0) or a HashSet (.net 3.5) are better suited for this purpose.

In log4j, does checking isDebugEnabled before logging improve performance?

In this particular case, Option 1 is better.

The guard statement (checking isDebugEnabled()) is there to prevent potentially expensive computation of the log message when it involves invocation of the toString() methods of various objects and concatenating the results.

In the given example, the log message is a constant string, so letting the logger discard it is just as efficient as checking whether the logger is enabled, and it lowers the complexity of the code because there are fewer branches.

Better yet is to use a more up-to-date logging framework where the log statements take a format specification and a list of arguments to be substituted by the logger—but "lazily," only if the logger is enabled. This is the approach taken by slf4j.

See my answer to a related question for more information, and an example of doing something like this with log4j.

Converting Integer to Long

Simply:

Integer i = 7;
Long l = new Long(i);

Deserialize JSON with Jackson into Polymorphic Types - A Complete Example is giving me a compile error

If using the fasterxml then,

these changes might be needed

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.Version;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.deser.std.StdDeserializer;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.node.ObjectNode;

in main method--

use

SimpleModule module =
  new SimpleModule("PolymorphicAnimalDeserializerModule");

instead of

new SimpleModule("PolymorphicAnimalDeserializerModule",
      new Version(1, 0, 0, null));

and in Animal deserialize() function, make below changes

//Iterator<Entry<String, JsonNode>> elementsIterator =  root.getFields();
Iterator<Entry<String, JsonNode>> elementsIterator = root.fields();

//return mapper.readValue(root, animalClass);
return  mapper.convertValue(root, animalClass); 

This works for fasterxml.jackson. If it still complains of the class fields. Use the same format as in the json for the field names (with "_" -underscore). as this
//mapper.setPropertyNamingStrategy(new CamelCaseNamingStrategy()); might not be supported.

abstract class Animal
{
  public String name;
}

class Dog extends Animal
{
  public String breed;
  public String leash_color;
}

class Cat extends Animal
{
  public String favorite_toy;
}

class Bird extends Animal
{
  public String wing_span;
  public String preferred_food;
}

Rollback transaction after @Test

In addition to adding @Transactional on @Test method, you also need to add @Rollback(false)

How to maintain a Unique List in Java?

I want to clarify some things here for the original poster which others have alluded to but haven't really explicitly stated. When you say that you want a Unique List, that is the very definition of an Ordered Set. Some other key differences between the Set Interface and the List interface are that List allows you to specify the insert index. So, the question is do you really need the List Interface (i.e. for compatibility with a 3rd party library, etc.), or can you redesign your software to use the Set interface? You also have to consider what you are doing with the interface. Is it important to find elements by their index? How many elements do you expect in your set? If you are going to have many elements, is ordering important?

If you really need a List which just has a unique constraint, there is the Apache Common Utils class org.apache.commons.collections.list.SetUniqueList which will provide you with the List interface and the unique constraint. Mind you, this breaks the List interface though. You will, however, get better performance from this if you need to seek into the list by index. If you can deal with the Set interface, and you have a smaller data set, then LinkedHashSet might be a good way to go. It just depends on the design and intent of your software.

Again, there are certain advantages and disadvantages to each collection. Some fast inserts but slow reads, some have fast reads but slow inserts, etc. It makes sense to spend a fair amount of time with the collections documentation to fully learn about the finer details of each class and interface.

Loop inside React JSX

You have to write in JSX:

<tbody>
    {
        objects.map((object, i) => (
            <ObjectRow obj={object} key={i} />
        ));
    }
</tbody>

How do I run a program with commandline arguments using GDB within a Bash script?

gdb -ex=r --args myprogram arg1 arg2

-ex=r is short for -ex=run and tells gdb to run your program immediately, rather than wait for you to type "run" at the prompt. Then --args says that everything that follows is the command and arguments, just as you'd normally type them at the commandline prompt.

Factorial in numpy and scipy

    from numpy import prod

    def factorial(n):
        print prod(range(1,n+1))

or with mul from operator:

    from operator import mul

    def factorial(n):
        print reduce(mul,range(1,n+1))

or completely without help:

    def factorial(n):
        print reduce((lambda x,y: x*y),range(1,n+1))

How to calculate the intersection of two sets?

Yes there is retainAll check out this

Set<Type> intersection = new HashSet<Type>(s1);
intersection.retainAll(s2);

SQL Server SELECT into existing table

If the destination table does exist but you don't want to specify column names:

DECLARE @COLUMN_LIST NVARCHAR(MAX);
DECLARE @SQL_INSERT NVARCHAR(MAX);

SET @COLUMN_LIST = (SELECT DISTINCT
    SUBSTRING(
        (
            SELECT ', table1.' + SYSCOL1.name  AS [text()]
            FROM sys.columns SYSCOL1
            WHERE SYSCOL1.object_id = SYSCOL2.object_id and SYSCOL1.is_identity <> 1
            ORDER BY SYSCOL1.object_id
            FOR XML PATH ('')
        ), 2, 1000)
FROM
    sys.columns SYSCOL2
WHERE
    SYSCOL2.object_id = object_id('dbo.TableOne') )

SET @SQL_INSERT =  'INSERT INTO dbo.TableTwo SELECT ' + @COLUMN_LIST + ' FROM dbo.TableOne table1 WHERE col3 LIKE ' + @search_key
EXEC sp_executesql @SQL_INSERT

How do you properly determine the current script directory?

First.. a couple missing use-cases here if we're talking about ways to inject anonymous code..

code.compile_command()
code.interact()
imp.load_compiled()
imp.load_dynamic()
imp.load_module()
__builtin__.compile()
loading C compiled shared objects? example: _socket?)

But, the real question is, what is your goal - are you trying to enforce some sort of security? Or are you just interested in whats being loaded.

If you're interested in security, the filename that is being imported via exec/execfile is inconsequential - you should use rexec, which offers the following:

This module contains the RExec class, which supports r_eval(), r_execfile(), r_exec(), and r_import() methods, which are restricted versions of the standard Python functions eval(), execfile() and the exec and import statements. Code executed in this restricted environment will only have access to modules and functions that are deemed safe; you can subclass RExec add or remove capabilities as desired.

However, if this is more of an academic pursuit.. here are a couple goofy approaches that you might be able to dig a little deeper into..

Example scripts:

./deep.py

print ' >> level 1'
execfile('deeper.py')
print ' << level 1'

./deeper.py

print '\t >> level 2'
exec("import sys; sys.path.append('/tmp'); import deepest")
print '\t << level 2'

/tmp/deepest.py

print '\t\t >> level 3'
print '\t\t\t I can see the earths core.'
print '\t\t << level 3'

./codespy.py

import sys, os

def overseer(frame, event, arg):
    print "loaded(%s)" % os.path.abspath(frame.f_code.co_filename)

sys.settrace(overseer)
execfile("deep.py")
sys.exit(0)

Output

loaded(/Users/synthesizerpatel/deep.py)
>> level 1
loaded(/Users/synthesizerpatel/deeper.py)
    >> level 2
loaded(/Users/synthesizerpatel/<string>)
loaded(/tmp/deepest.py)
        >> level 3
            I can see the earths core.
        << level 3
    << level 2
<< level 1

Of course, this is a resource-intensive way to do it, you'd be tracing all your code.. Not very efficient. But, I think it's a novel approach since it continues to work even as you get deeper into the nest. You can't override 'eval'. Although you can override execfile().

Note, this approach only coveres exec/execfile, not 'import'. For higher level 'module' load hooking you might be able to use use sys.path_hooks (Write-up courtesy of PyMOTW).

Thats all I have off the top of my head.

How to animate button in android?

Dependency

Add it in your root build.gradle at the end of repositories:

allprojects {
repositories {
    ...
    maven { url "https://jitpack.io" }
}}

and then add dependency dependencies { compile 'com.github.varunest:sparkbutton:1.0.5' }

Usage

XML

<com.varunest.sparkbutton.SparkButton
        android:id="@+id/spark_button"
        android:layout_width="40dp"
        android:layout_height="40dp"
        app:sparkbutton_activeImage="@drawable/active_image"
        app:sparkbutton_inActiveImage="@drawable/inactive_image"
        app:sparkbutton_iconSize="40dp"
        app:sparkbutton_primaryColor="@color/primary_color"
        app:sparkbutton_secondaryColor="@color/secondary_color" />

Java (Optional)

SparkButton button  = new SparkButtonBuilder(context)
            .setActiveImage(R.drawable.active_image)
            .setInActiveImage(R.drawable.inactive_image)
            .setDisabledImage(R.drawable.disabled_image)
            .setImageSizePx(getResources().getDimensionPixelOffset(R.dimen.button_size))
            .setPrimaryColor(ContextCompat.getColor(context, R.color.primary_color))
            .setSecondaryColor(ContextCompat.getColor(context, R.color.secondary_color))
            .build();

Printing long int value in C

To take input " long int " and output " long int " in C is :

long int n;
scanf("%ld", &n);
printf("%ld", n);

To take input " long long int " and output " long long int " in C is :

long long int n;
scanf("%lld", &n);
printf("%lld", n);

Hope you've cleared..

A 'for' loop to iterate over an enum in Java

Try to use a for each

for ( Direction direction : Direction.values()){
  System.out.println(direction.toString());
}

"No backupset selected to be restored" SQL Server 2012

I have run into the same issue. Run SSMS as administrator then right click and do database restore. Should work.

TabLayout tab selection

This is how I solved it:

void selectPage(int pageIndex){
    tabLayout.setScrollPosition(pageIndex,0f,true);
    viewPager.setCurrentItem(pageIndex);
}

How to implement zoom effect for image view in android?

Here is a great example on how to implement zoom affect on touch with a imageview

Zoom effect on imageview

EDIT:

Also here is another great one.

Pinch to zoom tutorial

javascript: calculate x% of a number

var number = 10000;
var result = .358 * number;

Getting index value on razor foreach

 @{int i = 0;}
 @foreach(var myItem in Model.Members)
 {
     <span>@i</span>
     @{i++;
      }
 }

// Use @{i++ to increment value}

Reading InputStream as UTF-8

String file = "";

try {

    InputStream is = new FileInputStream(filename);
    String UTF8 = "utf8";
    int BUFFER_SIZE = 8192;

    BufferedReader br = new BufferedReader(new InputStreamReader(is,
            UTF8), BUFFER_SIZE);
    String str;
    while ((str = br.readLine()) != null) {
        file += str;
    }
} catch (Exception e) {

}

Try this,.. :-)

java.lang.RuntimeException: com.android.builder.dexing.DexArchiveMergerException: Unable to merge dex in Android Studio 3.0

Enable Multidex through build.gradle of your app module

multiDexEnabled true

Same as below -

android {
    compileSdkVersion 27
    defaultConfig {
        applicationId "com.xx.xxx"
        minSdkVersion 15
        targetSdkVersion 27
        versionCode 1
        versionName "1.0"
        multiDexEnabled true //Add this
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            shrinkResources true
            minifyEnabled true
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
}

Then follow below steps -

  1. From the Build menu -> press the Clean Project button.
  2. When task completed, press the Rebuild Project button from the Build menu.
  3. From menu File -> Invalidate cashes / Restart

compile is now deprecated so it's better to use implementation or api

How to VueJS router-link active style

The :active pseudo-class is not the same as adding a class to style the element.

The :active CSS pseudo-class represents an element (such as a button) that is being activated by the user. When using a mouse, "activation" typically starts when the mouse button is pressed down and ends when it is released.

What we are looking for is a class, such as .active, which we can use to style the navigation item.

For a clearer example of the difference between :active and .active see the following snippet:

_x000D_
_x000D_
li:active {_x000D_
  background-color: #35495E;_x000D_
}_x000D_
_x000D_
li.active {_x000D_
  background-color: #41B883;_x000D_
}
_x000D_
<ul>_x000D_
  <li>:active (pseudo-class) - Click me!</li>_x000D_
  <li class="active">.active (class)</li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_


Vue-Router

vue-router automatically applies two active classes, .router-link-active and .router-link-exact-active, to the <router-link> component.


router-link-active

This class is applied automatically to the <router-link> component when its target route is matched.

The way this works is by using an inclusive match behavior. For example, <router-link to="/foo"> will get this class applied as long as the current path starts with /foo/ or is /foo.

So, if we had <router-link to="/foo"> and <router-link to="/foo/bar">, both components would get the router-link-active class when the path is /foo/bar.


router-link-exact-active

This class is applied automatically to the <router-link> component when its target route is an exact match. Take into consideration that both classes, router-link-active and router-link-exact-active, will be applied to the component in this case.

Using the same example, if we had <router-link to="/foo"> and <router-link to="/foo/bar">, the router-link-exact-activeclass would only be applied to <router-link to="/foo/bar"> when the path is /foo/bar.


The exact prop

Lets say we have <router-link to="/">, what will happen is that this component will be active for every route. This may not be something that we want, so we can use the exact prop like so: <router-link to="/" exact>. Now the component will only get the active class applied when it is an exact match at /.


CSS

We can use these classes to style our element, like so:

 nav li:hover,
 nav li.router-link-active,
 nav li.router-link-exact-active {
   background-color: indianred;
   cursor: pointer;
 }

The <router-link> tag was changed using the tag prop, <router-link tag="li" />.


Change default classes globally

If we wish to change the default classes provided by vue-router globally, we can do so by passing some options to the vue-router instance like so:

const router = new VueRouter({
  routes,
  linkActiveClass: "active",
  linkExactActiveClass: "exact-active",
})

Change default classes per component instance (<router-link>)

If instead we want to change the default classes per <router-link> and not globally, we can do so by using the active-class and exact-active-class attributes like so:

<router-link to="/foo" active-class="active">foo</router-link>

<router-link to="/bar" exact-active-class="exact-active">bar</router-link>

v-slot API

Vue Router 3.1.0+ offers low level customization through a scoped slot. This comes handy when we wish to style the wrapper element, like a list element <li>, but still keep the navigation logic in the anchor element <a>.

<router-link
  to="/foo"
  v-slot="{ href, route, navigate, isActive, isExactActive }"
>
  <li
    :class="[isActive && 'router-link-active', isExactActive && 'router-link-exact-active']"
  >
    <a :href="href" @click="navigate">{{ route.fullPath }}</a>
  </li>
</router-link>

CSS technique for a horizontal line with words in the middle

CSS grids to the rescue

Similar to the flex answers above, this can also be done using CSS Grids. This gives you more scope to offset the title, and a more simple way of expanding the gap between the lines (using grid-template-columns) and the content (using grid-gap).

The benefits of this method over flex methods is the ease of being able to offset the lines, and additionally only needing to add in a gap between columns once (not twice, for each the :before and :after pseudo element). It is also much more syntactically cleaner and obvious IMO.

_x000D_
_x000D_
h1 {
  display: grid;
  grid-template-columns: 1fr auto 1fr;
  align-items: center;
  grid-gap: 1rem;
}

h1:before,
h1:after {
  content: "";
  display: block;
  border-top: 2px solid currentColor;
}

h1.offset {
  grid-template-columns: 1fr auto 3fr;
}

h1.biggap {
  grid-gap: 4rem;
}
_x000D_
<h1>This is a title</h1>

<h1 class="offset">Offset title</h1>

<h1 class="biggap">Gappy title</h1>

<h1>
  <span>Multi-line<br />title</span>
</h1>
_x000D_
_x000D_
_x000D_

How to navigate to a section of a page

Use an call thru section, it works

<div id="content">
     <section id="home">
               ...
     </section>

Call the above the thru

 <a href="#home">page1</a>

Scrolling needs jquery paste this.. on above to ending body closing tag..

<script>
  $(function() {
      $('a[href*=#]:not([href=#])').click(function() {
          if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
              var target = $(this.hash);
              target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
              if (target.length) {
                  $('html,body').animate({
                      scrollTop: target.offset().top
                  }, 1000);
                  return false;
              }
          }
      });
  });
</script>

CSS hexadecimal RGBA?

See here http://www.w3.org/TR/css3-color/#rgba-color

It is not possible, most probably because 0xFFFFFFFF is greater than the maximum value for 32bit integers

What is JavaScript's highest integer value that a number can go to without losing precision?

I did a simple test with a formula, X-(X+1)=-1, and the largest value of X I can get to work on Safari, Opera and Firefox (tested on OS X) is 9e15. Here is the code I used for testing:

javascript: alert(9e15-(9e15+1));

Valid content-type for XML, HTML and XHTML documents

HTML: text/html, full-stop.

XHTML: application/xhtml+xml, or only if following HTML compatbility guidelines, text/html. See the W3 Media Types Note.

XML: text/xml, application/xml (RFC 2376).

There are also many other media types based around XML, for example application/rss+xml or image/svg+xml. It's a safe bet that any unrecognised but registered ending in +xml is XML-based. See the IANA list for registered media types ending in +xml.

(For unregistered x- types, all bets are off, but you'd hope +xml would be respected.)

Indenting code in Sublime text 2?

There is no default shortcut for reindenting a file. However you can create one by following eznme's answer above.

You can also use the Command Palette by pressing:

  1. Control+Shift+P (or ?+Shift+P on a Mac)
  2. Type the first few characters of Reindent e.g: rein
  3. Press Enter to run the command
    (The first command at the top should now show Indentation: Reindent Lines)

How to make Firefox headless programmatically in Selenium with Python?

The first answer does't work anymore.

This worked for me:

from selenium.webdriver.firefox.options import Options as FirefoxOptions
from selenium import webdriver

options = FirefoxOptions()
options.add_argument("--headless")
driver = webdriver.Firefox(options=options)
driver.get("http://google.com")

Use grep --exclude/--include syntax to not grep through certain files

In grep 2.5.1 you have to add this line to ~/.bashrc or ~/.bash profile

export GREP_OPTIONS="--exclude=\*.svn\*"

Understanding `scale` in R

I thought I would contribute by providing a concrete example of the practical use of the scale function. Say you have 3 test scores (Math, Science, and English) that you want to compare. Maybe you may even want to generate a composite score based on each of the 3 tests for each observation. Your data could look as as thus:

student_id <- seq(1,10)
math <- c(502,600,412,358,495,512,410,625,573,522)
science <- c(95,99,80,82,75,85,80,95,89,86)
english <- c(25,22,18,15,20,28,15,30,27,18)
df <- data.frame(student_id,math,science,english)

Obviously it would not make sense to compare the means of these 3 scores as the scale of the scores are vastly different. By scaling them however, you have more comparable scoring units:

z <- scale(df[,2:4],center=TRUE,scale=TRUE)

You could then use these scaled results to create a composite score. For instance, average the values and assign a grade based on the percentiles of this average. Hope this helped!

Note: I borrowed this example from the book "R In Action". It's a great book! Would definitely recommend.

Read an Excel file directly from a R script

Expanding on the answer provided by @Mikko you can use a neat trick to speed things up without having to "know" your column classes ahead of time. Simply use read.xlsx to grab a limited number of records to determine the classes and then followed it up with read.xlsx2

Example

# just the first 50 rows should do...
df.temp <- read.xlsx("filename.xlsx", 1, startRow=1, endRow=50) 
df.real <- read.xlsx2("filename.xlsx", 1, 
                      colClasses=as.vector(sapply(df.temp, mode)))

How to debug external class library projects in visual studio?

Assume the path of

Project A

C:\Projects\ProjectA

Project B

C:\Projects\ProjectB

and the dll of ProjectB is in

C:\Projects\ProjectB\bin\Debug\

To debug into ProjectB from ProjectA, do the following

  1. Copy B's dll with dll's .PDB to the ProjectA's compiling directory.
  2. Now debug ProjectA. When code reaches the part where you need to call dll's method or events etc while debugging, press F11 to step into the dll's code.

NOTE : DO NOT MISS TO COPY THE .PDB FILE

Notification Icon with the new Firebase Cloud Messaging system

Just set targetSdkVersion to 19. The notification icon will be colored. Then wait for Firebase to fix this issue.

Angular ng-class if else

Both John Conde's and ryeballar's answers are correct and will work.

If you want to get too geeky:

  • John's has the downside that it has to make two decisions per $digest loop (it has to decide whether to add/remove center and it has to decide whether to add/remove left), when clearly only one is needed.

  • Ryeballar's relies on the ternary operator which is probably going to be removed at some point (because the view should not contain any logic). (We can't be sure it will indeed be removed and it probably won't be any time soon, but if there is a more "safe" solution, why not ?)


So, you can do the following as an alternative:

ng-class="{true:'center',false:'left'}[page.isSelected(1)]"

Eliminate extra separators below UITableView

You can just add an empty footer at the end then it will hide the empty cells but it will also look quite ugly:

tableView.tableFooterView = UIView()

enter image description here

There is a better approach: add a 1 point line at the end of the table view as the footer and the empty cells will also not been shown anymore.

let footerView = UIView()
footerView.frame = CGRect(x: 0, y: 0, width: tableView.frame.size.width, height: 1)
footerView.backgroundColor = tableView.separatorColor
tableView.tableFooterView = footerView

enter image description here

Finding modified date of a file/folder

Here's what worked for me:

$a = Get-ChildItem \\server\XXX\Received_Orders\*.* | Where{$_.LastWriteTime -ge (Get-Date).AddDays(-7)}
if ($a = (Get-ChildItem \\server\XXX\Received_Orders\*.* | Where{$_.LastWriteTime -gt (Get-Date).AddDays(-7)}  
#Im using the -gt switch instead of -ge
{}
Else
{
'STORE XXX HAS NOT RECEIVED ANY ORDERS IN THE PAST 7 DAYS'
}


$b = Get-ChildItem \\COMP NAME\Folder\*.* | Where{$_.LastWriteTime -ge (Get-Date).AddDays(-1)}
if ($b = (Get-ChildItem \\COMP NAME\TFolder\*.* | Where{$_.LastWriteTime -gt (Get-Date).AddDays(-1)))}
{}
Else
{
'STORE XXX DID NOT RUN ITS BACKUP LAST NIGHT'
}

Change GitHub Account username

Yes, it's possible. But first read, "What happens when I change my username?"

To change your username, click your profile picture in the top right corner, then click Settings. On the left side, click Account. Then click Change username.

Two HTML tables side by side, centered on the page

Give your inner div a width.

EXAMPLE

Change your CSS:

<style>
#outer { text-align: center; }
#inner { text-align: left; margin: 0 auto; }
.t { float: left; }
table { border: 1px solid black; }
#clearit { clear: left; }
</style>

To this:

<style>
#outer { text-align: center; }
#inner { text-align: left; margin: 0 auto; width:500px }
.t { float: left; }
table { border: 1px solid black; }
#clearit { clear: left; }
</style>

HTTP POST with Json on Body - Flutter/Dart

This would also work :

import 'package:http/http.dart' as http;

  sendRequest() async {

    Map data = {
       'apikey': '12345678901234567890'
    };

    var url = 'https://pae.ipportalegre.pt/testes2/wsjson/api/app/ws-authenticate';
    http.post(url, body: data)
        .then((response) {
      print("Response status: ${response.statusCode}");
      print("Response body: ${response.body}");
    });  
  }

How to tackle daylight savings using TimeZone in Java

Other answers are correct, especially the one by Jon Skeet, but outdated.

java.time

These old date-time classes have been supplanted by the java.time framework built into Java 8 and later.

If you simply want the current time in UTC, use the Instant class.

Instant now = Instant.now();

EST is not a time zone, as explained in the correct Answer by Jon Skeet. Such 3-4 letter codes are neither standardized nor unique, and further the confusion over Daylight Saving Time (DST). Use a proper time zone name in the "continent/region" format.

Perhaps you meant Eastern Standard Time in east coast of north America? Or Egypt Standard Time? Or European Standard Time?

ZoneId zoneId = ZoneId.of( "America/New_York" );
ZoneId zoneId = ZoneId.of( "Africa/Cairo" );
ZoneId zoneId = ZoneId.of( "Europe/Lisbon" );

Use any such ZoneId object to get the current moment adjusted to a particular time zone to produce a ZonedDateTime object.

ZonedDateTime zdt = ZonedDateTime.now( zoneId ) ;

Adjust that ZonedDateTime into a different time zone by producing another ZonedDateTime object from the first. The java.time framework uses immutable objects rather than changing (mutating) existing objects.

ZonedDateTime zdtGuam = zdt.withZoneSameInstant( ZoneId.of( "Pacific/Guam" ) ) ;

Table of date-time types in Java, both modern and legacy.

What's the difference between commit() and apply() in SharedPreferences

The docs give a pretty good explanation of the difference between apply() and commit():

Unlike commit(), which writes its preferences out to persistent storage synchronously, apply() commits its changes to the in-memory SharedPreferences immediately but starts an asynchronous commit to disk and you won't be notified of any failures. If another editor on this SharedPreferences does a regular commit() while a apply() is still outstanding, the commit() will block until all async commits are completed as well as the commit itself. As SharedPreferences instances are singletons within a process, it's safe to replace any instance of commit() with apply() if you were already ignoring the return value.

Read text file into string. C++ ifstream

To read a whole line from a file into a string, use std::getline like so:

 std::ifstream file("my_file");
 std::string temp;
 std::getline(file, temp);

You can do this in a loop to until the end of the file like so:

 std::ifstream file("my_file");
 std::string temp;
 while(std::getline(file, temp)) {
      //Do with temp
 }

References

http://en.cppreference.com/w/cpp/string/basic_string/getline

http://en.cppreference.com/w/cpp/string/basic_string

Nginx Different Domains on Same IP

Your "listen" directives are wrong. See this page: http://nginx.org/en/docs/http/server_names.html.

They should be

server {
    listen      80;
    server_name www.domain1.com;
    root /var/www/domain1;
}

server {
    listen       80;
    server_name www.domain2.com;
    root /var/www/domain2;
}

Note, I have only included the relevant lines. Everything else looked okay but I just deleted it for clarity. To test it you might want to try serving a text file from each server first before actually serving php. That's why I left the 'root' directive in there.

How to delete rows in tables that contain foreign keys to other tables

Need to set the foreign key option as on delete cascade... in tables which contains foreign key columns.... It need to set at the time of table creation or add later using ALTER table

How to get a password from a shell script without echoing

A POSIX compliant answer. Notice the use of /bin/sh instead of /bin/bash. (It does work with bash, but it does not require bash.)

#!/bin/sh
stty -echo
printf "Password: "
read PASSWORD
stty echo
printf "\n"

Launch Image does not show up in my iOS App

* (Xcode 7.2 / Deployment Target 7.0 / Landscape Orientation Only) *

I know is an old question but with Xcode 7.2 I'm still getting the message and I fixed with this:

1) Select PORTRAIT and both landscapes. Add "Launch Images Source" and "Launch Screen File"

enter image description here

2) In your Launch Image select iPhone "8.0 and Later" and "7.0 and Later".

enter image description here

3) Add this code in your appDelegate:

#if __IPHONE_OS_VERSION_MAX_ALLOWED < 90000
- (NSUInteger)supportedInterfaceOrientations
{
    return UIInterfaceOrientationMaskLandscape;
}
#else
- (UIInterfaceOrientationMask)application:(UIApplication *)application     supportedInterfaceOrientationsForWindow:(UIWindow *)window
{
    return (UIInterfaceOrientationMaskLandscape);
}
#endif

4) Add this on your ViewController

#if __IPHONE_OS_VERSION_MAX_ALLOWED < 90000
- (NSUInteger)supportedInterfaceOrientations
#else
- (UIInterfaceOrientationMask)supportedInterfaceOrientations
#endif
{
     return UIInterfaceOrientationMaskLandscape;
}

I hope help to somebody else.

bool to int conversion

Section 6.5.8.6 of the C standard says:

Each of the operators < (less than), > (greater than), <= (less than or equal to), and >= (greater than or equal to) shall yield 1 if the specified relation is true and 0 if it is false.) The result has type int.

A div with auto resize when changing window width\height

  <!DOCTYPE html>
    <html>
  <head>
  <style> 
   div {

   padding: 20px; 

   resize: both;
  overflow: auto;
   }
    img{
   height: 100%;
    width: 100%;
 object-fit: contain;
 }
 </style>
  </head>
  <body>
 <h1>The resize Property</h1>

 <div>
 <p>Let the user resize both the height and the width of this 1234567891011 div 
   element. 
  </p>
 <p>To resize: Click and drag the bottom right corner of this div element.</p>
  <img src="images/scenery.jpg" alt="Italian ">
  </div>

   <p><b>Note:</b> Internet Explorer does not support the resize property.</p>

 </body>
 </html>

How to pass data to all views in Laravel 5?

The documentation is hear https://laravel.com/docs/5.4/views#view-composers but i will break it down

  1. Look for the directory app\Providers in the root directory of your application and create the file ComposerServiceProvider.php and copy and past the text below into it and save it.

    <?php
        namespace App\Providers;
        use Illuminate\Support\Facades\View;
        use Illuminate\Support\ServiceProvider;
    
        class ComposerServiceProvider extends ServiceProvider
        {
            /**
            * Register bindings in the container.
            *
            * @return void
            */
        public function boot()
        {
            // Using class based composers...
            View::composer(
                'profile', 'App\Http\ViewComposers\ProfileComposer'
            );
    
            // Using Closure based composers...
            View::composer('dashboard', function ($view) {
                //
            });
        }
    
        /**
        * Register the service provider.
        *
        * @return void
        */
        public function register()
        {
            //
        }
    }
    
  2. From the root of your application open Config/app.php and look for the Providers section in the file and copy and past this 'App\Providers\ComposerServiceProvider', to the array.

By doing this, we have created the Composer Service Provider. When you run your application with the view Profile like so http://yourdomain/something/profile, the service provider ComposerServiceProvider is called and the class App\Http\ViewComposers\ProfileComposer is instantiated calling the method Composer due to the code below inside the boot method or function.

 // Using class based composers...
 View::composer(
   'profile', 'App\Http\ViewComposers\ProfileComposer'
 );
  1. If you refresh your application you will get an error because the class App\Http\ViewComposers\ProfileComposer does not exist yet. Now lets create it.

Go to the directory path app/Http

  • Create the directory called ViewComposers

  • Create the file ProfileComposer.php.

    class ProfileComposer
    {
        /**
        * The user repository implementation.
        *
        * @var UserRepository
        */
        protected $users;
    
        /**
        * Create a new profile composer.
        *
        * @param  UserRepository  $users
        * @return void
        */
        public function __construct(UserRepository $users)
        {
            // Dependencies automatically resolved by service container...
            $this->users = $users;
        }
    
        /**
        * Bind data to the view.
        *
        * @param  View  $view
        * @return void
        */
        public function compose(View $view)
        {
            $view->with('count', $this->users->count());
        }
    }
    

Now go to your view or in this case Profile.blade.php and add

{{ $count }}

and that will show the count of users on the profile page.

To show the count on all pages change

// Using class based composers...
View::composer(
    'profile', 'App\Http\ViewComposers\ProfileComposer'
);

To

// Using class based composers...
View::composer(
    '*', 'App\Http\ViewComposers\ProfileComposer'
);

Creating an iframe with given HTML dynamically

Setting the src of a newly created iframe in javascript does not trigger the HTML parser until the element is inserted into the document. The HTML is then updated and the HTML parser will be invoked and process the attribute as expected.

http://jsfiddle.net/9k9Pe/2/

var iframe = document.createElement('iframe');
var html = '<body>Foo</body>';
iframe.src = 'data:text/html;charset=utf-8,' + encodeURI(html);
document.body.appendChild(iframe);
console.log('iframe.contentWindow =', iframe.contentWindow);

Also this answer your question it's important to note that this approach has compatibility issues with some browsers, please see the answer of @mschr for a cross-browser solution.

Finding all possible combinations of numbers to reach a given sum

C++ version of the same algorithm

#include <iostream>
#include <list>
void subset_sum_recursive(std::list<int> numbers, int target, std::list<int> partial)
{
        int s = 0;
        for (std::list<int>::const_iterator cit = partial.begin(); cit != partial.end(); cit++)
        {
            s += *cit;
        }
        if(s == target)
        {
                std::cout << "sum([";

                for (std::list<int>::const_iterator cit = partial.begin(); cit != partial.end(); cit++)
                {
                    std::cout << *cit << ",";
                }
                std::cout << "])=" << target << std::endl;
        }
        if(s >= target)
            return;
        int n;
        for (std::list<int>::const_iterator ai = numbers.begin(); ai != numbers.end(); ai++)
        {
            n = *ai;
            std::list<int> remaining;
            for(std::list<int>::const_iterator aj = ai; aj != numbers.end(); aj++)
            {
                if(aj == ai)continue;
                remaining.push_back(*aj);
            }
            std::list<int> partial_rec=partial;
            partial_rec.push_back(n);
            subset_sum_recursive(remaining,target,partial_rec);

        }
}

void subset_sum(std::list<int> numbers,int target)
{
    subset_sum_recursive(numbers,target,std::list<int>());
}
int main()
{
    std::list<int> a;
    a.push_back (3); a.push_back (9); a.push_back (8);
    a.push_back (4);
    a.push_back (5);
    a.push_back (7);
    a.push_back (10);
    int n = 15;
    //std::cin >> n;
    subset_sum(a, n);
    return 0;
}

MVC 3 file upload and model binding

Your form doesn't contain any input tag other than the file so in your controller action you cannot expect to get anything else than the uploaded file (that's all that's being sent to the server). One way to achieve this would be to include a hidden tag containing the id of the model which will allow you to retrieve it from your datastore inside the controller action you are posting to (use this if the user is not supposed to modify the model but simply attach a file):

@using (Html.BeginForm("Uploadfile", "Containers", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    @Html.HiddenFor(x => x.Id)
    <input type="file" name="file" id="file" />
    <input type="submit" value="submit" />
}

and then in your controller action:

[HttpPost]
public ActionResult Uploadfile(int id, HttpPostedFileBase file)
{
    Containers containers = Repository.GetContainers(id);
    ...
}

On the other hand if you wanted to allow the user to modify this model then you will need to include the proper input fields for each field of your model that you want to be sent to the server:

@using (Html.BeginForm("Uploadfile", "Containers", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    @Html.TextBoxFor(x => x.Prop1)
    @Html.TextBoxFor(x => x.Prop2)
    @Html.TextBoxFor(x => x.Prop3)
    <input type="file" name="file" id="file" />
    <input type="submit" value="submit" />
}

and then you will have the default model binder reconstruct this model from the request:

[HttpPost]
public ActionResult Uploadfile(Container containers, HttpPostedFileBase file)
{
    ...
}

Leave menu bar fixed on top when scrolled

try with sticky jquery plugin

https://github.com/garand/sticky

_x000D_
_x000D_
<script src="jquery.js"></script>_x000D_
<script src="jquery.sticky.js"></script>_x000D_
<script>_x000D_
  $(document).ready(function(){_x000D_
    $("#sticker").sticky({topSpacing:0});_x000D_
  });_x000D_
</script>
_x000D_
_x000D_
_x000D_

How do I create a dictionary with keys from a list and values defaulting to (say) zero?

dict((el,0) for el in a) will work well.

Python 2.7 and above also support dict comprehensions. That syntax is {el:0 for el in a}.

how to File.listFiles in alphabetical order?

This is my code:

_x000D_
_x000D_
        try {_x000D_
            String folderPath = "../" + filePath.trim() + "/";_x000D_
            logger.info("Path: " + folderPath);_x000D_
            File folder = new File(folderPath);_x000D_
            File[] listOfFiles = folder.listFiles();_x000D_
            int length = listOfFiles.length;_x000D_
            logger.info("So luong files: " + length);_x000D_
            ArrayList<CdrFileBO> lstFile = new ArrayList< CdrFileBO>();_x000D_
_x000D_
            if (listOfFiles != null && length > 0) {_x000D_
                int count = 0;_x000D_
                for (int i = 0; i < length; i++) {_x000D_
                    if (listOfFiles[i].isFile()) {_x000D_
                        lstFile.add(new CdrFileBO(listOfFiles[i]));_x000D_
                    }_x000D_
                }_x000D_
                Collections.sort(lstFile);_x000D_
                for (CdrFileBO bo : lstFile) {_x000D_
                    //String newName = START_NAME + "_" + getSeq(SEQ_START) + "_" + DateSTR + ".s";_x000D_
                    String newName = START_NAME + DateSTR + getSeq(SEQ_START) + ".DAT";_x000D_
                    SEQ_START = SEQ_START + 1;_x000D_
                    bo.getFile().renameTo(new File(folderPath + newName));_x000D_
                    logger.info("newName: " + newName);_x000D_
                    logger.info("Next file: " + getSeq(SEQ_START));_x000D_
                }_x000D_
_x000D_
            }_x000D_
        } catch (Exception ex) {_x000D_
            logger.error(ex);_x000D_
            ex.printStackTrace();_x000D_
        }
_x000D_
_x000D_
_x000D_

Using Caps Lock as Esc in Mac OS X

It's possible.

Solution 1

From an arcticle on TrueAffection.net.

  • Download PCKeyboardHack and install it.
  • Go to PCKeyboardHack in System Preferences.
  • Enable ‘Change Caps Lock’ and set the keycode to 53.

Solution 2

This solution doesn't involve patching the keyboard driver, but gives you a Vim specific solution.

OS X supports mapping the Caps Lock key to a whole bunch of keys, but you have to do it 'by hand', editting .plist files. The process is described in this article. As addendum to that hint I suggest you first set Caps-Lock to None in the System Preferences, then you only need to change one value in the .plist file. Also, you can of course use the Property List Editor instead of going through the XML conversion steps.

The trick is to map the Caps Lock key to the Help key (code 6), which isn't on most keyboards. But if it is, it will be treated as the insert key, which you probably don't use anyway, since you ask about remapping your Caps Lock to prevent stretching your hands ;)

You can then map the Help and the Insert key to Esc in vim.

map  <Help> <Esc>
map! <Help> <Esc>
map  <Insert> <Esc>
map! <Insert> <Esc>

This will work for gvim (Vim.app). I didn't get it to work with vim in the Terminal and I haven't tested it with MacVim.

So, it's rather a complicated, half-baked solution or installing a third-party piece of hackery. Your pick ;)

Edit: Just noticed solution 3, if you're using MacVim you can use Ctrl, Option and Command as Esc. With the System Preferences it's trivial to map Caps Lock to one of those keys.

ssh: The authenticity of host 'hostname' can't be established

To disable (or control disabling), add the following lines to the beginning of /etc/ssh/ssh_config...

Host 192.168.0.*
   StrictHostKeyChecking=no
   UserKnownHostsFile=/dev/null

Options:

  • The Host subnet can be * to allow unrestricted access to all IPs.
  • Edit /etc/ssh/ssh_config for global configuration or ~/.ssh/config for user-specific configuration.

See http://linuxcommando.blogspot.com/2008/10/how-to-disable-ssh-host-key-checking.html

Similar question on superuser.com - see https://superuser.com/a/628801/55163

How to divide two columns?

Presumably, those columns are integer columns - which will be the reason as the result of the calculation will be of the same type.

e.g. if you do this:

SELECT 1 / 2

you will get 0, which is obviously not the real answer. So, convert the values to e.g. decimal and do the calculation based on that datatype instead.

e.g.

SELECT CAST(1 AS DECIMAL) / 2

gives 0.500000

WebSocket connection failed: Error during WebSocket handshake: Unexpected response code: 400

I solved this by changing transports from 'websocket' to 'polling'

   var socket = io.connect('xxx.xxx.xxx.xxx:8000', {
      transports: ['polling']
   });

How to merge two arrays in JavaScript and de-duplicate items

for the sake of it... here is a single line solution:

const x = [...new Set([['C', 'B'],['B', 'A']].reduce( (a, e) => a.concat(e), []))].sort()
// ['A', 'B', 'C']

Not particularly readable but it may help someone:

  1. Applies a reduce function with the initial accumulator value set to an empty array.
  2. The reduce function uses concat to append each sub-array onto the accumulator array.
  3. The result of this is passed as a constructor parameter to create a new Set.
  4. The spread operator is used to convert the Set to an array.
  5. The sort() function is applied to the new array.

Creating threads - Task.Factory.StartNew vs new Thread()

There is a big difference. Tasks are scheduled on the ThreadPool and could even be executed synchronous if appropiate.

If you have a long running background work you should specify this by using the correct Task Option.

You should prefer Task Parallel Library over explicit thread handling, as it is more optimized. Also you have more features like Continuation.

File 'app/hero.ts' is not a module error in the console, where to store interfaces files in directory structure with angular2?

As I experienced whenever I add a new file to my project, I got to stop and restarting the ng server.

How to query values from xml nodes?

This works, been tested...

SELECT  n.c.value('OrganizationReportReferenceIdentifier[1]','varchar(128)') AS 'OrganizationReportReferenceNumber',  
        n.c.value('(OrganizationNumber)[1]','varchar(128)') AS 'OrganizationNumber'
FROM    Batches t
Cross   Apply RawXML.nodes('/GrobXmlFile/Grob/ReportHeader') n(c)  

Get remote registry value

Try the Remote Registry Module, the registry provider cannot operate remotely:

Import-Module PSRemoteRegistry
Get-RegValue -ComputerName $Computer1 -Key SOFTWARE\Veritas\NetBackup\CurrentVersion -Value PackageVersion 

C# error: Use of unassigned local variable

A couple of different ways to solve the problem:

Just replace Environment.Exit with return. The compiler knows that return ends the method, but doesn't know that Environment.Exit does.

static void Main(string[] args) {
    if(args.Length != 0) {
       if(Byte.TryParse(args[0], out maxSize))
         queue = new Queue(){MaxSize = maxSize};
       else
         return;
    } else {
       return;   
}

Of course, you can really only get away with that because you're using 0 as your exit code in all cases. Really, you should return an int instead of using Environment.Exit. For this particular case, this would be my preferred method

static int Main(string[] args) {
    if(args.Length != 0) {
       if(Byte.TryParse(args[0], out maxSize))
         queue = new Queue(){MaxSize = maxSize};
       else
         return 1;
    } else {
       return 2;
    }
}

Initialize queue to null, which is really just a compiler trick that says "I'll figure out my own uninitialized variables, thank you very much". It's a useful trick, but I don't like it in this case - you have too many if branches to easily check that you're doing it properly. If you really wanted to do it this way, something like this would be clearer:

static void Main(string[] args) {
  Byte maxSize;
  Queue queue = null;

  if(args.Length == 0 || !Byte.TryParse(args[0], out maxSize)) {
     Environment.Exit(0);
  }
  queue = new Queue(){MaxSize = maxSize};

  for(Byte j = 0; j < queue.MaxSize; j++)
    queue.Insert(j);
  for(Byte j = 0; j < queue.MaxSize; j++)
    Console.WriteLine(queue.Remove());
}

Add a return statement after Environment.Exit. Again, this is more of a compiler trick - but is slightly more legit IMO because it adds semantics for humans as well (though it'll keep you from that vaunted 100% code coverage)

static void Main(String[] args) {
  if(args.Length != 0) {
     if(Byte.TryParse(args[0], out maxSize)) {
        queue = new Queue(){MaxSize = maxSize};
     } else {
        Environment.Exit(0);
        return;
     }
  } else { 
     Environment.Exit(0);
     return;
  }

  for(Byte j = 0; j < queue.MaxSize; j++)
     queue.Insert(j);
  for(Byte j = 0; j < queue.MaxSize; j++)
     Console.WriteLine(queue.Remove());
}

iOS how to set app icon and launch images

I recently found this App called Icon Set Creator in the App Store which is free, without ads, updated on new changes, straight forward and works just fine for every possible icon size in OSX, iOS and WatchOS:

In Icon Set Creator:

  1. Drag your image into the view
  2. Choose your target platform
  3. Export the Icon Set folder

iconSetCreator

In XCode:

  1. Navigate to the Assets.xcassets Folder
  2. Delete the pre existing AppIcon
  3. Right click -> Import your created Icon-Set as AppIcon and you're done

Test if number is odd or even

(bool)($number & 1)

or

(bool)(~ $number & 1)

How do you set EditText to only accept numeric values in Android?

Try the following code:

Edittext_name.setKeyListener(DigitsKeyListener.getInstance("0123456789"));

It will allow you to enter just numbers. You cannot enter chars. if you want to enter chars, not numbers, you can edit the values between the quotes inside getInstance.

JAVA_HOME directory in Linux

Here's an improvement, grabbing just the directory to stdout:

java -XshowSettings:properties -version 2>&1 \
   | sed '/^[[:space:]]*java\.home/!d;s/^[[:space:]]*java\.home[[:space:]]*=[[:space:]]*//'

How to position one element relative to another with jQuery?

Something like this?

$(menu).css("top", targetE1.y + "px"); 
$(menu).css("left", targetE1.x - widthOfMenu + "px");

Remove plot axis values

@Richie Cotton has a pretty good answer above. I can only add that this page provides some examples. Try the following:

x <- 1:20
y <- runif(20)
plot(x,y,xaxt = "n")
axis(side = 1, at = x, labels = FALSE, tck = -0.01)

Nested lists python

The question title is too wide and the author's need is more specific. In my case, I needed to extract all elements from nested list like in the example below:

Example:

input -> [1,2,[3,4]]
output -> [1,2,3,4]

The code below gives me the result, but I would like to know if anyone can create a simpler answer:

def get_elements_from_nested_list(l, new_l):
    if l is not None:
        e = l[0]
        if isinstance(e, list):
            get_elements_from_nested_list(e, new_l)
        else:
            new_l.append(e)
        if len(l) > 1:
            return get_elements_from_nested_list(l[1:], new_l)
        else:
            return new_l

Call of the method

l = [1,2,[3,4]]
new_l = []

get_elements_from_nested_list(l, new_l)

ViewDidAppear is not called when opening app from background

I think registering for the UIApplicationWillEnterForegroundNotification is risky as you may end up with more than one controller reacting to that notification. Nothing garanties that these controllers are still visible when the notification is received.

Here is what I do: I force call viewDidAppear on the active controller directly from the App's delegate didBecomeActive method:

Add the code below to - (void)applicationDidBecomeActive:(UIApplication *)application

UIViewController *activeController = window.rootViewController;
if ([activeController isKindOfClass:[UINavigationController class]]) {
    activeController = [(UINavigationController*)window.rootViewController topViewController];
}
[activeController viewDidAppear:NO];