Programs & Examples On #Workflow foundation

windows workflow foundation… provides a programming model, in-process workflow engine and rehostable designer to implement long-running processes as workflows within .NET applications.

Clear History and Reload Page on Login/Logout Using Ionic Framework

Welcome to the framework! Actually the routing in Ionic is powered by ui-router. You should probably check out this previous SO question to find a couple of different ways to accomplish this.

If you just want to reload the state you can use:

$state.go($state.current, {}, {reload: true});

If you actually want to reload the page (as in, you want to re-bootstrap everything) then you can use:

$window.location.reload(true)

Good luck!

How to list all installed packages and their versions in Python?

from command line

python -c help('modules')

can be used to view all modules, and for specific modules

python -c help('os')

For Linux below will work

python -c "help('os')"

"npm config set registry https://registry.npmjs.org/" is not working in windows bat file

Probably I am too late to answer. But if anybody need it, following works fine, as I have used it a lot of times.

npm config set registry=https://registry.npmjs.com/

Unlink of file Failed. Should I try again?

If closing your IDE and running various git commands listed here won't help, try manually killing all running Java processes. I had a Java process probably left over from eclipse that somehow kept a configuration file open.

Vertically align text to top within a UILabel

You can use TTTAttributedLabel, it supports vertical alignment.

@property (nonatomic) TTTAttributedLabel* label;
<...>

//view's or viewController's init method
_label.verticalAlignment = TTTAttributedLabelVerticalAlignmentTop;

How to display pdf in php

Download PDFObject library from https://pdfobject.com/ and check the below code: I hope it will work you.

<!DOCTYPE html>
<html>
<head>
    <title>Pdf Read</title>
    <style>
          .pdfobject-container { height: 500px;}
          .pdfobject { border: 1px solid #666; }
   </style>
   <script src="pdfobject.min.js"></script>
</head>
<body>
        <div id="example1"></div>
        <script>PDFObject.embed("pdfread.pdf", "#example1");</script>
</body>
</html>

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

I use this to cause 60 events per hour with most events occurring at the same number of seconds after the whole minute:

import math
import time
import random

TICK = 60 # one minute tick size
TICK_TIMING = 59 # execute on 59th second of the tick
TICK_MINIMUM = 30 # minimum catch up tick size when lagging

def set_timing():

    now = time.time()
    elapsed = now - info['begin']
    minutes = math.floor(elapsed/TICK)
    tick_elapsed = now - info['completion_time']
    if (info['tick']+1) > minutes:
        wait = max(0,(TICK_TIMING-(time.time() % TICK)))
        print ('standard wait: %.2f' % wait)
        time.sleep(wait)
    elif tick_elapsed < TICK_MINIMUM:
        wait = TICK_MINIMUM-tick_elapsed
        print ('minimum wait: %.2f' % wait)
        time.sleep(wait)
    else:
        print ('skip set_timing(); no wait')
    drift = ((time.time() - info['begin']) - info['tick']*TICK -
        TICK_TIMING + info['begin']%TICK)
    print ('drift: %.6f' % drift)

info['tick'] = 0
info['begin'] = time.time()
info['completion_time'] = info['begin'] - TICK

while 1:

    set_timing()

    print('hello world')

    #random real world event
    time.sleep(random.random()*TICK_MINIMUM)

    info['tick'] += 1
    info['completion_time'] = time.time()

Depending upon actual conditions you might get ticks of length:

60,60,62,58,60,60,120,30,30,60,60,60,60,60...etc.

but at the end of 60 minutes you'll have 60 ticks; and most of them will occur at the correct offset to the minute you prefer.

On my system I get typical drift of < 1/20th of a second until need for correction arises.

The advantage of this method is resolution of clock drift; which can cause issues if you're doing things like appending one item per tick and you expect 60 items appended per hour. Failure to account for drift can cause secondary indications like moving averages to consider data too deep into the past resulting in faulty output.

Angular2 use [(ngModel)] with [ngModelOptions]="{standalone: true}" to link to a reference to model's property

For me the code:

_x000D_
_x000D_
<form (submit)="addTodo()">_x000D_
  <input type="text" [(ngModel)]="text">_x000D_
</form>
_x000D_
_x000D_
_x000D_

throws error, but I added name attribute to input:

_x000D_
_x000D_
<form (submit)="addTodo()">_x000D_
  <input type="text" [(ngModel)]="text" name="text">_x000D_
</form>
_x000D_
_x000D_
_x000D_

and it started to work.

How to replace a string in an existing file in Perl?

It can be done using a single line:

perl -pi.back -e 's/oldString/newString/g;' inputFileName

Pay attention that oldString is processed as a Regular Expression.
In case the string contains any of {}[]()^$.|*+? (The special characters for Regular Expression syntax) make sure to escape them unless you want it to be processed as a regular expression.
Escaping it is done by \, so \[.

Where can I find php.ini?

phpinfo();

will tell you its location, or from the command line

php -i

How do you append to a file?

Here's my script, which basically counts the number of lines, then appends, then counts them again so you have evidence it worked.

shortPath  = "../file_to_be_appended"
short = open(shortPath, 'r')

## this counts how many line are originally in the file:
long_path = "../file_to_be_appended_to" 
long = open(long_path, 'r')
for i,l in enumerate(long): 
    pass
print "%s has %i lines initially" %(long_path,i)
long.close()

long = open(long_path, 'a') ## now open long file to append
l = True ## will be a line
c = 0 ## count the number of lines you write
while l: 
    try: 
        l = short.next() ## when you run out of lines, this breaks and the except statement is run
        c += 1
        long.write(l)

    except: 
        l = None
        long.close()
        print "Done!, wrote %s lines" %c 

## finally, count how many lines are left. 
long = open(long_path, 'r')
for i,l in enumerate(long): 
    pass
print "%s has %i lines after appending new lines" %(long_path, i)
long.close()

How to grant remote access to MySQL for a whole subnet?

It looks like you can also use a netmask, e.g.

GRANT ... TO 'user'@'192.168.0.0/255.255.255.0' IDENTIFIED BY ...

Giving multiple URL patterns to Servlet Filter

If an URL pattern starts with /, then it's relative to the context root. The /Admin/* URL pattern would only match pages on http://localhost:8080/EMS2/Admin/* (assuming that /EMS2 is the context path), but you have them actually on http://localhost:8080/EMS2/faces/Html/Admin/*, so your URL pattern never matches.

You need to prefix your URL patterns with /faces/Html as well like so:

<url-pattern>/faces/Html/Admin/*</url-pattern>

You can alternatively also just reconfigure your web project structure/configuration so that you can get rid of the /faces/Html path in the URLs so that you can just open the page by for example http://localhost:8080/EMS2/Admin/Upload.xhtml.

Your filter mapping syntax is all fine. However, a simpler way to specify multiple URL patterns is to just use only one <filter-mapping> with multiple <url-pattern> entries:

<filter-mapping>
    <filter-name>LoginFilter</filter-name>
    <url-pattern>/faces/Html/Employee/*</url-pattern>
    <url-pattern>/faces/Html/Admin/*</url-pattern>
    <url-pattern>/faces/Html/Supervisor/*</url-pattern>
</filter-mapping>

Hide/Show components in react native

I had the same issue where I would want to show / hide Views, but I really didn't want the UI jumping around when things were added/removed or necessarily to deal with re-rendering.

I wrote a simple Component to deal with it for me. Animated by default, but easy to toggle. I put it on GitHub and NPM with a readme, but all the code is below.

npm install --save react-native-hideable-view

import React, { Component, PropTypes } from 'react';
import { Animated  } from 'react-native';

class HideableView extends Component {
  constructor(props) {
    super(props);
    this.state = {
      opacity: new Animated.Value(this.props.visible ? 1 : 0)
    }
  }

  animate(show) {
    const duration = this.props.duration ? parseInt(this.props.duration) : 500;
    Animated.timing(
      this.state.opacity, {
        toValue: show ? 1 : 0,
        duration: !this.props.noAnimation ? duration : 0
      }
    ).start();
  }

  shouldComponentUpdate(nextProps) {
    return this.props.visible !== nextProps.visible;
  }

  componentWillUpdate(nextProps, nextState) {
    if (this.props.visible !== nextProps.visible) {
      this.animate(nextProps.visible);
    }
  }

  render() {
    if (this.props.removeWhenHidden) {
      return (this.visible && this.props.children);
    }
    return (
      <Animated.View style={{opacity: this.state.opacity}}>
        {this.props.children}
      </Animated.View>
    )
  }
}

HideableView.propTypes = {
  visible: PropTypes.bool.isRequired,
  duration: PropTypes.number,
  removeWhenHidden: PropTypes.bool,
  noAnimation: PropTypes.bool
}

export default HideableView;

How can I provide multiple conditions for data trigger in WPF?

Use MultiDataTrigger type

<Style TargetType="ListBoxItem">
    <Style.Triggers>
      <DataTrigger Binding="{Binding Path=State}" Value="WA">
        <Setter Property="Foreground" Value="Red" />
      </DataTrigger>    
      <MultiDataTrigger>
        <MultiDataTrigger.Conditions>
          <Condition Binding="{Binding Path=Name}" Value="Portland" />
          <Condition Binding="{Binding Path=State}" Value="OR" />
        </MultiDataTrigger.Conditions>
        <Setter Property="Background" Value="Cyan" />
      </MultiDataTrigger>
    </Style.Triggers>
  </Style>

Make Axios send cookies in its requests automatically

What worked for me:

Client Side:

import axios from 'axios';

const url = 'http://127.0.0.1:5000/api/v1';

export default {
  login(credentials) {
    return axios
      .post(`${url}/users/login/`, credentials, {
        withCredentials: true,
        credentials: 'include',
      })
      .then((response) => response.data);
  },
};

Server Side:

const express = require('express');
const cors = require('cors');

const app = express();
const port = process.env.PORT || 5000;

app.use(
  cors({
    origin: [`http://localhost:${port}`, `https://localhost:${port}`],
    credentials: 'true',
  })
);

How to calculate age in T-SQL with years, months, and days

I've seen the question several times with results outputting Years, Month, Days but never a numeric / decimal result. (At least not one that doesn't round incorrectly). I welcome feedback on this function. Might not still need a little adjusting.

-- Input to the function is two dates. -- Output is the numeric number of years between the two dates in Decimal(7,4) format. -- Output is always always a possitive number.

-- NOTE:Output does not handle if difference is greater than 999.9999

-- Logic is based on three steps. -- 1) Is the difference less than 1 year (0.5000, 0.3333, 0.6667, ect.) -- 2) Is the difference exactly a whole number of years (1,2,3, ect.)

-- 3) (Else)...The difference is years and some number of days. (1.5000, 2.3333, 7.6667, ect.)



CREATE Function [dbo].[F_Get_Actual_Age](@pi_date1 datetime,@pi_date2 datetime)
RETURNS Numeric(7,4)
AS
BEGIN

Declare 
 @l_tmp_date    DATETIME
,@l_days1       DECIMAL(9,6)
,@l_days2       DECIMAL(9,6)
,@l_result      DECIMAL(10,6)
,@l_years       DECIMAL(7,4)


  --Check to make sure there is a date for both inputs
  IF @pi_date1 IS NOT NULL and @pi_date2 IS NOT NULL  
  BEGIN

    IF @pi_date1 > @pi_date2 --Make sure the "older" date is in @pi_date1
      BEGIN
        SET @l_tmp_date = @pi_date2
        SET @pi_date2 = @Pi_date1
        SET @pi_date1 = @l_tmp_date
      END

    --Check #1 If date1 + 1 year is greater than date2, difference must be less than 1 year
    IF DATEADD(YYYY,1,@pi_date1) > @pi_date2  
      BEGIN
          --How many days between the two dates (numerator)
        SET @l_days1 = DATEDIFF(dd,@pi_date1, @pi_date2) 
          --subtract 1 year from date2 and calculate days bewteen it and date2
          --This is to get the denominator and accounts for leap year (365 or 366 days)
        SET @l_days2 = DATEDIFF(dd,dateadd(yyyy,-1,@pi_date2),@pi_date2) 
        SET @l_years = @l_days1 / @l_days2 -- Do the math
      END
    ELSE
      --Check #2  Are the dates an exact number of years apart.
      --Calculate years bewteen date1 and date2, then add the years to date1, compare dates to see if exactly the same.
      IF DATEADD(YYYY,DATEDIFF(YYYY,@pi_date1,@pi_date2),@pi_date1) = @pi_date2  
        SET @l_years = DATEDIFF(YYYY,@pi_date1, @pi_date2) --AS Years, 'Exactly even Years' AS Msg
      ELSE
      BEGIN
        --Check #3 The rest of the cases.
        --Check if datediff, returning years, over or under states the years difference
        SET @l_years = DATEDIFF(YYYY,@pi_date1, @pi_date2)
        IF DATEADD(YYYY,@l_years,@pi_date1) > @pi_date2
          SET @l_years = @l_years -1
          --use basicly same logic as in check #1  
        SET @l_days1 = DATEDIFF(dd,DATEADD(YYYY,@l_years,@pi_date1), @pi_date2) 
        SET @l_days2 = DATEDIFF(dd,dateadd(yyyy,-1,@pi_date2),@pi_date2) 
        SET @l_years = @l_years + @l_days1 / @l_days2
        --SELECT @l_years AS Years, 'Years Plus' AS Msg
      END
  END
  ELSE
    SET @l_years = 0  --If either date was null

RETURN @l_Years  --Return the result as decimal(7,4)
END  

`

How do I attach events to dynamic HTML elements with jQuery?

Binds a handler to an event (like click) for all current - and future - matched element. Can also bind custom events.

link text

$(function(){
    $(".myclass").live("click", function() {
        // do something
    });
});

Sending images using Http Post

I usually do this in the thread handling the json response:

try {
  Bitmap bitmap = BitmapFactory.decodeStream((InputStream)new URL(imageUrl).getContent());
} catch (MalformedURLException e) {
  e.printStackTrace();
} catch (IOException e) {
  e.printStackTrace();
}

If you need to do transformations on the image, you'll want to create a Drawable instead of a Bitmap.

How to call a .NET Webservice from Android using KSOAP2?

Typecast the envelope to SoapPrimitive:

SoapPrimitive result = (SoapPrimitive)envelope.getResponse();
String strRes = result.toString();

and it will work.

How to print matched regex pattern using awk?

Off topic, this can be done using the grep also, just posting it here in case if anyone is looking for grep solution

echo 'xxx yyy zzze ' | grep -oE 'yyy'

SQL order string as number

The column I'm sorting with has any combination of alpha and numeric, so I used the suggestions in this post as a starting point and came up with this.

DECLARE @tmp TABLE (ID VARCHAR(50));
INSERT INTO @tmp VALUES ('XYZ300');
INSERT INTO @tmp VALUES ('XYZ1002');
INSERT INTO @tmp VALUES ('106');
INSERT INTO @tmp VALUES ('206');
INSERT INTO @tmp VALUES ('1002');
INSERT INTO @tmp VALUES ('J206');
INSERT INTO @tmp VALUES ('J1002');

SELECT ID, (CASE WHEN ISNUMERIC(ID) = 1 THEN 0 ELSE 1 END) IsNum
FROM @tmp
ORDER BY IsNum, LEN(ID), ID;

Results

ID
------------------------
106
206
1002
J206
J1002
XYZ300
XYZ1002

Hope this helps

What does it mean to inflate a view from an xml file?

When you write an XML layout, it will be inflated by the Android OS which basically means that it will be rendered by creating view object in memory. Let's call that implicit inflation (the OS will inflate the view for you). For instance:

class Name extends Activity{
    public void onCreate(){
         // the OS will inflate the your_layout.xml
         // file and use it for this activity
         setContentView(R.layout.your_layout);
    }
}

You can also inflate views explicitly by using the LayoutInflater. In that case you have to:

  1. Get an instance of the LayoutInflater
  2. Specify the XML to inflate
  3. Use the returned View
  4. Set the content view with returned view (above)

For instance:

LayoutInflater inflater = LayoutInflater.from(YourActivity.this); // 1
View theInflatedView = inflater.inflate(R.layout.your_layout, null); // 2 and 3
setContentView(theInflatedView) // 4

Iterate a certain number of times without storing the iteration number anywhere

exec 'print "hello";' * 2

should work, but I'm kind of ashamed that I thought of it.

Update: Just thought of another one:

for _ in " "*10: print "hello"

How to stop PHP code execution?

I'm not sure you understand what "exit" states

Terminates execution of the script. Shutdown functions and object destructors will always be executed even if exit is called.

It's normal to do that, it must clear it's memmory of all the variables and functions you called before. Not doing this would mean your memmory would remain stuck and ocuppied in your RAM, and if this would happen several times you would need to reboot and flush your RAM in order to have any left.

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'id' in 'where clause' (SQL: select * from `songs` where `id` = 5 limit 1)

Just Go to Model file of the corresponding Controller and check the primary key filed name

such as

protected $primaryKey = 'info_id';

here info id is field name available in database table

More info can be found at "Primary Keys" section of the docs.

How do files get into the External Dependencies in Visual Studio C++?

The External Dependencies folder is populated by IntelliSense: the contents of the folder do not affect the build at all (you can in fact disable the folder in the UI).

You need to actually include the header (using a #include directive) to use it. Depending on what that header is, you may also need to add its containing folder to the "Additional Include Directories" property and you may need to add additional libraries and library folders to the linker options; you can set all of these in the project properties (right click the project, select Properties). You should compare the properties with those of the project that does build to determine what you need to add.

Test if string is a number in Ruby on Rails

How dumb is this solution?

def is_number?(i)
  begin
    i+0 == i
  rescue TypeError
    false
  end
end

"Parameter" vs "Argument"

A parameter is the variable which is part of the method’s signature (method declaration). An argument is an expression used when calling the method.

Consider the following code:

void Foo(int i, float f)
{
    // Do things
}

void Bar()
{
    int anInt = 1;
    Foo(anInt, 2.0);
}

Here i and f are the parameters, and anInt and 2.0 are the arguments.

ETag vs Header Expires

One additional thing I would like to mention that some of the answers may have missed is the downside to having both ETags and Expires/Cache-control in your headers.

Depending on your needs it may just add extra bytes in your headers which may increase packets which means more TCP overhead. Again, you should see if the overhead of having both things in your headers is necessary or will it just add extra weight in your requests which reduces performance.

You can read more about it on this excellent blog post by Kyle Simpson: http://calendar.perfplanet.com/2010/bloated-request-response-headers/

How to click a href link using Selenium

Use an explicit wait for the element like this:

WebDriverWait wait1 = new WebDriverWait(driver, 500);
wait1.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("path of element"))).click();

Java check if boolean is null

A boolean cannot be null in java.

A Boolean, however, can be null.

If a boolean is not assigned a value (say a member of a class) then it will be false by default.

The storage engine for the table doesn't support repair. InnoDB or MyISAM?

InnoDB works slightly different that MyISAM and they both are viable options. You should use what you think it fits the project.

Some keypoints will be:

  1. InnoDB does ACID-compliant transaction. http://en.wikipedia.org/wiki/ACID
  2. InnoDB does Referential Integrity (foreign key relations) http://www.w3resource.com/sql/joins/joining-tables-through-referential-integrity.php
  3. MyIsam does full text search, InnoDB doesn't
  4. I have been told InnoDB is faster on executing writes but slower than MyISAM doing reads (I cannot back this up and could not find any article that analyses this, I do however have the guy that told me this in high regard), feel free to ignore this point or do your own research.
  5. Default configuration does not work very well for InnoDB needs to be tweaked accordingly, run a tool like http://mysqltuner.pl/mysqltuner.pl to help you.

Notes:

  • In my opinion the second point is probably the one were InnoDB has a huge advantage over MyISAM.
  • Full text search not working with InnoDB is a bit of a pain, You can mix different storage engines but be careful when doing so.

Notes2: - I am reading this book "High performance MySQL", the author says "InnoDB loads data and creates indexes slower than MyISAM", this could also be a very important factor when deciding what to use.

TypeError: unhashable type: 'numpy.ndarray'

numpy.ndarray can contain any type of element, e.g. int, float, string etc. Check the type an do a conversion if neccessary.

Read line by line in bash script

while read CMD; do
    echo $CMD
done  << EOF
data line 1
data line 2
..
EOF

AngularJS : ng-model binding not updating when changed with jQuery

Just run the following line at the end of your function:

$scope.$apply()

How to let PHP to create subdomain automatically for each user?

Don't fuss around with .htaccess files when you can use Apache mass virtual hosting.

From the documentation:

#include part of the server name in the filenames VirtualDocumentRoot /www/hosts/%2/docs

In a way it's the reverse of your question: every 'subdomain' is a user. If the user does not exist, you get an 404.

The only drawback is that the environment variable DOCUMENT_ROOT is not correctly set to the used subdirectory, but the default document_root in de htconfig.

Using Node.js require vs. ES6 import/export

Not sure why (probably optimization - lazy loading?) is it working like that, but I have noticed that import may not parse code if imported modules are not used.
Which may not be expected behaviour in some cases.

Take hated Foo class as our sample dependency.

foo.ts

export default class Foo {}
console.log('Foo loaded');

For example:

index.ts

import Foo from './foo'
// prints nothing

index.ts

const Foo = require('./foo').default;
// prints "Foo loaded"

index.ts

(async () => {
    const FooPack = await import('./foo');
    // prints "Foo loaded"
})();

On the other hand:

index.ts

import Foo from './foo'
typeof Foo; // any use case
// prints "Foo loaded"

Why would a "java.net.ConnectException: Connection timed out" exception occur when URL is up?

I'd recommend raising the connection timeout time before getting the output stream, like so:

urlConnection.setConnectTimeout(1000);

Where 1000 is in milliseconds (1000 milliseconds = 1 second).

Spring: @Component versus @Bean

Let's consider I want specific implementation depending on some dynamic state. @Bean is perfect for that case.

@Bean
@Scope("prototype")
public SomeService someService() {
    switch (state) {
    case 1:
        return new Impl1();
    case 2:
        return new Impl2();
    case 3:
        return new Impl3();
    default:
        return new Impl();
    }
}

However there is no way to do that with @Component.

How to evaluate a boolean variable in an if block in bash?

bash doesn't know boolean variables, nor does test (which is what gets called when you use [).

A solution would be:

if $myVar ; then ... ; fi

because true and false are commands that return 0 or 1 respectively which is what if expects.

Note that the values are "swapped". The command after if must return 0 on success while 0 means "false" in most programming languages.

SECURITY WARNING: This works because BASH expands the variable, then tries to execute the result as a command! Make sure the variable can't contain malicious code like rm -rf /

How to order citations by appearance using BibTeX?

Just a brief note - I'm using a modified version of plain.bst sitting in the directory with my Latex files; it turns out having sorting by order of appearance is a relatively easy change; just find the piece of code:

...
ITERATE {presort}

SORT
...

... and comment it - I turned it to:

...
%% % avoid sort:
%% ITERATE {presort}
%%
%% SORT
...

... and then, after running bibtex, pdflatex, pdflatex - the citations will be sorted by order of appearance (that is, they will be unsorted :) ).

Cheers!

EDIT: just realized that what I wrote is actually in the comment by @ChrisN: "can you edit it to remove the SORT command" ;)

Image Greyscale with CSS & re-color on mouse-over?

I use the following code on http://www.diagnomics.com/

Smooth transition from b/w to color with magnifying effect (scale)

    img.color_flip {
      filter: url(filters.svg#grayscale); /* Firefox 3.5+ */
      filter: gray; /* IE5+ */
      -webkit-filter: grayscale(1); /* Webkit Nightlies & Chrome Canary */
      -webkit-transition: all .5s ease-in-out;
    }

    img.color_flip:hover {
      filter: none;
      -webkit-filter: grayscale(0);
      -webkit-transform: scale(1.1);
    }

numbers not allowed (0-9) - Regex Expression in javascript

\D is a non-digit, and so then \D* is any number of non-digits in a row. So your whole string should match ^\D*$.

Check on http://rubular.com/r/AoWBmrbUkN it works perfectly.

You can also try on http://regexpal.com/ OR http://www.regextester.com/

Angular 2 How to redirect to 404 or other path if the path does not exist

For version v2.2.2 and newer

In version v2.2.2 and up, name property no longer exists and it shouldn't be used to define the route. path should be used instead of name and no leading slash is needed on the path. In this case use path: '404' instead of path: '/404':

 {path: '404', component: NotFoundComponent},
 {path: '**', redirectTo: '/404'}

For versions older than v2.2.2

you can use {path: '/*path', redirectTo: ['redirectPathName']}:

{path: '/home/...', name: 'Home', component: HomeComponent}
{path: '/', redirectTo: ['Home']},
{path: '/user/...', name: 'User', component: UserComponent},
{path: '/404', name: 'NotFound', component: NotFoundComponent},

{path: '/*path', redirectTo: ['NotFound']}

if no path matches then redirect to NotFound path

Angular IE Caching issue for $http

An option is to use the simple approach of adding a Timestamp with each request no need to clear cache.

    let c=new Date().getTime();
    $http.get('url?d='+c)

Apply CSS rules if browser is IE

In browsers up to and including IE9, this is done through conditional comments.

<!--[if IE]>
<style type="text/css">
  IE specific CSS rules go here
</style>
<![endif]-->

CSS: Position text in the middle of the page

Here's a method using display:flex:

_x000D_
_x000D_
.container {_x000D_
  height: 100%;_x000D_
  width: 100%;_x000D_
  display: flex;_x000D_
  position: fixed;_x000D_
  align-items: center;_x000D_
  justify-content: center;_x000D_
}
_x000D_
<div class="container">_x000D_
  <div>centered text!</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

View on Codepen
Check Browser Compatability

#1062 - Duplicate entry for key 'PRIMARY'

Repair the database by your domain provider cpanel.

Or see if you didnt merged something in the phpMyAdmin

Difference between Hashing a Password and Encrypting it

Ideally you should do both.

First Hash the pass password for the one way security. Use a salt for extra security.

Then encrypt the hash to defend against dictionary attacks if your database of password hashes is compromised.

MySQL combine two columns and add into a new column

Add new column to your table and perfrom the query:

UPDATE tbl SET combined = CONCAT(zipcode, ' - ', city, ', ', state)

KeyListener, keyPressed versus keyTyped

Neither. You should NOT use a KeyLIstener.

Swing was designed to be used with Key Bindings. Read the section from the Swing tutorial on How to Use Key Bindings.

How to send email from Terminal?

echo "this is the body" | mail -s "this is the subject" "to@address"

How do I check for vowels in JavaScript?

Lots of answers available, speed is irrelevant for such small functions unless you are calling them a few hundred thousand times in a short period of time. For me, a regular expression is best, but keep it in a closure so you don't build it every time:

Simple version:

function vowelTest(s) {
  return (/^[aeiou]$/i).test(s);
}

More efficient version:

var vowelTest = (function() {
  var re = /^[aeiou]$/i;
  return function(s) {
    return re.test(s);
  }
})();

Returns true if s is a single vowel (upper or lower case) and false for everything else.

slf4j: how to log formatted message, object array, exception

As of SLF4J 1.6.0, in the presence of multiple parameters and if the last argument in a logging statement is an exception, then SLF4J will presume that the user wants the last argument to be treated as an exception and not a simple parameter. See also the relevant FAQ entry.

So, writing (in SLF4J version 1.7.x and later)

 logger.error("one two three: {} {} {}", "a", "b", 
              "c", new Exception("something went wrong"));

or writing (in SLF4J version 1.6.x)

 logger.error("one two three: {} {} {}", new Object[] {"a", "b", 
              "c", new Exception("something went wrong")});

will yield

one two three: a b c
java.lang.Exception: something went wrong
    at Example.main(Example.java:13)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at ...

The exact output will depend on the underlying framework (e.g. logback, log4j, etc) as well on how the underlying framework is configured. However, if the last parameter is an exception it will be interpreted as such regardless of the underlying framework.

Access denied for user 'root'@'localhost' (using password: Yes) after password reset LINUX

In my case:

  1. /etc/init.d/mysql stop
  2. mysqld_safe --skip-grant-tables &

(in new window)

  1. mysql -u root
  2. mysql> use mysql;
  3. mysql> update user set authentication_string=password('password') where user='root';
  4. mysql>flush privileges;
  5. mysql> quit
  6. /etc/init.d/mysql restart

Add/remove HTML inside div using JavaScript

To remove node you can try this solution it helped me.

var rslt = (nodee=document.getElementById(id)).parentNode.removeChild(nodee);

Ignore cells on Excel line graph

Not for blanks in the middle of a range, but this works for a complex chart from a start date until infinity (ie no need to adjust the chart's data source each time informatiom is added), without showing any lines for dates that have not yet been entered. As you add dates and data to the spreadsheet, the chart expands. Without it, the chart has a brain hemorrhage.

So, to count a complex range of conditions over an extended period of time but only if the date of the events is not blank :

=IF($B6<>"",(COUNTIF($O6:$O6,Q$5)),"") returns “#N/A” if there is no date in column B.

In other words, "count apples or oranges or whatever in column O (as determined by what is in Q5) but only if column B (the dates) is not blank". By returning “#N/A”, the chart will skip the "blank" rows (blank as in a zero value or rather "#N/A").

From that table of returned values you can make a chart from a date in the past to infinity

How to add bootstrap in angular 6 project?

npm install bootstrap --save

and add relevent files into angular.json file under the style property for css files and under scripts for JS files.

 "styles": [
  "../node_modules/bootstrap/dist/css/bootstrap.min.css",
   ....
]

How do I generate a random number between two variables that I have stored?

Really fast, really easy:

srand(time(NULL)); // Seed the time
int finalNum = rand()%(max-min+1)+min; // Generate the number, assign to variable.

And that is it. However, this is biased towards the lower end, but if you are using C++ TR1/C++11 you can do it using the random header to avoid that bias like so:

#include <random>

std::mt19937 rng(seed);
std::uniform_int_distribution<int> gen(min, max); // uniform, unbiased

int r = gen(rng);

But you can also remove the bias in normal C++ like this:

int rangeRandomAlg2 (int min, int max){
    int n = max - min + 1;
    int remainder = RAND_MAX % n;
    int x;
    do{
        x = rand();
    }while (x >= RAND_MAX - remainder);
    return min + x % n;
}

and that was gotten from this post.

Get Date in YYYYMMDD format in windows batch file

You can try this ! This should work on windows machines.

for /F "usebackq tokens=1,2,3 delims=-" %%I IN (`echo %date%`) do echo "%%I" "%%J" "%%K"

Why would you use Expression<Func<T>> rather than Func<T>?

LINQ is the canonical example (for example, talking to a database), but in truth, any time you care more about expressing what to do, rather than actually doing it. For example, I use this approach in the RPC stack of protobuf-net (to avoid code-generation etc) - so you call a method with:

string result = client.Invoke(svc => svc.SomeMethod(arg1, arg2, ...));

This deconstructs the expression tree to resolve SomeMethod (and the value of each argument), performs the RPC call, updates any ref/out args, and returns the result from the remote call. This is only possible via the expression tree. I cover this more here.

Another example is when you are building the expression trees manually for the purpose of compiling to a lambda, as done by the generic operators code.

You need to use a Theme.AppCompat theme (or descendant) with this activity

I was experiencing this problem even though my Theme was an AppCompat Theme and my Activity was an AppCompatActivity (or Activity, as suggested on other's answers). So I cleaned, rebuild and rerun the project.

(Build -> Clean Project ; Build -> Rebuild Project ; Run -> Run)

It may seem dumb, but now it works great!

Just hope it helps!

Name node is in safe mode. Not able to leave

In order to forcefully let the namenode leave safemode, following command should be executed:

 bin/hadoop dfsadmin -safemode leave

You are getting Unknown command error for your command as -safemode isn't a sub-command for hadoop fs, but it is of hadoop dfsadmin.

Also after the above command, I would suggest you to once run hadoop fsck so that any inconsistencies crept in the hdfs might be sorted out.

Update:

Use hdfs command instead of hadoop command for newer distributions. The hadoop command is being deprecated:

hdfs dfsadmin -safemode leave

hadoop dfsadmin has been deprecated and so is hadoop fs command, all hdfs related tasks are being moved to a separate command hdfs.

Centering Bootstrap input fields

Try applying this style to your div class="input-group":

text-align:center;

View it: Fiddle.

Call ASP.NET function from JavaScript?

Regarding:

var button = document.getElementById(/* Button client id */);

button.click();

It should be like:

var button = document.getElementById('<%=formID.ClientID%>');

Where formID is the ASP.NET control ID in the .aspx file.

What is the difference between Views and Materialized Views in Oracle?

A view uses a query to pull data from the underlying tables.

A materialized view is a table on disk that contains the result set of a query.

Materialized views are primarily used to increase application performance when it isn't feasible or desirable to use a standard view with indexes applied to it. Materialized views can be updated on a regular basis either through triggers or by using the ON COMMIT REFRESH option. This does require a few extra permissions, but it's nothing complex. ON COMMIT REFRESH has been in place since at least Oracle 10.

Way to get all alphabetic chars in an array in PHP?

$alphabet = array('A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z');

How to use a decimal range() step value?

Python's range() can only do integers, not floating point. In your specific case, you can use a list comprehension instead:

[x * 0.1 for x in range(0, 10)]

(Replace the call to range with that expression.)

For the more general case, you may want to write a custom function or generator.

Organizing a multiple-file Go project

jdi has the right information concerning the use of GOPATH. I would add that if you intend to have a binary as well you might want to add one additional level to the directories.

~/projects/src/
    myproj/
        mypack/
            lib.go
            lib_test.go
            ...
        myapp/
            main.go

running go build myproj/mypack will build the mypack package along with it's dependencies running go build myproj/myapp will build the myapp binary along with it's dependencies which probably includes the mypack library.

Why doesn't Mockito mock static methods?

In some cases, static methods can be difficult to test, especially if they need to be mocked, which is why most mocking frameworks don't support them. I found this blog post to be very useful in determining how to mock static methods and classes.

Make outer div be automatically the same height as its floating content

I know some people will hate me, but I've found display:table-cell to help in this cases.

It is really cleaner.

Extract the filename from a path

You can try this:

[System.IO.FileInfo]$path = "D:\Server\User\CUST\MEA\Data\In\Files\CORRECTED\CUST_MEAFile.csv"
# Returns name and extension
$path.Name
# Returns just name
$path.BaseName

Drop all data in a pandas dataframe

My favorite:

df = df.iloc[0:0]

But be aware df.index.max() will be nan. To add items I use:

df.loc[0 if math.isnan(df.index.max()) else df.index.max() + 1] = data

document.getElementById(id).focus() is not working for firefox or chrome

My case was a bit different. I was trying to focus() an input from within a browser developer console. Turns out it was interfering with the input somehow, and once I minimized the console everything worked as expected. I understand this isn't a programmatical solution, but in case someone found this on a search engine jist like I did, there's a chance this information might help.

Returning a promise in an async function in TypeScript

It's complicated.

First of all, in this code

const p = new Promise((resolve) => {
    resolve(4);
});

the type of p is inferred as Promise<{}>. There is open issue about this on typescript github, so arguably this is a bug, because obviously (for a human), p should be Promise<number>.

Then, Promise<{}> is compatible with Promise<number>, because basically the only property a promise has is then method, and then is compatible in these two promise types in accordance with typescript rules for function types compatibility. That's why there is no error in whatever1.

But the purpose of async is to pretend that you are dealing with actual values, not promises, and then you get the error in whatever2 because {} is obvioulsy not compatible with number.

So the async behavior is the same, but currently some workaround is necessary to make typescript compile it. You could simply provide explicit generic argument when creating a promise like this:

const whatever2 = async (): Promise<number> => {
    return new Promise<number>((resolve) => {
        resolve(4);
    });
};

Best way to remove from NSMutableArray while iterating?

Here's the easy and clean way. I like to duplicate my array right in the fast enumeration call:

for (LineItem *item in [NSArray arrayWithArray:self.lineItems]) 
{
    if ([item.toBeRemoved boolValue] == YES) 
    {
        [self.lineItems removeObject:item];
    }
}

This way you enumerate through a copy of the array being deleted from, both holding the same objects. An NSArray holds object pointers only so this is totally fine memory/performance wise.

React passing parameter via onclick event using ES6 syntax

in function component, this works great - a new React user since 2020 :)

handleRemove = (e, id) => {
    //removeById(id);
}

return(<button onClick={(e)=> handleRemove(e, id)}></button> )

How can I trigger a Bootstrap modal programmatically?

you can show the model via jquery (javascript)

$('#yourModalID').modal({
  show: true
})

Demo: here

or you can just remove the class "hide"

<div class="modal" id="yourModalID">
  # modal content
</div>

?

How do I make a transparent border with CSS?

The easiest solution to this is to use rgba as the color: border-color: rgba(0,0,0,0); That is fully transparent border color.

JavaScript REST client Library

While you may wish to use a library, such as the excellent jQuery, you don't have to: all modern browsers support HTTP very well in their JavaScript implementations via the XMLHttpRequest API, which, despite its name, is not limited to XML representations.

Here's an example of making a synchronous HTTP PUT request in JavaScript:

var url = "http://host/path/to/resource";
var representationOfDesiredState = "The cheese is old and moldy, where is the bathroom?";

var client = new XMLHttpRequest();

client.open("PUT", url, false);

client.setRequestHeader("Content-Type", "text/plain");

client.send(representationOfDesiredState);

if (client.status == 200)
    alert("The request succeeded!\n\nThe response representation was:\n\n" + client.responseText)
else
    alert("The request did not succeed!\n\nThe response status was: " + client.status + " " + client.statusText + ".");

This example is synchronous because that makes it a little easier, but it's quite easy to make asynchronous requests using this API as well.

There are thousands of pages and articles on the web about learning XmlHttpRequest — they usually use the term AJAX – unfortunately I can't recommend a specific one. You may find this reference handy though.

Saving timestamp in mysql table using php

pass like this

date('Y-m-d H:i:s','1299762201428')

Rebasing a Git merge commit

Given that I just lost a day trying to figure this out and actually found a solution with the help of a coworker, I thought I should chime in.

We have a large code base and we have to deal with 2 branch heavily being modified at the same time. There is a main branch and a secondary branch if you which.

While I merge the secondary branch into the main branch, work continues in the main branch and by the time i'm done, I can't push my changes because they are incompatible.

I therefore need to "rebase" my "merge".

This is how we finally did it :

1) make note of the SHA. ex.: c4a924d458ea0629c0d694f1b9e9576a3ecf506b

git log -1

2) Create the proper history but this will break the merge.

git rebase -s ours --preserve-merges origin/master

3) make note of the SHA. ex.: 29dd8101d78

git log -1

4) Now reset to where you were before

git reset c4a924d458ea0629c0d694f1b9e9576a3ecf506b --hard

5) Now merge the current master into your working branch

git merge origin/master
git mergetool
git commit -m"correct files

6) Now that you have the right files, but the wrong history, get the right history on top of your change with :

git reset 29dd8101d78 --soft

7) And then --amend the results in your original merge commit

git commit --amend

Voila!

Hibernate vs JPA vs JDO - pros and cons of each?

I made a sample WebApp in May 2012 that uses JDO 3.0 & DataNucleus 3.0 - take a look how clean it is: https://github.com/TorbenVesterager/BadAssWebApp

Okay maybe it's a little bit too clean, because I use the POJOs both for the database and the JSON client, but it's fun :)

PS: Contains a few SuppressWarnings annotations (developed in IntelliJ 11)

What is the difference/usage of homebrew, macports or other package installation tools?

By default, Homebrew installs packages to your /usr/local. Macport commands require sudo to install and upgrade (similar to apt-get in Ubuntu).

For more detail:

This site suggests using Hombrew: http://deephill.com/macports-vs-homebrew/

whereas this site lists the advantages of using Macports: http://arstechnica.com/civis/viewtopic.php?f=19&t=1207907

I also switched from Ubuntu recently, and I enjoy using homebrew (it's simple and easy to use!), but if you feel attached to using sudo, Macports might be the better way to go!

How to download/checkout a project from Google Code in Windows?

If you don't want to install anything but do want to download an SVN or GIT repository, then you can use this: http://downloadsvn.codeplex.com/

I have nothing to do with this project, but I just used it now and it saved me a few minutes. Maybe it will help someone.

Django: Display Choice Value

For every field that has choices set, the object will have a get_FOO_display() method, where FOO is the name of the field. This method returns the “human-readable” value of the field.

In Views

person = Person.objects.filter(to_be_listed=True)
context['gender'] = person.get_gender_display()

In Template

{{ person.get_gender_display }}

Documentation of get_FOO_display()

How do I add an active class to a Link from React Router?

React-Router V4 comes with a NavLink component out of the box

To use, simply set the activeClassName attribute to the class you have appropriately styled, or directly set activeStyle to the styles you want. See the docs for more details.

<NavLink
  to="/hello"
  activeClassName="active"
>Hello</NavLink>

Check for null variable in Windows batch

Late answer, but currently the accepted one is at least suboptimal.

Using quotes is ALWAYS better than using any other characters to enclose %1.
Because when %1 contains spaces or special characters like &, the IF [%1] == simply stops with a syntax error.

But for the case that %1 contains quotes, like in myBatch.bat "my file.txt", a simple IF "%1" == "" would fail.

But as you can't know if quotes are used or not, there is the syntax %~1, this removes enclosing quotes when necessary.

Therefore, the code should look like

set "file1=%~1"
IF "%~1"=="" set "file1=default file"

type "%file1%"   --- always enclose your variables in quotes

If you have to handle stranger and nastier arguments like myBatch.bat "This & will "^&crash
Then take a look at SO:How to receive even the strangest command line parameters?

Where to put default parameter value in C++?

You may do in either (according to standard), but remember, if your code is seeing the declaration without default argument(s) before the definition that contains default argument, then compilation error can come.

For example, if you include header containing function declaration without default argument list, thus compiler will look for that prototype as it is unaware of your default argument values and hence prototype won't match.

If you are putting function with default argument in definition, then include that file but I won't suggest that.

What is the difference between Release and Debug modes in Visual Studio?

Well, it depends on what language you are using, but in general they are 2 separate configurations, each with its own settings. By default, Debug includes debug information in the compiled files (allowing easy debugging) while Release usually has optimizations enabled.

As far as conditional compilation goes, they each define different symbols that can be checked in your program, but they are language-specific macros.

JavaScript Extending Class

For traditional extending you can simply write superclass as constructor function, and then apply this constructor for your inherited class.

     function AbstractClass() {
      this.superclass_method = function(message) {
          // do something
        };
     }

     function Child() {
         AbstractClass.apply(this);
         // Now Child will have superclass_method()
     }

Example on angularjs:

http://plnkr.co/edit/eFixlsgF3nJ1LeWUJKsd?p=preview

app.service('noisyThing', 
  ['notify',function(notify){
    this._constructor = function() {
      this.scream = function(message) {
          message = message + " by " + this.get_mouth();
          notify(message); 
          console.log(message);
        };

      this.get_mouth = function(){
        return 'abstract mouth';
      }
    }
  }])
  .service('cat',
  ['noisyThing', function(noisyThing){
    noisyThing._constructor.apply(this)
    this.meow = function() {
      this.scream('meooooow');
    }
    this.get_mouth = function(){
      return 'fluffy mouth';
    }
  }])
  .service('bird',
  ['noisyThing', function(noisyThing){
    noisyThing._constructor.apply(this)
    this.twit = function() {
      this.scream('fuuuuuuck');
    }
  }])

How to use JQuery with ReactJS

Yes, we can use jQuery in ReactJs. Here I will tell how we can use it using npm.

step 1: Go to your project folder where the package.json file is present via using terminal using cd command.

step 2: Write the following command to install jquery using npm : npm install jquery --save

step 3: Now, import $ from jquery into your jsx file where you need to use.

Example:

write the below in index.jsx

import React from 'react';
import ReactDOM from 'react-dom';
import $ from 'jquery';


//   react code here


$("button").click(function(){
    $.get("demo_test.asp", function(data, status){
        alert("Data: " + data + "\nStatus: " + status);
    });
});

// react code here

write the below in index.html

<!DOCTYPE html>
<html>
<head>
    <script src="index.jsx"></script>
    <!-- other scripting files -->
</head>
<body>
    <!-- other useful tags -->
    <div id="div1">
        <h2>Let jQuery AJAX Change This Text</h2>
    </div>
    <button>Get External Content</button>
</body>
</html>

What is the difference between max-device-width and max-width for mobile web?

Don't use device-width/height anymore.

device-width, device-height and device-aspect-ratio are deprecated in Media Queries Level 4: https://developer.mozilla.org/en-US/docs/Web/CSS/@media#Media_features

Just use width/height (without min/max) in combination with orientation & (min/max-)resolution to target specific devices. On mobile width/height should be the same as device-width/height.

Check if a string contains another string

You wouldn't really want to do this given the existing Instr/InstrRev functions but there are times when it is handy to use EVALUATE to return the result of Excel worksheet functions within VBA

Option Explicit

Public Sub test()

    Debug.Print ContainsSubString("bc", "abc,d")

End Sub
Public Function ContainsSubString(ByVal substring As String, ByVal testString As String) As Boolean
    'substring = string to test for; testString = string to search
    ContainsSubString = Evaluate("=ISNUMBER(FIND(" & Chr$(34) & substring & Chr$(34) & ", " & Chr$(34) & testString & Chr$(34) & "))")

End Function

send mail from linux terminal in one line

You can also use sendmail:

/usr/sbin/sendmail [email protected] < /file/to/send

How to download Javadoc to read offline?

JAVA Fax Api documentation

You could download the mac 2.2 preview release from here and unzip it.

http://www.oracle.com/technetwork/java/javafx/downloads/devpreview-1429449.html

The javadoc won't quite match 2.1, but it will be close and if you use the preview instead, it will match exactly.

I think this would help you :)

Passive Link in Angular 2 - <a href=""> equivalent

Here are some ways to do it:

  • <a href="" (click)="false">Click Me</a>

  • <a style="cursor: pointer;">Click Me</a>

  • <a href="javascript:void(0)">Click Me</a>

Select Top and Last rows in a table (SQL server)

You must sort your data according your needs (es. in reverse order) and use select top query

PHP MySQL Google Chart JSON - Complete Example

Some might encounter this error (I got it while implementing PHP-MySQLi-JSON-Google Chart Example):

You called the draw() method with the wrong type of data rather than a DataTable or DataView.

The solution would be: replace jsapi and just use loader.js with:

google.charts.load('current', {packages: ['corechart']}) and 
google.charts.setOnLoadCallback 

-- according to the release notes --> The version of Google Charts that remains available via the jsapi loader is no longer being updated consistently. Please use the new gstatic loader from now on.

How to upgrade rubygems

For me it sufficed to simply run

gem update

What is inf and nan?

You say:

when i do nan - inf i dont get -inf i get nan

This is because any operation containing NaN as an operand would return NaN.

A comparison with NaN would return an unordered result.

>>> float('Inf') == float('Inf')
True
>>> float('NaN') == float('NaN')
False

How to remove certain characters from a string in C++?

remove_if() has already been mentioned. But, with C++0x, you can specify the predicate for it with a lambda instead.

Below is an example of that with 3 different ways of doing the filtering. "copy" versions of the functions are included too for cases when you're working with a const or don't want to modify the original.

#include <iostream>
#include <string>
#include <algorithm>
#include <cctype>
using namespace std;

string& remove_chars(string& s, const string& chars) {
    s.erase(remove_if(s.begin(), s.end(), [&chars](const char& c) {
        return chars.find(c) != string::npos;
    }), s.end());
    return s;
}
string remove_chars_copy(string s, const string& chars) {
    return remove_chars(s, chars);
}

string& remove_nondigit(string& s) {
    s.erase(remove_if(s.begin(), s.end(), [](const char& c) {
        return !isdigit(c);
    }), s.end());
    return s;
}
string remove_nondigit_copy(string s) {
    return remove_nondigit(s);
}

string& remove_chars_if_not(string& s, const string& allowed) {
    s.erase(remove_if(s.begin(), s.end(), [&allowed](const char& c) {
        return allowed.find(c) == string::npos;
    }), s.end());
    return s;
}
string remove_chars_if_not_copy(string s, const string& allowed) {
    return remove_chars_if_not(s, allowed);
}

int main() {
    const string test1("(555) 555-5555");
    string test2(test1);
    string test3(test1);
    string test4(test1);
    cout << remove_chars_copy(test1, "()- ") << endl;
    cout << remove_chars(test2, "()- ") << endl;
    cout << remove_nondigit_copy(test1) << endl;
    cout << remove_nondigit(test3) << endl;
    cout << remove_chars_if_not_copy(test1, "0123456789") << endl;
    cout << remove_chars_if_not(test4, "0123456789") << endl;
}

FileNotFoundError: [Errno 2] No such file or directory

For people who are still getting error despite of passing absolute path, should check that if file has a valid name. For me I was trying to create a file with '/' in the file name. As soon as I removed '/', I was able to create the file.

download csv file from web api in angular js

Workable solution:

downloadCSV(data){   
 const newBlob = new Blob([decodeURIComponent(encodeURI(data))], { type: 'text/csv;charset=utf-8;' });

        // IE doesn't allow using a blob object directly as link href
        // instead it is necessary to use msSaveOrOpenBlob
        if (window.navigator && window.navigator.msSaveOrOpenBlob) {
          window.navigator.msSaveOrOpenBlob(newBlob);
          return;
        }

        // For other browsers:
        // Create a link pointing to the ObjectURL containing the blob.
        const fileData = window.URL.createObjectURL(newBlob);

        const link = document.createElement('a');
        link.href = fileData;
        link.download = `Usecase-Unprocessed.csv`;
        // this is necessary as link.click() does not work on the latest firefox
        link.dispatchEvent(new MouseEvent('click', { bubbles: true, cancelable: true, view: window }));

        setTimeout(function () {
          // For Firefox it is necessary to delay revoking the ObjectURL
          window.URL.revokeObjectURL(fileData);
          link.remove();
        }, 5000);
  }

Setting dropdownlist selecteditem programmatically

ddlData.SelectedIndex will contain the int value To select the specific value into DropDown :

ddlData.SelectedIndex=ddlData.Items.IndexOf(ddlData.Items.FindByText("value"));

return type of ddlData.Items.IndexOf(ddlData.Items.FindByText("value")); is int.

How do I open a URL from C++?

There're already answers for windows. In linux, I noticed open https://www.google.com always launch browser from shell, so you can try:

system("open https://your.domain/uri");

that's say

system(("open "s + url).c_str()); // c++

https://linux.die.net/man/1/open

How can I parse JSON with C#?

System.Text.Json

.NET core 3.0 comes with System.Text.Json built-in which means you can deserialize/serialize JSON without using a third-party library.

To serialize your class(es) to JSON string:

var json = JsonSerializer.Serialize(order);

To deserialize the JSON into a strongly typed class:

var order = JsonSerializer.Deserialize<Order>(json);

So if you have a class like below:

public class Order
{
    public int Id { get; set; }
    public string OrderNumber { get; set; }
    public decimal Balance { get; set; }
    public DateTime Opened { get; set; }
}

var json = JsonSerializer.Serialize(order);
// creates JSON ==>
{
    "id": 123456,
    "orderNumber": "ABC-123-456",
    "balance": 9876.54,
    "opened": "2019-10-21T23:47:16.85",
};

var order = JsonSerializer.Deserialize<Order>(json);
// ==> creates the above class

One thing to note is that System.Text.Json does not automatically handle camelCase JSON properties when using your own code (however, it does when using MVC/WebAPI requests and the model binder).

To resolve this you need to pass JsonSerializerOptions as a parameter.

JsonSerializerOptions options = new JsonSerializerOptions
{        
    PropertyNamingPolicy = JsonNamingPolicy.CamelCase,  // set camelCase       
    WriteIndented = true                                // write pretty json
};

// pass options to serializer
var json = JsonSerializer.Serialize(order, options);
// pass options to deserializer
var order = JsonSerializer.Deserialize<Order>(json, options);

System.Text.Json is also available for .Net Framework and .Net Standard as a Nu-get package System.Text.Json

When is a language considered a scripting language?

I see a scripting language as anything not requiring an overt heavy-weight feeling 'compile' step. The main feature from a programmers standpoint is: you edit code and run it right away.

Thus I would regard JavaScript and PHP as scripting languages, whereas ActionScript 3/Flex is not really.

How to extract or unpack an .ab file (Android Backup file)

I have had to unpack a .ab-file, too and found this post while looking for an answer. My suggested solution is Android Backup Extractor, a free Java tool for Windows, Linux and Mac OS.

Make sure to take a look at the README, if you encounter a problem. You might have to download further files, if your .ab-file is password-protected.

Usage:
java -jar abe.jar [-debug] [-useenv=yourenv] unpack <backup.ab> <backup.tar> [password]

Example:

Let's say, you've got a file test.ab, which is not password-protected, you're using Windows and want the resulting .tar-Archive to be called test.tar. Then your command should be:

java.exe -jar abe.jar unpack test.ab test.tar ""

How to insert a string which contains an "&"

If you are doing it from SQLPLUS use

SET DEFINE OFF  

to stop it treading & as a special case

Max retries exceeded with URL in requests

Adding my own experience for those who are experiencing this in the future. My specific error was

Failed to establish a new connection: [Errno 8] nodename nor servname provided, or not known'

It turns out that this was actually because I had reach the maximum number of open files on my system. It had nothing to do with failed connections, or even a DNS error as indicated.

How do I install Java on Mac OSX allowing version switching?

With Homebrew and jenv:

Assumption: Mac machine and you already have installed homebrew.

Install cask:

$ brew tap caskroom/cask
$ brew tap caskroom/versions

To install latest java:

$ brew cask install java

To install java 8:

$ brew cask install java8

To install java 9:

$ brew cask install java9

If you want to install/manage multiple version then you can use 'jenv':

Install and configure jenv:

$ brew install jenv
$ echo 'export PATH="$HOME/.jenv/bin:$PATH"' >> ~/.bash_profile
$ echo 'eval "$(jenv init -)"' >> ~/.bash_profile
$ source ~/.bash_profile

Add the installed java to jenv:

$ jenv add /Library/Java/JavaVirtualMachines/jdk1.8.0_202.jdk/Contents/Home
$ jenv add /Library/Java/JavaVirtualMachines/jdk1.11.0_2.jdk/Contents/Home

To see all the installed java:

$ jenv versions

Above command will give the list of installed java:

* system (set by /Users/lyncean/.jenv/version)
1.8
1.8.0.202-ea
oracle64-1.8.0.202-ea

Configure the java version which you want to use:

$ jenv global oracle64-1.6.0.39

Using sed, Insert a line above or below the pattern?

The following adds one line after SearchPattern.

sed -i '/SearchPattern/aNew Text' SomeFile.txt

It inserts New Text one line below each line that contains SearchPattern.

To add two lines, you can use a \ and enter a newline while typing New Text.

POSIX sed requires a \ and a newline after the a sed function. [1] Specifying the text to append without the newline is a GNU sed extension (as documented in the sed info page), so its usage is not as portable.

[1] https://unix.stackexchange.com/questions/52131/sed-on-osx-insert-at-a-certain-line/

How to pass text in a textbox to JavaScript function?

This is what I have done. (Adapt from all of your answers)

<input name="textbox1" type="text" id="txt1"/>
<input name="buttonExecute" onclick="execute(document.getElementById('txt1').value)" type="button" value="Execute" />

It works. Thanks to all of you. :)

How to block users from closing a window in Javascript?

If you don't want to display popup for all event you can add conditions like

window.onbeforeunload = confirmExit;
    function confirmExit() {
        if (isAnyTaskInProgress) {
           return "Some task is in progress. Are you sure, you want to close?";
        }
    }

This works fine for me

Could not install packages due to an EnvironmentError: [WinError 5] Access is denied:

I had the same issue while adding Flask. So used one of the above command.

pip install --ignore-installed --upgrade --user flask

Got only a small warning and it worked!!

Installing collected packages: click, MarkupSafe, Jinja2, itsdangerous, Werkzeug, flask WARNING: The script flask.exe is installed in 'C:\Users\Admin\AppData\Roaming\Python\Python38\Scripts' which is not on PATH. Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location. Successfully installed Jinja2-2.11.2 MarkupSafe-1.1.1 Werkzeug-1.0.1 click-7.1.2 flask-1.1.2 itsdangerous-1.1.0 WARNING: You are using pip version 20.1.1; however, version 20.2 is available. You should consider upgrading via the 'c:\python38\python.exe -m pip install --upgrade pip' command.

sub and gsub function?

That won't work if the string contains more than one match... try this:

echo "/x/y/z/x" | awk '{ gsub("/", "_") ; system( "echo "  $0) }'

or better (if the echo isn't a placeholder for something else):

echo "/x/y/z/x" | awk '{ gsub("/", "_") ; print $0 }'

In your case you want to make a copy of the value before changing it:

echo "/x/y/z/x" | awk '{ c=$0; gsub("/", "_", c) ; system( "echo " $0 " " c )}'

How to show progress bar while loading, using ajax

_x000D_
_x000D_
$(document).ready(function () { _x000D_
 $(document).ajaxStart(function () {_x000D_
        $('#wait').show();_x000D_
    });_x000D_
    $(document).ajaxStop(function () {_x000D_
        $('#wait').hide();_x000D_
    });_x000D_
    $(document).ajaxError(function () {_x000D_
        $('#wait').hide();_x000D_
    });   _x000D_
});
_x000D_
<div id="wait" style="display: none; width: 100%; height: 100%; top: 100px; left: 0px; position: fixed; z-index: 10000; text-align: center;">_x000D_
            <img src="../images/loading_blue2.gif" width="45" height="45" alt="Loading..." style="position: fixed; top: 50%; left: 50%;" />_x000D_
</div>
_x000D_
_x000D_
_x000D_

How can I use the apply() function for a single column?

You don't need a function at all. You can work on a whole column directly.

Example data:

>>> df = pd.DataFrame({'a': [100, 1000], 'b': [200, 2000], 'c': [300, 3000]})
>>> df

      a     b     c
0   100   200   300
1  1000  2000  3000

Half all the values in column a:

>>> df.a = df.a / 2
>>> df

     a     b     c
0   50   200   300
1  500  2000  3000

Sharing link on WhatsApp from mobile website (not application) for Android

Try to make it this way:

<a href="https://wa.me/(phone)?text=(text URL encoded)">Link</a>

Even you can send messages without enter the phone number in the link:

<a href="https://wa.me/?text=Hello%20world!">Say hello</a>

After clicking on the link, you will be shown a list of contacts you can send your message to.

More info in https://faq.whatsapp.com/en/general/26000030.

Good luck!

403 Forbidden vs 401 Unauthorized HTTP responses

  • 401 Unauthorized: I don't know who you are. This an authentication error.
  • 403 Forbidden: I know who you are, but you don't have permission to access this resource. This is an authorization error.

Angular: Cannot find a differ supporting object '[object Object]'

Missing square brackets around input property may cause this error. For example:

Component Foo {
    @Input()
    bars: BarType[];
}

Correct:

<app-foo [bars]="smth"></app-foo>

Incorrect (triggering error):

<app-foo bars="smth"></app-foo>

How to get the list of all printers in computer

Get Network and Local Printer List in ASP.NET

This method uses the Windows Management Instrumentation or the WMI interface. It’s a technology used to get information about various systems (hardware) running on a Windows Operating System.

private void GetAllPrinterList()
        {
            ManagementScope objScope = new ManagementScope(ManagementPath.DefaultPath); //For the local Access
            objScope.Connect();

            SelectQuery selectQuery = new SelectQuery();
            selectQuery.QueryString = "Select * from win32_Printer";
            ManagementObjectSearcher MOS = new ManagementObjectSearcher(objScope, selectQuery);
            ManagementObjectCollection MOC = MOS.Get();
            foreach (ManagementObject mo in MOC)
            {
                lstPrinterList.Items.Add(mo["Name"].ToString());
            }
        }

Click here to download source and application demo

Demo of application which listed network and local printer

enter image description here

Debian 8 (Live-CD) what is the standard login and password?

Although this is an old question, I had the same question when using the Standard console version. The answer can be found in the Debian Live manual under the section 10.1 Customizing the live user. It says:

It is also possible to change the default username "user" and the default password "live".

I tried the username user and password live and it did work. If you want to run commands as root you can preface each command with sudo

Producer/Consumer threads using a Queue

  1. Java code "BlockingQueue" which has synchronized put and get method.
  2. Java code "Producer" , producer thread to produce data.
  3. Java code "Consumer" , consumer thread to consume the data produced.
  4. Java code "ProducerConsumer_Main", main function to start the producer and consumer thread.

BlockingQueue.java

public class BlockingQueue 
{
    int item;
    boolean available = false;

    public synchronized void put(int value) 
    {
        while (available == true)
        {
            try 
            {
                wait();
            } catch (InterruptedException e) { 
            } 
        }

        item = value;
        available = true;
        notifyAll();
    }

    public synchronized int get()
    {
        while(available == false)
        {
            try
            {
                wait();
            }
            catch(InterruptedException e){
            }
        }

        available = false;
        notifyAll();
        return item;
    }
}

Consumer.java

package com.sukanya.producer_Consumer;

public class Consumer extends Thread
{
    blockingQueue queue;
    private int number;
    Consumer(BlockingQueue queue,int number)
    {
        this.queue = queue;
        this.number = number;
    }

    public void run()
    {
        int value = 0;

        for (int i = 0; i < 10; i++) 
        {
            value = queue.get();
            System.out.println("Consumer #" + this.number+ " got: " + value);
        }
    }
}

ProducerConsumer_Main.java

package com.sukanya.producer_Consumer;

public class ProducerConsumer_Main 
{
    public static void main(String args[])
    {
        BlockingQueue queue = new BlockingQueue();
        Producer producer1 = new Producer(queue,1);
        Consumer consumer1 = new Consumer(queue,1);
        producer1.start();
        consumer1.start();
    }
}

Maintain aspect ratio of div but fill screen width and height in CSS?

Danield's answer is good, but it can only be used when the div fills the whole viewport, or by using a bit of calc, can be used if the width and height of the other content in the viewport is known.

However, by combining the margin-bottom trick with the method in the aforementioned answer, the problem can be reduced to just having to know the height of the other content. This is useful if you have a fixed height header, but the width of the sidebar, for example, is not known.

_x000D_
_x000D_
body {_x000D_
  margin: 0;_x000D_
  margin-top: 100px; /* simulating a header */_x000D_
}_x000D_
_x000D_
main {_x000D_
  margin: 0 auto;_x000D_
  max-width: calc(200vh - 200px);_x000D_
}_x000D_
_x000D_
section {_x000D_
  padding-bottom: 50%;_x000D_
  position: relative;_x000D_
}_x000D_
_x000D_
div {_x000D_
  position:absolute;_x000D_
  background-color: red;_x000D_
  top: 0;_x000D_
  left: 0;_x000D_
  bottom: 0;_x000D_
  right: 0;_x000D_
}
_x000D_
<main>_x000D_
  <section>_x000D_
    <div></div>_x000D_
  </section>_x000D_
</main>
_x000D_
_x000D_
_x000D_

Here it is in a jsfiddle using scss, which makes it more obvious where the values come from.

How to specify the current directory as path in VBA?

I thought I had misunderstood but I was right. In this scenario, it will be ActiveWorkbook.Path

But the main issue was not here. The problem was with these 2 lines of code

strFile = Dir(strPath & "*.csv")

Which should have written as

strFile = Dir(strPath & "\*.csv")

and

With .QueryTables.Add(Connection:="TEXT;" & strPath & strFile, _

Which should have written as

With .QueryTables.Add(Connection:="TEXT;" & strPath & "\" & strFile, _

What is the difference between null and undefined in JavaScript?

This is the difference

(adding characters due to lack of characters, so I'm allowed to post this.)

Get Value of Radio button group

Your quotes only need to surround the value part of the attribute-equals selector, [attr='val'], like this:

$('a#check_var').click(function() {
  alert($("input:radio[name='r']:checked").val()+ ' '+
        $("input:radio[name='s']:checked").val());
});?

You can see the working version here.

Iterating over ResultSet and adding its value in an ArrayList

If I've understood your problem correctly, there are two possible problems here:

  • resultset is null - I assume that this can't be the case as if it was you'd get an exception in your while loop and nothing would be output.
  • The second problem is that resultset.getString(i++) will get columns 1,2,3 and so on from each subsequent row.

I think that the second point is probably your problem here.

Lets say you only had 1 row returned, as follows:

Col 1, Col 2, Col 3 
A    ,     B,     C

Your code as it stands would only get A - it wouldn't get the rest of the columns.

I suggest you change your code as follows:

ResultSet resultset = ...;
ArrayList<String> arrayList = new ArrayList<String>(); 
while (resultset.next()) {                      
    int i = 1;
    while(i <= numberOfColumns) {
        arrayList.add(resultset.getString(i++));
    }
    System.out.println(resultset.getString("Col 1"));
    System.out.println(resultset.getString("Col 2"));
    System.out.println(resultset.getString("Col 3"));                    
    System.out.println(resultset.getString("Col n"));
}

Edit:

To get the number of columns:

ResultSetMetaData metadata = resultset.getMetaData();
int numberOfColumns = metadata.getColumnCount();

Constructors in Go

There are actually two accepted best practices:

  1. Make the zero value of your struct a sensible default. (While this looks strange to most people coming from "traditional" oop it often works and is really convenient).
  2. Provide a function func New() YourTyp or if you have several such types in your package functions func NewYourType1() YourType1 and so on.

Document if a zero value of your type is usable or not (in which case it has to be set up by one of the New... functions. (For the "traditionalist" oops: Someone who does not read the documentation won't be able to use your types properly, even if he cannot create objects in undefined states.)

Disable Transaction Log

SQL Server requires a transaction log in order to function.

That said there are two modes of operation for the transaction log:

  • Simple
  • Full

In Full mode the transaction log keeps growing until you back up the database. In Simple mode: space in the transaction log is 'recycled' every Checkpoint.

Very few people have a need to run their databases in the Full recovery model. The only point in using the Full model is if you want to backup the database multiple times per day, and backing up the whole database takes too long - so you just backup the transaction log.

The transaction log keeps growing all day, and you keep backing just it up. That night you do your full backup, and SQL Server then truncates the transaction log, begins to reuse the space allocated in the transaction log file.

If you only ever do full database backups, you don't want the Full recovery mode.

"Unicode Error "unicodeescape" codec can't decode bytes... Cannot open text files in Python 3

I had same error, just uninstalled and installed again the numpy package, that worked!

Google Chrome form autofill and its yellow background

Try this code:

_x000D_
_x000D_
  $(function(){_x000D_
     setTimeout(function(){_x000D_
      $('[name=user_password]').attr('type', 'password');_x000D_
     }, 1000);_x000D_
    });
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>_x000D_
<input name="user_password" type="password">
_x000D_
_x000D_
_x000D_

SELECT * FROM multiple tables. MySQL

You will have the duplicate values for name and price here. And ids are duplicate in the drinks_photos table.There is no way you can avoid them.Also what exactly you want the output ?

How do I escape only single quotes?

In some cases, I just convert it into ENTITIES:

                        // i.e.,  $x= ABC\DEFGH'IJKL
$x = str_ireplace("'",  "&apos;", $x);
$x = str_ireplace("\\", "&bsol;", $x);
$x = str_ireplace('"',  "&quot;", $x);

On the HTML page, the visual output is the same:

ABC\DEFGH'IJKL

However, it is sanitized in source.

changing the language of error message in required field in html5 contact form

TLDR: Usually, you don't need to change the validation message but if you do use this:

<input
    oninvalid="this.setCustomValidity('Your custom message / ???????')"
    oninput="this.setCustomValidity('')"
    required="required"
    type="text"
    name="text"
>

The validation messages are coming from your browser and if your browser is in English the message will be in English, if the browser is in French the message will be in French and so on.

If you an input for which the default validation messages doesn't work for you, the easiest solution is to provide your custom message to setCustomValidity as a parameter.

...
oninvalid="this.setCustomValidity('Your custom message / ???????')"
...

This is a native input's method which overwrites the default message. But now we have one problem, once the validation is triggered, the message will keep showing while the user is typing. So to stop the message from showing you can set the validity message to empty string using the oninput attribute.

...
oninput="this.setCustomValidity('')"
...

How to solve ADB device unauthorized in Android ADB host device?

For unknown reasons, I only had ~/.android/adbkey, but not ~/.android/adbkey.pub.

I guess that adb was unable to push the public key to the device, and thus the device could never show the authorization dialog.

After killing the adb server, removing the adbkey file and starting adb again, the authorization dialog popped up on the phone.

SQL Server query to find all permissions/access for all users in a database

Here is my version, adapted from others. I spent 30 minutes just now trying to remember how I came up with this, and @Jeremy 's answer seems to be the core inspiration. I didn't want to update Jeremy's answer, just in case I introduced bugs, so I am posting my version of it here.

I suggest pairing the full script with some inspiration taken from Kenneth Fisher's T-SQL Tuesday: What Permissions Does a Specific User Have?: This will allow you to answer compliance/audit questions bottom-up, as opposed to top-down.

EXECUTE AS LOGIN = '<loginname>'

SELECT token.name AS GroupNames
FROM sys.login_token token
JOIN sys.server_principals grp
    ON token.sid = grp.sid
WHERE token.[type] = 'WINDOWS GROUP'
  AND grp.[type] = 'G'

REVERT

To understand what this covers, consider Contoso\DB_AdventureWorks_Accounting Windows AD Group with member Contoso\John.Doe. John.Doe authenticates to AdventureWorks via server_principal Contoso\DB_AdventureWorks_Logins Windows AD Group. If someone asks you, "What permissions does John.Doe have?", you cannot answer that question with just the below script. You need to then iterate through each row returned by the below script and join it to the above script. (You may also need to normalize for stale name values via looking up the SID in your Active Directory provider.)

Here is the script, without incorporating such reverse look-up logic.

/*


--Script source found at :  http://stackoverflow.com/a/7059579/1387418
Security Audit Report
1) List all access provisioned to a sql user or windows user/group directly 
2) List all access provisioned to a sql user or windows user/group through a database or application role
3) List all access provisioned to the public role



Columns Returned:
UserName         : SQL or Windows/Active Directory user account.  This could also be an Active Directory group.
UserType         : Value will be either 'SQL User' or 'Windows User'.  This reflects the type of user defined for the 
                  SQL Server user account.
PrinciaplUserName: if UserName is not blank, then UserName else DatabaseUserName
PrincipalType    : Possible values are 'SQL User', 'Windows User', 'Database Role', 'Windows Group'
DatabaseUserName : Name of the associated user as defined in the database user account.  The database user may not be the
                   same as the server user.
Role             : The role name.  This will be null if the associated permissions to the object are defined at directly
                   on the user account, otherwise this will be the name of the role that the user is a member of.
PermissionType   : Type of permissions the user/role has on an object. Examples could include CONNECT, EXECUTE, SELECT
                   DELETE, INSERT, ALTER, CONTROL, TAKE OWNERSHIP, VIEW DEFINITION, etc.
                   This value may not be populated for all roles.  Some built in roles have implicit permission
                   definitions.
PermissionState  : Reflects the state of the permission type, examples could include GRANT, DENY, etc.
                   This value may not be populated for all roles.  Some built in roles have implicit permission
                   definitions.
ObjectType       : Type of object the user/role is assigned permissions on.  Examples could include USER_TABLE, 
                   SQL_SCALAR_FUNCTION, SQL_INLINE_TABLE_VALUED_FUNCTION, SQL_STORED_PROCEDURE, VIEW, etc.   
                   This value may not be populated for all roles.  Some built in roles have implicit permission
                   definitions.          
ObjectName       : Name of the object that the user/role is assigned permissions on.  
                   This value may not be populated for all roles.  Some built in roles have implicit permission
                   definitions.
ColumnName       : Name of the column of the object that the user/role is assigned permissions on. This value
                   is only populated if the object is a table, view or a table value function.                 
*/

DECLARE @HideDatabaseDiagrams BIT = 1;

--List all access provisioned to a sql user or windows user/group directly 
SELECT  
    [UserName] = CASE dbprinc.[type] 
                    WHEN 'S' THEN dbprinc.[name] -- SQL User
                    WHEN 'U' THEN sprinc.[name] -- Windows User
                    WHEN 'R' THEN NULL -- Database Role
                    WHEN 'G' THEN NULL -- Windows Group
                    ELSE NULL
                 END,
    [UserType] = CASE dbprinc.[type]
                    WHEN 'S' THEN 'SQL User'
                    WHEN 'U' THEN 'Windows User'
                    WHEN 'R' THEN NULL -- Database Role
                    WHEN 'G' THEN NULL -- Windows Group
                    ELSE dbprinc.[type]
                 END,
    [PrincipalUserName] = COALESCE(
                    CASE dbprinc.[type]
                        WHEN 'S' THEN dbprinc.[name] -- SQL User
                        WHEN 'U' THEN sprinc.[name] -- Windows User
                        WHEN 'R' THEN NULL -- Database Role
                        WHEN 'G' THEN NULL -- Windows Group
                        ELSE NULL
                     END,
                     dbprinc.[name]
                 ),
    [PrincipalType] = CASE dbprinc.[type]
                    WHEN 'S' THEN 'SQL User'
                    WHEN 'U' THEN 'Windows User'
                    WHEN 'R' THEN 'Database Role'
                    WHEN 'G' THEN 'Windows Group'
                 END,
    [DatabaseUserName] = dbprinc.[name],
    [Role] = null,
    [PermissionType] = perm.[permission_name],
    [PermissionState] = perm.[state_desc],
    [ObjectType] = obj.[type_desc],--perm.[class_desc],
    [ObjectSchema] = OBJECT_SCHEMA_NAME(perm.major_id),
    [ObjectName] = OBJECT_NAME(perm.major_id),
    [ColumnName] = col.[name]
FROM    
    --database user
    sys.database_principals dbprinc  
LEFT JOIN
    --Login accounts
    sys.server_principals sprinc on dbprinc.[sid] = sprinc.[sid]
LEFT JOIN        
    --Permissions
    sys.database_permissions perm ON perm.[grantee_principal_id] = dbprinc.[principal_id]
LEFT JOIN
    --Table columns
    sys.columns col ON col.[object_id] = perm.major_id 
                    AND col.[column_id] = perm.[minor_id]
LEFT JOIN
    sys.objects obj ON perm.[major_id] = obj.[object_id]
WHERE 
    dbprinc.[type] in ('S','U')
    AND CASE
        WHEN @HideDatabaseDiagrams = 1 AND
        dbprinc.[name] = 'guest'
        AND (
            (
                obj.type_desc = 'SQL_SCALAR_FUNCTION'
                AND OBJECT_NAME(perm.major_id) = 'fn_diagramobjects'
            )
            OR (
                obj.type_desc = 'SQL_STORED_PROCEDURE'
                AND OBJECT_NAME(perm.major_id) IN
                (
                    N'sp_alterdiagram',
                    N'sp_creatediagram',
                    N'sp_dropdiagram',
                    N'sp_helpdiagramdefinition',
                    N'sp_helpdiagrams',
                    N'sp_renamediagram'
                )
            )
        )
        THEN 0
        ELSE 1
    END = 1
UNION
--List all access provisioned to a sql user or windows user/group through a database or application role
SELECT  
    [UserName] = CASE memberprinc.[type]
                    WHEN 'S' THEN memberprinc.[name]
                    WHEN 'U' THEN sprinc.[name]
                    WHEN 'R' THEN NULL -- Database Role
                    WHEN 'G' THEN NULL -- Windows Group
                    ELSE NULL
                 END,
    [UserType] = CASE memberprinc.[type]
                    WHEN 'S' THEN 'SQL User'
                    WHEN 'U' THEN 'Windows User'
                    WHEN 'R' THEN NULL -- Database Role
                    WHEN 'G' THEN NULL -- Windows Group
                 END, 
    [PrincipalUserName] = COALESCE(
                    CASE memberprinc.[type]
                        WHEN 'S' THEN memberprinc.[name]
                        WHEN 'U' THEN sprinc.[name]
                        WHEN 'R' THEN NULL -- Database Role
                        WHEN 'G' THEN NULL -- Windows Group
                        ELSE NULL
                     END,
                     memberprinc.[name]
                 ),
    [PrincipalType] = CASE memberprinc.[type]
                    WHEN 'S' THEN 'SQL User'
                    WHEN 'U' THEN 'Windows User'
                    WHEN 'R' THEN 'Database Role'
                    WHEN 'G' THEN 'Windows Group'
                 END, 
    [DatabaseUserName] = memberprinc.[name],
    [Role] = roleprinc.[name],
    [PermissionType] = perm.[permission_name],
    [PermissionState] = perm.[state_desc],
    [ObjectType] = obj.type_desc,--perm.[class_desc],
    [ObjectSchema] = OBJECT_SCHEMA_NAME(perm.major_id),
    [ObjectName] = OBJECT_NAME(perm.major_id),
    [ColumnName] = col.[name]
FROM    
    --Role/member associations
    sys.database_role_members members
JOIN
    --Roles
    sys.database_principals roleprinc ON roleprinc.[principal_id] = members.[role_principal_id]
JOIN
    --Role members (database users)
    sys.database_principals memberprinc ON memberprinc.[principal_id] = members.[member_principal_id]
LEFT JOIN
    --Login accounts
    sys.server_principals sprinc on memberprinc.[sid] = sprinc.[sid]
LEFT JOIN
    --Permissions
    sys.database_permissions perm ON perm.[grantee_principal_id] = roleprinc.[principal_id]
LEFT JOIN
    --Table columns
    sys.columns col on col.[object_id] = perm.major_id 
                    AND col.[column_id] = perm.[minor_id]
LEFT JOIN
    sys.objects obj ON perm.[major_id] = obj.[object_id]
WHERE    
    CASE
        WHEN @HideDatabaseDiagrams = 1 AND
        memberprinc.[name] = 'guest'
        AND (
            (
                obj.type_desc = 'SQL_SCALAR_FUNCTION'
                AND OBJECT_NAME(perm.major_id) = 'fn_diagramobjects'
            )
            OR (
                obj.type_desc = 'SQL_STORED_PROCEDURE'
                AND OBJECT_NAME(perm.major_id) IN
                (
                    N'sp_alterdiagram',
                    N'sp_creatediagram',
                    N'sp_dropdiagram',
                    N'sp_helpdiagramdefinition',
                    N'sp_helpdiagrams',
                    N'sp_renamediagram'
                )
            )
        )
        THEN 0
        ELSE 1
    END = 1
UNION
--List all access provisioned to the public role, which everyone gets by default
SELECT  
    [UserName] = '{All Users}',
    [UserType] = '{All Users}',
    [PrincipalUserName] = '{All Users}',
    [PrincipalType] = '{All Users}',
    [DatabaseUserName] = '{All Users}',
    [Role] = roleprinc.[name],
    [PermissionType] = perm.[permission_name],
    [PermissionState] = perm.[state_desc],
    [ObjectType] = obj.type_desc,--perm.[class_desc],
    [ObjectSchema] = OBJECT_SCHEMA_NAME(perm.major_id),
    [ObjectName] = OBJECT_NAME(perm.major_id),
    [ColumnName] = col.[name]
FROM    
    --Roles
    sys.database_principals roleprinc
LEFT JOIN        
    --Role permissions
    sys.database_permissions perm ON perm.[grantee_principal_id] = roleprinc.[principal_id]
LEFT JOIN
    --Table columns
    sys.columns col on col.[object_id] = perm.major_id
                    AND col.[column_id] = perm.[minor_id]
JOIN 
    --All objects
    sys.objects obj ON obj.[object_id] = perm.[major_id]
WHERE
    --Only roles
    roleprinc.[type] = 'R' AND
    --Only public role
    roleprinc.[name] = 'public' AND
    --Only objects of ours, not the MS objects
    obj.is_ms_shipped = 0
    AND CASE
        WHEN @HideDatabaseDiagrams = 1 AND
        roleprinc.[name] = 'public'
        AND (
            (
                obj.type_desc = 'SQL_SCALAR_FUNCTION'
                AND OBJECT_NAME(perm.major_id) = 'fn_diagramobjects'
            )
            OR (
                obj.type_desc = 'SQL_STORED_PROCEDURE'
                AND OBJECT_NAME(perm.major_id) IN
                (
                    N'sp_alterdiagram',
                    N'sp_creatediagram',
                    N'sp_dropdiagram',
                    N'sp_helpdiagramdefinition',
                    N'sp_helpdiagrams',
                    N'sp_renamediagram'
                )
            )
        )
        THEN 0
        ELSE 1
    END = 1
ORDER BY
    dbprinc.[Name],
    OBJECT_NAME(perm.major_id),
    col.[name],
    perm.[permission_name],
    perm.[state_desc],
    obj.type_desc--perm.[class_desc]

How do I create 7-Zip archives with .NET?

I use this code

                string PZipPath = @"C:\Program Files\7-Zip\7z.exe";
                string sourceCompressDir = @"C:\Test";
                string targetCompressName = @"C:\Test\abc.zip";
                string CompressName = targetCompressName.Split('\\').Last();
                string[] fileCompressList = Directory.GetFiles(sourceCompressDir, "*.*");

                    if (fileCompressList.Length == 0)
                    {
                        MessageBox.Show("No file in directory", "Important Message");
                        return;
                    }
                    string filetozip = null;
                    foreach (string filename in fileCompressList)
                    {
                        filetozip = filetozip + "\"" + filename + " ";
                    }

                    ProcessStartInfo pCompress = new ProcessStartInfo();
                    pCompress.FileName = PZipPath;
                    if (chkRequestPWD.Checked == true)
                    {
                        pCompress.Arguments = "a -tzip \"" + targetCompressName + "\" " + filetozip + " -mx=9" + " -p" + tbPassword.Text;
                    }
                    else
                    {
                        pCompress.Arguments = "a -tzip \"" + targetCompressName + "\" \"" + filetozip + "\" -mx=9";
                    }
                    pCompress.WindowStyle = ProcessWindowStyle.Hidden;
                    Process x = Process.Start(pCompress);
                    x.WaitForExit();

Sass .scss: Nesting and multiple classes?

You can use the parent selector reference &, it will be replaced by the parent selector after compilation:

For your example:

.container {
    background:red;
    &.desc{
       background:blue;
    }
}

/* compiles to: */
.container {
    background: red;
}
.container.desc {
    background: blue;
}

The & will completely resolve, so if your parent selector is nested itself, the nesting will be resolved before replacing the &.

This notation is most often used to write pseudo-elements and -classes:

.element{
    &:hover{ ... }
    &:nth-child(1){ ... }
}

However, you can place the & at virtually any position you like*, so the following is possible too:

.container {
    background:red;
    #id &{
       background:blue;
    }
}

/* compiles to: */
.container {
    background: red;
}
#id .container {
    background: blue;
}

However be aware, that this somehow breaks your nesting structure and thus may increase the effort of finding a specific rule in your stylesheet.

*: No other characters than whitespaces are allowed in front of the &. So you cannot do a direct concatenation of selector+& - #id& would throw an error.

Long vs Integer, long vs int, what to use and when?

When it comes to using a very long number that may exceed 32 bits to represent, you may use long to make sure that you'll not have strange behavior.

From Java 5 you can use in-boxing and out-boxing features to make the use of int and Integer completely the same. It means that you can do :

int myInt = new Integer(11);
Integer myInt2 = myInt;

The in and out boxing allow you to switch between int and Integer without any additional conversion (same for Long,Double,Short too)

You may use int all the time, but Integer contains some helper methods that can help you to do some complex operations with integers (such as Integer.parseInt(String) )

Python float to int conversion

What Every Computer Scientist Should Know About Floating-Point Arithmetic

Floating-point numbers cannot represent all the numbers. In particular, 2.51 cannot be represented by a floating-point number, and is represented by a number very close to it:

>>> print "%.16f" % 2.51
2.5099999999999998
>>> 2.51*100
250.99999999999997
>>> 4.02*100
401.99999999999994

If you use int, which truncates the numbers, you get:

250
401

Have a look at the Decimal type.

Extract Data from PDF and Add to Worksheet

Over time, I have found that extracting text from PDFs in a structured format is tough business. However if you are looking for an easy solution, you might want to consider XPDF tool pdftotext.

Pseudocode to extract the text would include:

  1. Using SHELL VBA statement to extract the text from PDF to a temporary file using XPDF
  2. Using sequential file read statements to read the temporary file contents into a string
  3. Pasting the string into Excel

Simplified example below:

    Sub ReadIntoExcel(PDFName As String)
        'Convert PDF to text
        Shell "C:\Utils\pdftotext.exe -layout " & PDFName & " tempfile.txt"

        'Read in the text file and write to Excel
        Dim TextLine as String
        Dim RowNumber as Integer
        Dim F1 as Integer
        RowNumber = 1
        F1 = Freefile()
        Open "tempfile.txt" for Input as #F1
            While Not EOF(#F1)
                Line Input #F1, TextLine
                ThisWorkbook.WorkSheets(1).Cells(RowNumber, 1).Value = TextLine
                RowNumber = RowNumber + 1
            Wend
        Close #F1
    End Sub

What is python's site-packages directory?

site-packages is the target directory of manually built Python packages. When you build and install Python packages from source (using distutils, probably by executing python setup.py install), you will find the installed modules in site-packages by default.

There are standard locations:

  • Unix (pure)1: prefix/lib/pythonX.Y/site-packages
  • Unix (non-pure): exec-prefix/lib/pythonX.Y/site-packages
  • Windows: prefix\Lib\site-packages

1 Pure means that the module uses only Python code. Non-pure can contain C/C++ code as well.

site-packages is by default part of the Python search path, so modules installed there can be imported easily afterwards.


Useful reading

Go build: "Cannot find package" (even though GOPATH is set)

TL;DR: Follow Go conventions! (lesson learned the hard way), check for old go versions and remove them. Install latest.

For me the solution was different. I worked on a shared Linux server and after verifying my GOPATH and other environment variables several times it still didn't work. I encountered several errors including 'Cannot find package' and 'unrecognized import path'. After trying to reinstall with this solution by the instructions on golang.org (including the uninstall part) still encountered problems.

Took me some time to realize that there's still an old version that hasn't been uninstalled (running go version then which go again... DAHH) which got me to this question and finally solved.

Detect change to ngModel on a select tag (Angular 2)

I have stumbled across this question and I will submit my answer that I used and worked pretty well. I had a search box that filtered and array of objects and on my search box I used the (ngModelChange)="onChange($event)"

in my .html

<input type="text" [(ngModel)]="searchText" (ngModelChange)="reSearch(newValue)" placeholder="Search">

then in my component.ts

reSearch(newValue: string) {
    //this.searchText would equal the new value
    //handle my filtering with the new value
}

CSS body background image fixed to full screen even when zooming in/out

I've used these techniques before and they both work well. If you read the pros/cons of each you can decide which is right for your site.

Alternatively you could use the full size background image jQuery plugin if you want to get away from the bugs in the above.

How to log Apache CXF Soap Request and Soap Response using Log4j?

Simplest way to achieve pretty logging in Preethi Jain szenario:

LoggingInInterceptor loggingInInterceptor = new LoggingInInterceptor();
loggingInInterceptor.setPrettyLogging(true);
LoggingOutInterceptor loggingOutInterceptor = new LoggingOutInterceptor();
loggingOutInterceptor.setPrettyLogging(true);
factory.getInInterceptors().add(loggingInInterceptor);
factory.getOutInterceptors().add(loggingOutInterceptor);

Redirect echo output in shell script to logfile

#!/bin/sh
# http://www.tldp.org/LDP/abs/html/io-redirection.html
echo "Hello World"
exec > script.log 2>&1
echo "Start logging out from here to a file"
bad command
echo "End logging out from here to a file"
exec > /dev/tty 2>&1 #redirects out to controlling terminal
echo "Logged in the terminal"

Output:

> ./above_script.sh                                                                
Hello World
Not logged in the file
> cat script.log
Start logging out from here to a file
./logging_sample.sh: line 6: bad: command not found
End logging out from here to a file

Read more here: http://www.tldp.org/LDP/abs/html/io-redirection.html

How to render an ASP.NET MVC view as a string?

If you want to forgo MVC entirely, thereby avoiding all the HttpContext mess...

using RazorEngine;
using RazorEngine.Templating; // For extension methods.

string razorText = System.IO.File.ReadAllText(razorTemplateFileLocation);
string emailBody = Engine.Razor.RunCompile(razorText, "templateKey", typeof(Model), model);

This uses the awesome open source Razor Engine here: https://github.com/Antaris/RazorEngine

How can I strip HTML tags from a string in ASP.NET?

I've posted this on the asp.net forums, and it still seems to be one of the easiest solutions out there. I won't guarantee it's the fastest or most efficient, but it's pretty reliable. In .NET you can use the HTML Web Control objects themselves. All you really need to do is insert your string into a temporary HTML object such as a DIV, then use the built-in 'InnerText' to grab all text that is not contained within tags. See below for a simple C# example:


System.Web.UI.HtmlControls.HtmlGenericControl htmlDiv = new System.Web.UI.HtmlControls.HtmlGenericControl("div");
htmlDiv.InnerHtml = htmlString;
String plainText = htmlDiv.InnerText;

How do you run a command for each line of a file?

I see that you tagged bash, but Perl would also be a good way to do this:

perl -p -e '`chmod 755 $_`' file.txt

You could also apply a regex to make sure you're getting the right files, e.g. to only process .txt files:

perl -p -e 'if(/\.txt$/) `chmod 755 $_`' file.txt

To "preview" what's happening, just replace the backticks with double quotes and prepend print:

perl -p -e 'if(/\.txt$/) print "chmod 755 $_"' file.txt

"No X11 DISPLAY variable" - what does it mean?

One more thing that might be the problem in a case similar to described - X is not forwarded and $DISPLAY is not set when 'xauth' program is not installed on the remote side. You can see it searches for it when you run "ssh -Xv ip_address", and, if not found, fails, which's not seen unless you turn on verbose mode (a fail IMO). You can usually find 'xauth' in a package with the same name.

How to change root logging level programmatically for logback

I seem to be having success doing

org.jboss.logmanager.Logger logger = org.jboss.logmanager.Logger.getLogger("");
logger.setLevel(java.util.logging.Level.ALL);

Then to get detailed logging from netty, the following has done it

org.slf4j.impl.SimpleLogger.setLevel(org.slf4j.impl.SimpleLogger.TRACE);

How to get the last N records in mongodb?

You can't "skip" based on the size of the collection, because it will not take the query conditions into account.

The correct solution is to sort from the desired end-point, limit the size of the result set, then adjust the order of the results if necessary.

Here is an example, based on real-world code.

var query = collection.find( { conditions } ).sort({$natural : -1}).limit(N);

query.exec(function(err, results) {
    if (err) { 
    }
    else if (results.length == 0) {
    }
    else {
        results.reverse(); // put the results into the desired order
        results.forEach(function(result) {
            // do something with each result
        });
    }
});

PostgreSQL - max number of parameters in "IN" clause?

According to the source code located here, starting at line 850, PostgreSQL doesn't explicitly limit the number of arguments.

The following is a code comment from line 870:

/*
 * We try to generate a ScalarArrayOpExpr from IN/NOT IN, but this is only
 * possible if the inputs are all scalars (no RowExprs) and there is a
 * suitable array type available.  If not, we fall back to a boolean
 * condition tree with multiple copies of the lefthand expression.
 * Also, any IN-list items that contain Vars are handled as separate
 * boolean conditions, because that gives the planner more scope for
 * optimization on such clauses.
 *
 * First step: transform all the inputs, and detect whether any are
 * RowExprs or contain Vars.
 */

Error: org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'text/plain;charset=UTF-8' not supported

For me it turned out that I had a @JsonManagedReferece in one entity without a @JsonBackReference in the other referenced entity. This caused the marshaller to throw an error.

Append an object to a list in R in amortized constant time, O(1)?

I think what you want to do is actually pass by reference (pointer) to the function-- create a new environment (which are passed by reference to functions) with the list added to it:

listptr=new.env(parent=globalenv())
listptr$list=mylist

#Then the function is modified as:
lPtrAppend <- function(lstptr, obj) {
    lstptr$list[[length(lstptr$list)+1]] <- obj
}

Now you are only modifying the existing list (not creating a new one)

Push items into mongo array via mongoose

Assuming, var friend = { firstName: 'Harry', lastName: 'Potter' };

There are two options you have:

Update the model in-memory, and save (plain javascript array.push):

person.friends.push(friend);
person.save(done);

or

PersonModel.update(
    { _id: person._id }, 
    { $push: { friends: friend } },
    done
);

I always try and go for the first option when possible, because it'll respect more of the benefits that mongoose gives you (hooks, validation, etc.).

However, if you are doing lots of concurrent writes, you will hit race conditions where you'll end up with nasty version errors to stop you from replacing the entire model each time and losing the previous friend you added. So only go to the former when it's absolutely necessary.

What primitive data type is time_t?

It's platform-specific. But you can cast it to a known type.

printf("%lld\n", (long long) time(NULL));

Can I serve multiple clients using just Flask app.run() as standalone?

flask.Flask.run accepts additional keyword arguments (**options) that it forwards to werkzeug.serving.run_simple - two of those arguments are threaded (a boolean) and processes (which you can set to a number greater than one to have werkzeug spawn more than one process to handle requests).

threaded defaults to True as of Flask 1.0, so for the latest versions of Flask, the default development server will be able to serve multiple clients simultaneously by default. For older versions of Flask, you can explicitly pass threaded=True to enable this behaviour.

For example, you can do

if __name__ == '__main__':
    app.run(threaded=True)

to handle multiple clients using threads in a way compatible with old Flask versions, or

if __name__ == '__main__':
    app.run(threaded=False, processes=3)

to tell Werkzeug to spawn three processes to handle incoming requests, or just

if __name__ == '__main__':
    app.run()

to handle multiple clients using threads if you know that you will be using Flask 1.0 or later.

That being said, Werkzeug's serving.run_simple wraps the standard library's wsgiref package - and that package contains a reference implementation of WSGI, not a production-ready web server. If you are going to use Flask in production (assuming that "production" is not a low-traffic internal application with no more than 10 concurrent users) make sure to stand it up behind a real web server (see the section of Flask's docs entitled Deployment Options for some suggested methods).

How to prevent XSS with HTML/PHP?

One of the most important steps is to sanitize any user input before it is processed and/or rendered back to the browser. PHP has some "filter" functions that can be used.

The form that XSS attacks usually have is to insert a link to some off-site javascript that contains malicious intent for the user. Read more about it here.

You'll also want to test your site - I can recommend the Firefox add-on XSS Me.

How to print / echo environment variables?

On windows, you can print with this command in your CLI C:\Users\dir\env | more

You can view all environment variables set on your system with the env command. The list is long, so pipe the output through more to make it easier to read.

Does C# have extension properties?

No they do not exist in C# 3.0 and will not be added in 4.0. It's on the list of feature wants for C# so it may be added at a future date.

At this point the best you can do is GetXXX style extension methods.

How do I center this form in css?

i dont know if the full resolution has been made for this yet. i know that from doing a 2 column page with fixed left side bar, to get a contact us form centered on my page i put the following:

    form {
 width: 100%;
 margin-left: auto;
 margin-right: auto;
 display: inline-block;
 }

this worked for me so thought id throw in my resolution to the same problem

How to execute mongo commands through shell scripts?

You can also evaluate a command using the --eval flag, if it is just a single command.

mongo --eval "printjson(db.serverStatus())"

Please note: if you are using Mongo operators, starting with a $ sign, you'll want to surround the eval argument in single quotes to keep the shell from evaluating the operator as an environment variable:

mongo --eval 'db.mycollection.update({"name":"foo"},{$set:{"this":"that"}});' myDbName

Otherwise you may see something like this:

mongo --eval "db.test.update({\"name\":\"foo\"},{$set:{\"this\":\"that\"}});"
> E QUERY    SyntaxError: Unexpected token :

How to fast-forward a branch to head?

No complexities required just stand at your branch and do a git pull it worked for me

Or, as a second try git pull origin master only in case if you are unlucky with the first command

If "0" then leave the cell blank

=iferror(1/ (1/ H15+G16-F16 ), "")

this way avoids repeating the central calculation (which can often be much longer or more processor hungry than the one you have here...

enjoy

How would I get a cron job to run every 30 minutes?

Try this:

0,30 * * * * your command goes here

According to the official Mac OS X crontab(5) manpage, the / syntax is supported. Thus, to figure out why it wasn't working for you, you'll need to look at the logs for cron. In those logs, you should find a clear failure message.

Note: Mac OS X appears to use Vixie Cron, the same as Linux and the BSDs.

Center text in table cell

How about simply (Please note, come up with a better name for the class name this is simply an example):

.centerText{
   text-align: center;
}


<div>
   <table style="width:100%">
   <tbody>
   <tr>
      <td class="centerText">Cell 1</td>
      <td>Cell 2</td>
    </tr>
    <tr>
      <td class="centerText">Cell 3</td>
      <td>Cell 4</td>
    </tr>
    </tbody>
    </table>
</div>

Example here

You can place the css in a separate file, which is recommended. In my example, I created a file called styles.css and placed my css rules in it. Then include it in the html document in the <head> section as follows:

<head>
    <link href="styles.css" rel="stylesheet" type="text/css">
</head>

The alternative, not creating a seperate css file, not recommended at all... Create <style> block in your <head> in the html document. Then just place your rules there.

<head>
 <style type="text/css">
   .centerText{
       text-align: center;
    }
 </style>
</head>

Django CSRF check failing with an Ajax POST request

In my case the problem was with the nginx config that I've copied from main server to a temporary one with disabling https that is not needed on the second one in the process.

I had to comment out these two lines in the config to make it work again:

# uwsgi_param             UWSGI_SCHEME    https;
# uwsgi_pass_header       X_FORWARDED_PROTO;

Cannot import scipy.misc.imread

If you have Pillow installed with scipy and it is still giving you error then check your scipy version because it has been removed from scipy since 1.3.0rc1.

rather install scipy 1.1.0 by :

pip install scipy==1.1.0

check https://github.com/scipy/scipy/issues/6212


The method imread in scipy.misc requires the forked package of PIL named Pillow. If you are having problem installing the right version of PIL try using imread in other packages:

from matplotlib.pyplot import imread
im = imread(image.png)

To read jpg images without PIL use:

import cv2 as cv
im = cv.imread(image.jpg)

You can try from scipy.misc.pilutil import imread instead of from scipy.misc import imread

Please check the GitHub page : https://github.com/amueller/mglearn/issues/2 for more details.

Oracle row count of table by count(*) vs NUM_ROWS from DBA_TABLES

According to the documentation NUM_ROWS is the "Number of rows in the table", so I can see how this might be confusing. There, however, is a major difference between these two methods.

This query selects the number of rows in MY_TABLE from a system view. This is data that Oracle has previously collected and stored.

select num_rows from all_tables where table_name = 'MY_TABLE'

This query counts the current number of rows in MY_TABLE

select count(*) from my_table

By definition they are difference pieces of data. There are two additional pieces of information you need about NUM_ROWS.

  1. In the documentation there's an asterisk by the column name, which leads to this note:

    Columns marked with an asterisk (*) are populated only if you collect statistics on the table with the ANALYZE statement or the DBMS_STATS package.

    This means that unless you have gathered statistics on the table then this column will not have any data.

  2. Statistics gathered in 11g+ with the default estimate_percent, or with a 100% estimate, will return an accurate number for that point in time. But statistics gathered before 11g, or with a custom estimate_percent less than 100%, uses dynamic sampling and may be incorrect. If you gather 99.999% a single row may be missed, which in turn means that the answer you get is incorrect.

If your table is never updated then it is certainly possible to use ALL_TABLES.NUM_ROWS to find out the number of rows in a table. However, and it's a big however, if any process inserts or deletes rows from your table it will be at best a good approximation and depending on whether your database gathers statistics automatically could be horribly wrong.

Generally speaking, it is always better to actually count the number of rows in the table rather then relying on the system tables.

Hyphen, underscore, or camelCase as word delimiter in URIs?

In general, it's not going to have enough of an impact to worry about, particularly since it's an intranet app and not a general-use Internet app. In particular, since it's intranet, SEO isn't a concern, since your intranet shouldn't be accessible to search engines. (and if it is, it isn't an intranet app).

And any framework worth it's salt either already has a default way to do this, or is fairly easy to change how it deals with multi-word URL components, so I wouldn't worry about it too much.

That said, here's how I see the various options:

Hyphen

  • The biggest danger for hyphens is that the same character (typically) is also used for subtraction and numerical negation (ie. minus or negative).
  • Hyphens feel awkward in URL components. They seem to only make sense at the end of a URL to separate words in the title of an article. Or, for example, the title of a Stack Overflow question that is added to the end of a URL for SEO and user-clarity purposes.

Underscore

  • Again, they feel wrong in URL components. They break up the flow (and beauty/simplicity) of a URL, since they essentially add a big, heavy apparent space in the middle of a clean, flowing URL.
  • They tend to blend in with underlines. If you expect your users to copy-paste your URLs into MS Word or other similar text-editing programs, or anywhere else that might pick up on a URL and style it with an underline (like links traditionally are), then you might want to avoid underscores as word separators. Particularly when printed, an underlined URL with underscores tends to look like it has spaces in it instead of underscores.

CamelCase

  • By far my favorite, since it makes the URLs seem to flow better and doesn't have any of the faults that the previous two options do.
  • Can be slightly harder to read for people that have a hard time differentiating upper-case from lower-case, but this shouldn't be much of an issue in a URL, because most "words" should be URL components and separated by a / anyways. If you find that you have a URL component that is more than 2 "words" long, you should probably try to find a better name for that concept.
  • It does have a possible issue with case sensitivity, but most platforms can be adjusted to be either case-sensitive or case-insensitive. Any it's only really an issue for 2 cases: a.) humans typing the URL in, and b.) Programmers (since we are not human) typing the URL in. Typos are always a problem, regardless of case sensitivity, so this is no different that all one case.

rsync copy over only certain types of files using include option

The answer by @chepner will copy all the sub-directories irrespective of the fact if it contains the file or not. If you need to exclude the sub-directories that dont contain the file and still retain the directory structure, use

rsync -zarv  --prune-empty-dirs --include "*/"  --include="*.sh" --exclude="*" "$from" "$to"

check if variable empty

here i have explained how the empty function and isset works please use the one that is appropriate also you can use is_null function also

<?php
    $val = 0;
    //evaluates to true because $var is empty
    if (empty($val)) {
        echo '$val is either 0, empty, or not set at all';
    }
    //evaluates to true because $VAR IS SET
    if (isset($val)) {
        echo '$val is set even though it is empty';
    }
    ?>

how to know status of currently running jobs

It looks like you can use msdb.dbo.sysjobactivity, checking for a record with a non-null start_execution_date and a null stop_execution_date, meaning the job was started, but has not yet completed.

This would give you currently running jobs:

SELECT sj.name
   , sja.*
FROM msdb.dbo.sysjobactivity AS sja
INNER JOIN msdb.dbo.sysjobs AS sj ON sja.job_id = sj.job_id
WHERE sja.start_execution_date IS NOT NULL
   AND sja.stop_execution_date IS NULL

jQuery window scroll event does not fire up

My issue was I had this code in my css

html,
body {
    height: 100%;
    width: 100%;
    overflow: auto;
}

Once I removed it, the scroll event on window fired again

process.env.NODE_ENV is undefined

We ran into this problem when working with node on Windows.

Rather than requiring anyone who attempts to run the app to set these variables, we provided a fallback within the application.

var environment = process.env.NODE_ENV || 'development';

In a production environment, we would define it per the usual methods (SET/export).

UnicodeDecodeError: 'utf8' codec can't decode bytes in position 3-6: invalid data

The string you're trying to parse as a JSON is not encoded in UTF-8. Most likely it is encoded in ISO-8859-1. Try the following:

json.loads(unicode(opener.open(...), "ISO-8859-1"))

That will handle any umlauts that might get in the JSON message.

You should read Joel Spolsky's The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!). I hope that it will clarify some issues you're having around Unicode.

How can I get a process handle by its name in C++?

The following code can be used:

DWORD FindProcessId(const std::wstring& processName)
{
    PROCESSENTRY32 processInfo;
    processInfo.dwSize = sizeof(processInfo);

    HANDLE processesSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, NULL);
    if (processesSnapshot == INVALID_HANDLE_VALUE) {
        return 0;
    }

    Process32First(processesSnapshot, &processInfo);
    if (!processName.compare(processInfo.szExeFile))
    {
        CloseHandle(processesSnapshot);
        return processInfo.th32ProcessID;
    }

    while (Process32Next(processesSnapshot, &processInfo))
    {
        if (!processName.compare(processInfo.szExeFile))
        {
            CloseHandle(processesSnapshot);
            return processInfo.th32ProcessID;
        }
    }

    CloseHandle(processesSnapshot);
    return 0;
}

Usage:

auto processId = FindProcessId(L"blabla.exe");

Getting a handle should be obvious, just call OpenProcess() or similar on it.

How to get the PID of a process by giving the process name in Mac OS X ?

Why don't you run TOP and use the options to sort by other metrics, other than PID? Like, highest used PID from the CPU/MEM?

top -o cpu <---sorts all processes by CPU Usage

How to change the version of the 'default gradle wrapper' in IntelliJ IDEA?

I was facing same issue for changing default gradle version from 5.0 to 4.7, Below are the steps to change default gradle version in intellij enter image description here
1) Change gradle version in gradle/wrapper/gradle-wrapper.properties in this property distributionUrl

2) Hit refresh button in gradle projects menu so that it will start downloading new gradle zip version

What is the Python equivalent of static variables inside a function?

Here is a fully encapsulated version that doesn't require an external initialization call:

def fn():
    fn.counter=vars(fn).setdefault('counter',-1)
    fn.counter+=1
    print (fn.counter)

In Python, functions are objects and we can simply add, or monkey patch, member variables to them via the special attribute __dict__. The built-in vars() returns the special attribute __dict__.

EDIT: Note, unlike the alternative try:except AttributeError answer, with this approach the variable will always be ready for the code logic following initialization. I think the try:except AttributeError alternative to the following will be less DRY and/or have awkward flow:

def Fibonacci(n):
   if n<2: return n
   Fibonacci.memo=vars(Fibonacci).setdefault('memo',{}) # use static variable to hold a results cache
   return Fibonacci.memo.setdefault(n,Fibonacci(n-1)+Fibonacci(n-2)) # lookup result in cache, if not available then calculate and store it

EDIT2: I only recommend the above approach when the function will be called from multiple locations. If instead the function is only called in one place, it's better to use nonlocal:

def TheOnlyPlaceStaticFunctionIsCalled():
    memo={}
    def Fibonacci(n):
       nonlocal memo  # required in Python3. Python2 can see memo
       if n<2: return n
       return memo.setdefault(n,Fibonacci(n-1)+Fibonacci(n-2))
    ...
    print (Fibonacci(200))
    ...

Password Strength Meter

Here's a collection of scripts: http://webtecker.com/2008/03/26/collection-of-password-strength-scripts/

I think both of them rate the password and don't use jQuery... but I don't know if they have native support for disabling the form?

How to clear https proxy setting of NPM?

Try deleting them with:

npm config delete proxy
npm config delete https-proxy

Content Security Policy "data" not working for base64 Images in Chrome 28

According to the grammar in the CSP spec, you need to specify schemes as scheme:, not just scheme. So, you need to change the image source directive to:

img-src 'self' data:;

How do I deal with installing peer dependencies in Angular CLI?

You can ignore the peer dependency warnings by using the --force flag with Angular cli when updating dependencies.

ng update @angular/cli @angular/core --force

For a full list of options, check the docs: https://angular.io/cli/update

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);

How to make tesseract to recognize only numbers, when they are mixed with letters?

add "--psm 7 -c tessedit_char_whitelist=0123456789'" works for me when the image contain's only 1 line.

java.lang.IllegalStateException: Only fullscreen opaque activities can request orientation

In android Oreo (API 26) you can not change orientation for Activity that have below line(s) in style

 <item name="android:windowIsTranslucent">true</item>

or

 <item name="android:windowIsFloating">true</item>

You have several way to solving this :

1) You can simply remove above line(s) (or turn it to false) and your app works fine.

2) Or you can first remove below line from manifest for that activity

android:screenOrientation="portrait"

Then you must add this line to your activity (in onCreate())

    //android O fix bug orientation
    if (android.os.Build.VERSION.SDK_INT != Build.VERSION_CODES.O) {
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
    }

3) You can create new styles.xml in values-v26 folder and add this to your style.xml. (Thanks to AbdelHady comment)

 <item name="android:windowIsTranslucent">false</item>
 <item name="android:windowIsFloating">false</item>

How do I time a method's execution in Java?

Really good code.

http://www.rgagnon.com/javadetails/java-0585.html

import java.util.concurrent.TimeUnit;

long startTime = System.currentTimeMillis();
........
........
........
long finishTime = System.currentTimeMillis();

String diff = millisToShortDHMS(finishTime - startTime);


  /**
   * converts time (in milliseconds) to human-readable format
   *  "<dd:>hh:mm:ss"
   */
  public static String millisToShortDHMS(long duration) {
    String res = "";
    long days  = TimeUnit.MILLISECONDS.toDays(duration);
    long hours = TimeUnit.MILLISECONDS.toHours(duration)
                   - TimeUnit.DAYS.toHours(TimeUnit.MILLISECONDS.toDays(duration));
    long minutes = TimeUnit.MILLISECONDS.toMinutes(duration)
                     - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(duration));
    long seconds = TimeUnit.MILLISECONDS.toSeconds(duration)
                   - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(duration));
    if (days == 0) {
      res = String.format("%02d:%02d:%02d", hours, minutes, seconds);
    }
    else {
      res = String.format("%dd%02d:%02d:%02d", days, hours, minutes, seconds);
    }
    return res;
  }

How I can delete in VIM all text from current line to end of file?

dG will delete from the current line to the end of file

dCtrl+End will delete from the cursor to the end of the file

But if this file is as large as you say, you may be better off reading the first few lines with head rather than editing and saving the file.

head hugefile > firstlines

(If you are on Windows you can use the Win32 port of head)

Oracle Partition - Error ORA14400 - inserted partition key does not map to any partition

select partition_name,column_name,high_value,partition_position
from ALL_TAB_PARTITIONS a , ALL_PART_KEY_COLUMNS b 
where table_name='YOUR_TABLE' and a.table_name = b.name;

This query lists the column name used as key and the allowed values. make sure, you insert the allowed values(high_value). Else, if default partition is defined, it would go there.


EDIT:

I presume, your TABLE DDL would be like this.

CREATE TABLE HE0_DT_INF_INTERFAZ_MES
  (
    COD_PAIS NUMBER,
    FEC_DATA NUMBER,
    INTERFAZ VARCHAR2(100)
  )
  partition BY RANGE(COD_PAIS, FEC_DATA)
  (
    PARTITION PDIA_98_20091023 VALUES LESS THAN (98,20091024)
  );

Which means I had created a partition with multiple columns which holds value less than the composite range (98,20091024);

That is first COD_PAIS <= 98 and Also FEC_DATA < 20091024

Combinations And Result:

98, 20091024     FAIL
98, 20091023     PASS
99, ********     FAIL
97, ********     PASS
 < 98, ********     PASS

So the below INSERT fails with ORA-14400; because (98,20091024) in INSERT is EQUAL to the one in DDL but NOT less than it.

SQL> INSERT INTO HE0_DT_INF_INTERFAZ_MES(COD_PAIS, FEC_DATA, INTERFAZ)
                                  VALUES(98, 20091024, 'CTA');  2
INSERT INTO HE0_DT_INF_INTERFAZ_MES(COD_PAIS, FEC_DATA, INTERFAZ)
            *
ERROR at line 1:
ORA-14400: inserted partition key does not map to any partition

But, we I attempt (97,20091024), it goes through

SQL> INSERT INTO HE0_DT_INF_INTERFAZ_MES(COD_PAIS, FEC_DATA, INTERFAZ)
  2                                    VALUES(97, 20091024, 'CTA');

1 row created.

How do you reindex an array in PHP but with indexes starting from 1?

Well, I would like to think that for whatever your end goal is, you wouldn't actually need to modify the array to be 1-based as opposed to 0-based, but could instead handle it at iteration time like Gumbo posted.

However, to answer your question, this function should convert any array into a 1-based version

function convertToOneBased( $arr )
{
    return array_combine( range( 1, count( $arr ) ), array_values( $arr ) );
}

EDIT

Here's a more reusable/flexible function, should you desire it

$arr = array( 'a', 'b', 'c' );

echo '<pre>';
print_r( reIndexArray( $arr ) );
print_r( reIndexArray( $arr, 1 ) );
print_r( reIndexArray( $arr, 2 ) );
print_r( reIndexArray( $arr, 10 ) );
print_r( reIndexArray( $arr, -10 ) );
echo '</pre>';

function reIndexArray( $arr, $startAt=0 )
{
    return ( 0 == $startAt )
        ? array_values( $arr )
        : array_combine( range( $startAt, count( $arr ) + ( $startAt - 1 ) ), array_values( $arr ) );
}