Programs & Examples On #Atl

The Active Template Library (ATL) is a library of C++ class templates provided by Microsoft that simplify the programming of Component Object Model (COM) objects. This tag should be used to indicate questions about the use of ATL. For questions about COM unrelated to ATL use the com tag.

R : how to simply repeat a command?

It's not clear whether you're asking this because you are new to programming, but if that's the case then you should probably read this article on loops and indeed read some basic materials on programming.

If you already know about control structures and you want the R-specific implementation details then there are dozens of tutorials around, such as this one. The other answer uses replicate and colMeans, which is idiomatic when writing in R and probably blazing fast as well, which is important if you want 10,000 iterations.

However, one more general and (for beginners) straightforward way to approach problems of this sort would be to use a for loop.

> for (ii in 1:5) { + print(ii) + } [1] 1 [1] 2 [1] 3 [1] 4 [1] 5 > 

So in your case, if you just wanted to print the mean of your Tandem object 5 times:

for (ii in 1:5) {     Tandem <- sample(OUT, size = 815, replace = TRUE, prob = NULL)     TandemMean <- mean(Tandem)     print(TandemMean) } 

As mentioned above, replicate is a more natural way to deal with this specific problem using R. Either way, if you want to store the results - which is surely the case - you'll need to start thinking about data structures like vectors and lists. Once you store something you'll need to be able to access it to use it in future, so a little knowledge is vital.

set.seed(1234) OUT <- runif(100000, 1, 2) tandem <- list() for (ii in 1:10000) {     tandem[[ii]] <- mean(sample(OUT, size = 815, replace = TRUE, prob = NULL)) }  tandem[1] tandem[100] tandem[20:25] 

...creates this output:

> set.seed(1234) > OUT <- runif(100000, 1, 2) > tandem <- list() > for (ii in 1:10000) { +     tandem[[ii]] <- mean(sample(OUT, size = 815, replace = TRUE, prob = NULL)) + } >  > tandem[1] [[1]] [1] 1.511923  > tandem[100] [[1]] [1] 1.496777  > tandem[20:25] [[1]] [1] 1.500669  [[2]] [1] 1.487552  [[3]] [1] 1.503409  [[4]] [1] 1.501362  [[5]] [1] 1.499728  [[6]] [1] 1.492798  >  

Generic XSLT Search and Replace template

Here's one way in XSLT 2

<?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">   <xsl:template match="@*|node()">     <xsl:copy>       <xsl:apply-templates select="@*|node()"/>     </xsl:copy>   </xsl:template>   <xsl:template match="text()">     <xsl:value-of select="translate(.,'&quot;','''')"/>   </xsl:template> </xsl:stylesheet> 

Doing it in XSLT1 is a little more problematic as it's hard to get a literal containing a single apostrophe, so you have to resort to a variable:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">   <xsl:template match="@*|node()">     <xsl:copy>       <xsl:apply-templates select="@*|node()"/>     </xsl:copy>   </xsl:template>   <xsl:variable name="apos">'</xsl:variable>   <xsl:template match="text()">     <xsl:value-of select="translate(.,'&quot;',$apos)"/>   </xsl:template> </xsl:stylesheet> 

Use NSInteger as array index

According to the error message, you declared myLoc as a pointer to an NSInteger (NSInteger *myLoc) rather than an actual NSInteger (NSInteger myLoc). It needs to be the latter.

Two Page Login with Spring Security 3.2.x

There should be three pages here:

  1. Initial login page with a form that asks for your username, but not your password.
  2. You didn't mention this one, but I'd check whether the client computer is recognized, and if not, then challenge the user with either a CAPTCHA or else a security question. Otherwise the phishing site can simply use the tendered username to query the real site for the security image, which defeats the purpose of having a security image. (A security question is probably better here since with a CAPTCHA the attacker could have humans sitting there answering the CAPTCHAs to get at the security images. Depends how paranoid you want to be.)
  3. A page after that that displays the security image and asks for the password.

I don't see this short, linear flow being sufficiently complex to warrant using Spring Web Flow.

I would just use straight Spring Web MVC for steps 1 and 2. I wouldn't use Spring Security for the initial login form, because Spring Security's login form expects a password and a login processing URL. Similarly, Spring Security doesn't provide special support for CAPTCHAs or security questions, so you can just use Spring Web MVC once again.

You can handle step 3 using Spring Security, since now you have a username and a password. The form login page should display the security image, and it should include the user-provided username as a hidden form field to make Spring Security happy when the user submits the login form. The only way to get to step 3 is to have a successful POST submission on step 1 (and 2 if applicable).

Best way to "push" into C# array

This is acceptable as assigning to an array. But if you are asking for pushing, I am pretty sure its not possible in array. Rather it can be achieved by using Stack, Queue or any other data structure. Real arrays doesn't have such functions. But derived classes such as ArrayList have it.

Google Maps shows "For development purposes only"

Now google maps is free for development only.

If you want to use map free like earlier, then create an account with valid details (billing, payment, etc.) google gives $200 MONTHLY CREDIT Which is EQUIVALENT To FREE USAGE

For more details please see Googles new price details: google map new pricing

Also see the old price details: Old one

AttributeError: Module Pip has no attribute 'main'

I faced the same error while using pip on anaconda3 4.4.0 (python 3.6) on windows.

I fixed the problem by the following command:

easy_install pip==18.*  ### installing the latest version pip

Or if lower version pip required, mention the same in the command.

Or you can try installing the lower version and then upgrading the same to latest version as follow:

easy_install pip==9.0.1

easy_install --upgrade pip

'mat-form-field' is not a known element - Angular 5 & Material2

You're only exporting it in your NgModule, you need to import it too

@NgModule({
  imports: [
    MatButtonModule,
    MatFormFieldModule,
    MatInputModule,
    MatRippleModule,
 ]
  exports: [
    MatButtonModule,
    MatFormFieldModule,
    MatInputModule,
    MatRippleModule,
  ],
  declarations: [
    SearchComponent,
  ],
})export class MaterialModule {};

better yet

const modules = [
        MatButtonModule,
        MatFormFieldModule,
        MatInputModule,
        MatRippleModule
];

@NgModule({
  imports: [...modules],
  exports: [...modules]
  ,
})export class MaterialModule {};

update

You're declaring component (SearchComponent) depending on Angular Material before all Angular dependency are imported

Like BrowserAnimationsModule

Try moving it to MaterialModule, or before it

How to import JSON File into a TypeScript file?

let fs = require('fs');
let markers;
fs.readFile('./markers.json', handleJSONFile);

var handleJSONFile = function (err, data) {
   if (err) {
      throw err;
   }
   markers= JSON.parse(data);
 }

Cordova app not displaying correctly on iPhone X (Simulator)

For a manual fix to an existing cordova project

The black bars

Add this to your info.plist file. Fixing the launch image is a separate issue i.e. How to Add iPhoneX Launch Image

<key>UILaunchStoryboardName</key>
<string>CDVLaunchScreen</string>

The white bars

Set viewport-fit=cover in the meta tag

<meta name="viewport" content="initial-scale=1, width=device-width, height=device-height, viewport-fit=cover">

Passing headers with axios POST request

axios.post can recieve accept 3 arguments that last argument can accept a config object that you can set header

Sample code with your question:

var data = {
'key1': 'val1',
'key2': 'val2'
}
axios.post(Helper.getUserAPI(), data, {
        headers: {Authorization: token && `Bearer ${ token }`}
})       
.then((response) => {
    dispatch({type: FOUND_USER, data: response.data[0]})
})
.catch((error) => {
    dispatch({type: ERROR_FINDING_USER})
})

How to enable CORS in ASP.net Core WebAPI

I think if you use your own CORS middleware you need to make sure it is really CORS request by checking origin header.

 public class CorsMiddleware
{
    private readonly RequestDelegate _next;
    private readonly IMemoryCache _cache;
    private readonly ILogger<CorsMiddleware> _logger;

    public CorsMiddleware(RequestDelegate next, IMemoryCache cache, ILogger<CorsMiddleware> logger)
    {
        _next = next;
        _cache = cache;
        _logger = logger;
    }
    public async Task InvokeAsync(HttpContext context, IAdministrationApi adminApi)
    {
        if (context.Request.Headers.ContainsKey(CorsConstants.Origin) || context.Request.Headers.ContainsKey("origin"))
        {
            if (!context.Request.Headers.TryGetValue(CorsConstants.Origin, out var origin))
            {
                context.Request.Headers.TryGetValue("origin", out origin);
            }

            bool isAllowed;
            // Getting origin from DB to check with one from request and save it in cache 
            var result = _cache.GetOrCreateAsync(origin, async cacheEntry => await adminApi.DoesExistAsync(origin));
            isAllowed = result.Result.Result;

            if (isAllowed)
            {
                context.Response.Headers.Add(CorsConstants.AccessControlAllowOrigin, origin);
                context.Response.Headers.Add(
                    CorsConstants.AccessControlAllowHeaders,
                    $"{HeaderNames.Authorization}, {HeaderNames.ContentType}, {HeaderNames.AcceptLanguage}, {HeaderNames.Accept}");
                context.Response.Headers.Add(CorsConstants.AccessControlAllowMethods, "POST, GET, PUT, PATCH, DELETE, OPTIONS");

                if (context.Request.Method == "OPTIONS")
                {
                    _logger.LogInformation("CORS with origin {Origin} was handled successfully", origin);
                    context.Response.StatusCode = (int)HttpStatusCode.NoContent;
                    return;
                }

                await _next(context);
            }
            else
            {
                if (context.Request.Method == "OPTIONS")
                {
                    _logger.LogInformation("Preflight CORS request with origin {Origin} was declined", origin);
                    context.Response.StatusCode = (int)HttpStatusCode.NoContent;
                    return;
                }

                _logger.LogInformation("Simple CORS request with origin {Origin} was declined", origin);
                context.Response.StatusCode = (int)HttpStatusCode.Forbidden;
                return;
            }
        }

        await _next(context);
    }

The use of Swift 3 @objc inference in Swift 4 mode is deprecated?

You can simply pass to "default" instead of "ON". Seems more adherent to Apple logic.

(but all the other comments about the use of @obj remains valid.)

The create-react-app imports restriction outside of src directory

If you need multiple modifications, like when using ant design, you can combine multiple functions like this:

const {
  override,
  removeModuleScopePlugin,
  fixBabelImports,
} = require('customize-cra');

module.exports = override(
  fixBabelImports('import', {
    libraryName: 'antd',
    libraryDirectory: 'es',
    style: 'css',
  }),
  removeModuleScopePlugin(),
);

Relative imports - ModuleNotFoundError: No module named x

You have to append your project's path to PYTHONPATH and make sure to use absolute imports.


For UNIX (Linux, OSX, ...)

export PYTHONPATH="${PYTHONPATH}:/path/to/your/project/"

For Windows

set PYTHONPATH=%PYTHONPATH%;C:\path\to\your\project\

Absolute imports

Assuming that we have the following project structure,

+-- myproject
    +-- mypackage
    ¦   +-- a.py
    +-- anotherpackage
        +-- b.py
        +-- c.py
        +-- mysubpackage
            +-- d.py

just make sure to reference each import starting from the project's root directory. For instance,

# in module a.py
import anotherpackage.mysubpackage.d

# in module b
import anotherpackage.c
import mypackage.a

For a more comprehensive explanation, refer to the article How to fix ModuleNotFoundError and ImportError

How to loop through a JSON object with typescript (Angular2)

Assuming your json object from your GET request looks like the one you posted above simply do:

let list: string[] = [];

json.Results.forEach(element => {
    list.push(element.Id);
});

Or am I missing something that prevents you from doing it this way?

I am getting an "Invalid Host header" message when connecting to webpack-dev-server remotely

If you have not ejected from CRA yet, you can't easily modify your webpack config. The config file is hidden in node_modules/react_scripts/config/webpackDevServer.config.js. You are discouraged to change that config.

Instead, you can just set the environment variable DANGEROUSLY_DISABLE_HOST_CHECK to true to disable the host check:

DANGEROUSLY_DISABLE_HOST_CHECK=true yarn start  
# or the equivalent npm command

Angular 2 Cannot find control with unspecified name attribute on formArrays

Remove the brackets from

[formArrayName]="areas" 

and use only

formArrayName="areas"

This, because with [ ] you are trying to bind a variable, which this is not. Also notice your submit, it should be:

(ngSubmit)="onSubmit(areasForm.value)"

instead of areasForm.values.

How to re-render flatlist?

I am using functional component, in that I am using Flatlist with redux data. I am managing all the state with Redux store. Here is the solution to update the Flatlist data after the api call.

I was first doing like this:-

const DATA  = useSelector((state) => state.address.address);


<FlatList
    style = {styles.myAddressList}
    data = {DATA}
    renderItem = {renderItem}
    keyExtractor = {item => item._id}
    ListEmptyComponent = {EmptyList}
    ItemSeparatorComponent={SeparatorWhite}
    extraData = {refresh}
    
    />

but the data was not re-rendering my Flatlist data at all.

As a solution I did like given Below:-

<FlatList
    style = {styles.myAddressList}
    data = {useSelector((state) => state.address.address)}
    renderItem = {renderItem}
    keyExtractor = {item => item._id}
    ListEmptyComponent = {EmptyList}
    ItemSeparatorComponent={SeparatorWhite}
    />

I am passing the Redux state directly to the Flatlist Datasource rather than allocating it to the variable.

Thank you.

ADB server version (36) doesn't match this client (39) {Not using Genymotion}

To add yet another potential solution, Helium by Clockworkmod has it's own version of ADB built in that kept being started. Exiting the Helium Desktop application resolves the issue.

Psql could not connect to server: No such file or directory, 5432 error?

These two steps solved it for me on Mac:

rm /usr/local/var/postgres/postmaster.pid
brew services restart postgresql

EDIT:

In case you face this issue (reported by @luckyguy73): psql: FATAL: database "postgresql" does not exist

You can run

brew postgresql-upgrade-database

to fix it.

Flask - Calling python function on button OnClick event

You can simply do this with help of AJAX... Here is a example which calls a python function which prints hello without redirecting or refreshing the page.

In app.py put below code segment.

#rendering the HTML page which has the button
@app.route('/json')
def json():
    return render_template('json.html')

#background process happening without any refreshing
@app.route('/background_process_test')
def background_process_test():
    print ("Hello")
    return ("nothing")

And your json.html page should look like below.

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type=text/javascript>
        $(function() {
          $('a#test').on('click', function(e) {
            e.preventDefault()
            $.getJSON('/background_process_test',
                function(data) {
              //do nothing
            });
            return false;
          });
        });
</script>


//button
<div class='container'>
    <h3>Test</h3>
        <form>
            <a href=# id=test><button class='btn btn-default'>Test</button></a>
        </form>

</div>

Here when you press the button Test simple in the console you can see "Hello" is displaying without any refreshing.

How can I create an observable with a delay

What you want is a timer:

// RxJS v6+
import { timer } from 'rxjs';

//emit [1, 2, 3] after 1 second.
const source = timer(1000).map(([1, 2, 3]);
//output: [1, 2, 3]
const subscribe = source.subscribe(val => console.log(val));

Ansible: how to get output to display

Every Ansible task when run can save its results into a variable. To do this, you have to specify which variable to save the results into. Do this with the register parameter, independently of the module used.

Once you save the results to a variable you can use it later in any of the subsequent tasks. So for example if you want to get the standard output of a specific task you can write the following:

---
- hosts: localhost
  tasks:
    - shell: ls
      register: shell_result

    - debug:
        var: shell_result.stdout_lines

Here register tells ansible to save the response of the module into the shell_result variable, and then we use the debug module to print the variable out.

An example run would look like the this:

PLAY [localhost] ***************************************************************

TASK [command] *****************************************************************
changed: [localhost]

TASK [debug] *******************************************************************
ok: [localhost] => {
    "shell_result.stdout_lines": [
        "play.yml"
    ]
}

Responses can contain multiple fields. stdout_lines is one of the default fields you can expect from a module's response.

Not all fields are available from all modules, for example for a module which doesn't return anything to the standard out you wouldn't expect anything in the stdout or stdout_lines values, however the msg field might be filled in this case. Also there are some modules where you might find something in a non-standard variable, for these you can try to consult the module's documentation for these non-standard return values.

Alternatively you can increase the verbosity level of ansible-playbook. You can choose between different verbosity levels: -v, -vvv and -vvvv. For example when running the playbook with verbosity (-vvv) you get this:

PLAY [localhost] ***************************************************************

TASK [command] *****************************************************************
(...)
changed: [localhost] => {
    "changed": true,
    "cmd": "ls",
    "delta": "0:00:00.007621",
    "end": "2017-02-17 23:04:41.912570",
    "invocation": {
        "module_args": {
            "_raw_params": "ls",
            "_uses_shell": true,
            "chdir": null,
            "creates": null,
            "executable": null,
            "removes": null,
            "warn": true
        },
        "module_name": "command"
    },
    "rc": 0,
    "start": "2017-02-17 23:04:41.904949",
    "stderr": "",
    "stdout": "play.retry\nplay.yml",
    "stdout_lines": [
        "play.retry",
        "play.yml"
    ],
    "warnings": []
}

As you can see this will print out the response of each of the modules, and all of the fields available. You can see that the stdout_lines is available, and its contents are what we expect.

To answer your main question about the jenkins_script module, if you check its documentation, you can see that it returns the output in the output field, so you might want to try the following:

tasks:
  - jenkins_script:
      script: (...)
    register: jenkins_result

  - debug:
      var: jenkins_result.output

`col-xs-*` not working in Bootstrap 4

you could do this, if you want to use the old syntax (or don't want to rewrite every template)

@for $i from 1 through $grid-columns {
  @include media-breakpoint-up(xs) {
    .col-xs-#{$i} {
      @include make-col-ready();
      @include make-col($i);
    }
  }
}

ssh connection refused on Raspberry Pi

Apparently, the SSH server on Raspbian is now disabled by default. If there is no server listening for connections, it will not accept them. You can manually enable the SSH server according to this raspberrypi.org tutorial :

As of the November 2016 release, Raspbian has the SSH server disabled by default.

There are now multiple ways to enable it. Choose one:

From the desktop

  1. Launch Raspberry Pi Configuration from the Preferences menu
  2. Navigate to the Interfaces tab
  3. Select Enabled next to SSH
  4. Click OK

From the terminal with raspi-config

  1. Enter sudo raspi-config in a terminal window
  2. Select Interfacing Options
  3. Navigate to and select SSH
  4. Choose Yes
  5. Select Ok
  6. Choose Finish

Start the SSH service with systemctl

sudo systemctl enable ssh
sudo systemctl start ssh

On a headless Raspberry Pi

For headless setup, SSH can be enabled by placing a file named ssh, without any extension, onto the boot partition of the SD card. When the Pi boots, it looks for the ssh file. If it is found, SSH is enabled, and the file is deleted. The content of the file does not matter: it could contain text, or nothing at all.

Vue - Deep watching an array of objects and calculating the change?

This is what I use to deep watch an object. My requirement was watching the child fields of the object.

new Vue({
    el: "#myElement",
    data:{
        entity: {
            properties: []
        }
    },
    watch:{
        'entity.properties': {
            handler: function (after, before) {
                // Changes detected.    
            },
            deep: true
        }
    }
});

FromBody string parameter is giving null

Try the below code:

[Route("/test")]
[HttpPost]
public async Task Test()
{
   using (var reader = new StreamReader(Request.Body, Encoding.UTF8))
   {
      var textFromBody = await reader.ReadToEndAsync();                    
   }            
}

Getting permission denied (public key) on gitlab

make sure you are not running sudo git clone [email protected]:project/somethiing.git, otherwise ssh will look in /root/.ssh instead of the key you uploaded ~/.ssh/id_rsa

How to reset selected file with input tag file type in Angular 2?

Short version Plunker:

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

@Component({
  selector: 'my-app',
  template: `
      <input #myInput type="file" placeholder="File Name" name="filename">
      <button (click)="myInput.value = ''">Reset</button>
  `
})
export class AppComponent {


}

And i think more common case is to not using button but do reset automatically. Angular Template statements support chaining expressions so Plunker:

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

@Component({
  selector: 'my-app',
  template: `
      <input #myInput type="file" (change)="onChange(myInput.value, $event); myInput.value = ''" placeholder="File Name" name="filename">
  `
})
export class AppComponent {

  onChange(files, event) {
    alert( files );
    alert( event.target.files[0].name );
  }

}

And interesting link about why there is no recursion on value change.

ln (Natural Log) in Python

math.log is the natural logarithm:

From the documentation:

math.log(x[, base]) With one argument, return the natural logarithm of x (to base e).

Your equation is therefore:

n = math.log((1 + (FV * r) / p) / math.log(1 + r)))

Note that in your code you convert n to a str twice which is unnecessary

Saving a high resolution image in R

A simpler way is

ggplot(data=df, aes(x=xvar, y=yvar)) + 
geom_point()

ggsave(path = path, width = width, height = height, device='tiff', dpi=700)

Swift - How to detect orientation changes

You can use viewWillTransition(to:with:) and tap into animate(alongsideTransition:completion:) to get the interface orientation AFTER the transition is complete. You just have to define and implement a protocol similar to this in order to tap into the event. Note that this code was used for a SpriteKit game and your specific implementation may differ.

protocol CanReceiveTransitionEvents {
    func viewWillTransition(to size: CGSize)
    func interfaceOrientationChanged(to orientation: UIInterfaceOrientation)
}
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
        super.viewWillTransition(to: size, with: coordinator)

        guard
            let skView = self.view as? SKView,
            let canReceiveRotationEvents = skView.scene as? CanReceiveTransitionEvents else { return }

        coordinator.animate(alongsideTransition: nil) { _ in
            if let interfaceOrientation = UIApplication.shared.windows.first?.windowScene?.interfaceOrientation {
                canReceiveRotationEvents.interfaceOrientationChanged(to: interfaceOrientation)
            }
        }

        canReceiveRotationEvents.viewWillTransition(to: size)
    }

You can set breakpoints in these functions and observe that interfaceOrientationChanged(to orientation: UIInterfaceOrientation) is always called after viewWillTransition(to size: CGSize) with the updated orientation.

Getting "Cannot call a class as a function" in my React Project

Happened to me because I used

PropTypes.arrayOf(SomeClass)

instead of

PropTypes.arrayOf(PropTypes.instanceOf(SomeClass))

Spring Data and Native Query with pagination

Removing \n#pageable\n from both query and count query worked for me. Springboot version : 2.1.5.RELEASE DB : Mysql

Angular 2 Date Input not binding to date value

In your component

let today: string;

ngOnInit() {
  this.today = new Date().toISOString().split('T')[0];
}

and in your html file

<input name="date" [(ngModel)]="today" type="date" required>

How can I run Tensorboard on a remote server?

While running the tensorboard give one more option --host=ip of your system and then you can access it from other system using http://ip of your host system:6006

How to use npm with ASP.NET Core

Much simpler approach is to use OdeToCode.UseNodeModules Nuget package. I just tested it with .Net Core 3.0. All you need to do is add the package to the solution and reference it in the Configure method of the Startup class:

app.UseNodeModules();

I learned about it from the excellent Building a Web App with ASP.NET Core, MVC, Entity Framework Core, Bootstrap, and Angular Pluralsight course by Shawn Wildermuth.

You don't have write permissions for the /var/lib/gems/2.3.0 directory

I encountered the same error in GitHub Actions. Adding sudo solved the issue.

sudo gem install bundler

How to get rid of underline for Link component of React Router?

style={{ backgroundImage: "none" }}

Only this worked for me

How to markdown nested list items in Bitbucket?

Possibilities

  • It is possible to nest a bulleted-unnumbered list into a higher numbered list.
  • But in the bulleted-unnumbered list the automatically numbered list will not start: Its is not supported.
    • To start a new numbered list after a bulleted-unnumbered one, put a piece of text between them, or a subtitle: A new numbered list cannot start just behind the bulleted: The interpreter will not start the numbering.

in practice

  1. Dog

    1. German Shepherd - with only a single space ahead.
    2. Belgian Shepherd - max 4 spaces ahead.
      • Number in front of a line interpreted as a "numbering bullet", so making the indentation.
        • ..and ignores the written digit: Places/generates its own, in compliance with the structure.
        • So it is OK to use only just "1" ones, to get your numbered list.
          • Or whatever integer number, even of more digits: The list numbering will continue by increment ++1.
        • However, the first item in the numbered list will be kept, so the first leading will usually be the number "1".
    3. Malinois - 5 spaces makes 3rd level already.
      1. MalinoisB - 5 spaces makes 3rd level already.
      2. Groenendael - 8 spaces makes 3rd level yet too.
        1. Tervuren - 9 spaces for 4th level - Intentionaly started by "55".
        2. TervurenB - numbered by "88", in the source code.
  2. Cat

    1. Siberian; a. SiberianA - problem reproduced: letters (i.e. "a" here) not recognized by the interpreter as "numbering".
      • No matter, it is indented to its separated line, in the source code.
    2. Siamese
      • a. so written manually as a workaround misusing bullets, unnumbered list.

How to solve the memory error in Python

Assuming your example text is representative of all the text, one line would consume about 75 bytes on my machine:

In [3]: sys.getsizeof('usedfor zipper fasten_coat')
Out[3]: 75

Doing some rough math:

75 bytes * 8,000,000 lines / 1024 / 1024 = ~572 MB

So roughly 572 meg to store the strings alone for one of these files. Once you start adding in additional, similarly structured and sized files, you'll quickly approach your virtual address space limits, as mentioned in @ShadowRanger's answer.

If upgrading your python isn't feasible for you, or if it only kicks the can down the road (you have finite physical memory after all), you really have two options: write your results to temporary files in-between loading in and reading the input files, or write your results to a database. Since you need to further post-process the strings after aggregating them, writing to a database would be the superior approach.

Add Favicon with React and Webpack

In my case -- I am running Visual Studio (Professional 2017) in debug mode with webpack 2.4.1 -- it was necessary to put the favicon.ico into the root directory of the project, right where the folder src is rather than in a folder public, even though according to https://create-react-app.dev/docs/using-the-public-folder the latter should be the official location.

EPPlus - Read Excel Table

Not sure why but none of the above solution work for me. So sharing what worked:

public void readXLS(string FilePath)
{
    FileInfo existingFile = new FileInfo(FilePath);
    using (ExcelPackage package = new ExcelPackage(existingFile))
    {
        //get the first worksheet in the workbook
        ExcelWorksheet worksheet = package.Workbook.Worksheets[1];
        int colCount = worksheet.Dimension.End.Column;  //get Column Count
        int rowCount = worksheet.Dimension.End.Row;     //get row count
        for (int row = 1; row <= rowCount; row++)
        {
            for (int col = 1; col <= colCount; col++)
            {
                Console.WriteLine(" Row:" + row + " column:" + col + " Value:" + worksheet.Cells[row, col].Value?.ToString().Trim());
            }
        }
    }
}

Nginx upstream prematurely closed connection while reading response header from upstream, for large requests

I don't think this is your case, but I'll post it if it helps anyone. I had the same issue and the problem was that Node didn't respond at all (I had a condition that when failed didn't do anything - so no response) - So if increasing all your timeouts didn't solve it, make sure all scenarios get a response.

How can I show current location on a Google Map on Android Marshmallow?

For using FusedLocationProviderClient with Google Play Services 11 and higher:

see here: How to get current Location in GoogleMap using FusedLocationProviderClient

For using (now deprecated) FusedLocationProviderApi:

If your project uses Google Play Services 10 or lower, using the FusedLocationProviderApi is the optimal choice.

The FusedLocationProviderApi offers less battery drain than the old open source LocationManager API. Also, if you're already using Google Play Services for Google Maps, there's no reason not to use it.

Here is a full Activity class that places a Marker at the current location, and also moves the camera to the current position.

It also checks for the Location permission at runtime for Android 6 and later (Marshmallow, Nougat, Oreo). In order to properly handle the Location permission runtime check that is necessary on Android M/Android 6 and later, you need to ensure that the user has granted your app the Location permission before calling mGoogleMap.setMyLocationEnabled(true) and also before requesting location updates.

public class MapLocationActivity extends AppCompatActivity
        implements OnMapReadyCallback,
        GoogleApiClient.ConnectionCallbacks,
        GoogleApiClient.OnConnectionFailedListener,
        LocationListener {

    GoogleMap mGoogleMap;
    SupportMapFragment mapFrag;
    LocationRequest mLocationRequest;
    GoogleApiClient mGoogleApiClient;
    Location mLastLocation;
    Marker mCurrLocationMarker;

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

        getSupportActionBar().setTitle("Map Location Activity");

        mapFrag = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
        mapFrag.getMapAsync(this);
    }

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

        //stop location updates when Activity is no longer active
        if (mGoogleApiClient != null) {
            LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
        }
    }

    @Override
    public void onMapReady(GoogleMap googleMap)
    {
        mGoogleMap=googleMap;
        mGoogleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);

        //Initialize Google Play Services
        if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (ContextCompat.checkSelfPermission(this,
                    Manifest.permission.ACCESS_FINE_LOCATION)
                    == PackageManager.PERMISSION_GRANTED) {
                //Location Permission already granted
                buildGoogleApiClient();
                mGoogleMap.setMyLocationEnabled(true);
            } else {
                //Request Location Permission
                checkLocationPermission();
            }
        }
        else {
            buildGoogleApiClient();
            mGoogleMap.setMyLocationEnabled(true);
        }
    }

    protected synchronized void buildGoogleApiClient() {
        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build();
        mGoogleApiClient.connect();
    }

    @Override
    public void onConnected(Bundle bundle) {
        mLocationRequest = new LocationRequest();
        mLocationRequest.setInterval(1000);
        mLocationRequest.setFastestInterval(1000);
        mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
        if (ContextCompat.checkSelfPermission(this,
                Manifest.permission.ACCESS_FINE_LOCATION)
                == PackageManager.PERMISSION_GRANTED) {
            LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
        }
    }

    @Override
    public void onConnectionSuspended(int i) {}

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {}

    @Override
    public void onLocationChanged(Location location)
    {
        mLastLocation = location;
        if (mCurrLocationMarker != null) {
            mCurrLocationMarker.remove();
        }

        //Place current location marker
        LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
        MarkerOptions markerOptions = new MarkerOptions();
        markerOptions.position(latLng);
        markerOptions.title("Current Position");
        markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));
        mCurrLocationMarker = mGoogleMap.addMarker(markerOptions);

        //move map camera
        mGoogleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng,11));

    }

    public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
    private void checkLocationPermission() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED) {

            // Should we show an explanation?
            if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                    Manifest.permission.ACCESS_FINE_LOCATION)) {

                // Show an explanation to the user *asynchronously* -- don't block
                // this thread waiting for the user's response! After the user
                // sees the explanation, try again to request the permission.
                new AlertDialog.Builder(this)
                        .setTitle("Location Permission Needed")
                        .setMessage("This app needs the Location permission, please accept to use location functionality")
                        .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                //Prompt the user once explanation has been shown
                                ActivityCompat.requestPermissions(MapLocationActivity.this,
                                        new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                                        MY_PERMISSIONS_REQUEST_LOCATION );
                            }
                        })
                        .create()
                        .show();


            } else {
                // No explanation needed, we can request the permission.
                ActivityCompat.requestPermissions(this,
                        new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                        MY_PERMISSIONS_REQUEST_LOCATION );
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           String permissions[], int[] grantResults) {
        switch (requestCode) {
            case MY_PERMISSIONS_REQUEST_LOCATION: {
                // If request is cancelled, the result arrays are empty.
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                    // permission was granted, yay! Do the
                    // location-related task you need to do.
                    if (ContextCompat.checkSelfPermission(this,
                            Manifest.permission.ACCESS_FINE_LOCATION)
                            == PackageManager.PERMISSION_GRANTED) {

                        if (mGoogleApiClient == null) {
                            buildGoogleApiClient();
                        }
                        mGoogleMap.setMyLocationEnabled(true);
                    }

                } else {

                    // permission denied, boo! Disable the
                    // functionality that depends on this permission.
                    Toast.makeText(this, "permission denied", Toast.LENGTH_LONG).show();
                }
                return;
            }

            // other 'case' lines to check for other
            // permissions this app might request
        }
    }

}

activity_main.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <fragment xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        xmlns:map="http://schemas.android.com/apk/res-auto"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/map"
        tools:context=".MapLocationActivity"
        android:name="com.google.android.gms.maps.SupportMapFragment"/>

</LinearLayout>

Result:

Show permission explanation if needed using an AlertDialog (this happens if the user denies a permission request, or grants the permission and then later revokes it in the settings):

enter image description here

Prompt the user for Location permission by calling ActivityCompat.requestPermissions():

enter image description here

Move camera to current location and place Marker when the Location permission is granted:

enter image description here

How to fix the error; 'Error: Bootstrap tooltips require Tether (http://github.hubspot.com/tether/)'

If you are using npm and browserify:

// es6 imports
import tether from 'tether';
global.Tether = tether;

// require
global.Tether = require('tether');

Docker-Compose can't connect to Docker Daemon

I think it's because of right of access, you just have to write

sudo docker-compose-deps.yml up

Generate PDF from HTML using pdfMake in Angularjs

I know its not relevant to this post but might help others converting HTML to PDF on client side. This is a simple solution if you use kendo. It also preserves the css (most of the cases).

_x000D_
_x000D_
var generatePDF = function() {_x000D_
  kendo.drawing.drawDOM($("#formConfirmation")).then(function(group) {_x000D_
    kendo.drawing.pdf.saveAs(group, "Converted PDF.pdf");_x000D_
  });_x000D_
}
_x000D_
<!DOCTYPE html>_x000D_
<html lang="en">_x000D_
_x000D_
<head>_x000D_
  <meta charset="utf-8">_x000D_
  <meta http-equiv="X-UA-Compatible" content="IE=edge">_x000D_
  <meta name="viewport" content="width=device-width, initial-scale=1">_x000D_
  <!-- Latest compiled and minified CSS -->_x000D_
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">_x000D_
  <!-- Optional theme -->_x000D_
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css">_x000D_
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>_x000D_
  <!-- Latest compiled and minified JavaScript -->_x000D_
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>_x000D_
  <script src="//kendo.cdn.telerik.com/2016.3.914/js/kendo.all.min.js"></script>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
  <br/>_x000D_
  <button class="btn btn-primary" onclick="generatePDF()"><i class="fa fa-save"></i> Save as PDF</button>_x000D_
  <br/>_x000D_
  <br/>_x000D_
  <div id="formConfirmation">_x000D_
_x000D_
    <div class="container theme-showcase" role="main">_x000D_
      <!-- Main jumbotron for a primary marketing message or call to action -->_x000D_
      <div class="jumbotron">_x000D_
        <h1>Theme example</h1>_x000D_
        <p>This is a template showcasing the optional theme stylesheet included in Bootstrap. Use it as a starting point to create something more unique by building on or modifying it.</p>_x000D_
      </div>_x000D_
      <div class="page-header">_x000D_
        <h1>Buttons</h1>_x000D_
      </div>_x000D_
      <p>_x000D_
        <button type="button" class="btn btn-lg btn-default">Default</button>_x000D_
        <button type="button" class="btn btn-lg btn-primary">Primary</button>_x000D_
        <button type="button" class="btn btn-lg btn-success">Success</button>_x000D_
        <button type="button" class="btn btn-lg btn-info">Info</button>_x000D_
        <button type="button" class="btn btn-lg btn-warning">Warning</button>_x000D_
        <button type="button" class="btn btn-lg btn-danger">Danger</button>_x000D_
        <button type="button" class="btn btn-lg btn-link">Link</button>_x000D_
      </p>_x000D_
      <p>_x000D_
        <button type="button" class="btn btn-default">Default</button>_x000D_
        <button type="button" class="btn btn-primary">Primary</button>_x000D_
        <button type="button" class="btn btn-success">Success</button>_x000D_
        <button type="button" class="btn btn-info">Info</button>_x000D_
        <button type="button" class="btn btn-warning">Warning</button>_x000D_
        <button type="button" class="btn btn-danger">Danger</button>_x000D_
        <button type="button" class="btn btn-link">Link</button>_x000D_
      </p>_x000D_
      <p>_x000D_
        <button type="button" class="btn btn-sm btn-default">Default</button>_x000D_
        <button type="button" class="btn btn-sm btn-primary">Primary</button>_x000D_
        <button type="button" class="btn btn-sm btn-success">Success</button>_x000D_
        <button type="button" class="btn btn-sm btn-info">Info</button>_x000D_
        <button type="button" class="btn btn-sm btn-warning">Warning</button>_x000D_
        <button type="button" class="btn btn-sm btn-danger">Danger</button>_x000D_
        <button type="button" class="btn btn-sm btn-link">Link</button>_x000D_
      </p>_x000D_
      <p>_x000D_
        <button type="button" class="btn btn-xs btn-default">Default</button>_x000D_
        <button type="button" class="btn btn-xs btn-primary">Primary</button>_x000D_
        <button type="button" class="btn btn-xs btn-success">Success</button>_x000D_
        <button type="button" class="btn btn-xs btn-info">Info</button>_x000D_
        <button type="button" class="btn btn-xs btn-warning">Warning</button>_x000D_
        <button type="button" class="btn btn-xs btn-danger">Danger</button>_x000D_
        <button type="button" class="btn btn-xs btn-link">Link</button>_x000D_
      </p>_x000D_
      <div class="page-header">_x000D_
        <h1>Tables</h1>_x000D_
      </div>_x000D_
      <div class="row">_x000D_
        <div class="col-md-6">_x000D_
          <table class="table">_x000D_
            <thead>_x000D_
              <tr>_x000D_
                <th>#</th>_x000D_
                <th>First Name</th>_x000D_
                <th>Last Name</th>_x000D_
                <th>Username</th>_x000D_
              </tr>_x000D_
            </thead>_x000D_
            <tbody>_x000D_
              <tr>_x000D_
                <td>1</td>_x000D_
                <td>Mark</td>_x000D_
                <td>Otto</td>_x000D_
                <td>@mdo</td>_x000D_
              </tr>_x000D_
              <tr>_x000D_
                <td>2</td>_x000D_
                <td>Jacob</td>_x000D_
                <td>Thornton</td>_x000D_
                <td>@fat</td>_x000D_
              </tr>_x000D_
              <tr>_x000D_
                <td>3</td>_x000D_
                <td>Larry</td>_x000D_
                <td>the Bird</td>_x000D_
                <td>@twitter</td>_x000D_
              </tr>_x000D_
            </tbody>_x000D_
          </table>_x000D_
        </div>_x000D_
        <div class="col-md-6">_x000D_
          <table class="table table-striped">_x000D_
            <thead>_x000D_
              <tr>_x000D_
                <th>#</th>_x000D_
                <th>First Name</th>_x000D_
                <th>Last Name</th>_x000D_
                <th>Username</th>_x000D_
              </tr>_x000D_
            </thead>_x000D_
            <tbody>_x000D_
              <tr>_x000D_
                <td>1</td>_x000D_
                <td>Mark</td>_x000D_
                <td>Otto</td>_x000D_
                <td>@mdo</td>_x000D_
              </tr>_x000D_
              <tr>_x000D_
                <td>2</td>_x000D_
                <td>Jacob</td>_x000D_
                <td>Thornton</td>_x000D_
                <td>@fat</td>_x000D_
              </tr>_x000D_
              <tr>_x000D_
                <td>3</td>_x000D_
                <td>Larry</td>_x000D_
                <td>the Bird</td>_x000D_
                <td>@twitter</td>_x000D_
              </tr>_x000D_
            </tbody>_x000D_
          </table>_x000D_
        </div>_x000D_
      </div>_x000D_
      <div class="row">_x000D_
        <div class="col-md-6">_x000D_
          <table class="table table-bordered">_x000D_
            <thead>_x000D_
              <tr>_x000D_
                <th>#</th>_x000D_
                <th>First Name</th>_x000D_
                <th>Last Name</th>_x000D_
                <th>Username</th>_x000D_
              </tr>_x000D_
            </thead>_x000D_
            <tbody>_x000D_
              <tr>_x000D_
                <td rowspan="2">1</td>_x000D_
                <td>Mark</td>_x000D_
                <td>Otto</td>_x000D_
                <td>@mdo</td>_x000D_
              </tr>_x000D_
              <tr>_x000D_
                <td>Mark</td>_x000D_
                <td>Otto</td>_x000D_
                <td>@TwBootstrap</td>_x000D_
              </tr>_x000D_
              <tr>_x000D_
                <td>2</td>_x000D_
                <td>Jacob</td>_x000D_
                <td>Thornton</td>_x000D_
                <td>@fat</td>_x000D_
              </tr>_x000D_
              <tr>_x000D_
                <td>3</td>_x000D_
                <td colspan="2">Larry the Bird</td>_x000D_
                <td>@twitter</td>_x000D_
              </tr>_x000D_
            </tbody>_x000D_
          </table>_x000D_
        </div>_x000D_
        <div class="col-md-6">_x000D_
          <table class="table table-condensed">_x000D_
            <thead>_x000D_
              <tr>_x000D_
                <th>#</th>_x000D_
                <th>First Name</th>_x000D_
                <th>Last Name</th>_x000D_
                <th>Username</th>_x000D_
              </tr>_x000D_
            </thead>_x000D_
            <tbody>_x000D_
              <tr>_x000D_
                <td>1</td>_x000D_
                <td>Mark</td>_x000D_
                <td>Otto</td>_x000D_
                <td>@mdo</td>_x000D_
              </tr>_x000D_
              <tr>_x000D_
                <td>2</td>_x000D_
                <td>Jacob</td>_x000D_
                <td>Thornton</td>_x000D_
                <td>@fat</td>_x000D_
              </tr>_x000D_
              <tr>_x000D_
                <td>3</td>_x000D_
                <td colspan="2">Larry the Bird</td>_x000D_
                <td>@twitter</td>_x000D_
              </tr>_x000D_
            </tbody>_x000D_
          </table>_x000D_
        </div>_x000D_
      </div>_x000D_
      <div class="page-header">_x000D_
        <h1>Thumbnails</h1>_x000D_
      </div>_x000D_
      <img data-src="holder.js/200x200" class="img-thumbnail" alt="A generic square placeholder image with a white border around it, making it resemble a photograph taken with an old instant camera">_x000D_
      <div class="page-header">_x000D_
        <h1>Labels</h1>_x000D_
      </div>_x000D_
      <h1>_x000D_
        <span class="label label-default">Default</span>_x000D_
        <span class="label label-primary">Primary</span>_x000D_
        <span class="label label-success">Success</span>_x000D_
        <span class="label label-info">Info</span>_x000D_
        <span class="label label-warning">Warning</span>_x000D_
        <span class="label label-danger">Danger</span>_x000D_
      </h1>_x000D_
      <h2>_x000D_
        <span class="label label-default">Default</span>_x000D_
        <span class="label label-primary">Primary</span>_x000D_
        <span class="label label-success">Success</span>_x000D_
        <span class="label label-info">Info</span>_x000D_
        <span class="label label-warning">Warning</span>_x000D_
        <span class="label label-danger">Danger</span>_x000D_
      </h2>_x000D_
      <h3>_x000D_
        <span class="label label-default">Default</span>_x000D_
        <span class="label label-primary">Primary</span>_x000D_
        <span class="label label-success">Success</span>_x000D_
        <span class="label label-info">Info</span>_x000D_
        <span class="label label-warning">Warning</span>_x000D_
        <span class="label label-danger">Danger</span>_x000D_
      </h3>_x000D_
      <h4>_x000D_
        <span class="label label-default">Default</span>_x000D_
        <span class="label label-primary">Primary</span>_x000D_
        <span class="label label-success">Success</span>_x000D_
        <span class="label label-info">Info</span>_x000D_
        <span class="label label-warning">Warning</span>_x000D_
        <span class="label label-danger">Danger</span>_x000D_
      </h4>_x000D_
      <h5>_x000D_
        <span class="label label-default">Default</span>_x000D_
        <span class="label label-primary">Primary</span>_x000D_
        <span class="label label-success">Success</span>_x000D_
        <span class="label label-info">Info</span>_x000D_
        <span class="label label-warning">Warning</span>_x000D_
        <span class="label label-danger">Danger</span>_x000D_
      </h5>_x000D_
      <h6>_x000D_
        <span class="label label-default">Default</span>_x000D_
        <span class="label label-primary">Primary</span>_x000D_
        <span class="label label-success">Success</span>_x000D_
        <span class="label label-info">Info</span>_x000D_
        <span class="label label-warning">Warning</span>_x000D_
        <span class="label label-danger">Danger</span>_x000D_
      </h6>_x000D_
      <p>_x000D_
        <span class="label label-default">Default</span>_x000D_
        <span class="label label-primary">Primary</span>_x000D_
        <span class="label label-success">Success</span>_x000D_
        <span class="label label-info">Info</span>_x000D_
        <span class="label label-warning">Warning</span>_x000D_
        <span class="label label-danger">Danger</span>_x000D_
      </p>_x000D_
      <div class="page-header">_x000D_
        <h1>Badges</h1>_x000D_
      </div>_x000D_
      <p>_x000D_
        <a href="#">Inbox <span class="badge">42</span></a>_x000D_
      </p>_x000D_
      <ul class="nav nav-pills" role="tablist">_x000D_
        <li role="presentation" class="active"><a href="#">Home <span class="badge">42</span></a>_x000D_
        </li>_x000D_
        <li role="presentation"><a href="#">Profile</a>_x000D_
        </li>_x000D_
        <li role="presentation"><a href="#">Messages <span class="badge">3</span></a>_x000D_
        </li>_x000D_
      </ul>_x000D_
      <div class="page-header">_x000D_
        <h1>Dropdown menus</h1>_x000D_
      </div>_x000D_
      <div class="dropdown theme-dropdown clearfix">_x000D_
        <a id="dropdownMenu1" href="#" class="sr-only dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Dropdown <span class="caret"></span></a>_x000D_
        <ul class="dropdown-menu" aria-labelledby="dropdownMenu1">_x000D_
          <li class="active"><a href="#">Action</a>_x000D_
          </li>_x000D_
          <li><a href="#">Another action</a>_x000D_
          </li>_x000D_
          <li><a href="#">Something else here</a>_x000D_
          </li>_x000D_
          <li role="separator" class="divider"></li>_x000D_
          <li><a href="#">Separated link</a>_x000D_
          </li>_x000D_
        </ul>_x000D_
      </div>_x000D_
      <div class="page-header">_x000D_
        <h1>Navs</h1>_x000D_
      </div>_x000D_
      <ul class="nav nav-tabs" role="tablist">_x000D_
        <li role="presentation" class="active"><a href="#">Home</a>_x000D_
        </li>_x000D_
        <li role="presentation"><a href="#">Profile</a>_x000D_
        </li>_x000D_
        <li role="presentation"><a href="#">Messages</a>_x000D_
        </li>_x000D_
      </ul>_x000D_
      <ul class="nav nav-pills" role="tablist">_x000D_
        <li role="presentation" class="active"><a href="#">Home</a>_x000D_
        </li>_x000D_
        <li role="presentation"><a href="#">Profile</a>_x000D_
        </li>_x000D_
        <li role="presentation"><a href="#">Messages</a>_x000D_
        </li>_x000D_
      </ul>_x000D_
      <div class="page-header">_x000D_
        <h1>Navbars</h1>_x000D_
      </div>_x000D_
      <nav class="navbar navbar-default">_x000D_
        <div class="container">_x000D_
          <div class="navbar-header">_x000D_
            <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target=".navbar-collapse">_x000D_
              <span class="sr-only">Toggle navigation</span>_x000D_
              <span class="icon-bar"></span>_x000D_
              <span class="icon-bar"></span>_x000D_
              <span class="icon-bar"></span>_x000D_
            </button>_x000D_
            <a class="navbar-brand" href="#">Project name</a>_x000D_
          </div>_x000D_
          <div class="navbar-collapse collapse">_x000D_
            <ul class="nav navbar-nav">_x000D_
              <li class="active"><a href="#">Home</a>_x000D_
              </li>_x000D_
              <li><a href="#about">About</a>_x000D_
              </li>_x000D_
              <li><a href="#contact">Contact</a>_x000D_
              </li>_x000D_
              <li class="dropdown">_x000D_
                <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Dropdown <span class="caret"></span></a>_x000D_
                <ul class="dropdown-menu">_x000D_
                  <li><a href="#">Action</a>_x000D_
                  </li>_x000D_
                  <li><a href="#">Another action</a>_x000D_
                  </li>_x000D_
                  <li><a href="#">Something else here</a>_x000D_
                  </li>_x000D_
                  <li role="separator" class="divider"></li>_x000D_
                  <li class="dropdown-header">Nav header</li>_x000D_
                  <li><a href="#">Separated link</a>_x000D_
                  </li>_x000D_
                  <li><a href="#">One more separated link</a>_x000D_
                  </li>_x000D_
                </ul>_x000D_
              </li>_x000D_
            </ul>_x000D_
          </div>_x000D_
          <!--/.nav-collapse -->_x000D_
        </div>_x000D_
      </nav>_x000D_
      <nav class="navbar navbar-inverse">_x000D_
        <div class="container">_x000D_
          <div class="navbar-header">_x000D_
            <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target=".navbar-collapse">_x000D_
              <span class="sr-only">Toggle navigation</span>_x000D_
              <span class="icon-bar"></span>_x000D_
              <span class="icon-bar"></span>_x000D_
              <span class="icon-bar"></span>_x000D_
            </button>_x000D_
            <a class="navbar-brand" href="#">Project name</a>_x000D_
          </div>_x000D_
          <div class="navbar-collapse collapse">_x000D_
            <ul class="nav navbar-nav">_x000D_
              <li class="active"><a href="#">Home</a>_x000D_
              </li>_x000D_
              <li><a href="#about">About</a>_x000D_
              </li>_x000D_
              <li><a href="#contact">Contact</a>_x000D_
              </li>_x000D_
              <li class="dropdown">_x000D_
                <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Dropdown <span class="caret"></span></a>_x000D_
                <ul class="dropdown-menu">_x000D_
                  <li><a href="#">Action</a>_x000D_
                  </li>_x000D_
                  <li><a href="#">Another action</a>_x000D_
                  </li>_x000D_
                  <li><a href="#">Something else here</a>_x000D_
                  </li>_x000D_
                  <li role="separator" class="divider"></li>_x000D_
                  <li class="dropdown-header">Nav header</li>_x000D_
                  <li><a href="#">Separated link</a>_x000D_
                  </li>_x000D_
                  <li><a href="#">One more separated link</a>_x000D_
                  </li>_x000D_
                </ul>_x000D_
              </li>_x000D_
            </ul>_x000D_
          </div>_x000D_
          <!--/.nav-collapse -->_x000D_
        </div>_x000D_
      </nav>_x000D_
      <div class="page-header">_x000D_
        <h1>Alerts</h1>_x000D_
      </div>_x000D_
      <div class="alert alert-success" role="alert">_x000D_
        <strong>Well done!</strong> You successfully read this important alert message._x000D_
      </div>_x000D_
      <div class="alert alert-info" role="alert">_x000D_
        <strong>Heads up!</strong> This alert needs your attention, but it's not super important._x000D_
      </div>_x000D_
      <div class="alert alert-warning" role="alert">_x000D_
        <strong>Warning!</strong> Best check yo self, you're not looking too good._x000D_
      </div>_x000D_
      <div class="alert alert-danger" role="alert">_x000D_
        <strong>Oh snap!</strong> Change a few things up and try submitting again._x000D_
      </div>_x000D_
      <div class="page-header">_x000D_
        <h1>Progress bars</h1>_x000D_
      </div>_x000D_
      <div class="progress">_x000D_
        <div class="progress-bar" role="progressbar" aria-valuenow="60" aria-valuemin="0" aria-valuemax="100" style="width: 60%;"><span class="sr-only">60% Complete</span>_x000D_
        </div>_x000D_
      </div>_x000D_
      <div class="progress">_x000D_
        <div class="progress-bar progress-bar-success" role="progressbar" aria-valuenow="40" aria-valuemin="0" aria-valuemax="100" style="width: 40%"><span class="sr-only">40% Complete (success)</span>_x000D_
        </div>_x000D_
      </div>_x000D_
      <div class="progress">_x000D_
        <div class="progress-bar progress-bar-info" role="progressbar" aria-valuenow="20" aria-valuemin="0" aria-valuemax="100" style="width: 20%"><span class="sr-only">20% Complete</span>_x000D_
        </div>_x000D_
      </div>_x000D_
      <div class="progress">_x000D_
        <div class="progress-bar progress-bar-warning" role="progressbar" aria-valuenow="60" aria-valuemin="0" aria-valuemax="100" style="width: 60%"><span class="sr-only">60% Complete (warning)</span>_x000D_
        </div>_x000D_
      </div>_x000D_
      <div class="progress">_x000D_
        <div class="progress-bar progress-bar-danger" role="progressbar" aria-valuenow="80" aria-valuemin="0" aria-valuemax="100" style="width: 80%"><span class="sr-only">80% Complete (danger)</span>_x000D_
        </div>_x000D_
      </div>_x000D_
      <div class="progress">_x000D_
        <div class="progress-bar progress-bar-striped" role="progressbar" aria-valuenow="60" aria-valuemin="0" aria-valuemax="100" style="width: 60%"><span class="sr-only">60% Complete</span>_x000D_
        </div>_x000D_
      </div>_x000D_
      <div class="progress">_x000D_
        <div class="progress-bar progress-bar-success" style="width: 35%"><span class="sr-only">35% Complete (success)</span>_x000D_
        </div>_x000D_
        <div class="progress-bar progress-bar-warning" style="width: 20%"><span class="sr-only">20% Complete (warning)</span>_x000D_
        </div>_x000D_
        <div class="progress-bar progress-bar-danger" style="width: 10%"><span class="sr-only">10% Complete (danger)</span>_x000D_
        </div>_x000D_
      </div>_x000D_
      <div class="page-header">_x000D_
        <h1>List groups</h1>_x000D_
      </div>_x000D_
      <div class="row">_x000D_
        <div class="col-sm-4">_x000D_
          <ul class="list-group">_x000D_
            <li class="list-group-item">Cras justo odio</li>_x000D_
            <li class="list-group-item">Dapibus ac facilisis in</li>_x000D_
            <li class="list-group-item">Morbi leo risus</li>_x000D_
            <li class="list-group-item">Porta ac consectetur ac</li>_x000D_
            <li class="list-group-item">Vestibulum at eros</li>_x000D_
          </ul>_x000D_
        </div>_x000D_
        <!-- /.col-sm-4 -->_x000D_
        <div class="col-sm-4">_x000D_
          <div class="list-group">_x000D_
            <a href="#" class="list-group-item active">_x000D_
              Cras justo odio_x000D_
            </a>_x000D_
            <a href="#" class="list-group-item">Dapibus ac facilisis in</a>_x000D_
            <a href="#" class="list-group-item">Morbi leo risus</a>_x000D_
            <a href="#" class="list-group-item">Porta ac consectetur ac</a>_x000D_
            <a href="#" class="list-group-item">Vestibulum at eros</a>_x000D_
          </div>_x000D_
        </div>_x000D_
        <!-- /.col-sm-4 -->_x000D_
        <div class="col-sm-4">_x000D_
          <div class="list-group">_x000D_
            <a href="#" class="list-group-item active">_x000D_
              <h4 class="list-group-item-heading">List group item heading</h4>_x000D_
              <p class="list-group-item-text">Donec id elit non mi porta gravida at eget metus. Maecenas sed diam eget risus varius blandit.</p>_x000D_
            </a>_x000D_
            <a href="#" class="list-group-item">_x000D_
              <h4 class="list-group-item-heading">List group item heading</h4>_x000D_
              <p class="list-group-item-text">Donec id elit non mi porta gravida at eget metus. Maecenas sed diam eget risus varius blandit.</p>_x000D_
            </a>_x000D_
            <a href="#" class="list-group-item">_x000D_
              <h4 class="list-group-item-heading">List group item heading</h4>_x000D_
              <p class="list-group-item-text">Donec id elit non mi porta gravida at eget metus. Maecenas sed diam eget risus varius blandit.</p>_x000D_
            </a>_x000D_
          </div>_x000D_
        </div>_x000D_
        <!-- /.col-sm-4 -->_x000D_
      </div>_x000D_
      <div class="page-header">_x000D_
        <h1>Panels</h1>_x000D_
      </div>_x000D_
      <div class="row">_x000D_
        <div class="col-sm-4">_x000D_
          <div class="panel panel-default">_x000D_
            <div class="panel-heading">_x000D_
              <h3 class="panel-title">Panel title</h3>_x000D_
            </div>_x000D_
            <div class="panel-body">_x000D_
              Panel content_x000D_
            </div>_x000D_
          </div>_x000D_
          <div class="panel panel-primary">_x000D_
            <div class="panel-heading">_x000D_
              <h3 class="panel-title">Panel title</h3>_x000D_
            </div>_x000D_
            <div class="panel-body">_x000D_
              Panel content_x000D_
            </div>_x000D_
          </div>_x000D_
        </div>_x000D_
        <!-- /.col-sm-4 -->_x000D_
        <div class="col-sm-4">_x000D_
          <div class="panel panel-success">_x000D_
            <div class="panel-heading">_x000D_
              <h3 class="panel-title">Panel title</h3>_x000D_
            </div>_x000D_
            <div class="panel-body">_x000D_
              Panel content_x000D_
            </div>_x000D_
          </div>_x000D_
          <div class="panel panel-info">_x000D_
            <div class="panel-heading">_x000D_
              <h3 class="panel-title">Panel title</h3>_x000D_
            </div>_x000D_
            <div class="panel-body">_x000D_
              Panel content_x000D_
            </div>_x000D_
          </div>_x000D_
        </div>_x000D_
        <!-- /.col-sm-4 -->_x000D_
        <div class="col-sm-4">_x000D_
          <div class="panel panel-warning">_x000D_
            <div class="panel-heading">_x000D_
              <h3 class="panel-title">Panel title</h3>_x000D_
            </div>_x000D_
            <div class="panel-body">_x000D_
              Panel content_x000D_
            </div>_x000D_
          </div>_x000D_
          <div class="panel panel-danger">_x000D_
            <div class="panel-heading">_x000D_
              <h3 class="panel-title">Panel title</h3>_x000D_
            </div>_x000D_
            <div class="panel-body">_x000D_
              Panel content_x000D_
            </div>_x000D_
          </div>_x000D_
        </div>_x000D_
        <!-- /.col-sm-4 -->_x000D_
      </div>_x000D_
    </div>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

MySQL error - #1932 - Table 'phpmyadmin.pma user config' doesn't exist in engine

if someone is still facing this issue, for me it started to occur after I changed my mysql/data with mysql/backup earlier to solve another issue.

I tried a lot of methods, and finally found the solution was very simple! Just click on this icon(Reset session) after opening PhPMyAdmin(it was loading in my case) just below the logo of PhPMyAdmin. It fixed the issue in one-click!

For me, the error code was #1142

PhpMyAdmin Reset Session

PhpMyAdmin Reset Session

What does from __future__ import absolute_import actually do?

The changelog is sloppily worded. from __future__ import absolute_import does not care about whether something is part of the standard library, and import string will not always give you the standard-library module with absolute imports on.

from __future__ import absolute_import means that if you import string, Python will always look for a top-level string module, rather than current_package.string. However, it does not affect the logic Python uses to decide what file is the string module. When you do

python pkg/script.py

pkg/script.py doesn't look like part of a package to Python. Following the normal procedures, the pkg directory is added to the path, and all .py files in the pkg directory look like top-level modules. import string finds pkg/string.py not because it's doing a relative import, but because pkg/string.py appears to be the top-level module string. The fact that this isn't the standard-library string module doesn't come up.

To run the file as part of the pkg package, you could do

python -m pkg.script

In this case, the pkg directory will not be added to the path. However, the current directory will be added to the path.

You can also add some boilerplate to pkg/script.py to make Python treat it as part of the pkg package even when run as a file:

if __name__ == '__main__' and __package__ is None:
    __package__ = 'pkg'

However, this won't affect sys.path. You'll need some additional handling to remove the pkg directory from the path, and if pkg's parent directory isn't on the path, you'll need to stick that on the path too.

How to change the MySQL root account password on CentOS7?

All,

Here a little bit twist with mysql-community-server 5.7 I share some steps, how to reset mysql5.7 root password or set password. it will work centos7 and RHEL7 as well.

step1. 1st stop your databases

service mysqld stop

step2. 2nd modify /etc/my.cnf file add "skip-grant-tables"

vi /etc/my.cnf

[mysqld] skip-grant-tables

step3. 3rd start mysql

service mysqld start

step4. select mysql default database

mysql -u root

mysql>use mysql;

step4. set a new password

mysql> update user set authentication_string=PASSWORD("yourpassword") where User='root';

step5 restart mysql database

service mysqld restart

 mysql -u root -p

enjoy :)

ImportError: No module named pandas

I fixed the same problem with the below commands... Type python on your terminal. If you see python version 2.x then run these two commands to install pandas:

sudo python -m pip install wheel

and

sudo python -m pip install pandas

Else if you see python version 3.x then run these two commands to install pandas:

sudo python3 -m pip install wheel

and

sudo python3 -m pip install pandas

Good Luck!

What is the easiest way to install BLAS and LAPACK for scipy?

For windows: Best is to use pre-compiled package available from this site: http://www.lfd.uci.edu/%7Egohlke/pythonlibs/#scipy

Bootstrap datetimepicker is not a function

I changed the import sequence without fixing the problem, until finally I installed moments and tempus dominius (Core and bootrap), using npm and include them in boostrap.js

try {
window.Popper = require('popper.js').default;
window.$ = window.jQuery = require('jquery');
require('moment'); /*added*/
require('bootstrap');
require('tempusdominus-bootstrap-4');/*added*/} catch (e) {}

No 'Access-Control-Allow-Origin' header is present on the requested resource - Resteasy

Seems your resource POSTmethod won't get hit as @peeskillet mention. Most probably your ~POST~ request won't work, because it may not be a simple request. The only simple requests are GET, HEAD or POST and request headers are simple(The only simple headers are Accept, Accept-Language, Content-Language, Content-Type= application/x-www-form-urlencoded, multipart/form-data, text/plain).

Since in you already add Access-Control-Allow-Origin headers to your Response, you can add new OPTIONS method to your resource class.

    @OPTIONS
@Path("{path : .*}")
public Response options() {
    return Response.ok("")
            .header("Access-Control-Allow-Origin", "*")
            .header("Access-Control-Allow-Headers", "origin, content-type, accept, authorization")
            .header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, HEAD")
            .header("Access-Control-Max-Age", "2000")
            .build();
}

How to declare a vector of zeros in R

X <- c(1:3)*0

Maybe this is not the most efficient way to initialize a vector to zero, but this requires to remember only the c() function, which is very frequently cited in tutorials as a usual way to declare a vector.

As as side-note: To someone learning her way into R from other languages, the multitude of functions to do same thing in R may be mindblowing, just as demonstrated by the previous answers here.

Google maps Marker Label with multiple characters

OK, here is one solution I have come up with which is pretty messed up.

I put the full label text into the div using the fontFamily label attribute. Then I use querySelectorAll to match the resulting style attributes to pull out the refs and rewrite the tags once the map has loaded:

var label = "A123";
var marker = new google.maps.Marker({
  position: latLon,
  label: {
    text: label,
    // Add in the custom label here
    fontFamily: 'Roboto, Arial, sans-serif, custom-label-' + label
  },
  map: map,
  icon: {
    path: 'custom icon path',
    fillColor: '#000000',
    labelOrigin: new google.maps.Point(26.5, 20),
    anchor: new google.maps.Point(26.5, 43), 
    scale: 1
  }
});

google.maps.event.addListener(map, 'idle', function() {
  var labels = document.querySelectorAll("[style*='custom-label']")
  for (var i = 0; i < labels.length; i++) {
    // Retrieve the custom labels and rewrite the tag content
    var matches = labels[i].getAttribute('style').match(/custom-label-(A\d\d\d)/);
    labels[i].innerHTML = matches[1];
  }
});

This seems pretty brittle. Are there any approaches which are less awful?

Check for special characters in string

Wouldn't it be easier to negative-match alphanumerics instead?

return string.match(/^[^a-zA-Z0-9]+$/) ? true : false;

Android "gps requires ACCESS_FINE_LOCATION" error, even though my manifest file contains this

CAUSE: "Beginning in Android 6.0 (API level 23), users grant permissions to apps while the app is running, not when they install the app." In this case, "ACCESS_FINE_LOCATION" is a "dangerous permission and for that reason, you get this 'java.lang.SecurityException: "gps" location provider requires ACCESS_FINE_LOCATION permission.' error (https://developer.android.com/training/permissions/requesting.html).

SOLUTION: Implementing the code provided at https://developer.android.com/training/permissions/requesting.html under the "Request the permissions you need" and "Handle the permissions request response" headings.

sys.argv[1], IndexError: list index out of range

sys.argv is the list of command line arguments passed to a Python script, where sys.argv[0] is the script name itself.

It is erroring out because you are not passing any commandline argument, and thus sys.argv has length 1 and so sys.argv[1] is out of bounds.

To "fix", just make sure to pass a commandline argument when you run the script, e.g.

python ConcatenateFiles.py /the/path/to/the/directory

However, you likely wanted to use some default directory so it will still work when you don't pass in a directory:

cur_dir = sys.argv[1] if len(sys.argv) > 1 else '.'

with open(cur_dir + '/Concatenated.csv', 'w+') as outfile:

    try:
        with open(cur_dir + '/MatrixHeader.csv') as headerfile:
            for line in headerfile:
                outfile.write(line + '\n')
    except:
        print 'No Header File'

Cordova - Error code 1 for command | Command failed for

In my case it was the file size restriction which was put on proxy server. Zip file of gradle was not able to download due this restriction. I was getting 401 error while downloading gradle zip file. If you are getting 401 or 403 error in log, make sure you are able to download those files manually.

ImportError: No module named sklearn.cross_validation

sklearn.cross_validation is now changed to sklearn.model_selection

Just use

from sklearn.model_selection import train_test_split

I think that will work.

Figure out size of UILabel based on String in Swift

I found that the accepted answer worked for a fixed width, but not a fixed height. For a fixed height, it would just increase the width to fit everything on one line, unless there was a line break in the text.

The width function calls the height function multiple times, but it is a quick calculation and I didn't notice performance issues using the function in the rows of a UITable.

extension String {

    public func height(withConstrainedWidth width: CGFloat, font: UIFont) -> CGFloat {
        let constraintRect = CGSize(width: width, height: .greatestFiniteMagnitude)
        let boundingBox = self.boundingRect(with: constraintRect, options: .usesLineFragmentOrigin, attributes: [.font : font], context: nil)

        return ceil(boundingBox.height)
    }

    public func width(withConstrainedHeight height: CGFloat, font: UIFont, minimumTextWrapWidth:CGFloat) -> CGFloat {

        var textWidth:CGFloat = minimumTextWrapWidth
        let incrementWidth:CGFloat = minimumTextWrapWidth * 0.1
        var textHeight:CGFloat = self.height(withConstrainedWidth: textWidth, font: font)

        //Increase width by 10% of minimumTextWrapWidth until minimum width found that makes the text fit within the specified height
        while textHeight > height {
            textWidth += incrementWidth
            textHeight = self.height(withConstrainedWidth: textWidth, font: font)
        }
        return ceil(textWidth)
    }
}

Override default Spring-Boot application.properties settings in Junit Test

Another approach suitable for overriding a few properties in your test, if you are using @SpringBootTest annotation:

@SpringBootTest(properties = {"propA=valueA", "propB=valueB"})

Docker - Container is not running

First of all, we have to start the docker container

ankit@ankit-HP-Notebook:~$  sudo docker start 3a19b39ea021

                        3a19b39ea021

After that, check the docker container:

ankit@ankit-HP-Notebook:~$  sudo docker ps -a

 CONTAINER ID        IMAGE                         COMMAND             CREATED             STATUS                   PORTS               NAMES

  3a19b39ea021        coreapps/ubuntu16.04:latest   "bash"              13 hours ago        
  Up 9 seconds                                 ubuntu1

  455b66057060        hello-world                   "/hello"            4 weeks ago         

Exited (0) 4 weeks ago                       vigorous_bardeen

Then execute by using the command below:

ankit@ankit-HP-Notebook:~$  sudo docker exec -it 3a19b39ea021 bash

root@3a19b39ea021:/# 

python filter list of dictionaries based on key value

Use filter, or if the number of dictionaries in exampleSet is too high, use ifilter of the itertools module. It would return an iterator, instead of filling up your system's memory with the entire list at once:

from itertools import ifilter
for elem in ifilter(lambda x: x['type'] in keyValList, exampleSet):
    print elem

Running PowerShell as another user, and launching a script

In windows server 2012 or 2016 you can search for Windows PowerShell and then "Pin to Start". After this you will see "Run as different user" option on a right click on the start page tiles.

Sum across multiple columns with dplyr

I would use regular expression matching to sum over variables with certain pattern names. For example:

df <- df %>% mutate(sum1 = rowSums(.[grep("x[3-5]", names(.))], na.rm = TRUE),
                    sum_all = rowSums(.[grep("x", names(.))], na.rm = TRUE))

This way you can create more than one variable as a sum of certain group of variables of your data frame.

"Could not find acceptable representation" using spring-boot-starter-web

For me, the problem was trying to pass a filename in a url, with a dot. For example

"http://localhost:8080/something/asdf.jpg" //causes error because of '.jpg'

It could be solved by not passing the .jpg extension, or sending it all in a request body.

Pandas How to filter a Series

As DACW pointed out, there are method-chaining improvements in pandas 0.18.1 that do what you are looking for very nicely.

Rather than using .where, you can pass your function to either the .loc indexer or the Series indexer [] and avoid the call to .dropna:

test = pd.Series({
383:    3.000000,
663:    1.000000,
726:    1.000000,
737:    9.000000,
833:    8.166667
})

test.loc[lambda x : x!=1]

test[lambda x: x!=1]

Similar behavior is supported on the DataFrame and NDFrame classes.

No such keg: /usr/local/Cellar/git

Give another go at force removing the brewed version of git

brew uninstall --force git

Then cleanup any older versions and clear the brew cache

brew cleanup -s git

Remove any dead symlinks

brew cleanup --prune-prefix

Then try reinstalling git

brew install git

If that doesn't work, I'd remove that installation of Homebrew altogether and reinstall it. If you haven't placed anything else in your brew --prefix directory (/usr/local by default), you can simply rm -rf $(brew --prefix). Otherwise the Homebrew wiki recommends using a script at https://gist.github.com/mxcl/1173223#file-uninstall_homebrew-sh

Null pointer Exception on .setOnClickListener

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

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

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

And then in your MainActivity class, declare it as:

Button buttonXYZ;

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

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

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

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

IndexError: too many indices for array

The message that you are getting is not for the default Exception of Python:

For a fresh python list, IndexError is thrown only on index not being in range (even docs say so).

>>> l = []
>>> l[1]
IndexError: list index out of range

If we try passing multiple items to list, or some other value, we get the TypeError:

>>> l[1, 2]
TypeError: list indices must be integers, not tuple

>>> l[float('NaN')]
TypeError: list indices must be integers, not float

However, here, you seem to be using matplotlib that internally uses numpy for handling arrays. On digging deeper through the codebase for numpy, we see:

static NPY_INLINE npy_intp
unpack_tuple(PyTupleObject *index, PyObject **result, npy_intp result_n)
{
    npy_intp n, i;
    n = PyTuple_GET_SIZE(index);
    if (n > result_n) {
        PyErr_SetString(PyExc_IndexError,
                        "too many indices for array");
        return -1;
    }
    for (i = 0; i < n; i++) {
        result[i] = PyTuple_GET_ITEM(index, i);
        Py_INCREF(result[i]);
    }
    return n;
}

where, the unpack method will throw an error if it the size of the index is greater than that of the results.

So, Unlike Python which raises a TypeError on incorrect Indexes, Numpy raises the IndexError because it supports multidimensional arrays.

TypeError: 'list' object cannot be interpreted as an integer

remove the range.

for i in myList

range takes in an integer. you want for each element in the list.

Upload a file to Amazon S3 with NodeJS

Or Using promises:

const AWS = require('aws-sdk');
AWS.config.update({
    accessKeyId: 'accessKeyId',
    secretAccessKey: 'secretAccessKey',
    region: 'region'
});

let params = {
    Bucket: "yourBucketName",
    Key: 'someUniqueKey',
    Body: 'someFile'
};
try {
    let uploadPromise = await new AWS.S3().putObject(params).promise();
    console.log("Successfully uploaded data to bucket");
} catch (e) {
    console.log("Error uploading data: ", e);
}

How to use OAuth2RestTemplate?

You can find examples for writing OAuth clients here:

In your case you can't just use default or base classes for everything, you have a multiple classes Implementing OAuth2ProtectedResourceDetails. The configuration depends of how you configured your OAuth service but assuming from your curl connections I would recommend:

@EnableOAuth2Client
@Configuration
class MyConfig{

    @Value("${oauth.resource:http://localhost:8082}")
    private String baseUrl;
    @Value("${oauth.authorize:http://localhost:8082/oauth/authorize}")
    private String authorizeUrl;
    @Value("${oauth.token:http://localhost:8082/oauth/token}")
    private String tokenUrl;

    @Bean
    protected OAuth2ProtectedResourceDetails resource() {
        ResourceOwnerPasswordResourceDetails resource;
        resource = new ResourceOwnerPasswordResourceDetails();

        List scopes = new ArrayList<String>(2);
        scopes.add("write");
        scopes.add("read");
        resource.setAccessTokenUri(tokenUrl);
        resource.setClientId("restapp");
        resource.setClientSecret("restapp");
        resource.setGrantType("password");
        resource.setScope(scopes);
        resource.setUsername("**USERNAME**");
        resource.setPassword("**PASSWORD**");
        return resource;
    }

    @Bean
    public OAuth2RestOperations restTemplate() {
        AccessTokenRequest atr = new DefaultAccessTokenRequest();
        return new OAuth2RestTemplate(resource(), new DefaultOAuth2ClientContext(atr));
    }
}

@Service
@SuppressWarnings("unchecked")
class MyService {

    @Autowired
    private OAuth2RestOperations restTemplate;

    public MyService() {
        restTemplate.getAccessToken();
    }
}

Do not forget about @EnableOAuth2Client on your config class, also I would suggest to try that the urls you are using are working with curl first, also try to trace it with the debugger because lot of exceptions are just consumed and never printed out due security reasons, so it gets little hard to find where the issue is. You should use logger with debug enabled set. Good luck

I uploaded sample springboot app on github https://github.com/mariubog/oauth-client-sample to depict your situation because I could not find any samples for your scenario .

Return multiple values from a function in swift

you should return three different values from this method and get these three in a single variable like this.

func getTime()-> (hour:Int,min:Int,sec:Int){
//your code
return (hour,min,sec)
}

get the value in single variable

let getTime = getTime()

now you can access the hour,min and seconds simply by "." ie.

print("hour:\(getTime.hour) min:\(getTime.min) sec:\(getTime.sec)")

Choosing bootstrap vs material design

As far as I know you can use all mentioned technologies separately or together. It's up to you. I think you look at the problem from the wrong angle. Material Design is just the way particular elements of the page are designed, behave and put together. Material Design provides great UI/UX, but it relies on the graphic layout (HTML/CSS) rather than JS (events, interactions).

On the other hand, AngularJS and Bootstrap are front-end frameworks that can speed up your development by saving you from writing tons of code. For example, you can build web app utilizing AngularJS, but without Material Design. Or You can build simple HTML5 web page with Material Design without AngularJS or Bootstrap. Finally you can build web app that uses AngularJS with Bootstrap and with Material Design. This is the best scenario. All technologies support each other.

  1. Bootstrap = responsive page
  2. AngularJS = MVC
  3. Material Design = great UI/UX

You can check awesome material design components for AngularJS:

https://material.angularjs.org


enter image description here

Demo: https://material.angularjs.org/latest/demo/ enter image description here

Cannot resolve method 'getSupportFragmentManager ( )' inside Fragment

you should use

getActivity.getSupportFragmentManager() like
//in my fragment 
SupportMapFragment fm = (SupportMapFragment)    
getActivity().getSupportFragmentManager().findFragmentById(R.id.map);

I have also this issues but resolved after adding getActivity() before getSupportFragmentManager.

Woocommerce, get current product id

If the query hasn't been modified by a plugin for some reason, you should be able to get a single product page's "id" via

global $post;
$id = $post->ID

OR

global $product;
$id = $product->id;

EDIT: As of WooCommerce 3.0 this needs to be

global $product;
$id = $product->get_id();

Unable to add window -- token null is not valid; is your activity running?

You need to pass your activity in the constructor

 PopupWindow popupWindow = new PopupWindow(YourActivity.this)

pandas create new column based on values from other columns / apply a function of multiple columns, row-wise

As @user3483203 pointed out, numpy.select is the best approach

Store your conditional statements and the corresponding actions in two lists

conds = [(df['eri_hispanic'] == 1),(df[['eri_afr_amer', 'eri_asian', 'eri_hawaiian', 'eri_nat_amer', 'eri_white']].sum(1).gt(1)),(df['eri_nat_amer'] == 1),(df['eri_asian'] == 1),(df['eri_afr_amer'] == 1),(df['eri_hawaiian'] == 1),(df['eri_white'] == 1,])

actions = ['Hispanic', 'Two Or More', 'A/I AK Native', 'Asian', 'Black/AA', 'Haw/Pac Isl.', 'White']

You can now use np.select using these lists as its arguments

df['label_race'] = np.select(conds,actions,default='Other')

Reference: https://numpy.org/doc/stable/reference/generated/numpy.select.html

How to convert a python numpy array to an RGB image with Opencv 2.4?

The size of your image is not sufficient to see in a naked eye. So please try to use atleast 50x50

import cv2 as cv
import numpy as np

black_screen = np.zeros([50,50,3])

black_screen[:, :, 2] = np.ones([50,50])*64/255.0
cv.imshow("Simple_black", black_screen)
cv.waitKey(0)
cv.displayAllWindows()

Touch move getting stuck Ignored attempt to cancel a touchmove

Please remove e.preventDefault(), because event.cancelable of touchmove is false. So you can't call this method.

Python Function to test ping

Adding on to the other answers, you can check the OS and decide whether to use "-c" or "-n":

import os, platform
host = "8.8.8.8"
os.system("ping " + ("-n 1 " if  platform.system().lower()=="windows" else "-c 1 ") + host)

This will work on Windows, OS X, and Linux

You can also use sys:

import os, sys
host = "8.8.8.8"
os.system("ping " + ("-n 1 " if  sys.platform().lower()=="win32" else "-c 1 ") + host)

resize2fs: Bad magic number in super-block while trying to open

I ran into the same exact problem around noon today and finally found a solution here --> Trying to resize2fs EB volume fails

I skipped mounting, since the partition was already mounted.

Apparently CentOS 7 uses XFS as the default file system and as a result resize2fs will fail.

I took a look in /etc/fstab, and guess what, XFS was staring me in the face... Hope this helps.

Move view with keyboard using Swift

For Black Screen Error ( Swift 4 & 4.2 ) .

I fixed the black screen problem. In the verified solution The keyboard height changes after tapping and this is causing black screen.

Have to use UIKeyboardFrameEndUserInfoKey instead of UIKeyboardFrameBeginUserInfoKey

var isKeyboardAppear = false

override func viewDidLoad() {
    super.viewDidLoad() 
    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
}

@objc func keyboardWillShow(notification: NSNotification) {
    if !isKeyboardAppear {
        if let keyboardSize = (notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue {
            if self.view.frame.origin.y == 0{
                self.view.frame.origin.y -= keyboardSize.height
            }
        }
        isKeyboardAppear = true
    }
}

@objc func keyboardWillHide(notification: NSNotification) {
    if isKeyboardAppear {
        if let keyboardSize = (notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue {
            if self.view.frame.origin.y != 0{
                self.view.frame.origin.y += keyboardSize.height
            }
        }
         isKeyboardAppear = false
    }
}

How to see remote tags?

Even without cloning or fetching, you can check the list of tags on the upstream repo with git ls-remote:

git ls-remote --tags /url/to/upstream/repo

(as illustrated in "When listing git-ls-remote why there's “^{}” after the tag name?")

xbmono illustrates in the comments that quotes are needed:

git ls-remote --tags /some/url/to/repo "refs/tags/MyTag^{}"

Note that you can always push your commits and tags in one command with (git 1.8.3+, April 2013):

git push --follow-tags

See Push git commits & tags simultaneously.


Regarding Atlassian SourceTree specifically:

Note that, from this thread, SourceTree ONLY shows local tags.

There is an RFE (Request for Enhancement) logged in SRCTREEWIN-4015 since Dec. 2015.

A simple workaround:

see a list of only unpushed tags?

git push --tags

or check the "Push all tags" box on the "Push" dialog box, all tags will be pushed to your remote.

https://community.atlassian.com/tnckb94959/attachments/tnckb94959/sourcetree-questions/10923/1/Screen%20Shot%202015-12-15%20at%208.49.48%20AM.png

That way, you will be "sure that they are present in remote so that other developers can pull them".

how to open .mat file without using MATLAB?

A .mat-file is a compressed binary file. It is not possible to open it with a text editor (except you have a special plugin as Dennis Jaheruddin says). Otherwise you will have to convert it into a text file (csv for example) with a script. This could be done by python for example: Read .mat files in Python.

Django: OperationalError No Such Table

If you get to the bottom of this list and find this answer, I am almost sure it will solve all your issues :) In my case, I had dropped a database table and I was not getting anywhere with makemigrations and migrate

So I got a very detailed answer on how to reset everything on this link

Passing multiple parameters to pool.map() function in Python

You could use a map function that allows multiple arguments, as does the fork of multiprocessing found in pathos.

>>> from pathos.multiprocessing import ProcessingPool as Pool
>>> 
>>> def add_and_subtract(x,y):
...   return x+y, x-y
... 
>>> res = Pool().map(add_and_subtract, range(0,20,2), range(-5,5,1))
>>> res
[(-5, 5), (-2, 6), (1, 7), (4, 8), (7, 9), (10, 10), (13, 11), (16, 12), (19, 13), (22, 14)]
>>> Pool().map(add_and_subtract, *zip(*res))
[(0, -10), (4, -8), (8, -6), (12, -4), (16, -2), (20, 0), (24, 2), (28, 4), (32, 6), (36, 8)]

pathos enables you to easily nest hierarchical parallel maps with multiple inputs, so we can extend our example to demonstrate that.

>>> from pathos.multiprocessing import ThreadingPool as TPool
>>> 
>>> res = TPool().amap(add_and_subtract, *zip(*Pool().map(add_and_subtract, range(0,20,2), range(-5,5,1))))
>>> res.get()
[(0, -10), (4, -8), (8, -6), (12, -4), (16, -2), (20, 0), (24, 2), (28, 4), (32, 6), (36, 8)]

Even more fun, is to build a nested function that we can pass into the Pool. This is possible because pathos uses dill, which can serialize almost anything in python.

>>> def build_fun_things(f, g):
...   def do_fun_things(x, y):
...     return f(x,y), g(x,y)
...   return do_fun_things
... 
>>> def add(x,y):
...   return x+y
... 
>>> def sub(x,y):
...   return x-y
... 
>>> neato = build_fun_things(add, sub)
>>> 
>>> res = TPool().imap(neato, *zip(*Pool().map(neato, range(0,20,2), range(-5,5,1))))
>>> list(res)
[(0, -10), (4, -8), (8, -6), (12, -4), (16, -2), (20, 0), (24, 2), (28, 4), (32, 6), (36, 8)]

If you are not able to go outside of the standard library, however, you will have to do this another way. Your best bet in that case is to use multiprocessing.starmap as seen here: Python multiprocessing pool.map for multiple arguments (noted by @Roberto in the comments on the OP's post)

Get pathos here: https://github.com/uqfoundation

Explanation of polkitd Unregistered Authentication Agent

I found this problem too. Because centos service depend on multi-user.target for none desktop Cenots 7.2. so I delete multi-user.target from my .service file. It had missed.

Cannot deserialize instance of object out of START_ARRAY token in Spring Webservice

Your json contains an array, but you're trying to parse it as an object. This error occurs because objects must start with {.

You have 2 options:

  1. You can get rid of the ShopContainer class and use Shop[] instead

    ShopContainer response  = restTemplate.getForObject(
        url, ShopContainer.class);
    

    replace with

    Shop[] response  = restTemplate.getForObject(url, Shop[].class);
    

    and then make your desired object from it.

  2. You can change your server to return an object instead of a list

    return mapper.writerWithDefaultPrettyPrinter().writeValueAsString(list);
    

    replace with

    return mapper.writerWithDefaultPrettyPrinter().writeValueAsString(
        new ShopContainer(list));
    

How to get a specific column value from a DataTable in c#

The table normally contains multiple rows. Use a loop and use row.Field<string>(0) to access the value of each row.

foreach(DataRow row in dt.Rows)
{
    string file = row.Field<string>("File");
}

You can also access it via index:

foreach(DataRow row in dt.Rows)
{
    string file = row.Field<string>(0);
}

If you expect only one row, you can also use the indexer of DataRowCollection:

string file = dt.Rows[0].Field<string>(0); 

Since this fails if the table is empty, use dt.Rows.Count to check if there is a row:

if(dt.Rows.Count > 0)
    file = dt.Rows[0].Field<string>(0);

Create or update mapping in elasticsearch

Generally speaking, you can update your index mapping using the put mapping api (reference here) :

curl -XPUT 'http://localhost:9200/advert_index/_mapping/advert_type' -d '
{
    "advert_type" : {
        "properties" : {

          //your new mapping properties

        }
    }
}
'

It's especially useful for adding new fields. However, in your case, you will try to change the location type, which will cause a conflict and prevent the new mapping from being used.

You could use the put mapping api to add another property containing the location as a lat/lon array, but you won't be able to update the previous location field itself.

Finally, you will have to reindex your data for your new mapping to be taken into account.

The best solution would really be to create a new index.

If your problem with creating another index is downtime, you should take a look at aliases to make things go smoothly.

python 2.7: cannot pip on windows "bash: pip: command not found"

On windows 7, you have to use this command: python -m pip install xxx. All above don't work for me.

Alternating Row Colors in Bootstrap 3 - No Table

I was having trouble coloring rows in table using bootstrap table-striped class then realized delete table-striped class and do this in css file

tr:nth-of-type(odd)
{  
background-color: red;
}
tr:nth-of-type(even)
{  
background-color: blue;
}

The bootstrap table-striped class will over ride your selectors.

Scrolling to an Anchor using Transition/CSS3

Just apply scroll behaviour to all elements with this one-line code:

_x000D_
_x000D_
*{
scroll-behavior: smooth !important;
}
_x000D_
_x000D_
_x000D_

javac: invalid target release: 1.8

if you are going to step down, then change your project's source to 1.7 as well,

right click on your Project -> Properties -> Sources window and set 1.7 here" Jigar Joshi

Also go to the build-impl.xml and look for the property excludeFromCopy="${copylibs.excludes}" and delete this property on my code was at line 827 but I`ve seen it on other lines

for me was taking a code from MAC OS java 1.8 to WIN XP java 1.7

pandas dataframe columns scaling with sklearn

You can do it using pandas only:

In [235]:
dfTest = pd.DataFrame({'A':[14.00,90.20,90.95,96.27,91.21],'B':[103.02,107.26,110.35,114.23,114.68], 'C':['big','small','big','small','small']})
df = dfTest[['A', 'B']]
df_norm = (df - df.min()) / (df.max() - df.min())
print df_norm
print pd.concat((df_norm, dfTest.C),1)

          A         B
0  0.000000  0.000000
1  0.926219  0.363636
2  0.935335  0.628645
3  1.000000  0.961407
4  0.938495  1.000000
          A         B      C
0  0.000000  0.000000    big
1  0.926219  0.363636  small
2  0.935335  0.628645    big
3  1.000000  0.961407  small
4  0.938495  1.000000  small

System.Collections.Generic.List does not contain a definition for 'Select'

You need to have the System.Linq namespace included in your view since Select is an extension method. You have a couple of options on how to do this:

Add @using System.Linq to the top of your cshtml file.

If you find that you will be using this namespace often in many of your views, you can do this for all views by modifying the web.config inside of your Views folder (not the one at the root). You should see a pages/namespace XML element, create a new add child that adds System.Linq. Here is an example:

<configuration>
    <system.web.webPages.razor>
        <pages>
            <namespaces>
                <add namespace="System.Linq" />
            </namespaces>
        </pages>
    </system.web.webPages.razor>
</configuration>

Excel Formula which places date/time in cell when data is entered in another cell in the same row

Not sure if this works for cells with functions but I found this code elsewhere for single cell entries and modified it for my use. If done properly, you do not need to worry about entering a function in a cell or the file changing the dates to that day's date every time it is opened.

  • open Excel
  • press "Alt+F11"
  • Double-click on the worksheet that you want to apply the change to (listed on the left)
  • copy/paste the code below
  • adjust the Range(:) input to correspond to the column you will update
  • adjust the Offset(0,_) input to correspond to the column where you would like the date displayed (in the version below I am making updates to column D and I want the date displayed in column F, hence the input entry of "2" for 2 columns over from column D)
  • hit save
  • repeat steps above if there are other worksheets in your workbook that need the same code
  • you may have to change the number format of the column displaying the date to "General" and increase the column's width if it is displaying "####" after you make an updated entry

Copy/Paste Code below:


Private Sub Worksheet_Change(ByVal Target As Range)

If Intersect(Target, Range("D:D")) Is Nothing Then Exit Sub
Target.Offset(0, 2) = Date

End Sub


Good luck...

Creating Accordion Table with Bootstrap

For anyone who came here looking for how to get the true accordion effect and only allow one row to be expanded at a time, you can add an event handler for show.bs.collapse like so:

$('.collapse').on('show.bs.collapse', function () {
    $('.collapse.in').collapse('hide');
});

I modified this example to do so here: http://jsfiddle.net/QLfMU/116/

DSO missing from command line

DSO here means Dynamic Shared Object; since the error message says it's missing from the command line, I guess you have to add it to the command line.

That is, try adding -lpthread to your command line.

python to arduino serial read & write

You shouldn't be closing the serial port in Python between writing and reading. There is a chance that the port is still closed when the Arduino responds, in which case the data will be lost.

while running:  
    # Serial write section
    setTempCar1 = 63
    setTempCar2 = 37
    setTemp1 = str(setTempCar1)
    setTemp2 = str(setTempCar2)
    print ("Python value sent: ")
    print (setTemp1)
    ard.write(setTemp1)
    time.sleep(6) # with the port open, the response will be buffered 
                  # so wait a bit longer for response here

    # Serial read section
    msg = ard.read(ard.inWaiting()) # read everything in the input buffer
    print ("Message from arduino: ")
    print (msg)

The Python Serial.read function only returns a single byte by default, so you need to either call it in a loop or wait for the data to be transmitted and then read the whole buffer.

On the Arduino side, you should consider what happens in your loop function when no data is available.

void loop()
{
  // serial read section
  while (Serial.available()) // this will be skipped if no data present, leading to
                             // the code sitting in the delay function below
  {
    delay(30);  //delay to allow buffer to fill 
    if (Serial.available() >0)
    {
      char c = Serial.read();  //gets one byte from serial buffer
      readString += c; //makes the string readString
    }
  }

Instead, wait at the start of the loop function until data arrives:

void loop()
{
  while (!Serial.available()) {} // wait for data to arrive
  // serial read section
  while (Serial.available())
  {
    // continue as before

EDIT 2

Here's what I get when interfacing with your Arduino app from Python:

>>> import serial
>>> s = serial.Serial('/dev/tty.usbmodem1411', 9600, timeout=5)
>>> s.write('2')
1
>>> s.readline()
'Arduino received: 2\r\n'

So that seems to be working fine.

In testing your Python script, it seems the problem is that the Arduino resets when you open the serial port (at least my Uno does), so you need to wait a few seconds for it to start up. You are also only reading a single line for the response, so I've fixed that in the code below also:

#!/usr/bin/python
import serial
import syslog
import time

#The following line is for serial over GPIO
port = '/dev/tty.usbmodem1411' # note I'm using Mac OS-X


ard = serial.Serial(port,9600,timeout=5)
time.sleep(2) # wait for Arduino

i = 0

while (i < 4):
    # Serial write section

    setTempCar1 = 63
    setTempCar2 = 37
    ard.flush()
    setTemp1 = str(setTempCar1)
    setTemp2 = str(setTempCar2)
    print ("Python value sent: ")
    print (setTemp1)
    ard.write(setTemp1)
    time.sleep(1) # I shortened this to match the new value in your Arduino code

    # Serial read section
    msg = ard.read(ard.inWaiting()) # read all characters in buffer
    print ("Message from arduino: ")
    print (msg)
    i = i + 1
else:
    print "Exiting"
exit()

Here's the output of the above now:

$ python ardser.py
Python value sent:
63
Message from arduino:
Arduino received: 63
Arduino sends: 1


Python value sent:
63
Message from arduino:
Arduino received: 63
Arduino sends: 1


Python value sent:
63
Message from arduino:
Arduino received: 63
Arduino sends: 1


Python value sent:
63
Message from arduino:
Arduino received: 63
Arduino sends: 1


Exiting

Javascript Uncaught Reference error Function is not defined

Change the wrapping from "onload" to "No wrap - in <body>"

The function defined has a different scope.

Project with path ':mypath' could not be found in root project 'myproject'

Remove all the texts in android/settings.gradle and paste the below code

rootProject.name = '****Your Project Name****'
apply from: file("../node_modules/@react-native-community/cli-platform-android/native_modules.gradle"); applyNativeModulesSettingsGradle(settings)
include ':app'

This issue will usually happen when you migrate from react-native < 0.60 to react-native >0.60. If you create a new project in react-native >0.60 you will see the same settings as above mentioned

Form Submission without page refresh

<script type="text/javascript">
    var frm = $('#myform');
    frm.submit(function (ev) {
        $.ajax({
            type: frm.attr('method'),
            url: frm.attr('action'),
            data: frm.serialize(),
            success: function (data) {
                alert('ok');
            }
        });

        ev.preventDefault();
    });
</script>

<form id="myform" action="/your_url" method="post">
    ...
</form>

Execute function after Ajax call is complete

Append .done() to your ajax request.

$.ajax({
  url: "test.html",
  context: document.body
}).done(function() { //use this
  alert("DONE!");
});

See the JQuery Doc for .done()

Error: getaddrinfo ENOTFOUND in nodejs for get call

When I tried to install a new ionic app, I got the same error as follows, I tried many sources and found the mistake made in User Environment and System Environment unnecessarily included the PROXY value. I removed the ```user variables http://host:port PROXY

system Variables http_proxy http://username:password@host:port ```` and now it is working fine without trouble.

[ERROR] Network connectivity error occurred, are you offline?

        If you are behind a firewall and need to configure proxy settings, see: https://ion.link/cli-proxy-docs

        Error: getaddrinfo ENOTFOUND host host:80

3-dimensional array in numpy

No need to go in such deep technicalities, and get yourself blasted. Let me explain it in the most easiest way. We all have studied "Sets" during our school-age in Mathematics. Just consider 3D numpy array as the formation of "sets".

x = np.zeros((2,3,4)) 

Simply Means:

2 Sets, 3 Rows per Set, 4 Columns

Example:

Input

x = np.zeros((2,3,4))

Output

Set # 1 ---- [[[ 0.,  0.,  0.,  0.],  ---- Row 1
               [ 0.,  0.,  0.,  0.],  ---- Row 2
               [ 0.,  0.,  0.,  0.]], ---- Row 3 
    
Set # 2 ----  [[ 0.,  0.,  0.,  0.],  ---- Row 1
               [ 0.,  0.,  0.,  0.],  ---- Row 2
               [ 0.,  0.,  0.,  0.]]] ---- Row 3

Explanation: See? we have 2 Sets, 3 Rows per Set, and 4 Columns.

Note: Whenever you see a "Set of numbers" closed in double brackets from both ends. Consider it as a "set". And 3D and 3D+ arrays are always built on these "sets".

SQL server stored procedure return a table

I had a similar situation and solved by using a temp table inside the procedure, with the same fields being returned by the original Stored Procedure:

CREATE PROCEDURE mynewstoredprocedure
AS 
BEGIN

INSERT INTO temptable (field1, field2)
EXEC mystoredprocedure @param1, @param2

select field1, field2 from temptable

-- (mystoredprocedure returns field1, field2)

END

How to add noise (Gaussian/salt and pepper etc) to image in Python with OpenCV

The Function adds gaussian , salt-pepper , poisson and speckle noise in an image

Parameters
----------
image : ndarray
    Input image data. Will be converted to float.
mode : str
    One of the following strings, selecting the type of noise to add:

    'gauss'     Gaussian-distributed additive noise.
    'poisson'   Poisson-distributed noise generated from the data.
    's&p'       Replaces random pixels with 0 or 1.
    'speckle'   Multiplicative noise using out = image + n*image,where
                n is uniform noise with specified mean & variance.


import numpy as np
import os
import cv2
def noisy(noise_typ,image):
   if noise_typ == "gauss":
      row,col,ch= image.shape
      mean = 0
      var = 0.1
      sigma = var**0.5
      gauss = np.random.normal(mean,sigma,(row,col,ch))
      gauss = gauss.reshape(row,col,ch)
      noisy = image + gauss
      return noisy
   elif noise_typ == "s&p":
      row,col,ch = image.shape
      s_vs_p = 0.5
      amount = 0.004
      out = np.copy(image)
      # Salt mode
      num_salt = np.ceil(amount * image.size * s_vs_p)
      coords = [np.random.randint(0, i - 1, int(num_salt))
              for i in image.shape]
      out[coords] = 1

      # Pepper mode
      num_pepper = np.ceil(amount* image.size * (1. - s_vs_p))
      coords = [np.random.randint(0, i - 1, int(num_pepper))
              for i in image.shape]
      out[coords] = 0
      return out
  elif noise_typ == "poisson":
      vals = len(np.unique(image))
      vals = 2 ** np.ceil(np.log2(vals))
      noisy = np.random.poisson(image * vals) / float(vals)
      return noisy
  elif noise_typ =="speckle":
      row,col,ch = image.shape
      gauss = np.random.randn(row,col,ch)
      gauss = gauss.reshape(row,col,ch)        
      noisy = image + image * gauss
      return noisy

How to make div same height as parent (displayed as table-cell)

The child can only take a height if the parent has one already set. See this exaple : Vertical Scrolling 100% height

 html, body {
        height: 100%;
        margin: 0;
    }
    .header{
        height: 10%;
        background-color: #a8d6fe;
    }
    .middle {
        background-color: #eba5a3;
        min-height: 80%;
    }
    .footer {
        height: 10%;
        background-color: #faf2cc;
    }

_x000D_
_x000D_
    $(function() {_x000D_
      $('a[href*="#nav-"]').click(function() {_x000D_
        if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') && location.hostname == this.hostname) {_x000D_
          var target = $(this.hash);_x000D_
          target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');_x000D_
          if (target.length) {_x000D_
            $('html, body').animate({_x000D_
              scrollTop: target.offset().top_x000D_
            }, 500);_x000D_
            return false;_x000D_
          }_x000D_
        }_x000D_
      });_x000D_
    });
_x000D_
html,_x000D_
body {_x000D_
  height: 100%;_x000D_
  margin: 0;_x000D_
}_x000D_
.header {_x000D_
  height: 100%;_x000D_
  background-color: #a8d6fe;_x000D_
}_x000D_
.middle {_x000D_
  background-color: #eba5a3;_x000D_
  min-height: 100%;_x000D_
}_x000D_
.footer {_x000D_
  height: 100%;_x000D_
  background-color: #faf2cc;_x000D_
}_x000D_
nav {_x000D_
  position: fixed;_x000D_
  top: 10px;_x000D_
  left: 0px;_x000D_
}_x000D_
nav li {_x000D_
  display: inline-block;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<body>_x000D_
  <nav>_x000D_
    <ul>_x000D_
      <li>_x000D_
        <a href="#nav-a">got to a</a>_x000D_
      </li>_x000D_
      <li>_x000D_
        <a href="#nav-b">got to b</a>_x000D_
      </li>_x000D_
      <li>_x000D_
        <a href="#nav-c">got to c</a>_x000D_
      </li>_x000D_
    </ul>_x000D_
  </nav>_x000D_
  <div class="header" id="nav-a">_x000D_
_x000D_
  </div>_x000D_
  <div class="middle" id="nav-b">_x000D_
_x000D_
  </div>_x000D_
  <div class="footer" id="nav-c">_x000D_
_x000D_
  </div>
_x000D_
_x000D_
_x000D_

"The underlying connection was closed: An unexpected error occurred on a send." With SSL Certificate

It if helps someone, ours was an issue with missing certificate. Environment is Windows Server 2016 Standard with .Net 4.6.

There is a self hosted WCF service https URI, for which Service.Open() would execute without errors. Another thread would keep accessing https://OurIp:443/OurService?wsdl to ensure that the service was available. Accessing the WSDL used to fail with:

The underlying connection was closed: An unexpected error occurred on a send.

Using ServicePointManager.SecurityProtocol with applicable settings did not work. Playing with server roles and features did not help either. Then stepped in Jaise George, the SE, resolving the issue in a couple of minutes. Jaise installed a self signed certificate in the IIS, poofing the issue. This is what he did to address the issue:

(1) Open IIS manager (inetmgr) (2) Click on the server node in the left panel, and double click "Server certificates". (3) Click on "Create Self-Signed Certificate" on the right panel and type in anything you want for the friendly name. (4) Click on “Default Web site” in the left panel, click "Bindings" on the right panel, click "Add", select "https", select the certificate you just created, and click "OK" (5) Access the https URL, it should be accessible.

Peak signal detection in realtime timeseries data

This problem looks similar to one I encountered in a hybrid/embedded systems course, but that was related to detecting faults when the input from a sensor is noisy. We used a Kalman filter to estimate/predict the hidden state of the system, then used statistical analysis to determine the likelihood that a fault had occurred. We were working with linear systems, but nonlinear variants exist. I remember the approach being surprisingly adaptive, but it required a model of the dynamics of the system.

Debugging the error "gcc: error: x86_64-linux-gnu-gcc: No such file or directory"

After a fair amount of work, I was able to get it to build on Ubuntu 12.04 x86 and Debian 7.4 x86_64. I wrote up a guide below. Can you please try following it to see if it resolves the issue?

If not please let me know where you get stuck.

Install Common Dependencies

sudo apt-get install build-essential autoconf libtool pkg-config python-opengl python-imaging python-pyrex python-pyside.qtopengl idle-python2.7 qt4-dev-tools qt4-designer libqtgui4 libqtcore4 libqt4-xml libqt4-test libqt4-script libqt4-network libqt4-dbus python-qt4 python-qt4-gl libgle3 python-dev

Install NumArray 1.5.2

wget http://goo.gl/6gL0q3 -O numarray-1.5.2.tgz
tar xfvz numarray-1.5.2.tgz
cd numarray-1.5.2
sudo python setup.py install

Install Numeric 23.8

wget http://goo.gl/PxaHFW -O numeric-23.8.tgz
tar xfvz numeric-23.8.tgz
cd Numeric-23.8
sudo python setup.py install

Install HDF5 1.6.5

wget ftp://ftp.hdfgroup.org/HDF5/releases/hdf5-1.6/hdf5-1.6.5.tar.gz
tar xfvz hdf5-1.6.5.tar.gz
cd hdf5-1.6.5
./configure --prefix=/usr/local
sudo make 
sudo make install

Install Nanoengineer

git clone https://github.com/kanzure/nanoengineer.git
cd nanoengineer
./bootstrap
./configure
make
sudo make install

Troubleshooting

On Debian Jessie, you will receive the error message that cant pants mentioned. There seems to be an issue in the automake scripts. x86_64-linux-gnu-gcc is inserted in CFLAGS and gcc will interpret that as a name of one of the source files. As a workaround, let's create an empty file with that name. Empty so that it won't change the program and that very name so that compiler picks it up. From the cloned nanoengineer directory, run this command to make gcc happy (it is a hack yes, but it does work) ...

touch sim/src/x86_64-linux-gnu-gcc

If you receive an error message when attemping to compile HDF5 along the lines of: "error: call to ‘__open_missing_mode’ declared with attribute error: open with O_CREAT in second argument needs 3 arguments", then modify the file perform/zip_perf.c, line 548 to look like the following and then rerun make...

output = open(filename, O_RDWR | O_CREAT, S_IRUSR|S_IWUSR);

If you receive an error message about Numeric/arrayobject.h not being found when building Nanoengineer, try running

export CPPFLAGS=-I/usr/local/include/python2.7
./configure
make
sudo make install

If you receive an error message similar to "TRACE_PREFIX undeclared", modify the file sim/src/simhelp.c lines 38 to 41 to look like this and re-run make:

#ifdef DISTUTILS
static char tracePrefix[] = "";
#else
static char tracePrefix[] = "";

If you receive an error message when trying to launch NanoEngineer-1 that mentions something similar to "cannot import name GL_ARRAY_BUFFER_ARB", modify the lines in the following files

/usr/local/bin/NanoEngineer1_0.9.2.app/program/graphics/drawing/setup_draw.py
/usr/local/bin/NanoEngineer1_0.9.2.app/program/graphics/drawing/GLPrimitiveBuffer.py
/usr/local/bin/NanoEngineer1_0.9.2.app/program/prototype/test_drawing.py

that look like this:

from OpenGL.GL import GL_ARRAY_BUFFER_ARB
from OpenGL.GL import GL_ELEMENT_ARRAY_BUFFER_ARB

to look like this:

from OpenGL.GL.ARB.vertex_buffer_object import GL_ARRAY_BUFFER_AR
from OpenGL.GL.ARB.vertex_buffer_object import GL_ELEMENT_ARRAY_BUFFER_ARB

I also found an additional troubleshooting text file that has been removed, but you can find it here

SQL Error: ORA-01861: literal does not match format string 01861

Try replacing the string literal for date '1989-12-09' with TO_DATE('1989-12-09','YYYY-MM-DD')

How to rollback everything to previous commit

If you have pushed the commits upstream...

Select the commit you would like to roll back to and reverse the changes by clicking Reverse File, Reverse Hunk or Reverse Selected Lines. Do this for all the commits after the commit you would like to roll back to also.

reverse stuff reverse commit

If you have not pushed the commits upstream...

Right click on the commit and click on Reset current branch to this commit.

reset branch to commit

Python Script to convert Image into Byte array

Use bytearray:

with open("img.png", "rb") as image:
  f = image.read()
  b = bytearray(f)
  print b[0]

You can also have a look at struct which can do many conversions of that kind.

How to fix Warning Illegal string offset in PHP

Please check that your key exists in the array or not, instead of simply trying to access it.

Replace:

$myVar = $someArray['someKey']

With something like:

if (isset($someArray['someKey'])) {
    $myVar = $someArray['someKey']
}

or something like:

if(is_array($someArray['someKey'])) {
    $theme_img = 'recent_works_iso_thumbnail';
}else {
    $theme_img = 'recent_works_iso_thumbnail';
}

mysqldump & gzip commands to properly create a compressed file of a MySQL database using crontab

Besides the solution of m79lkm above, my 2 cents on this topic is not to directly pipe the result in gzip but first dump it as a .sql file, and then gzip it. (Use && instead of | )

The dump itself will be faster. (for what I tested it was double as fast)

Otherwise you tables will be locked longer and the downtime/slow-responding of your application can bother the users. The mysqldump command is taking a lot of resources from your server.

So I would go for "&& gzip" instead of "| gzip"

Important: check for free disk space first with df -h since you will need more then piping | gzip.

mysqldump -u user -p[user_password] [database_name] > dumpfilename.sql && gzip dumpfilename.sql

-> which will also result in 1 file called dumpfilename.sql.gz

Furthermore the option --single-transaction prevents the tables being locked but still result in a solid backup. So you might consider to use that option. See docs here

mysqldump --single-transaction -u user -p[user_password] [database_name] > dumpfilename.sql && gzip dumpfilename.sql

How to download a file from my server using SSH (using PuTTY on Windows)

try this scp -r -P2222 [email protected]:/home2/kwazy/www/utrecht-connected.nl /Desktop

Another easier option if you're going to be pulling files left and right is to just use an SFTP client like WinSCP. Then you're not typing out 100 characters every time you want to pull something, just drag and drop.

Edit: Just noticed /Desktop probably isn't where you're looking to download the file to. Should be something like C:\Users\you\Desktop

java.net.MalformedURLException: no protocol on URL based on a string modified with URLEncoder

You want to use URI templates. Look carefully at the README of this project: URLEncoder.encode() does NOT work for URIs.

Let us take your original URL:

http://site-test.test.com/Meetings/IC/DownloadDocument?meetingId=c21c905c-8359-4bd6-b864-844709e05754&itemId=a4b724d1-282e-4b36-9d16-d619a807ba67&file=\s604132shvw140\Test-Documents\c21c905c-8359-4bd6-b864-844709e05754_attachments\7e89c3cb-ce53-4a04-a9ee-1a584e157987\myDoc.pdf

and convert it to a URI template with two variables (on multiple lines for clarity):

http://site-test.test.com/Meetings/IC/DownloadDocument
    ?meetingId={meetingID}&itemId={itemID}&file={file}

Now let us build a variable map with these three variables using the library mentioned in the link:

final VariableMap = VariableMap.newBuilder()
    .addScalarValue("meetingID", "c21c905c-8359-4bd6-b864-844709e05754")
    .addScalarValue("itemID", "a4b724d1-282e-4b36-9d16-d619a807ba67e")
    .addScalarValue("file", "\\\\s604132shvw140\\Test-Documents"
        + "\\c21c905c-8359-4bd6-b864-844709e05754_attachments"
        + "\\7e89c3cb-ce53-4a04-a9ee-1a584e157987\\myDoc.pdf")
    .build();

final URITemplate template
    = new URITemplate("http://site-test.test.com/Meetings/IC/DownloadDocument"
        + "meetingId={meetingID}&itemId={itemID}&file={file}");

// Generate URL as a String
final String theURL = template.expand(vars);

This is GUARANTEED to return a fully functional URL!

Running powershell script within python script, how to make python print the powershell output while it is running

  1. Make sure you can run powershell scripts (it is disabled by default). Likely you have already done this. http://technet.microsoft.com/en-us/library/ee176949.aspx

    Set-ExecutionPolicy RemoteSigned
    
  2. Run this python script on your powershell script helloworld.py:

    # -*- coding: iso-8859-1 -*-
    import subprocess, sys
    
    p = subprocess.Popen(["powershell.exe", 
                  "C:\\Users\\USER\\Desktop\\helloworld.ps1"], 
                  stdout=sys.stdout)
    p.communicate()
    

This code is based on python3.4 (or any 3.x series interpreter), though it should work on python2.x series as well.

C:\Users\MacEwin\Desktop>python helloworld.py
Hello World

Bootstrap 3 .img-responsive images are not responsive inside fieldset in FireFox

Change the img-class responsive to:

.img-responsive, x:-moz-any-link {
display: block;
max-width: 100%;
width: auto;
height: auto;

Best approach to real time http streaming to HTML5 video client

EDIT 3: As of IOS 10, HLS will support fragmented mp4 files. The answer now, is to create fragmented mp4 assets, with a DASH and HLS manifest. > Pretend flash, iOS9 and below and IE 10 and below don't exist.

Everything below this line is out of date. Keeping it here for posterity.


EDIT 2: As people in the comments are pointing out, things change. Almost all browsers will support AVC/AAC codecs. iOS still requires HLS. But via adaptors like hls.js you can play HLS in MSE. The new answer is HLS+hls.js if you need iOS. or just Fragmented MP4 (i.e. DASH) if you don't

There are many reasons why video and, specifically, live video is very difficult. (Please note that the original question specified that HTML5 video is a requirement, but the asker stated Flash is possible in the comments. So immediately, this question is misleading)

First I will restate: THERE IS NO OFFICIAL SUPPORT FOR LIVE STREAMING OVER HTML5. There are hacks, but your mileage may vary.

EDIT: since I wrote this answer Media Source Extensions have matured, and are now very close to becoming a viable option. They are supported on most major browsers. IOS continues to be a hold out.

Next, you need to understand that Video on demand (VOD) and live video are very different. Yes, they are both video, but the problems are different, hence the formats are different. For example, if the clock in your computer runs 1% faster than it should, you will not notice on a VOD. With live video, you will be trying to play video before it happens. If you want to join a a live video stream in progress, you need the data necessary to initialize the decoder, so it must be repeated in the stream, or sent out of band. With VOD, you can read the beginning of the file them seek to whatever point you wish.

Now let's dig in a bit.

Platforms:

  • iOS
  • PC
  • Mac
  • Android

Codecs:

  • vp8/9
  • h.264
  • thora (vp3)

Common Delivery methods for live video in browsers:

  • DASH (HTTP)
  • HLS (HTTP)
  • flash (RTMP)
  • flash (HDS)

Common Delivery methods for VOD in browsers:

  • DASH (HTTP Streaming)
  • HLS (HTTP Streaming)
  • flash (RTMP)
  • flash (HTTP Streaming)
  • MP4 (HTTP pseudo streaming)
  • I'm not going to talk about MKV and OOG because I do not know them very well.

html5 video tag:

  • MP4
  • webm
  • ogg

Lets look at which browsers support what formats

Safari:

  • HLS (iOS and mac only)
  • h.264
  • MP4

Firefox

  • DASH (via MSE but no h.264)
  • h.264 via Flash only!
  • VP9
  • MP4
  • OGG
  • Webm

IE

  • Flash
  • DASH (via MSE IE 11+ only)
  • h.264
  • MP4

Chrome

  • Flash
  • DASH (via MSE)
  • h.264
  • VP9
  • MP4
  • webm
  • ogg

MP4 cannot be used for live video (NOTE: DASH is a superset of MP4, so don't get confused with that). MP4 is broken into two pieces: moov and mdat. mdat contains the raw audio video data. But it is not indexed, so without the moov, it is useless. The moov contains an index of all data in the mdat. But due to its format, it can not be 'flattened' until the timestamps and size of EVERY frame is known. It may be possible to construct an moov that 'fibs' the frame sizes, but is is very wasteful bandwidth wise.

So if you want to deliver everywhere, we need to find the least common denominator. You will see there is no LCD here without resorting to flash example:

  • iOS only supports h.264 video. and it only supports HLS for live.
  • Firefox does not support h.264 at all, unless you use flash
  • Flash does not work in iOS

The closest thing to an LCD is using HLS to get your iOS users, and flash for everyone else. My personal favorite is to encode HLS, then use flash to play HLS for everyone else. You can play HLS in flash via JW player 6, (or write your own HLS to FLV in AS3 like I did)

Soon, the most common way to do this will be HLS on iOS/Mac and DASH via MSE everywhere else (This is what Netflix will be doing soon). But we are still waiting for everyone to upgrade their browsers. You will also likely need a separate DASH/VP9 for Firefox (I know about open264; it sucks. It can't do video in main or high profile. So it is currently useless).

Basic authentication for REST API using spring restTemplate

There are multiple ways to add the basic HTTP authentication to the RestTemplate.

1. For a single request

try {
    // request url
    String url = "https://jsonplaceholder.typicode.com/posts";

    // create auth credentials
    String authStr = "username:password";
    String base64Creds = Base64.getEncoder().encodeToString(authStr.getBytes());

    // create headers
    HttpHeaders headers = new HttpHeaders();
    headers.add("Authorization", "Basic " + base64Creds);

    // create request
    HttpEntity request = new HttpEntity(headers);

    // make a request
    ResponseEntity<String> response = new RestTemplate().exchange(url, HttpMethod.GET, request, String.class);

    // get JSON response
    String json = response.getBody();

} catch (Exception ex) {
    ex.printStackTrace();
}

If you are using Spring 5.1 or higher, it is no longer required to manually set the authorization header. Use headers.setBasicAuth() method instead:

// create headers
HttpHeaders headers = new HttpHeaders();
headers.setBasicAuth("username", "password");

2. For a group of requests

@Service
public class RestService {

    private final RestTemplate restTemplate;

    public RestService(RestTemplateBuilder restTemplateBuilder) {
        this.restTemplate = restTemplateBuilder
                .basicAuthentication("username", "password")
                .build();
    }

   // use `restTemplate` instance here
}

3. For each and every request

@Bean
RestOperations restTemplateBuilder(RestTemplateBuilder restTemplateBuilder) {
    return restTemplateBuilder.basicAuthentication("username", "password").build();
}

I hope it helps!

Share data between AngularJS controllers

As pointed out by @MaNn in one of the comments of the accepted answers, the solution wont work if the page is refreshed.

The Solution for this is to use localStorage or sessionStorage for temporary persistence of the data you want to share across controllers.

  1. Either you make a sessionService whose GET and SET method, encrypts and decrypts the data and reads the data from either localStorage or sessionStorage. So now you use this service directly to read and write the data in the storage via any controller or service you want. This is a open approach and easy one
  2. Else you make a DataSharing Service and use localStorage inside it - so that if the page is refreshed the service will try and check the storage and reply back via the Getters and Setters you have made public or private in this service file.

Excel VBA For Each Worksheet Loop

Try this more succinct code:

Sub LoopOverEachColumn()
    Dim WS As Worksheet
    For Each WS In ThisWorkbook.Worksheets
        ResizeColumns WS
    Next WS
End Sub

Private Sub ResizeColumns(WS As Worksheet)
    Dim StrSize As String
    Dim ColIter As Long
    StrSize = "20.14;9.71;35.86;30.57;23.57;21.43;18.43;23.86;27.43;36.71;30.29;31.14;31;41.14;33.86"
    For ColIter = 1 To 15
        WS.Columns(ColIter).ColumnWidth = Split(StrSize, ";")(ColIter - 1)
    Next ColIter
End Sub

If you want additional columns, just change 1 to 15 to 1 to X where X is the column index of the column you want, and append the column size you want to StrSize.

For example, if you want P:P to have a width of 25, just add ;25 to StrSize and change ColIter... to ColIter = 1 to 16.

Hope this helps.

Installation Issue with matplotlib Python

Problem Cause

In mac os image rendering back end of matplotlib (what-is-a-backend to render using the API of Cocoa by default). There are Qt4Agg and GTKAgg and as a back-end is not the default. Set the back end of macosx that is differ compare with other windows or linux os.

Solution

  • I assume you have installed the pip matplotlib, there is a directory in your root called ~/.matplotlib.
  • Create a file ~/.matplotlib/matplotlibrc there and add the following code: backend: TkAgg

From this link you can try different diagrams.

c++ "Incomplete type not allowed" error accessing class reference information (Circular dependency with forward declaration)

Here is what I had and what caused my "incomplete type error":

#include "X.h" // another already declared class
class Big {...} // full declaration of class A

class Small : Big {
    Small() {}
    Small(X); // line 6
}
//.... all other stuff

What I did in the file "Big.cpp", where I declared the A2's constructor with X as a parameter is..

Big.cpp

Small::Big(X my_x) { // line 9 <--- LOOK at this !
}

I wrote "Small::Big" instead of "Small::Small", what a dumb mistake.. I received the error "incomplete type is now allowed" for the class X all the time (in lines 6 and 9), which made a total confusion..

Anyways, that is where a mistake can happen, and the main reason is that I was tired when I wrote it and I needed 2 hours of exploring and rewriting the code to reveal it.

Parse json string to find and element (key / value)

Use a JSON parser, like JSON.NET

string json = "{ \"Atlantic/Canary\": \"GMT Standard Time\", \"Europe/Lisbon\": \"GMT Standard Time\", \"Antarctica/Mawson\": \"West Asia Standard Time\", \"Etc/GMT+3\": \"SA Eastern Standard Time\", \"Etc/GMT+2\": \"UTC-02\", \"Etc/GMT+1\": \"Cape Verde Standard Time\", \"Etc/GMT+7\": \"US Mountain Standard Time\", \"Etc/GMT+6\": \"Central America Standard Time\", \"Etc/GMT+5\": \"SA Pacific Standard Time\", \"Etc/GMT+4\": \"SA Western Standard Time\", \"Pacific/Wallis\": \"UTC+12\", \"Europe/Skopje\": \"Central European Standard Time\", \"America/Coral_Harbour\": \"SA Pacific Standard Time\", \"Asia/Dhaka\": \"Bangladesh Standard Time\", \"America/St_Lucia\": \"SA Western Standard Time\", \"Asia/Kashgar\": \"China Standard Time\", \"America/Phoenix\": \"US Mountain Standard Time\", \"Asia/Kuwait\": \"Arab Standard Time\" }";
var data = (JObject)JsonConvert.DeserializeObject(json);
string timeZone = data["Atlantic/Canary"].Value<string>();

Error: [ng:areq] from angular controller

I ran into this issue when I had defined the module in the Angular controller but neglected to set the app name in my HTML file. For example:

<html ng-app>

instead of the correct:

<html ng-app="myApp">

when I had defined something like:

angular.module('myApp', []).controller(...

and referenced it in my HTML file.

Java Object Null Check for method

Inside your for-loop, just add the following line:

if(books[i] != null) {
     total += books[i].getPrice();
}

Difference between two numpy arrays in python

This is pretty simple with numpy, just subtract the arrays:

diffs = array1 - array2

I get:

diffs == array([ 0.1,  0.2,  0.3])

Python equivalent to 'hold on' in Matlab

Just call plt.show() at the end:

import numpy as np
import matplotlib.pyplot as plt

plt.axis([0,50,60,80])
for i in np.arange(1,5):
    z = 68 + 4 * np.random.randn(50)
    zm = np.cumsum(z) / range(1,len(z)+1)
    plt.plot(zm)    

n = np.arange(1,51)
su = 68 + 4 / np.sqrt(n)
sl = 68 - 4 / np.sqrt(n)

plt.plot(n,su,n,sl)

plt.show()

how to get current location in google map android

Add the permissions to the app manifest

Add one of the following permissions as a child of the element in your Android manifest. Either the coarse location permission:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.myapp" >
  ...
  <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
  ...
</manifest>

Or the fine location permission:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.myapp" >
  ...
  <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
  ...
</manifest>

The following code sample checks for permission using the Support library before enabling the My Location layer:

if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
                == PackageManager.PERMISSION_GRANTED) {
    mMap.setMyLocationEnabled(true);
} else {
    // Show rationale and request permission.
}
The following sample handles the result of the permission request by implementing the ActivityCompat.OnRequestPermissionsResultCallback from the Support library:

@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
    if (requestCode == MY_LOCATION_REQUEST_CODE) {
      if (permissions.length == 1 &&
          permissions[0] == Manifest.permission.ACCESS_FINE_LOCATION &&
          grantResults[0] == PackageManager.PERMISSION_GRANTED) {
        mMap.setMyLocationEnabled(true);
    } else {
      // Permission was denied. Display an error message.
    }
}

This example provides current location update using GPS provider. Entire Android app code is as follows,

import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.widget.TextView;

import android.util.Log;

public class MainActivity extends Activity implements LocationListener{
protected LocationManager locationManager;
protected LocationListener locationListener;
protected Context context;
TextView txtLat;
String lat;
String provider;
protected String latitude,longitude; 
protected boolean gps_enabled,network_enabled;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtLat = (TextView) findViewById(R.id.textview1);

locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
}
@Override
public void onLocationChanged(Location location) {
txtLat = (TextView) findViewById(R.id.textview1);
txtLat.setText("Latitude:" + location.getLatitude() + ", Longitude:" + location.getLongitude());
}

@Override
public void onProviderDisabled(String provider) {
Log.d("Latitude","disable");
}

@Override
public void onProviderEnabled(String provider) {
Log.d("Latitude","enable");
}

@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
Log.d("Latitude","status");
}
}

datetime dtypes in pandas read_csv

I tried using the dtypes=[datetime, ...] option, but

import pandas as pd
from datetime import datetime
headers = ['col1', 'col2', 'col3', 'col4'] 
dtypes = [datetime, datetime, str, float] 
pd.read_csv(file, sep='\t', header=None, names=headers, dtype=dtypes)

I encountered the following error:

TypeError: data type not understood

The only change I had to make is to replace datetime with datetime.datetime

import pandas as pd
from datetime import datetime
headers = ['col1', 'col2', 'col3', 'col4'] 
dtypes = [datetime.datetime, datetime.datetime, str, float] 
pd.read_csv(file, sep='\t', header=None, names=headers, dtype=dtypes)

How to list AD group membership for AD users using input list?

Or add "sort name" to list alphabetically

Get-ADPrincipalGroupMembership username | select name | sort name

Uncaught ReferenceError: $ is not defined error in jQuery

Include the jQuery file first:

 <script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
 <script type="text/javascript" src="./javascript.js"></script>
    <script
        src="http://maps.googleapis.com/maps/api/js?key=AIzaSyCJnj2nWoM86eU8Bq2G4lSNz3udIkZT4YY&sensor=false">
    </script>

Eclipse/Maven error: "No compiler is provided in this environment"

Maven requires JDK to compile. In Eclipse you need to CHANGE/ REPLACE your JRE to the JDK path that your JAVA_HOME points to. Navigate to Window > Preferences > Java > Installed JREs.

Make sure that the maven-compiler-plugin in you pom.xml has the source and target of the java version in your JAVA_HOME

http://learn-automation.com/maven-no-compiler-is-provided-in-this-environment-selenium/

Why won't bundler install JSON gem?

bundle update json. Helped to get through.

Attempt to write a readonly database - Django w/ SELinux error

You can change acls without touching the ownership and permissions of file/directory.

Use the following commands:

setfacl -m u:www-data:rwx /home/user/website
setfacl -m u:www-data:rw /home/user/website/db.sqlite3

Responsive bootstrap 3 timepicker?

As an update to the OP's question, I can confirm that the timepicker found at http://jdewit.github.io/bootstrap-timepicker/ does in fact work with Bootstrap 3 now with no problems at all.

Regular expression to search multiple strings (Textpad)

I suggest much better solution. Task in my case: add http://google.com/ path before each record and import multiple fields.

CSV single field value (all images just have filenames, separate by |):
"123.jpg|345.jpg|567.jpg"

Tamper 1st plugin: find and replace by REGEXP: pattern: /([a-zA-Z0-9]*)./ replacement: http://google.com/$1

Tamper 2nd plugin: explode setting: explode by |

In this case you don't need any additinal fields mappings and can use 1 field in CSV

Python conversion between coordinates

Thinking about it in general, I would strongly consider hiding coordinate system behind well-designed abstraction. Quoting Uncle Bob and his book:

class Point(object)
    def setCartesian(self, x, y)
    def setPolar(self, rho, theta)
    def getX(self)
    def getY(self)
    def getRho(self)
    def setTheta(self)

With interface like that any user of Point class may choose convenient representation, no explicit conversions will be performed. All this ugly sines, cosines etc. will be hidden in one place. Point class. Only place where you should care which representation is used in computer memory.

Laravel Eloquent get results grouped by days

You can use Carbon (integrated in Laravel)

// Carbon
use Carbon\Carbon;   
$visitorTraffic = PageView::select('id', 'title', 'created_at')
    ->get()
    ->groupBy(function($date) {
        return Carbon::parse($date->created_at)->format('Y'); // grouping by years
        //return Carbon::parse($date->created_at)->format('m'); // grouping by months
    });

No Main class found in NetBeans

Make sure the access modifier is public and not private. I keep having this problem and always that's my issue.

public static void main(String[] args)

How to fix Uncaught InvalidValueError: setPosition: not a LatLng or LatLngLiteral: in property lat: not a number?

I was having the same problem, the fact is that the input of lat and long should be String. Only then did I manage.

for example:

Controller.

 ViewBag.Lat = object.Lat.ToString().Replace(",", ".");

 ViewBag.Lng = object.Lng.ToString().Replace(",", ".");

View - function javascript

<script>
    function initMap() {
        var myLatLng = { lat: @ViewBag.Lat, lng: @ViewBag.Lng};

        // Create a map object and specify the DOM element for display.
        var map = new window.google.maps.Map(document.getElementById('map'),
        {
            center: myLatLng,
            scrollwheel: false,
            zoom: 16
        });

        // Create a marker and set its position.
        var marker = new window.google.maps.Marker({
            map: map,
            position: myLatLng
            //title: "Blue"
        });
    }
</script>

I convert the double value to string and do a Replace in the ',' to '.' And so everything works normally.

Play audio as microphone input

Just as there are printer drivers that do not connect to a printer at all but rather write to a PDF file, analogously there are virtual audio drivers available that do not connect to a physical microphone at all but can pipe input from other sources such as files or other programs.

I hope I'm not breaking any rules by recommending free/donation software, but VB-Audio Virtual Cable should let you create a pair of virtual input and output audio devices. Then you could play an MP3 into the virtual output device and then set the virtual input device as your "microphone". In theory I think that should work.

If all else fails, you could always roll your own virtual audio driver. Microsoft provides some sample code but unfortunately it is not applicable to the older Windows XP audio model. There is probably sample code available for XP too.

Selenium WebDriver can't find element by link text

Use xpath and text()

driver.findElement(By.Xpath("//strong[contains(text(),'" + service +"')]"));

Submit button not working in Bootstrap form

The .btn classes are designed for , or elements (though some browsers may apply a slightly different rendering).

If you’re using .btn classes on elements that are used to trigger functionality ex. collapsing content, these links should be given a role="button" to adequately communicate their meaning to assistive technologies such as screen readers. I hope this help.

How can I access getSupportFragmentManager() in a fragment?

You can use getActivity().getSupportFragmentManager() anytime you want to getSupportFragmentManager.

hierarchy is Activity -> fragment. fragment is not capable of directly calling getSupportFragmentManger but Activity can . Thus, you can use getActivity to call the current activity which the fragment is in and get getSupportFragmentManager()

How to check version of python modules?

Some modules don't have __version__ attribute, so the easiest way is check in the terminal: pip list

Is it possible to 'prefill' a google form using data from a google spreadsheet?

You can create a pre-filled form URL from within the Form Editor, as described in the documentation for Drive Forms. You'll end up with a URL like this, for example:

https://docs.google.com/forms/d/--form-id--/viewform?entry.726721210=Mike+Jones&entry.787184751=1975-05-09&entry.1381372492&entry.960923899

buildUrls()

In this example, question 1, "Name", has an ID of 726721210, while question 2, "Birthday" is 787184751. Questions 3 and 4 are blank.

You could generate the pre-filled URL by adapting the one provided through the UI to be a template, like this:

function buildUrls() {
  var template = "https://docs.google.com/forms/d/--form-id--/viewform?entry.726721210=##Name##&entry.787184751=##Birthday##&entry.1381372492&entry.960923899";
  var ss = SpreadsheetApp.getActive().getSheetByName("Sheet1");  // Email, Name, Birthday
  var data = ss.getDataRange().getValues();

  // Skip headers, then build URLs for each row in Sheet1.
  for (var i = 1; i < data.length; i++ ) {
    var url = template.replace('##Name##',escape(data[i][1]))
                      .replace('##Birthday##',data[i][2].yyyymmdd());  // see yyyymmdd below
    Logger.log(url);  // You could do something more useful here.
  }
};

This is effective enough - you could email the pre-filled URL to each person, and they'd have some questions already filled in.

betterBuildUrls()

Instead of creating our template using brute force, we can piece it together programmatically. This will have the advantage that we can re-use the code without needing to remember to change the template.

Each question in a form is an item. For this example, let's assume the form has only 4 questions, as you've described them. Item [0] is "Name", [1] is "Birthday", and so on.

We can create a form response, which we won't submit - instead, we'll partially complete the form, only to get the pre-filled form URL. Since the Forms API understands the data types of each item, we can avoid manipulating the string format of dates and other types, which simplifies our code somewhat.

(EDIT: There's a more general version of this in How to prefill Google form checkboxes?)

/**
 * Use Form API to generate pre-filled form URLs
 */
function betterBuildUrls() {
  var ss = SpreadsheetApp.getActive();
  var sheet = ss.getSheetByName("Sheet1");
  var data = ss.getDataRange().getValues();  // Data for pre-fill

  var formUrl = ss.getFormUrl();             // Use form attached to sheet
  var form = FormApp.openByUrl(formUrl);
  var items = form.getItems();

  // Skip headers, then build URLs for each row in Sheet1.
  for (var i = 1; i < data.length; i++ ) {
    // Create a form response object, and prefill it
    var formResponse = form.createResponse();

    // Prefill Name
    var formItem = items[0].asTextItem();
    var response = formItem.createResponse(data[i][1]);
    formResponse.withItemResponse(response);

    // Prefill Birthday
    formItem = items[1].asDateItem();
    response = formItem.createResponse(data[i][2]);
    formResponse.withItemResponse(response);

    // Get prefilled form URL
    var url = formResponse.toPrefilledUrl();
    Logger.log(url);  // You could do something more useful here.
  }
};

yymmdd Function

Any date item in the pre-filled form URL is expected to be in this format: yyyy-mm-dd. This helper function extends the Date object with a new method to handle the conversion.

When reading dates from a spreadsheet, you'll end up with a javascript Date object, as long as the format of the data is recognizable as a date. (Your example is not recognizable, so instead of May 9th 1975 you could use 5/9/1975.)

// From http://blog.justin.kelly.org.au/simple-javascript-function-to-format-the-date-as-yyyy-mm-dd/
Date.prototype.yyyymmdd = function() {
  var yyyy = this.getFullYear().toString();                                    
  var mm = (this.getMonth()+1).toString(); // getMonth() is zero-based         
  var dd  = this.getDate().toString();             

  return yyyy + '-' + (mm[1]?mm:"0"+mm[0]) + '-' + (dd[1]?dd:"0"+dd[0]);
};

A completely free agile software process tool

One possibility would be to use a Google Drawing, part of Google Drive, if you want a more visual and easy-to-edit option. You can create the cards by grouping a color-filled rectangle and one or more text fields together. Being a sufficiently free-form online vector drawing program, it doesn't really limit your possibilities like if you use a more dedicated solution.

The only real downsides are that you have to first create the building blocks from the beginning, and don't get numerical statistics like with a more structured tool.

MVC Form not able to post List of objects

Please read this: http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx
You should set indicies for your html elements "name" attributes like planCompareViewModel[0].PlanId, planCompareViewModel[1].PlanId to make binder able to parse them into IEnumerable.
Instead of @foreach (var planVM in Model) use for loop and render names with indexes.

install beautiful soup using pip

The easy method that will work even in corrupted setup environment is :

To download ez_setup.py and run it using command line

python ez_setup.py

output

Extracting in c:\uu\uu\appdata\local\temp\tmpjxvil3 Now working in c:\u\u\appdata\local\temp\tmpjxvil3\setuptools-5.6 Installing Setuptools

run

pip install beautifulsoup4

output

Downloading/unpacking beautifulsoup4 Running setup.py ... egg_info for package Installing collected packages: beautifulsoup4 Running setup.py install for beautifulsoup4 Successfully installed beautifulsoup4 Cleaning up...

Bam ! |Done¬

java.net.UnknownHostException: Unable to resolve host "<url>": No address associated with hostname and End of input at character 0 of

I encountered this error when running my Android app on my home WiFi, then trying to run it on different WiFi without closing my simulator.

Simply closing the simulator and re-launching the app worked for me!

How to store command results in a shell variable?

The syntax to store the command output into a variable is var=$(command).

So you can directly do:

result=$(ls -l | grep -c "rahul.*patle")

And the variable $result will contain the number of matches.

How can I parse a local JSON file from assets folder into a ListView?

As Faizan describes in their answer here:

First of all read the Json File from your assests file using below code.

and then you can simply read this string return by this function as

public String loadJSONFromAsset() {
    String json = null;
    try {
        InputStream is = getActivity().getAssets().open("yourfilename.json");
        int size = is.available();
        byte[] buffer = new byte[size];
        is.read(buffer);
        is.close();
        json = new String(buffer, "UTF-8");
    } catch (IOException ex) {
        ex.printStackTrace();
        return null;
    }
    return json;
}

and use this method like that

    try {
        JSONObject obj = new JSONObject(loadJSONFromAsset());
        JSONArray m_jArry = obj.getJSONArray("formules");
        ArrayList<HashMap<String, String>> formList = new ArrayList<HashMap<String, String>>();
        HashMap<String, String> m_li;

        for (int i = 0; i < m_jArry.length(); i++) {
            JSONObject jo_inside = m_jArry.getJSONObject(i);
            Log.d("Details-->", jo_inside.getString("formule"));
            String formula_value = jo_inside.getString("formule");
            String url_value = jo_inside.getString("url");

            //Add your values in your `ArrayList` as below:
            m_li = new HashMap<String, String>();
            m_li.put("formule", formula_value);
            m_li.put("url", url_value);

            formList.add(m_li);
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }

For further details regarding JSON Read HERE

Bootstrap 3 : Vertically Center Navigation Links when Logo Increasing The Height of Navbar

I actually ended up with something like this to allow for the navbar collapse.

@media (min-width: 768px) { //set this to wherever the navbar collapse executes
  .navbar-nav > li > a{
    line-height: 7em; //set this height to the height of the logo.
  }
}

How to store a datetime in MySQL with timezone info

I once also faced such an issue where i needed to save data which was used by different collaborators and i ended up storing the time in unix timestamp form which represents the number of seconds since january 1970 which is an integer format. Example todays date and time in tanzania is Friday, September 13, 2019 9:44:01 PM which when store in unix timestamp would be 1568400241

Now when reading the data simply use something like php or any other language and extract the date from the unix timestamp. An example with php will be

echo date('m/d/Y', 1568400241);

This makes it easier even to store data with other collaborators in different locations. They can simply convert the date to unix timestamp with their own gmt offset and store it in a integer format and when outputting this simply convert with a

laravel throwing MethodNotAllowedHttpException

The problem is the you are using POST but actually you have to perform PATCH To fix this add

<input name="_method" type="hidden" value="PATCH">

Just after the Form::model line

Get data from JSON file with PHP

Use json_decode to transform your JSON into a PHP array. Example:

$json = '{"a":"b"}';
$array = json_decode($json, true);
echo $array['a']; // b

Representing Directory & File Structure in Markdown Syntax

You can use tree to generate something very similar to your example. Once you have the output, you can wrap it in a <pre> tag to preserve the plain text formatting.

Amazon AWS Filezilla transfer permission denied

In my case, after 30 minutes changing permissions, got into account that the XLSX file I was trying to transfer was still open in Excel.

Multiple markers Google Map API v3 from array of addresses and avoid OVER_QUERY_LIMIT while geocoding on pageLoad

Here is my solution:

dependencies: Gmaps.js, jQuery

var Maps = function($) {
   var lost_addresses = [],
       geocode_count  = 0;

   var addMarker = function() { console.log('Marker Added!') };

   return {
     getGecodeFor: function(addresses) {
        var latlng;
        lost_addresses = [];
        for(i=0;i<addresses.length;i++) {
          GMaps.geocode({
            address: addresses[i],
            callback: function(response, status) {
              if(status == google.maps.GeocoderStatus.OK) {
                addMarker();
              } else if(status == google.maps.GeocoderStatus.OVER_QUERY_LIMIT) {
                lost_addresses.push(addresses[i]);
              }

               geocode_count++;
               // notify listeners when the geocode is done
               if(geocode_count == addresses.length) {
                 $.event.trigger({ type: 'done:geocoder' });
               }
            }
          });
        }
     },
     processLostAddresses: function() {
       if(lost_addresses.length > 0) {
         this.getGeocodeFor(lost_addresses);
       }
     }
   };
}(jQuery);

Maps.getGeocodeFor(address);

// listen to done:geocode event and process the lost addresses after 1.5s
$(document).on('done:geocode', function() {
  setTimeout(function() {
    Maps.processLostAddresses();
  }, 1500);
});

CASE WHEN statement for ORDER BY clause

Another simple example from here..

SELECT * FROM dbo.Employee
ORDER BY 
 CASE WHEN Gender='Male' THEN EmployeeName END Desc,
 CASE WHEN Gender='Female' THEN Country END ASC

How to get correlation of two vectors in python

The docs indicate that numpy.correlate is not what you are looking for:

numpy.correlate(a, v, mode='valid', old_behavior=False)[source]
  Cross-correlation of two 1-dimensional sequences.
  This function computes the correlation as generally defined in signal processing texts:
     z[k] = sum_n a[n] * conj(v[n+k])
  with a and v sequences being zero-padded where necessary and conj being the conjugate.

Instead, as the other comments suggested, you are looking for a Pearson correlation coefficient. To do this with scipy try:

from scipy.stats.stats import pearsonr   
a = [1,4,6]
b = [1,2,3]   
print pearsonr(a,b)

This gives

(0.99339926779878274, 0.073186395040328034)

You can also use numpy.corrcoef:

import numpy
print numpy.corrcoef(a,b)

This gives:

[[ 1.          0.99339927]
 [ 0.99339927  1.        ]]

TypeError: can only concatenate list (not "str") to list

You can use:

newinv=inventory+[add]

but using append is better since it doesn't create a new list:

inventory.append(add)

Center/Set Zoom of Map to cover all visible Markers?

The size of array must be greater than zero. ?therwise you will have unexpected results.

function zoomeExtends(){
  var bounds = new google.maps.LatLngBounds();
  if (markers.length>0) { 
      for (var i = 0; i < markers.length; i++) {
         bounds.extend(markers[i].getPosition());
        }    
        myMap.fitBounds(bounds);
    }
}

Printing out a linked list using toString

I do it the following way:

public static void main(String[] args) {

    LinkedList list = new LinkedList();
    list.insertFront(1);
    list.insertFront(2);
    list.insertFront(3);
    System.out.println(list.toString());
}

String toString() {
    StringBuilder result = new StringBuilder();
    for(Object item:this) {
        result.append(item.toString());
        result.append("\n"); //optional
    }
    return result.toString();
}

How to change icon on Google map marker

var marker = new google.maps.Marker({
  position: myLatLng,
  map: map,
  icon: 'your-icon.png'
});

MySQL error #1054 - Unknown column in 'Field List'

I had this error aswell.

I am working in mysql workbench. When giving the values they have to be inside "". That solved it for me.

Import-Module : The specified module 'activedirectory' was not loaded because no valid module file was found in any module directory

The ActiveDirectory module for powershell can be installed by adding the RSAT-AD-Powershell feature.

In an elevated powershell window:

Add-WindowsFeature RSAT-AD-PowerShell

or

Enable-WindowsOptionalFeature -FeatureName ActiveDirectory-Powershell -Online -All

jQuery add required to input fields

You can do it by using attr, the mistake that you made is that you put the true inside quotes. instead of that try this:

$("input").attr("required", true);

Adding custom radio buttons in android

Setting android:background and android:button of the RadioButton like the accepted answer didn't work for me. The drawable image was being displayed as a background(eventhough android:button was being set to transparent ) to the radio button text as enter image description here

android:background="@drawable/radiobuttonstyle"
    android:button="@android:color/transparent"

so gave radiobutton as the custom drawable radiobuttonstyle.xml

<RadioButton
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:checked="true"
    android:text="Maintenance"
    android:id="@+id/radioButton1"
    android:button="@drawable/radiobuttonstyle"
      />

and radiobuttonstyle.xml is as follows

<?xml version="1.0" encoding="utf-8" ?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
  <item android:state_checked="true" android:drawable="@drawable/ic_radio_checked"></item>
  <item android:state_checked="false" android:drawable="@drawable/ic_radio_unchecked"></item>
</selector>

and after this radiobutton with custom button style worked.

enter image description here

CSS float right not working correctly

Verry Easy, change order of element:

Origin

<div style="">

    My Text

    <button type="button" style="float: right; margin:5px;">
       My Button
    </button>

</div>

Change to:

<div style=""> 

    <button type="button" style="float: right; margin:5px;">
       My Button
     </button>

   My Text

</div>

jquery.ajax Access-Control-Allow-Origin

http://encosia.com/using-cors-to-access-asp-net-services-across-domains/

refer the above link for more details on Cross domain resource sharing.

you can try using JSONP . If the API is not supporting jsonp, you have to create a service which acts as a middleman between the API and your client. In my case, i have created a asmx service.

sample below:

ajax call:

$(document).ready(function () {
        $.ajax({
            crossDomain: true,
            type:"GET",
            contentType: "application/json; charset=utf-8",
            async:false,
            url: "<your middle man service url here>/GetQuote?callback=?",
            data: { symbol: 'ctsh' },
            dataType: "jsonp",                
            jsonpCallback: 'fnsuccesscallback'
        });
    });

service (asmx) which will return jsonp:

[WebMethod]
    [ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
    public void GetQuote(String symbol,string callback)
    {          

        WebProxy myProxy = new WebProxy("<proxy url here>", true);

        myProxy.Credentials = new System.Net.NetworkCredential("username", "password", "domain");
        StockQuoteProxy.StockQuote SQ = new StockQuoteProxy.StockQuote();
        SQ.Proxy = myProxy;
        String result = SQ.GetQuote(symbol);
        StringBuilder sb = new StringBuilder();
        JavaScriptSerializer js = new JavaScriptSerializer();
        sb.Append(callback + "(");
        sb.Append(js.Serialize(result));
        sb.Append(");");
        Context.Response.Clear();
        Context.Response.ContentType = "application/json";
        Context.Response.Write(sb.ToString());
        Context.Response.End();         
    }

Reading JSON POST using PHP

Hello this is a snippet from an old project of mine that uses curl to get ip information from some free ip databases services which reply in json format. I think it might help you.

$ip_srv = array("http://freegeoip.net/json/$this->ip","http://smart-ip.net/geoip-json/$this->ip");

getUserLocation($ip_srv);

Function:

function getUserLocation($services) {

        $ctx = stream_context_create(array('http' => array('timeout' => 15))); // 15 seconds timeout

        for ($i = 0; $i < count($services); $i++) {

            // Configuring curl options
            $options = array (
                CURLOPT_RETURNTRANSFER => true, // return web page
                //CURLOPT_HEADER => false, // don't return headers
                CURLOPT_HTTPHEADER => array('Content-type: application/json'),
                CURLOPT_FOLLOWLOCATION => true, // follow redirects
                CURLOPT_ENCODING => "", // handle compressed
                CURLOPT_USERAGENT => "test", // who am i
                CURLOPT_AUTOREFERER => true, // set referer on redirect
                CURLOPT_CONNECTTIMEOUT => 5, // timeout on connect
                CURLOPT_TIMEOUT => 5, // timeout on response
                CURLOPT_MAXREDIRS => 10 // stop after 10 redirects
            ); 

            // Initializing curl
            $ch = curl_init($services[$i]);
            curl_setopt_array ( $ch, $options );

            $content = curl_exec ( $ch );
            $err = curl_errno ( $ch );
            $errmsg = curl_error ( $ch );
            $header = curl_getinfo ( $ch );
            $httpCode = curl_getinfo ( $ch, CURLINFO_HTTP_CODE );

            curl_close ( $ch );

            //echo 'service: ' . $services[$i] . '</br>';
            //echo 'err: '.$err.'</br>';
            //echo 'errmsg: '.$errmsg.'</br>';
            //echo 'httpCode: '.$httpCode.'</br>';
            //print_r($header);
            //print_r(json_decode($content, true));

            if ($err == 0 && $httpCode == 200 && $header['download_content_length'] > 0) {

                return json_decode($content, true);

            } 

        }
    }

Function to calculate distance between two coordinates

I have written the function to find distance between two coordinates. It will return distance in meter.

 function findDistance() {
   var R = 6371e3; // R is earth’s radius
   var lat1 = 23.18489670753479; // starting point lat
   var lat2 = 32.726601;         // ending point lat
   var lon1 = 72.62524545192719; // starting point lon
   var lon2 = 74.857025;         // ending point lon
   var lat1radians = toRadians(lat1);
   var lat2radians = toRadians(lat2);

   var latRadians = toRadians(lat2-lat1);
   var lonRadians = toRadians(lon2-lon1);

   var a = Math.sin(latRadians/2) * Math.sin(latRadians/2) +
        Math.cos(lat1radians) * Math.cos(lat2radians) *
        Math.sin(lonRadians/2) * Math.sin(lonRadians/2);
   var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));

   var d = R * c;

   console.log(d)
}

function toRadians(val){
    var PI = 3.1415926535;
    return val / 180.0 * PI;
}

Return the characters after Nth character in a string

If your numbers are always 4 digits long:

=RIGHT(A1,LEN(A1)-5) //'0001 Baseball' returns Baseball

If the numbers are variable (i.e. could be more or less than 4 digits) then:

=RIGHT(A1,LEN(A1)-FIND(" ",A1,1)) //'123456 Baseball’ returns Baseball

Undefined Symbols for architecture x86_64: Compiling problems

There's no mystery here, the linker is telling you that you haven't defined the missing symbols, and you haven't.

Similarity::Similarity() or Similarity::~Similarity() are just missing and you have defined the others incorrectly,

void Similarity::readData(Scanner& inStream){
}

not

void readData(Scanner& inStream){
}

etc. etc.

The second one is a function called readData, only the first is the readData method of the Similarity class.

To be clear about this, in Similarity.h

void readData(Scanner& inStream);

but in Similarity.cpp

void Similarity::readData(Scanner& inStream){
}

VBA setting the formula for a cell

Try:

.Formula = "='" & strProjectName & "'!" & Cells(2, 7).Address

If your worksheet name (strProjectName) has spaces, you need to include the single quotes in the formula string.

If this does not resolve it, please provide more information about the specific error or failure.

Update

In comments you indicate you're replacing spaces with underscores. Perhaps you are doing something like:

strProjectName = Replace(strProjectName," ", "_")

But if you're not also pushing that change to the Worksheet.Name property, you can expect these to happen:

  1. The file browse dialog appears
  2. The formula returns #REF error

The reason for both is that you are passing a reference to a worksheet that doesn't exist, which is why you get the #REF error. The file dialog is an attempt to let you correct that reference, by pointing to a file wherein that sheet name does exist. When you cancel out, the #REF error is expected.

So you need to do:

Worksheets(strProjectName).Name = Replace(strProjectName," ", "_")
strProjectName = Replace(strProjectName," ", "_")

Then, your formula should work.

IIS error, Unable to start debugging on the webserver

go to Search > type services.msc and make sure that ASP.Net State Service is running.

Auto-click button element on page load using jQuery

We should rather use Javascript.

    <button href="images/car.jpg" id="myButton">
        Here is the Button to be clicked
    </button>


    <script>

        $(document).ready(function(){
            document.getElementById("myButton").click();
        });

    </script>

Trouble Connecting to sql server Login failed. "The login is from an untrusted domain and cannot be used with Windows authentication"

If you using windows authentication make sure that password of the user hasn't expired. An expired password can explain this error. This was the problem in my case.

html form - make inputs appear on the same line

You can wrap the following in a DIV:

<div class="your-class">

  <label for="First_Name">First Name:</label>
  <input name="first_name" id="First_Name" type="text" />
  <label for="Name">Last Name:</label>
  <input name="last_name" id="Last_Name" type="text" /> 

</div>

Give each input float:left in your CSS:

.your-class input{
  float:left;
}

example only

You might have to adjust margins.

Remember to apply clear:left or both to whatever comes after ".your-class"

Installing and Running MongoDB on OSX

Download MongoDB and install it on your local machine. Link https://www.mongodb.com/try/download/enterprise

Extract the file and put it on the desktop. Create another folder where you want to store the data. I have created mongodb-data folder. Then run the below command.

Desktop/mongodb/bin/mongod --dbpath=/Users/yourname/Desktop/mongodb-data/

Before the hyphen is the executable path of your mongoDB and after hyphen is your data store.

Google maps responsive resize

After few years, I moved to leaflet map and I have fixed this issue completely, the following could be applied to google maps too:

    var headerHeight = $("#navMap").outerHeight();
    var footerHeight = $("footer").outerHeight();
    var windowHeight = window.innerHeight;
    var mapContainerHeight = headerHeight + footerHeight;
    var totalMapHeight = windowHeight - mapContainerHeight;
    $("#map").css("margin-top", headerHeight);
    $("#map").height(totalMapHeight);

    $(window).resize(function(){
        var headerHeight = $("#navMap").outerHeight();
        var footerHeight = $("footer").outerHeight();
        var windowHeight = window.innerHeight;
        var mapContainerHeight = headerHeight + footerHeight;
        var totalMapHeight = windowHeight - mapContainerHeight;
        $("#map").css("margin-top", headerHeight);
        $("#map").height(totalMapHeight);
        map.fitBounds(group1.getBounds());
    });

Easiest way to make lua script wait/pause/sleep/block for a few seconds?

I agree with John on wrapping the sleep function. You could also use this wrapped sleep function to implement a pause function in lua (which would simply sleep then check to see if a certain condition has changed every so often). An alternative is to use hooks.

I'm not exactly sure what you mean with your third bulletpoint (don't commands usually complete before the next is executed?) but hooks may be able to help with this also.

See: Question: How can I end a Lua thread cleanly? for an example of using hooks.

Why did I get the compile error "Use of unassigned local variable"?

The following categories of variables are classified as initially unassigned:

  • Instance variables of initially unassigned struct variables.
  • Output parameters, including the this variable of struct instance constructors.
  • Local variables , except those declared in a catch clause or a foreach statement.

The following categories of variables are classified as initially assigned:

  • Static variables.
  • Instance variables of class instances.
  • Instance variables of initially assigned struct variables.
  • Array elements.
  • Value parameters.
  • Reference parameters.
  • Variables declared in a catch clause or a foreach statement.

How to get the CUDA version?

You could also use:

nvidia-smi | grep "CUDA Version:" 

To retrieve the explicit line.

Adding quotes to a string in VBScript

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

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

Frequency table for a single variable

Maybe .value_counts()?

>>> import pandas
>>> my_series = pandas.Series([1,2,2,3,3,3, "fred", 1.8, 1.8])
>>> my_series
0       1
1       2
2       2
3       3
4       3
5       3
6    fred
7     1.8
8     1.8
>>> counts = my_series.value_counts()
>>> counts
3       3
2       2
1.8     2
fred    1
1       1
>>> len(counts)
5
>>> sum(counts)
9
>>> counts["fred"]
1
>>> dict(counts)
{1.8: 2, 2: 2, 3: 3, 1: 1, 'fred': 1}

"Content is not allowed in prolog" when parsing perfectly valid XML on GAE

In the spirit of "just delete all those weird characters before the <?xml", here's my Java code, which works well with input via a BufferedReader:

    BufferedReader test = new BufferedReader(new InputStreamReader(fisTest));
    test.mark(4);
    while (true) {
        int earlyChar = test.read();
        System.out.println(earlyChar);
        if (earlyChar == 60) {
            test.reset();
            break;
        } else {
            test.mark(4);
        }
    }

FWIW, the bytes I was seeing are (in decimal): 239, 187, 191.

matplotlib set yaxis label size

If you are using the 'pylab' for interactive plotting you can set the labelsize at creation time with pylab.ylabel('Example', fontsize=40).

If you use pyplot programmatically you can either set the fontsize on creation with ax.set_ylabel('Example', fontsize=40) or afterwards with ax.yaxis.label.set_size(40).

java.lang.UnsatisfiedLinkError no *****.dll in java.library.path

  1. If you believe that you added a path of native lib to %PATH%, try testing with:

    System.out.println(System.getProperty("java.library.path"))
    

It should show you actually if your dll is on %PATH%

  1. Restart the IDE Idea, which appeared to work for me after I setup the env variable by adding it to the %PATH%

How to unapply a migration in ASP.NET Core with EF Core

To revert all the migrations which are applied to DB simply run:

update-database 0

It should be followed with running Remove-Migration as many times as there are migration files visible in the Migration directory. The command deletes the latest migration and also updates the snapshot.

How to execute the start script with Nodemon

This will be a simple command for this

nodemon --exec npm start

How to delete file from public folder in laravel 5.1

Its a very old thread, but I don't see that the solution is here or the this thread is marked as solved. I have also stuck into the same problem I solved it like this

  $path = public_path('../storage/YOUR_FOLDER_NAME/YOUR_FILE_NAME');
  if (!File::exists($path)) 
  {
    File::delete(public_path('storage/YOUR_FOLDER_NAME/YOUR_FILE_NAME'));
  }

The key is that you need to remove '..' from the delete method. Keep in mind that this goes true if you are using Storage as well, whether you are using Storage of File don't for get to use them like

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use File; // For File
use Storage; // For Storage

Hope that it will help someone.

ipython notebook clear cell output in code

You can use the IPython.display.clear_output to clear the output as mentioned in cel's answer. I would add that for me the best solution was to use this combination of parameters to print without any "shakiness" of the notebook:

from IPython.display import clear_output

for i in range(10):
    clear_output(wait=True)
    print(i, flush=True)

Do you (really) write exception safe code?

Leaving aside the confusion between SEH and C++ exceptions, you need to be aware that exceptions can be thrown at any time, and write your code with that in mind. The need for exception-safety is largely what drives the use of RAII, smart pointers, and other modern C++ techniques.

If you follow the well-established patterns, writing exception-safe code is not particularly hard, and in fact it's easier than writing code that handles error returns properly in all cases.

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

Why does fatal error "LNK1104: cannot open file 'C:\Program.obj'" occur when I compile a C++ project in Visual Studio?

For an assembly project (ProjectName -> Build Dependencies -> Build Customizations -> masm (selected)), setting Generate Preprocessed Source Listing to True caused the problem for me too, clearing the setting fixed it. VS2013 here.

How to run a PowerShell script

If you are on PowerShell 2.0, use PowerShell.exe's -File parameter to invoke a script from another environment, like cmd.exe. For example:

Powershell.exe -File C:\my_path\yada_yada\run_import_script.ps1

Cannot set property 'innerHTML' of null

You could tell javascript to perform the action "onload"... Try with this:

<script type ="text/javascript">
window.onload = function what(){
document.getElementById('hello').innerHTML = 'hi';
};
</script>

How to debug a GLSL shader?

If you want to visualize the variations of a value across the screen, you can use a heatmap function similar to this (I wrote it in hlsl, but it is easy to adapt to glsl):

float4 HeatMapColor(float value, float minValue, float maxValue)
{
    #define HEATMAP_COLORS_COUNT 6
    float4 colors[HEATMAP_COLORS_COUNT] =
    {
        float4(0.32, 0.00, 0.32, 1.00),
        float4(0.00, 0.00, 1.00, 1.00),
        float4(0.00, 1.00, 0.00, 1.00),
        float4(1.00, 1.00, 0.00, 1.00),
        float4(1.00, 0.60, 0.00, 1.00),
        float4(1.00, 0.00, 0.00, 1.00),
    };
    float ratio=(HEATMAP_COLORS_COUNT-1.0)*saturate((value-minValue)/(maxValue-minValue));
    float indexMin=floor(ratio);
    float indexMax=min(indexMin+1,HEATMAP_COLORS_COUNT-1);
    return lerp(colors[indexMin], colors[indexMax], ratio-indexMin);
}

Then in your pixel shader you just output something like:

return HeatMapColor(myValue, 0.00, 50.00);

And can get an idea of how it varies across your pixels:

enter image description here

Of course you can use any set of colors you like.

Programmatically Creating UILabel

UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(20, 30, 300, 50)];
label.backgroundColor = [UIColor clearColor];
label.textAlignment = NSTextAlignmentCenter;
label.textColor = [UIColor whiteColor];
label.numberOfLines = 0;
label.lineBreakMode = UILineBreakModeWordWrap;
label.text = @"Your Text";
[self.view addSubview:label];

Pad left or right with string.format (not padleft or padright) with arbitrary string

Simple:



    dim input as string = "SPQR"
    dim format as string =""
    dim result as string = ""

    'pad left:
    format = "{0,-8}"
    result = String.Format(format,input)
    'result = "SPQR    "

    'pad right
    format = "{0,8}"
    result = String.Format(format,input)
    'result = "    SPQR"


How to get object length

In jQuery i've made it in a such way:

len = function(obj) {
    var L=0;
    $.each(obj, function(i, elem) {
        L++;
    });
    return L;
}

Interface/enum listing standard mime-type constants

There's also a MediaType class in androidannotations in case you want to use with android! See here.

How to change the map center in Leaflet.js

You could also use:

var latLon = L.latLng(40.737, -73.923);
var bounds = latLon.toBounds(500); // 500 = metres
map.panTo(latLon).fitBounds(bounds);

This will set the view level to fit the bounds in the map leaflet.

How to set selected value of jquery select2?

$('#inputID').val("100").select2();

It would be more appropriate to apply select2 after choosing one of the current select.

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

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

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

That, or change your object to an array.

How to change root logging level programmatically for logback

I assume you are using logback (from the configuration file).

From logback manual, I see

Logger rootLogger = LoggerFactory.getLogger(org.slf4j.Logger.ROOT_LOGGER_NAME);

Perhaps this can help you change the value?

How to execute XPath one-liners from shell?

clacke’s answer is great but I think only works if your source is well-formed XML, not normal HTML.

So to do the same for normal Web content—HTML docs that aren’t necessarily well-formed XML:

echo "<p>foo<div>bar</div><p>baz" | python -c "from sys import stdin; \
from lxml import html; \
print '\n'.join(html.tostring(node) for node in html.parse(stdin).xpath('//p'))"

And to instead use html5lib (to ensure you get the same parsing behavior as Web browsers—because like browser parsers, html5lib conforms to the parsing requirements in the HTML spec).

echo "<p>foo<div>bar</div><p>baz" | python -c "from sys import stdin; \
import html5lib; from lxml import html; \
doc = html5lib.parse(stdin, treebuilder='lxml', namespaceHTMLElements=False); \
print '\n'.join(html.tostring(node) for node in doc.xpath('//p'))

Why is exception.printStackTrace() considered bad practice?

printStackTrace() prints to a console. In production settings, nobody is ever watching at that. Suraj is correct, should pass this information to a logger.

How to maximize the browser window in Selenium WebDriver (Selenium 2) using C#?

For Java:

driver.manage().window().maximize();

It will work in IE, Mozilla, Chrome

keypress, ctrl+c (or some combo like that)

I am a little late to the party but here is my part

$(document).on('keydown', function ( e ) {
    // You may replace `c` with whatever key you want
    if ((e.metaKey || e.ctrlKey) && ( String.fromCharCode(e.which).toLowerCase() === 'c') ) {
        console.log( "You pressed CTRL + C" );
    }
});

Why do we usually use || over |? What is the difference?

a | b: evaluate b in any case

a || b: evaluate b only if a evaluates to false

How do I check if an object's type is a particular subclass in C++?

 

class Base
{
  public: virtual ~Base() {}
};

class D1: public Base {};

class D2: public Base {};

int main(int argc,char* argv[]);
{
  D1   d1;
  D2   d2;

  Base*  x = (argc > 2)?&d1:&d2;

  if (dynamic_cast<D2*>(x) == nullptr)
  {
    std::cout << "NOT A D2" << std::endl;
  }
  if (dynamic_cast<D1*>(x) == nullptr)
  {
    std::cout << "NOT A D1" << std::endl;
  }
}

What is the printf format specifier for bool?

There is no format specifier for bool. You can print it using some of the existing specifiers for printing integral types or do something more fancy:

 printf("%s", x?"true":"false");

How can I convert JSON to CSV?

I was having trouble with Dan's proposed solution, but this worked for me:

import json
import csv 

f = open('test.json')
data = json.load(f)
f.close()

f=csv.writer(open('test.csv','wb+'))

for item in data:
  f.writerow([item['pk'], item['model']] + item['fields'].values())

Where "test.json" contained the following:

[ 
{"pk": 22, "model": "auth.permission", "fields": 
  {"codename": "add_logentry", "name": "Can add log entry", "content_type": 8 } }, 
{"pk": 23, "model": "auth.permission", "fields": 
  {"codename": "change_logentry", "name": "Can change log entry", "content_type": 8 } }, {"pk": 24, "model": "auth.permission", "fields": 
  {"codename": "delete_logentry", "name": "Can delete log entry", "content_type": 8 } }
]

Turn off textarea resizing

Try this CSS to disable resizing

The CSS to disable resizing for all textareas looks like this:

textarea {
    resize: none;
}

You could instead just assign it to a single textarea by name (where the textarea HTML is ):

textarea[name=foo] {
    resize: none;
}

Or by id (where the textarea HTML is ):

#foo {
    resize: none;
}

Taken from: http://www.electrictoolbox.com/disable-textarea-resizing-safari-chrome/

Java 8 Stream and operation on arrays

There are new methods added to java.util.Arrays to convert an array into a Java 8 stream which can then be used for summing etc.

int sum =  Arrays.stream(myIntArray)
                 .sum();

Multiplying two arrays is a little more difficult because I can't think of a way to get the value AND the index at the same time as a Stream operation. This means you probably have to stream over the indexes of the array.

//in this example a[] and b[] are same length
int[] a = ...
int[] b = ...

int[] result = new int[a.length];

IntStream.range(0, a.length)
         .forEach(i -> result[i] = a[i] * b[i]);

EDIT

Commenter @Holger points out you can use the map method instead of forEach like this:

int[] result = IntStream.range(0, a.length).map(i -> a[i] * b[i]).toArray();

height: calc(100%) not working correctly in CSS

All the parent elements in the hierarchy should have height 100%. Just give max-height:100% to the element and max-height:calc(100% - 90px) to the immediate parent element.

It worked for me on IE also.

html,
body {
    height: 100%
}

parent-element {
    max-height: calc(100% - 90px);
}

element {
    height:100%;
}

The Rendering in IE fails due to failure of Calc when the window is resized or data loaded in DOM. But this method mentioned above worked for me even in IE.

C++11 rvalues and move semantics confusion (return statement)

The simple answer is you should write code for rvalue references like you would regular references code, and you should treat them the same mentally 99% of the time. This includes all the old rules about returning references (i.e. never return a reference to a local variable).

Unless you are writing a template container class that needs to take advantage of std::forward and be able to write a generic function that takes either lvalue or rvalue references, this is more or less true.

One of the big advantages to the move constructor and move assignment is that if you define them, the compiler can use them in cases were the RVO (return value optimization) and NRVO (named return value optimization) fail to be invoked. This is pretty huge for returning expensive objects like containers & strings by value efficiently from methods.

Now where things get interesting with rvalue references, is that you can also use them as arguments to normal functions. This allows you to write containers that have overloads for both const reference (const foo& other) and rvalue reference (foo&& other). Even if the argument is too unwieldy to pass with a mere constructor call it can still be done:

std::vector vec;
for(int x=0; x<10; ++x)
{
    // automatically uses rvalue reference constructor if available
    // because MyCheapType is an unamed temporary variable
    vec.push_back(MyCheapType(0.f));
}


std::vector vec;
for(int x=0; x<10; ++x)
{
    MyExpensiveType temp(1.0, 3.0);
    temp.initSomeOtherFields(malloc(5000));

    // old way, passed via const reference, expensive copy
    vec.push_back(temp);

    // new way, passed via rvalue reference, cheap move
    // just don't use temp again,  not difficult in a loop like this though . . .
    vec.push_back(std::move(temp));
}

The STL containers have been updated to have move overloads for nearly anything (hash key and values, vector insertion, etc), and is where you will see them the most.

You can also use them to normal functions, and if you only provide an rvalue reference argument you can force the caller to create the object and let the function do the move. This is more of an example than a really good use, but in my rendering library, I have assigned a string to all the loaded resources, so that it is easier to see what each object represents in the debugger. The interface is something like this:

TextureHandle CreateTexture(int width, int height, ETextureFormat fmt, string&& friendlyName)
{
    std::unique_ptr<TextureObject> tex = D3DCreateTexture(width, height, fmt);
    tex->friendlyName = std::move(friendlyName);
    return tex;
}

It is a form of a 'leaky abstraction' but allows me to take advantage of the fact I had to create the string already most of the time, and avoid making yet another copying of it. This isn't exactly high-performance code but is a good example of the possibilities as people get the hang of this feature. This code actually requires that the variable either be a temporary to the call, or std::move invoked:

// move from temporary
TextureHandle htex = CreateTexture(128, 128, A8R8G8B8, string("Checkerboard"));

or

// explicit move (not going to use the variable 'str' after the create call)
string str("Checkerboard");
TextureHandle htex = CreateTexture(128, 128, A8R8G8B8, std::move(str));

or

// explicitly make a copy and pass the temporary of the copy down
// since we need to use str again for some reason
string str("Checkerboard");
TextureHandle htex = CreateTexture(128, 128, A8R8G8B8, string(str));

but this won't compile!

string str("Checkerboard");
TextureHandle htex = CreateTexture(128, 128, A8R8G8B8, str);

How do I reformat HTML code using Sublime Text 2?

I created a Package called HTMLBeautify that does a decent job of reformatting HTML. I based it off of a Perl script I found back in 1997—I updated it to work with all the new fangled modern tags. :)

Check it out and let me know what you think!

https://github.com/rareyman/HTMLBeautify

How do I send an HTML email?

The "loginVo.htmlBody(messageBodyPart);" will contain the html formatted designed information, but in mail does not receive it.

JAVA - STRUTS2

package com.action;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import com.opensymphony.xwork2.Action;
import com.bo.LoginBo;
import com.manager.AttendanceManager;
import com.manager.LoginManager;
import com.manager.SSLEmail;
import com.vo.AttendanceManagementVo;
import com.vo.LeaveManagementVo;
import com.vo.LoginVo;
import com.sun.corba.se.impl.protocol.giopmsgheaders.Message;
import com.sun.xml.internal.messaging.saaj.packaging.mime.internet.MimeBodyPart;

public class InsertApplyLeaveAction implements Action {
private AttendanceManagementVo attendanceManagementVo;

public AttendanceManagementVo getAttendanceManagementVo() {
    return attendanceManagementVo;
}

public void setAttendanceManagementVo(
        AttendanceManagementVo attendanceManagementVo) {
    this.attendanceManagementVo = attendanceManagementVo;
}

@Override
public String execute() throws Exception {
    String empId=attendanceManagementVo.getEmpId();
    String leaveType=attendanceManagementVo.getLeaveType();
    String leaveStartDate=attendanceManagementVo.getLeaveStartDate();
    String leaveEndDate=attendanceManagementVo.getLeaveEndDate();
    String reason=attendanceManagementVo.getReason();
    String employeeName=attendanceManagementVo.getEmployeeName();
    String manageEmployeeId=empId;
    float totalLeave=attendanceManagementVo.getTotalLeave();
    String leaveStatus=attendanceManagementVo.getLeaveStatus();
//  String approverId=attendanceManagementVo.getApproverId();
    attendanceManagementVo.setEmpId(empId);
    attendanceManagementVo.setLeaveType(leaveType);
    attendanceManagementVo.setLeaveStartDate(leaveStartDate);
    attendanceManagementVo.setLeaveEndDate(leaveEndDate);
    attendanceManagementVo.setReason(reason);
    attendanceManagementVo.setManageEmployeeId(manageEmployeeId);
    attendanceManagementVo.setTotalLeave(totalLeave);
    attendanceManagementVo.setLeaveStatus(leaveStatus);
    attendanceManagementVo.setEmployeeName(employeeName);

    AttendanceManagementVo attendanceManagementVo1=new AttendanceManagementVo();
    AttendanceManager attendanceManager=new AttendanceManager();    
    attendanceManagementVo1=attendanceManager.insertLeaveData(attendanceManagementVo);
    attendanceManagementVo1=attendanceManager.getApproverId(attendanceManagementVo);
    String approverId=attendanceManagementVo1.getApproverId();
    String approverEmployeeName=attendanceManagementVo1.getApproverEmployeeName();
    LoginVo loginVo=new LoginVo();
    LoginManager loginManager=new LoginManager();
    loginVo.setEmpId(approverId);
    loginVo=loginManager.getEmailAddress(loginVo);
    String emailAddress=loginVo.getEmailAddress();
    String subject="LEAVE IS SUBMITTED FOR AN APPROVAL BY THE  - " +employeeName;
//  String body =   "Hi "+approverEmployeeName+" ," + "\n" + "\n" +
//          leaveType+" is Applied for "+totalLeave+" days by the  " +employeeName+ "\n" + "\n" +
//          " Employee Name: " + employeeName +"\n" +
//          " Applied Leave Type: " + leaveType +"\n" +
//          " Total Days: " + totalLeave +"\n" + "\n" +
  //        " To view Leave History, Please visit the employee poratal or copy and paste the below link in your browser: " + "\n" +  

  //        " NOTE : This is an automated message. Please do not reply."+ "\n" +  "\n" +                        

    Session session = null;

    MimeBodyPart messageBodyPart = new MimeBodyPart();
    MimeMessage message = new MimeMessage(session);
    Multipart multipart = new MimeMultipart();

    String htmlText = ("<div style=\"color:red;\">BRIDGEYE</div>");
    messageBodyPart.setContent(htmlText, "text/html");

    loginVo.setHtmlBody(messageBodyPart);

    message.setContent(multipart);
    Transport.send(message);


    loginVo.setSubject(subject);
//  loginVo.setBody(body);
    loginVo.setEmailAddress(emailAddress);
    SSLEmail sSSEmail=new SSLEmail();
    sSSEmail.sendEmail(loginVo);
    return "success";
 }

 }

How do I rename a column in a SQLite database table?

While it is true that there is no ALTER COLUMN, if you only want to rename the column, drop the NOT NULL constraint, or change the data type, you can use the following set of commands:

Note: These commands have the potential to corrupt your database, so make sure you have a backup

PRAGMA writable_schema = 1;
UPDATE SQLITE_MASTER SET SQL = 'CREATE TABLE BOOKS ( title TEXT NOT NULL, publication_date TEXT)' WHERE NAME = 'BOOKS';
PRAGMA writable_schema = 0;

You will need to either close and reopen your connection or vacuum the database to reload the changes into the schema.

For example:

Y:\> sqlite3 booktest  
SQLite version 3.7.4  
Enter ".help" for instructions  
Enter SQL statements terminated with a ";"  
sqlite> create table BOOKS ( title TEXT NOT NULL, publication_date TEXT NOT NULL);  
sqlite> insert into BOOKS VALUES ("NULLTEST",null);  
Error: BOOKS.publication_date may not be NULL  
sqlite> PRAGMA writable_schema = 1; 
sqlite> UPDATE SQLITE_MASTER SET SQL = 'CREATE TABLE BOOKS ( title TEXT NOT NULL, publication_date TEXT)' WHERE NAME = 'BOOKS';  
sqlite> PRAGMA writable_schema = 0;  
sqlite> .q  

Y:\> sqlite3 booktest  
SQLite version 3.7.4  
Enter ".help" for instructions  
Enter SQL statements terminated with a ";"  
sqlite> insert into BOOKS VALUES ("NULLTEST",null);  
sqlite> .q  

REFERENCES FOLLOW:


pragma writable_schema
When this pragma is on, the SQLITE_MASTER tables in which database can be changed using ordinary UPDATE, INSERT, and DELETE statements. Warning: misuse of this pragma can easily result in a corrupt database file.

alter table
SQLite supports a limited subset of ALTER TABLE. The ALTER TABLE command in SQLite allows the user to rename a table or to add a new column to an existing table. It is not possible to rename a column, remove a column, or add or remove constraints from a table.

ALTER TABLE SYNTAX

Heatmap in matplotlib with pcolor?

Someone edited this question to remove the code I used, so I was forced to add it as an answer. Thanks to all who participated in answering this question! I think most of the other answers are better than this code, I'm just leaving this here for reference purposes.

With thanks to Paul H, and unutbu (who answered this question), I have some pretty nice-looking output:

import matplotlib.pyplot as plt
import numpy as np
column_labels = list('ABCD')
row_labels = list('WXYZ')
data = np.random.rand(4,4)
fig, ax = plt.subplots()
heatmap = ax.pcolor(data, cmap=plt.cm.Blues)

# put the major ticks at the middle of each cell
ax.set_xticks(np.arange(data.shape[0])+0.5, minor=False)
ax.set_yticks(np.arange(data.shape[1])+0.5, minor=False)

# want a more natural, table-like display
ax.invert_yaxis()
ax.xaxis.tick_top()

ax.set_xticklabels(row_labels, minor=False)
ax.set_yticklabels(column_labels, minor=False)
plt.show()

And here's the output:

Matplotlib HeatMap

How do DATETIME values work in SQLite?

SQLite does not have a storage class set aside for storing dates and/or times. Instead, the built-in Date And Time Functions of SQLite are capable of storing dates and times as TEXT, REAL, or INTEGER values:

TEXT as ISO8601 strings ("YYYY-MM-DD HH:MM:SS.SSS"). REAL as Julian day numbers, the number of days since noon in Greenwich on November 24, 4714 B.C. according to the proleptic Gregorian calendar. INTEGER as Unix Time, the number of seconds since 1970-01-01 00:00:00 UTC. Applications can chose to store dates and times in any of these formats and freely convert between formats using the built-in date and time functions.

Having said that, I would use INTEGER and store seconds since Unix epoch (1970-01-01 00:00:00 UTC).

How can I clear event subscriptions in C#?

Conceptual extended boring comment.

I rather use the word "event handler" instead of "event" or "delegate". And used the word "event" for other stuff. In some programming languages (VB.NET, Object Pascal, Objective-C), "event" is called a "message" or "signal", and even have a "message" keyword, and specific sugar syntax.

const
  WM_Paint = 998;  // <-- "question" can be done by several talkers
  WM_Clear = 546;

type
  MyWindowClass = class(Window)
    procedure NotEventHandlerMethod_1;
    procedure NotEventHandlerMethod_17;

    procedure DoPaintEventHandler; message WM_Paint; // <-- "answer" by this listener
    procedure DoClearEventHandler; message WM_Clear;
  end;

And, in order to respond to that "message", a "event handler" respond, whether is a single delegate or multiple delegates.

Summary: "Event" is the "question", "event handler (s)" are the answer (s).

Adding days to $Date in PHP

From PHP 5.2 on you can use modify with a DateTime object:

http://php.net/manual/en/datetime.modify.php

$Date1 = '2010-09-17';
$date = new DateTime($Date1);
$date->modify('+1 day');
$Date2 = $date->format('Y-m-d');

Be careful when adding months... (and to a lesser extent, years)

Export DataTable to Excel with Open Xml SDK in c#

I tried accepted answer and got message saying generated excel file is corrupted when trying to open. I was able to fix it by doing few modifications like adding below line end of the code.

workbookPart.Workbook.Save();

I have posted full code @ Export DataTable to Excel with Open XML in c#

How to indent HTML tags in Notepad++

Use the XML Tools plugin for Notepad++ and then you can Auto-Indent the code with Ctrl+Alt+Shift+B .For the more point-and-click inclined, you could also go to Plugins --> XML Tools --> Pretty Print.

Dynamically add script tag with src that may include document.write

the only way to do this is to replace document.write with your own function which will append elements to the bottom of your page. It is pretty straight forward with jQuery:

document.write = function(htmlToWrite) {
  $(htmlToWrite).appendTo('body');
}

If you have html coming to document.write in chunks like the question example you'll need to buffer the htmlToWrite segments. Maybe something like this:

document.write = (function() {
  var buffer = "";
  var timer;
  return function(htmlPieceToWrite) {
    buffer += htmlPieceToWrite;
    clearTimeout(timer);
    timer = setTimeout(function() {
      $(buffer).appendTo('body');
      buffer = "";
    }, 0)
  }
})()

CSS Outside Border

I shared two solutions depending on your needs:

<style type="text/css" ref="stylesheet">
  .border-inside-box {
    border: 1px solid black;
  }
  .border-inside-box-v1 {
    outline: 1px solid black; /* 'border-radius' not available */
  }
  .border-outside-box-v2 {
    box-shadow: 0 0 0 1px black; /* 'border-style' not available (dashed, solid, etc) */
  }
</style>

example: https://codepen.io/danieldd/pen/gObEYKj

Mean Squared Error in Numpy?

Another alternative to the accepted answer that avoids any issues with matrix multiplication:

 def MSE(Y, YH):
     return np.square(Y - YH).mean()

From the documents for np.square: "Return the element-wise square of the input."

How can I adjust DIV width to contents

You could try using float:left; or display:inline-block;.

Both of these will change the element's behaviour from defaulting to 100% width to defaulting to the natural width of its contents.

However, note that they'll also both have an impact on the layout of the surrounding elements as well. I would suggest that inline-block will have less of an impact though, so probably best to try that first.

How to use jQuery to select a dropdown option?

This works for me:

$selectedindex=4

If you want to randomise options, you could always do something like this:

$0selectedindex=Math.floor((Math.random()*($0.length-1)+1)

Whilst 2nd bullet lies outside scope of your questions, it serves to illustrate how 1st bullet could be applied / amended as req.

How to map and remove nil values in Ruby

You could use compact:

[1, nil, 3, nil, nil].compact
=> [1, 3] 

I'd like to remind people that if you're getting an array containing nils as the output of a map block, and that block tries to conditionally return values, then you've got code smell and need to rethink your logic.

For instance, if you're doing something that does this:

[1,2,3].map{ |i|
  if i % 2 == 0
    i
  end
}
# => [nil, 2, nil]

Then don't. Instead, prior to the map, reject the stuff you don't want or select what you do want:

[1,2,3].select{ |i| i % 2 == 0 }.map{ |i|
  i
}
# => [2]

I consider using compact to clean up a mess as a last-ditch effort to get rid of things we didn't handle correctly, usually because we didn't know what was coming at us. We should always know what sort of data is being thrown around in our program; Unexpected/unknown data is bad. Anytime I see nils in an array I'm working on, I dig into why they exist, and see if I can improve the code generating the array, rather than allow Ruby to waste time and memory generating nils then sifting through the array to remove them later.

'Just my $%0.2f.' % [2.to_f/100]

What does android:layout_weight mean?

Think it that way, will be simpler

If you have 3 buttons and their weights are 1,3,1 accordingly, it will work like table in HTML

Provide 5 portions for that line: 1 portion for button 1, 3 portion for button 2 and 1 portion for button 1

Regard,

How to test if a double is an integer

Personally, I prefer the simple modulo operation solution in the accepted answer. Unfortunately, SonarQube doesn't like equality tests with floating points without setting a round precision. So we have tried to find a more compliant solution. Here it is:

if (new BigDecimal(decimalValue).remainder(new BigDecimal(1)).equals(BigDecimal.ZERO)) {
    // no decimal places
} else {
    // decimal places
}

Remainder(BigDecimal) returns a BigDecimal whose value is (this % divisor). If this one's equal to zero, we know there is no floating point.

python dictionary sorting in descending order based on values

sort dictionary 'in_dict' by value in decreasing order

sorted_dict = {r: in_dict[r] for r in sorted(in_dict, key=in_dict.get, reverse=True)}

example above

sorted_d = {r: d[r] for r in sorted(d, key=d.get('key3'), reverse=True)}

Log record changes in SQL server in an audit table

I know this is old, but maybe this will help someone else.

Do not log "new" values. Your existing table, GUESTS, has the new values. You'll have double entry of data, plus your DB size will grow way too fast that way.

I cleaned this up and minimized it for this example, but here is the tables you'd need for logging off changes:

CREATE TABLE GUESTS (
      GuestID INT IDENTITY(1,1) PRIMARY KEY, 
      GuestName VARCHAR(50), 
      ModifiedBy INT, 
      ModifiedOn DATETIME
)

CREATE TABLE GUESTS_LOG (
      GuestLogID INT IDENTITY(1,1) PRIMARY KEY, 
      GuestID INT, 
      GuestName VARCHAR(50), 
      ModifiedBy INT, 
      ModifiedOn DATETIME
)

When a value changes in the GUESTS table (ex: Guest name), simply log off that entire row of data, as-is, to your Log/Audit table using the Trigger. Your GUESTS table has current data, the Log/Audit table has the old data.

Then use a select statement to get data from both tables:

SELECT 0 AS 'GuestLogID', GuestID, GuestName, ModifiedBy, ModifiedOn FROM [GUESTS] WHERE GuestID = 1
UNION
SELECT GuestLogID, GuestID, GuestName, ModifiedBy, ModifiedOn FROM [GUESTS_LOG] WHERE GuestID = 1
ORDER BY ModifiedOn ASC

Your data will come out with what the table looked like, from Oldest to Newest, with the first row being what was created & the last row being the current data. You can see exactly what changed, who changed it, and when they changed it.

Optionally, I used to have a function that looped through the RecordSet (in Classic ASP), and only displayed what values had changed on the web page. It made for a GREAT audit trail so that users could see what had changed over time.

Two color borders

This is very possible. It just takes a little CSS trickery!

_x000D_
_x000D_
div.border {_x000D_
  border: 1px solid #000;_x000D_
  position: relative;_x000D_
}_x000D_
_x000D_
div.border:before {_x000D_
  position: absolute;_x000D_
  display: block;_x000D_
  content: '';_x000D_
  border: 1px solid red;_x000D_
  height: 100%;_x000D_
  width: 100%;_x000D_
  box-sizing: border-box;_x000D_
  -moz-box-sizing: border-box;_x000D_
  -webkit-box-sizing: border-box;_x000D_
}
_x000D_
<div class="border">Hi I have two border colors<br />I am also Fluid</div>
_x000D_
_x000D_
_x000D_

Is that what you are looking for?

Writing image to local server

I have an easier solution using fs.readFileSync(./my_local_image_path.jpg)

This is for reading images from Azure Cognative Services's Vision API

const subscriptionKey = 'your_azure_subscrition_key';
const uriBase = // **MUST change your location (mine is 'eastus')**
    'https://eastus.api.cognitive.microsoft.com/vision/v2.0/analyze';

// Request parameters.
const params = {
    'visualFeatures': 'Categories,Description,Adult,Faces',
    'maxCandidates': '2',
    'details': 'Celebrities,Landmarks',
    'language': 'en'
};

const options = {
    uri: uriBase,
    qs: params,
    body: fs.readFileSync(./my_local_image_path.jpg),
    headers: {
        'Content-Type': 'application/octet-stream',
        'Ocp-Apim-Subscription-Key' : subscriptionKey
    }
};

request.post(options, (error, response, body) => {
if (error) {
    console.log('Error: ', error);
    return;
}
let jsonString = JSON.stringify(JSON.parse(body), null, '  ');
body = JSON.parse(body);
if (body.code) // err
{
    console.log("AZURE: " + body.message)
}

console.log('Response\n' + jsonString);

Importing a GitHub project into Eclipse

With the last ADT, you can import Github project using Eclipse :

  1. File -> Import -> Git -> Projects From Git > URI

  2. Enter the Github repository url

  3. Select the branch

Vue equivalent of setTimeout?

Arrow Function

The best and simplest way to solve this problem is by using an arrow function () => {}:

    addToBasket() {
        var item = this.photo;
        this.$http.post('/api/buy/addToBasket', item);
        this.basketAddSuccess = true;
        // now 'this' is referencing the Vue object and not the 'setTimeout' scope
        setTimeout(() => this.basketAddSuccess = false, 2000);
    }

This works because the this of arrow functions is bound to the this of its enclosing scope- in Vue, that's the parent/ enclosing component. Inside a traditional function called by setTimeout, however, this refers to the window object (which is why you ran into errors when you tried to access this.basketAddSuccess in that context).

Argument Passing

Another way of doing this would be passing this as an arg to your function through setTimeout's prototype using its setTimeout(callback, delay, arg1, arg2, ...) form:

    addToBasket() {
        item = this.photo;
        this.$http.post('/api/buy/addToBasket', item);
        this.basketAddSuccess = true;
        //Add scope argument to func, pass this after delay in setTimeout
        setTimeout(function(scope) {
             scope.basketAddSuccess = false;
        }, 2000, this);
    }

(It's worth noting that the arg passing syntax is incompatible with IE 9 and below, however.)

Local Variable

Another possible, but less eloquent and less encouraged, way is to bind this to a var outside of setTimeout:

    addToBasket() {
        item = this.photo;
        this.$http.post('/api/buy/addToBasket', item);
        this.basketAddSuccess = true;
        //Declare self, which is accessible inside setTimeout func
        var self = this;
        setTimeout(function() {
             self.basketAddSuccess = false;
        }, 2000);
    }

Using an arrow function would eliminate the need for this extra variable entirely however, and really should be used unless something else is preventing its use.

Python: How to create a unique file name?

You can use the datetime module

import datetime
uniq_filename = str(datetime.datetime.now().date()) + '_' + str(datetime.datetime.now().time()).replace(':', '.')

Note that: I am using replace since the colons are not allowed in filenames in many operating systems.

That's it, this will give you a unique filename every single time.

Fetch: POST json data

I have created a thin wrapper around fetch() with many improvements if you are using a purely json REST API:

// Small library to improve on fetch() usage
const api = function(method, url, data, headers = {}){
  return fetch(url, {
    method: method.toUpperCase(),
    body: JSON.stringify(data),  // send it as stringified json
    credentials: api.credentials,  // to keep the session on the request
    headers: Object.assign({}, api.headers, headers)  // extend the headers
  }).then(res => res.ok ? res.json() : Promise.reject(res));
};

// Defaults that can be globally overwritten
api.credentials = 'include';
api.headers = {
  'csrf-token': window.csrf || '',    // only if globally set, otherwise ignored
  'Accept': 'application/json',       // receive json
  'Content-Type': 'application/json'  // send json
};

// Convenient methods
['get', 'post', 'put', 'delete'].forEach(method => {
  api[method] = api.bind(null, method);
});

To use it you have the variable api and 4 methods:

api.get('/todo').then(all => { /* ... */ });

And within an async function:

const all = await api.get('/todo');
// ...

Example with jQuery:

$('.like').on('click', async e => {
  const id = 123;  // Get it however it is better suited

  await api.put(`/like/${id}`, { like: true });

  // Whatever:
  $(e.target).addClass('active dislike').removeClass('like');
});

Ignore <br> with CSS?

As per your question, to solve this problem for Firefox and Opera using Aneesh Karthik C approach you need to add "float" right" attribute.

Check the example here. This CSS works in Firefox (26.0) , Opera (12.15), Chrome (32.0.1700) and Safari (7.0)

br {
   content: " ";  
   float:right; 
}

I hope this will answer your question!!

GET URL parameter in PHP

I was getting nothing for any $_GET["..."] (e.g print_r($_GET) gave an empty array) yet $_SERVER['REQUEST_URI'] showed stuff should be there. In the end it turned out that I was only getting to the web page because my .htaccess was redirecting it there (my 404 handler was the same .php file, and I had made a typo in the browser when testing).

Simply changing the name meant the same php code worked once the 404 redirection wasn't kicking in!

So there are ways $_GET can return nothing even though the php code may be correct.

How to line-break from css, without using <br />?

At the CSS use the code

p {
    white-space: pre-line;
}

With this code css every enter inside the P tag will be a break-line at the html.

Is it a bad practice to use an if-statement without curly braces?

I am using the code formatter of the IDE I use. That might differ, but it can be setup in the Preferences/Options.

I like this one:

if (statement)
{
    // comment to denote in words the case
    do this;
    // keep this block simple, if more than 10-15 lines needed, I add a function for it
}
else
{
    do this;
}

How to check if a string contains an element from a list in Python

extensionsToCheck = ('.pdf', '.doc', '.xls')

'test.doc'.endswith(extensionsToCheck)   # returns True

'test.jpg'.endswith(extensionsToCheck)   # returns False

How to convert Varchar to Double in sql?

use DECIMAL() or NUMERIC() as they are fixed precision and scale numbers.

SELECT fullName, 
       CAST(totalBal as DECIMAL(9,2)) _totalBal
FROM client_info 
ORDER BY _totalBal DESC

XSL xsl:template match="/"

The value of the match attribute of the <xsl:template> instruction must be a match pattern.

Match patterns form a subset of the set of all possible XPath expressions. The first, natural, limitation is that a match pattern must select a set of nodes. There are also other limitations. In particular, reverse axes are not allowed in the location steps (but can be specified within the predicates). Also, no variable or parameter references are allowed in XSLT 1.0, but using these is legal in XSLT 2.x.

/ in XPath denotes the root or document node. In XPath 2.0 (and hence XSLT 2.x) this can also be written as document-node().

A match pattern can contain the // abbreviation.

Examples of match patterns:

<xsl:template match="table">

can be applied on any element named table.

<xsl:template match="x/y">

can be applied on any element named y whose parent is an element named x.

<xsl:template match="*">

can be applied to any element.

<xsl:template match="/*">

can be applied only to the top element of an XML document.

<xsl:template match="@*">

can be applied to any attribute.

<xsl:template match="text()">

can be applied to any text node.

<xsl:template match="comment()">

can be applied to any comment node.

<xsl:template match="processing-instruction()">

can be applied to any processing instruction node.

<xsl:template match="node()">

can be applied to any node: element, text, comment or processing instructon.

How do I calculate power-of in C#?

I'm answering this question because I don't find any answer why the ^ don't work for powers. The ^ operator in C# is an exclusive or operator shorten as XOR. The truth table of A ^ B shows that it outputs true whenever the inputs differ:

Input A Input B Output
0 0 0
0 1 1
1 0 1
1 1 0

Witch means that 100 ^ 3 does this calculation under the hood:

hex   binary
100 = 0110 0100 
  3 = 0000 0011
---   --------- ^
103 = 0110 0111

With is of course not the same as Math.Pow(100, 3) with results to one million. You can use that or one of the other existing answers.


You could also shorten your code to this that gives the same result because C# respects the order of operations.

double dimensions = 100 * 100 / Math.Pow(100, 3); // == 0.01

Python Checking a string's first and last character

You should either use

if str1[0] == '"' and str1[-1] == '"'

or

if str1.startswith('"') and str1.endswith('"')

but not slice and check startswith/endswith together, otherwise you'll slice off what you're looking for...

OpenJDK availability for Windows OS

You may find OpenJDK 6 and 7 binaries for Windows in openjdk-unofficial-builds github project.

Update: OpenJDK 8 and 11 LTS binaries for Windows x86_64 can be found in ojdkbuild github project.

Disclaimer: I've built them myself.

Update (2019): OpenJDK Updates Project Builds for 8 and 11 are available now.

Why doesn't logcat show anything in my Android?

Set the same date and time in your android phone and in your laptop.

I had a similar problem of logs not showing, and when I set the correct date in the phone I started seeing the logs (I restarted the phone and the hour was completely wrong!).

How do I load a file from resource folder?

I faced the same issue.

The file was not found by a class loader, which means it was not packed into the artifact (jar). You need to build the project. For example, with maven:

mvn clean install

So the files you added to resources folder will get into maven build and become available to the application.

I would like to keep my answer: it does not explain how to read a file (other answers do explain that), it answers why InputStream or resource was null. Similar answer is here.

QString to char* conversion

Qt provides the simplest API

const char *qPrintable(const QString &str)
const char *qUtf8Printable(const QString &str)

If you want non-const data pointer use

str.toLocal8Bit().data()
str.toUtf8().data()

How to access single elements in a table in R

Maybe not so perfect as above ones, but I guess this is what you were looking for.

data[1:1,3:3]    #works with positive integers
data[1:1, -3:-3] #does not work, gives the entire 1st row without the 3rd element
data[i:i,j:j]    #given that i and j are positive integers

Here indexing will work from 1, i.e,

data[1:1,1:1]    #means the top-leftmost element

Amazon S3 direct file upload from client browser - private key disclosure

I have given a simple code to upload files from Javascript browser to AWS S3 and list the all files in S3 bucket.

Steps:

  1. To know how to create Create IdentityPoolId http://docs.aws.amazon.com/cognito/latest/developerguide/identity-pools.html

    1. Goto S3's console page and open cors configuration from bucket properties and write following XML code into that.

      <?xml version="1.0" encoding="UTF-8"?>
      <CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
       <CORSRule>    
        <AllowedMethod>GET</AllowedMethod>
        <AllowedMethod>PUT</AllowedMethod>
        <AllowedMethod>DELETE</AllowedMethod>
        <AllowedMethod>HEAD</AllowedMethod>
        <AllowedHeader>*</AllowedHeader>
       </CORSRule>
      </CORSConfiguration>
      
    2. Create HTML file containing following code change the credentials, open file in browser and enjoy.

      <script type="text/javascript">
       AWS.config.region = 'ap-north-1'; // Region
       AWS.config.credentials = new AWS.CognitoIdentityCredentials({
       IdentityPoolId: 'ap-north-1:*****-*****',
       });
       var bucket = new AWS.S3({
       params: {
       Bucket: 'MyBucket'
       }
       });
      
       var fileChooser = document.getElementById('file-chooser');
       var button = document.getElementById('upload-button');
       var results = document.getElementById('results');
      
       function upload() {
       var file = fileChooser.files[0];
       console.log(file.name);
      
       if (file) {
       results.innerHTML = '';
       var params = {
       Key: n + '.pdf',
       ContentType: file.type,
       Body: file
       };
       bucket.upload(params, function(err, data) {
       results.innerHTML = err ? 'ERROR!' : 'UPLOADED.';
       });
       } else {
       results.innerHTML = 'Nothing to upload.';
       }    }
      </script>
      <body>
       <input type="file" id="file-chooser" />
       <input type="button" onclick="upload()" value="Upload to S3">
       <div id="results"></div>
      </body>
      

Generate war file from tomcat webapp folder

You can create .war file back from your existing folder.

Using this command

cd /to/your/folder/location
jar -cvf my_web_app.war *

Correct path for img on React.js

Adding file-loader npm to webpack.config.js per its official usage instruction like so:

config.module.rules.push(
    {
        test: /\.(png|jpg|gif)$/,
        use: [
            {
                loader: 'file-loader',
                options: {}
            }
        ]
    }
);

worked for me.

go to character in vim

:goto 21490 will take you to the 21490th byte in the buffer.

Comparison of Android Web Service and Networking libraries: OKHTTP, Retrofit and Volley

RoboSpice Vs. Volley

From https://groups.google.com/forum/#!topic/robospice/QwVCfY_glOQ

  • RoboSpice(RS) is service based and more respectful of Android philosophy than Volley. Volley is thread based and this is not the way background processing should take place on Android. Ultimately, you can dig down both libs and find that they are quite similar, but our way to do background processing is more Android oriented, it allow us, for instance, to tell users that RS is actually doing something in background, which would be hard for volley (actually it doesn't at all).
  • RoboSpice and volley both offer nice features like prioritization, retry policies, request cancellation. But RS offers more : a more advanced caching and that's a big one, with cache management, request aggregation, more features like repluging to a pending request, dealing with cache expiry without relying on server headers, etc.
  • RoboSpice does more outside of UI Thread : volley will deserialize your POJOs on the main thread, which is horrible to my mind. With RS your app will be more responsive.
  • In terms of speed, we definitely need metrics. RS has gotten super fast now, but still we don't have figure to put here. Volley should theoretically be a bit faster, but RS is now massively parallel... who knows ?
  • RoboSpice offers a large compatibility range with extensions. You can use it with okhttp, retrofit, ormlite (beta), jackson, jackson2, gson, xml serializer, google http client, spring android... Quite a lot. Volley can be used with ok http and uses gson. that's it.
  • Volley offers more UI sugar that RS. Volley provides NetworkImageView, RS does provide a spicelist adapter. In terms of feature it's not so far, but I believe Volley is more advanced on this topic.
  • More than 200 bugs have been solved in RoboSpice since its initial release. It's pretty robust and used heavily in production. Volley is less mature but its user base should be growing fast (Google effect).
  • RoboSpice is available on maven central. Volley is hard to find ;)

Why javascript getTime() is not a function?

dat1 and dat2 are Strings in JavaScript. There is no getTime function on the String prototype. I believe you want the Date.parse() function: http://www.w3schools.com/jsref/jsref_parse.asp

You would use it like this:

var date = Date.parse(dat1);

WPF Databinding: How do I access the "parent" data context?

You could try something like this:

...Binding="{Binding RelativeSource={RelativeSource FindAncestor, 
AncestorType={x:Type Window}}, Path=DataContext.AllowItemCommand}" ...

How do you use subprocess.check_output() in Python?

Adding on to the one mentioned by @abarnert

a better one is to catch the exception

import subprocess
try:
    py2output = subprocess.check_output(['python', 'py2.py', '-i', 'test.txt'],stderr= subprocess.STDOUT)  
    #print('py2 said:', py2output)
    print "here"
except subprocess.CalledProcessError as e:
    print "Calledprocerr"

this stderr= subprocess.STDOUT is for making sure you dont get the filenotfound error in stderr- which cant be usually caught in filenotfoundexception, else you would end up getting

python: can't open file 'py2.py': [Errno 2] No such file or directory

Infact a better solution to this might be to check, whether the file/scripts exist and then to run the file/script

Import Certificate to Trusted Root but not to Personal [Command Line]

If there are multiple certificates in a pfx file (key + corresponding certificate and a CA certificate) then this command worked well for me:

certutil -importpfx c:\somepfx.pfx this works but still a password is needed to be typed in manually for private key. Including -p and "password" cause error too many arguments for certutil on XP

How to avoid installing "Unlimited Strength" JCE policy files when deploying an application?

This is now no longer needed for Java 9, nor for any recent release of Java 6, 7, or 8. Finally! :)

Per JDK-8170157, the unlimited cryptographic policy is now enabled by default.

Specific versions from the JIRA issue:

  • Java 9 (10, 11, etc..): Any official release!
  • Java 8u161 or later (Available now)
  • Java 7u171 or later (Only available through 'My Oracle Support')
  • Java 6u181 or later (Only available through 'My Oracle Support')

Note that if for some odd reason the old behavior is needed in Java 9, it can be set using:

Security.setProperty("crypto.policy", "limited");

How do you run CMD.exe under the Local System Account?

Though I haven't personally tested, I have good reason to believe that the above stated AT COMMAND solution will work for XP, 2000 and Server 2003. Per my and Bryant's testing, we've identified that the same approach does not work with Vista or Windows Server 2008 -- most probably due to added security and the /interactive switch being deprecated.

However, I came across this article which demonstrates the use of PSTools from SysInternals (which was acquired by Microsoft in July, 2006.) I launched the command line via the following and suddenly I was running under the Local Admin Account like magic:

psexec -i -s cmd.exe

PSTools works well. It's a lightweight, well-documented set of tools which provides an appropriate solution to my problem.

Many thanks to those who offered help.

Error: Could not find gradle wrapper within Android SDK. Might need to update your Android SDK - Android

After experienced the same issue, just rename the package name in config.xml, attribute id with a name without "-" inside...

i.e.

com.web-projet.appname

renamed into :

com.webprojet.appname

and all was correct...

If it helps.

Credit card expiration dates - Inclusive or exclusive?

Have a look on one of your own credit cards. It'll have some text like EXPIRES END or VALID THRU above the date. So the card expires at the end of the given month.

What does the M stand for in C# Decimal literal notation?

M refers to the first non-ambiguous character in "decimal". If you don't add it the number will be treated as a double.

D is double.

Binding value to input in Angular JS

You don't need to set the value at all. ng-model takes care of it all:

  • set the input value from the model
  • update the model value when you change the input
  • update the input value when you change the model from js

Here's the fiddle for this: http://jsfiddle.net/terebentina/9mFpp/

Why can't I set text to an Android TextView?

Or you can do this way :

((TextView)findViewById(R.id.this_is_the_id_of_textview)).setText("Test");

Making HTTP Requests using Chrome Developer tools

If you want to do a POST from the same domain, you can always insert a form into the DOM using Developer tools and submit that:

Inserted form into document

How to get week numbers from dates?

I think the problem is that the week calculation somehow uses the first day of the year. I don't understand the internal mechanics, but you can see what I mean with this example:

library(data.table)

dd <- seq(as.IDate("2013-12-20"), as.IDate("2014-01-20"), 1)
# dd <- seq(as.IDate("2013-12-01"), as.IDate("2014-03-31"), 1)

dt <- data.table(i = 1:length(dd),
                 day = dd,
                 weekday = weekdays(dd),
                 day_rounded = round(dd, "weeks"))
## Now let's add the weekdays for the "rounded" date
dt[ , weekday_rounded := weekdays(day_rounded)]
## This seems to make internal sense with the "week" calculation
dt[ , weeknumber := week(day)]
dt 

    i        day   weekday day_rounded weekday_rounded weeknumber
1:  1 2013-12-20    Friday  2013-12-17         Tuesday         51
2:  2 2013-12-21  Saturday  2013-12-17         Tuesday         51
3:  3 2013-12-22    Sunday  2013-12-17         Tuesday         51
4:  4 2013-12-23    Monday  2013-12-24         Tuesday         52
5:  5 2013-12-24   Tuesday  2013-12-24         Tuesday         52
6:  6 2013-12-25 Wednesday  2013-12-24         Tuesday         52
7:  7 2013-12-26  Thursday  2013-12-24         Tuesday         52
8:  8 2013-12-27    Friday  2013-12-24         Tuesday         52
9:  9 2013-12-28  Saturday  2013-12-24         Tuesday         52
10: 10 2013-12-29    Sunday  2013-12-24         Tuesday         52
11: 11 2013-12-30    Monday  2013-12-31         Tuesday         53
12: 12 2013-12-31   Tuesday  2013-12-31         Tuesday         53
13: 13 2014-01-01 Wednesday  2014-01-01       Wednesday          1
14: 14 2014-01-02  Thursday  2014-01-01       Wednesday          1
15: 15 2014-01-03    Friday  2014-01-01       Wednesday          1
16: 16 2014-01-04  Saturday  2014-01-01       Wednesday          1
17: 17 2014-01-05    Sunday  2014-01-01       Wednesday          1
18: 18 2014-01-06    Monday  2014-01-01       Wednesday          1
19: 19 2014-01-07   Tuesday  2014-01-08       Wednesday          2
20: 20 2014-01-08 Wednesday  2014-01-08       Wednesday          2
21: 21 2014-01-09  Thursday  2014-01-08       Wednesday          2
22: 22 2014-01-10    Friday  2014-01-08       Wednesday          2
23: 23 2014-01-11  Saturday  2014-01-08       Wednesday          2
24: 24 2014-01-12    Sunday  2014-01-08       Wednesday          2
25: 25 2014-01-13    Monday  2014-01-08       Wednesday          2
26: 26 2014-01-14   Tuesday  2014-01-15       Wednesday          3
27: 27 2014-01-15 Wednesday  2014-01-15       Wednesday          3
28: 28 2014-01-16  Thursday  2014-01-15       Wednesday          3
29: 29 2014-01-17    Friday  2014-01-15       Wednesday          3
30: 30 2014-01-18  Saturday  2014-01-15       Wednesday          3
31: 31 2014-01-19    Sunday  2014-01-15       Wednesday          3
32: 32 2014-01-20    Monday  2014-01-15       Wednesday          3
     i        day   weekday day_rounded weekday_rounded weeknumber

My workaround is this function: https://github.com/geneorama/geneorama/blob/master/R/round_weeks.R

round_weeks <- function(x){
    require(data.table)
    dt <- data.table(i = 1:length(x),
                     day = x,
                     weekday = weekdays(x))
    offset <- data.table(weekday = c('Sunday', 'Monday', 'Tuesday', 'Wednesday', 
                                     'Thursday', 'Friday', 'Saturday'),
                         offset = -(0:6))
    dt <- merge(dt, offset, by="weekday")
    dt[ , day_adj := day + offset]
    setkey(dt, i)
    return(dt[ , day_adj])
}

Of course, you can easily change the offset to make Monday first or whatever. The best way to do this would be to add an offset to the offset... but I haven't done that yet.

I provided a link to my simple geneorama package, but please don't rely on it too much because it's likely to change and not very documented.

Checking if an object is null in C#

As others have already pointed out, it's not data but rather likely dataList that is null. In addition to that...

catch-throw is an antipattern that almost always makes me want to throw up every time that I see it. Imagine that something goes wrong deep in something that doOtherStuff() calls. All you get back is an Exception object, thrown at the throw in AddData(). No stack trace, no call information, no state, nothing at all to indicate the real source of the problem, unless you go in and switch your debugger to break on exception thrown rather than exception unhandled. If you are catching an exception and just re-throwing it in any way, particularly if the code in the try block is in any way nontrivial, do yourself (and your colleagues, present and future) a favor and throw out the entire try-catch block. Granted, throw; is better than the alternatives, but you are still giving yourself (or whoever else is trying to fix a bug in the code) completely unnecessary headaches. This is not to say that try-catch-throw is necessarily evil per se, as long as you do something relevant with the exception object that was thrown inside the catch block.

Then there's the potential problems of catching Exception in the first place, but that's another matter, particularly since in this particular case you throw an exception.

Another thing that strikes me as more than a little dangerous is that data could potentially change value during the execution of the function, since you are passing by reference. So the null check might pass but before the code gets to doing anything with the value, it's changed - perhaps to null. I'm not positive if this is a concern or not (it might not be), but it seems worth watching out for.

ActionController::InvalidAuthenticityToken

The authenticity token is a random value generated in your view to prove a request is submitted from a form on your site, not somewhere else. This protects against CSRF attacks:

http://en.wikipedia.org/wiki/Cross-site_request_forgery

Check to see who that client/IP is, it looks like they are using your site without loading your views.

If you need to debug further, this question is a good place to start: Understanding the Rails Authenticity Token

Edited to explain: It means they are calling the action to process your form submit without ever rendering your form on your website. This could be malicious (say posting spam comments) or it could indicate a customer trying to use your web service API directly. You're the only one who can answer that by the nature of your product and analyzing your requests.

Javascript (+) sign concatenates instead of giving sum of variables

Another alternative could be using:

divID = "question-" + (i - -1);

Subtracting a negative is the same as adding, and a minus cannot be used for concatenation

Edit: Forgot that brackets are still necessary since code is read from left to right.

Android check null or empty string in Android

if you check null or empty String so you can try this

if (createReminderRequest.getDate() == null && createReminderRequest.getDate().trim().equals("")){
    DialogUtility.showToast(this, ProjectUtils.getString(R.string.please_select_date_n_time));
}

Check if a radio button is checked jquery

if($("input:radio[name=test]").is(":checked")){
  //Code to append goes here
}

Installing ADB on macOS

Option 3 - Using MacPorts

Analoguously to the two options (homebrew / manual) posted by @brismuth, here's the MacPorts way:

  1. Install the Android SDK:

    sudo port install android
    
  2. Run the SDK manager:

    sh /opt/local/share/java/android-sdk-macosx/tools/android
    
  3. As @brismuth suggested, uncheck everything but Android SDK Platform-tools (optional)

  4. Install the packages, accepting licenses. Close the SDK Manager.

  5. Add platform-tools to your path; in MacPorts, they're in /opt/local/share/java/android-sdk-macosx/platform-tools. E.g., for bash:

    echo 'export PATH=$PATH:/opt/local/share/java/android-sdk-macosx/platform-tools' >> ~/.bash_profile
    
  6. Refresh your bash profile (or restart your terminal/shell):

    source ~/.bash_profile
    
  7. Start using adb:

    adb devices
    

Insert an item into sorted list in Python

This is a possible solution for you:

a = [15, 12, 10]
b = sorted(a)
print b # --> b = [10, 12, 15]
c = 13
for i in range(len(b)):
    if b[i] > c:
        break
d = b[:i] + [c] + b[i:]
print d # --> d = [10, 12, 13, 15]

Proper MIME type for .woff2 fonts

http://dev.w3.org/webfonts/WOFF2/spec/#IMT

It seem that w3c switched it to font/woff2

I see there is some discussion about the proper mime type. In the link we read:

This document defines a top-level MIME type "font" ...

... the officially defined IANA subtypes such as "application/font-woff" ...

The members of the W3C WebFonts WG believe the use of "application" top-level type is not ideal.

and later

6.5. WOFF 2.0

    Type name:

        font
    Subtype name:

        woff2

So proposition from W3C differs from IANA.

We can see that it also differs from woff type: http://dev.w3.org/webfonts/WOFF/spec/#IMT where we read:

Type name:

    application
Subtype name:

    font-woff

which is

application/font-woff

http://www.w3.org/TR/WOFF/#appendix-b

Find non-ASCII characters in varchar columns using SQL Server

I've been running this bit of code with success

declare @UnicodeData table (
     data nvarchar(500)
)
insert into 
    @UnicodeData
values 
    (N'Horse?')
    ,(N'Dog')
    ,(N'Cat')

select
    data
from
    @UnicodeData 
where
    data collate LATIN1_GENERAL_BIN != cast(data as varchar(max))

Which works well for known columns.

For extra credit, I wrote this quick script to search all nvarchar columns in a given table for Unicode characters.

declare 
    @sql    varchar(max)    = ''
    ,@table sysname         = 'mytable' -- enter your table here

;with ColumnData as (
    select
        RowId               = row_number() over (order by c.COLUMN_NAME)
        ,c.COLUMN_NAME
        ,ColumnName         = '[' + c.COLUMN_NAME + ']'
        ,TableName          = '[' + c.TABLE_SCHEMA + '].[' + c.TABLE_NAME + ']' 
    from
        INFORMATION_SCHEMA.COLUMNS c
    where
        c.DATA_TYPE         = 'nvarchar'
        and c.TABLE_NAME    = @table
)
select
    @sql = @sql + 'select FieldName = ''' + c.ColumnName + ''',         InvalidCharacter = [' + c.COLUMN_NAME + ']  from ' + c.TableName + ' where ' + c.ColumnName + ' collate LATIN1_GENERAL_BIN != cast(' + c.ColumnName + ' as varchar(max)) '  +  case when c.RowId <> (select max(RowId) from ColumnData) then  ' union all ' else '' end + char(13)
from
    ColumnData c

-- check
-- print @sql
exec (@sql)

I'm not a fan of dynamic SQL but it does have its uses for exploratory queries like this.

Error : Program type already present: android.support.design.widget.CoordinatorLayout$Behavior

I had this problem too; and i resolved that in this way:

configurations.all {
resolutionStrategy.eachDependency { DependencyResolveDetails details ->
    def requested = details.requested
    if (requested.group == 'com.android.support') {
        if (!requested.name.startsWith("multidex")) {
            details.useVersion '26.0.1'
        }
    }
  }
}

be careful my min SDk was 26 , you have to change it with yours!

Synchronizing a local Git repository with a remote one

Sounds like you want a mirror of the remote repository:

git clone --mirror url://to/remote.git local.git

That command creates a bare repository. If you don't want a bare repository, things get more complicated.

How to run JUnit test cases from the command line

Actually you can also make the Junit test a runnable Jar and call the runnable jar as java -jar

How to get file extension from string in C++

I use these two functions to get the extension and filename without extension:

std::string fileExtension(std::string file){

    std::size_t found = file.find_last_of(".");
    return file.substr(found+1);

}

std::string fileNameWithoutExtension(std::string file){

    std::size_t found = file.find_last_of(".");
    return file.substr(0,found);    
}

And these regex approaches for certain extra requirements:

std::string fileExtension(std::string file){

    std::regex re(".*[^\\.]+\\.([^\\.]+$)");
    std::smatch result;
    if(std::regex_match(file,result,re))return result[1];
    else return "";

}

std::string fileNameWithoutExtension(std::string file){

    std::regex re("(.*[^\\.]+)\\.[^\\.]+$");
    std::smatch result;
    if(std::regex_match(file,result,re))return result[1];
    else return file;

}

Extra requirements that are met by the regex method:

  1. If filename is like .config or something like this, extension will be an empty string and filename without extension will be .config.
  2. If filename doesn't have any extension, extention will be an empty string, filename without extension will be the filename unchanged.

EDIT:

The extra requirements can also be met by the following:

std::string fileExtension(const std::string& file){
    std::string::size_type pos=file.find_last_of('.');
    if(pos!=std::string::npos&&pos!=0)return file.substr(pos+1);
    else return "";
}


std::string fileNameWithoutExtension(const std::string& file){
    std::string::size_type pos=file.find_last_of('.');
    if(pos!=std::string::npos&&pos!=0)return file.substr(0,pos);
    else return file;
}

Note:

Pass only the filenames (not path) in the above functions.

PHP Fatal error: Cannot redeclare class

I had the same problem "PHP Fatal error: Cannot redeclare class XYZ.php".

I have two directories like controller and model and I uploaded by mistakenly XYZ.php in both directories.(so file with the same name cause the issue).

First solution:

Find in your whole project and make sure you have only one class XYZ.php.

Second solution:

Add a namespace in your class so you can use the same class name.

SQL UPDATE all values in a field with appended string CONCAT not working

convert the NULL values with empty string by wrapping it in COALESCE

"UPDATE table SET data = CONCAT(COALESCE(`data`,''), 'a')"

OR

Use CONCAT_WS instead:

"UPDATE table SET data = CONCAT_WS(',',data, 'a')"

How to get function parameter names/values dynamically?

I've tried doing this before, but never found a praticial way to get it done. I ended up passing in an object instead and then looping through it.

//define like
function test(args) {
    for(var item in args) {
        alert(item);
        alert(args[item]);
    }
}

//then used like
test({
    name:"Joe",
    age:40,
    admin:bool
});

Java - How do I make a String array with values?

You could do something like this

String[] myStrings = { "One", "Two", "Three" };

or in expression

functionCall(new String[] { "One", "Two", "Three" });

or

String myStrings[];
myStrings = new String[] { "One", "Two", "Three" };

Determining 32 vs 64 bit in C++

Try this:
#ifdef _WIN64
// 64 bit code
#elif _WIN32
// 32 bit code
#else
   if(sizeof(void*)==4)

       // 32 bit code
   else 

       // 64 bit code   
#endif

CSS Styling for a Button: Using <input type="button> instead of <button>

Do you want something like the given fiddle!


HTML

<div class="button">
    <input type="button" value="TELL ME MORE" onClick="document.location.reload(true)">
</div>

CSS

.button input[type="button"] {
    color:#08233e;
    font:2.4em Futura, ‘Century Gothic’, AppleGothic, sans-serif;
    font-size:70%;
    padding:14px;
    background:url(overlay.png) repeat-x center #ffcc00;
    background-color:rgba(255,204,0,1);
    border:1px solid #ffcc00;
    -moz-border-radius:10px;
    -webkit-border-radius:10px;
    border-radius:10px;
    border-bottom:1px solid #9f9f9f;
    -moz-box-shadow:inset 0 1px 0 rgba(255,255,255,0.5);
    -webkit-box-shadow:inset 0 1px 0 rgba(255,255,255,0.5);
    box-shadow:inset 0 1px 0 rgba(255,255,255,0.5);
    cursor:pointer;
    display:block;
    width:100%;
}
.button input[type="button"]:hover {
    background-color:rgba(255,204,0,0.8);
}

How do I enable saving of filled-in fields on a PDF form?

Open your PDF in Google Chrome. Edit the PDF as you want. Hit ctrl + p. Save as PDF to your desktop.

How to execute powershell commands from a batch file?

This is what the code would look like in a batch file(tested, works):

powershell -Command "& {set-location 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings'; set-location ZoneMap\Domains; new-item SERVERNAME; set-location SERVERNAME; new-itemproperty . -Name http -Value 2 -Type DWORD;}"

Based on the information from:

http://dmitrysotnikov.wordpress.com/2008/06/27/powershell-script-in-a-bat-file/

Flask SQLAlchemy query, specify column names

You can use load_only function:

from sqlalchemy.orm import load_only

fields = ['name', 'addr', 'phone', 'url']
companies = session.query(SomeModel).options(load_only(*fields)).all()

How to check if an element is off-screen

Depends on what your definition of "offscreen" is. Is that within the viewport, or within the defined boundaries of your page?

Using Element.getBoundingClientRect() you can easily detect whether or not your element is within the boundries of your viewport (i.e. onscreen or offscreen):

jQuery.expr.filters.offscreen = function(el) {
  var rect = el.getBoundingClientRect();
  return (
           (rect.x + rect.width) < 0 
             || (rect.y + rect.height) < 0
             || (rect.x > window.innerWidth || rect.y > window.innerHeight)
         );
};

You could then use that in several ways:

// returns all elements that are offscreen
$(':offscreen');

// boolean returned if element is offscreen
$('div').is(':offscreen');

How to workaround 'FB is not defined'?

Assuming FB is a variable containing the Facebook object, I'd try something like this:

if (typeof(FB) != 'undefined'
     && FB != null ) {
    // run the app
} else {
    // alert the user
}

In order to test that something is undefined in plain old JavaScript, you should use the "typeof" operator. The sample you show where you just compare it to the string 'undefined' will evaluate to false unless your FB object really does contain the string 'undefined'!

As an aside, you may wish to use various tools like Firebug (in Firefox) to see if you can work out why the Facebook file is not loading.

Install python 2.6 in CentOS

I unistalled the original version of python (2.6.6) and install 2.7(with option make && make altinstall) but when I tried install something with yum didn't work.

So I solved this issue as follow:

  1. # ln -s /usr/local/bin/python /usr/bin/python
  2. Download the RPM package python-2.6.6-36.el6.i686.rpm from http://rpm.pbone.net/index.php3/stat/4/idpl/20270470/dir/centos_6/com/python-2.6.6-36.el6.i686.rpm.html
  3. Execute as root rpm -Uvh python-2.6.6-36.el6.i686.rpm

Done

Error Message: Type or namespace definition, or end-of-file expected

This line:

public  object Hours { get; set; }}

Your have a redundand } at the end

Adding a library/JAR to an Eclipse Android project

Put the source in a folder outside yourt workspace. Rightclick in the project-explorer, and select "Import..."

Import the project in your workspace as an Android project. Try to build it, and make sure it is marked as a library project. Also make sure it is build with Google API support, if not you will get compile errors.

Then, in right click on your main project in the project explorer. Select properties, then select Android on the left. In the library section below, click "Add"..

The mapview-balloons library should now be available to add to your project..

Multiprocessing vs Threading Python

Python documentation quotes

The canonical version of this answer is now at the dupliquee question: What are the differences between the threading and multiprocessing modules?

I've highlighted the key Python documentation quotes about Process vs Threads and the GIL at: What is the global interpreter lock (GIL) in CPython?

Process vs thread experiments

I did a bit of benchmarking in order to show the difference more concretely.

In the benchmark, I timed CPU and IO bound work for various numbers of threads on an 8 hyperthread CPU. The work supplied per thread is always the same, such that more threads means more total work supplied.

The results were:

enter image description here

Plot data.

Conclusions:

  • for CPU bound work, multiprocessing is always faster, presumably due to the GIL

  • for IO bound work. both are exactly the same speed

  • threads only scale up to about 4x instead of the expected 8x since I'm on an 8 hyperthread machine.

    Contrast that with a C POSIX CPU-bound work which reaches the expected 8x speedup: What do 'real', 'user' and 'sys' mean in the output of time(1)?

    TODO: I don't know the reason for this, there must be other Python inefficiencies coming into play.

Test code:

#!/usr/bin/env python3

import multiprocessing
import threading
import time
import sys

def cpu_func(result, niters):
    '''
    A useless CPU bound function.
    '''
    for i in range(niters):
        result = (result * result * i + 2 * result * i * i + 3) % 10000000
    return result

class CpuThread(threading.Thread):
    def __init__(self, niters):
        super().__init__()
        self.niters = niters
        self.result = 1
    def run(self):
        self.result = cpu_func(self.result, self.niters)

class CpuProcess(multiprocessing.Process):
    def __init__(self, niters):
        super().__init__()
        self.niters = niters
        self.result = 1
    def run(self):
        self.result = cpu_func(self.result, self.niters)

class IoThread(threading.Thread):
    def __init__(self, sleep):
        super().__init__()
        self.sleep = sleep
        self.result = self.sleep
    def run(self):
        time.sleep(self.sleep)

class IoProcess(multiprocessing.Process):
    def __init__(self, sleep):
        super().__init__()
        self.sleep = sleep
        self.result = self.sleep
    def run(self):
        time.sleep(self.sleep)

if __name__ == '__main__':
    cpu_n_iters = int(sys.argv[1])
    sleep = 1
    cpu_count = multiprocessing.cpu_count()
    input_params = [
        (CpuThread, cpu_n_iters),
        (CpuProcess, cpu_n_iters),
        (IoThread, sleep),
        (IoProcess, sleep),
    ]
    header = ['nthreads']
    for thread_class, _ in input_params:
        header.append(thread_class.__name__)
    print(' '.join(header))
    for nthreads in range(1, 2 * cpu_count):
        results = [nthreads]
        for thread_class, work_size in input_params:
            start_time = time.time()
            threads = []
            for i in range(nthreads):
                thread = thread_class(work_size)
                threads.append(thread)
                thread.start()
            for i, thread in enumerate(threads):
                thread.join()
            results.append(time.time() - start_time)
        print(' '.join('{:.6e}'.format(result) for result in results))

GitHub upstream + plotting code on same directory.

Tested on Ubuntu 18.10, Python 3.6.7, in a Lenovo ThinkPad P51 laptop with CPU: Intel Core i7-7820HQ CPU (4 cores / 8 threads), RAM: 2x Samsung M471A2K43BB1-CRC (2x 16GiB), SSD: Samsung MZVLB512HAJQ-000L7 (3,000 MB/s).

Visualize which threads are running at a given time

This post https://rohanvarma.me/GIL/ taught me that you can run a callback whenever a thread is scheduled with the target= argument of threading.Thread and the same for multiprocessing.Process.

This allows us to view exactly which thread runs at each time. When this is done, we would see something like (I made this particular graph up):

            +--------------------------------------+
            + Active threads / processes           +
+-----------+--------------------------------------+
|Thread   1 |********     ************             |
|         2 |        *****            *************|
+-----------+--------------------------------------+
|Process  1 |***  ************** ******  ****      |
|         2 |** **** ****** ** ********* **********|
+-----------+--------------------------------------+
            + Time -->                             +
            +--------------------------------------+

which would show that:

  • threads are fully serialized by the GIL
  • processes can run in parallel

execute shell command from android

Process p;
StringBuffer output = new StringBuffer();
try {
    p = Runtime.getRuntime().exec(params[0]);
    BufferedReader reader = new BufferedReader(
            new InputStreamReader(p.getInputStream()));
    String line = "";
    while ((line = reader.readLine()) != null) {
        output.append(line + "\n");
        p.waitFor();
    }
} 
catch (IOException e) {
    e.printStackTrace();
} catch (InterruptedException e) {
    e.printStackTrace();
}
String response = output.toString();
return response;

Reading and writing binary file

Here is implementation of standard C++ 14 using vectors and tuples to Read and Write Text,Binary and Hex files.

Snippet code :

try {
if (file_type == BINARY_FILE) {

    /*Open the stream in binary mode.*/
    std::ifstream bin_file(file_name, std::ios::binary);

    if (bin_file.good()) {
        /*Read Binary data using streambuffer iterators.*/
        std::vector<uint8_t> v_buf((std::istreambuf_iterator<char>(bin_file)), (std::istreambuf_iterator<char>()));
        vec_buf = v_buf;
        bin_file.close();
    }

    else {
        throw std::exception();
    }

}

else if (file_type == ASCII_FILE) {

    /*Open the stream in default mode.*/
    std::ifstream ascii_file(file_name);
    string ascii_data;

    if (ascii_file.good()) {
        /*Read ASCII data using getline*/
        while (getline(ascii_file, ascii_data))
            str_buf += ascii_data + "\n";

        ascii_file.close();
    }
    else {
        throw std::exception();
    }
}

else if (file_type == HEX_FILE) {

    /*Open the stream in default mode.*/
    std::ifstream hex_file(file_name);

    if (hex_file.good()) {
        /*Read Hex data using streambuffer iterators.*/
        std::vector<char> h_buf((std::istreambuf_iterator<char>(hex_file)), (std::istreambuf_iterator<char>()));
        string hex_str_buf(h_buf.begin(), h_buf.end());
        hex_buf = hex_str_buf;

        hex_file.close();
    }
    else {
        throw std::exception();
    }
}

}

Full Source code can be found here

comma separated string of selected values in mysql

If you have multiple rows for parent_id.

SELECT GROUP_CONCAT(id) FROM table_level where parent_id=4 GROUP BY parent_id;

If you want to replace space with comma.

SELECT REPLACE(id,' ',',') FROM table_level where parent_id=4;

What certificates are trusted in truststore?

Is there any equivalent for the truststore? How can I view the trusted certificates?

Yes there is.The exact same command since keystore and truststore differ only in what they store i.e. private key or signed public key (certificate)

No other difference

How do you access the matched groups in a JavaScript regular expression?

You can access capturing groups like this:

_x000D_
_x000D_
var myString = "something format_abc";_x000D_
var myRegexp = /(?:^|\s)format_(.*?)(?:\s|$)/g;_x000D_
var match = myRegexp.exec(myString);_x000D_
console.log(match[1]); // abc
_x000D_
_x000D_
_x000D_

And if there are multiple matches you can iterate over them:

_x000D_
_x000D_
var myString = "something format_abc";_x000D_
var myRegexp = /(?:^|\s)format_(.*?)(?:\s|$)/g;_x000D_
match = myRegexp.exec(myString);_x000D_
while (match != null) {_x000D_
  // matched text: match[0]_x000D_
  // match start: match.index_x000D_
  // capturing group n: match[n]_x000D_
  console.log(match[0])_x000D_
  match = myRegexp.exec(myString);_x000D_
}
_x000D_
_x000D_
_x000D_

Edit: 2019-09-10

As you can see the way to iterate over multiple matches was not very intuitive. This lead to the proposal of the String.prototype.matchAll method. This new method is expected to ship in the ECMAScript 2020 specification. It gives us a clean API and solves multiple problems. It has been started to land on major browsers and JS engines as Chrome 73+ / Node 12+ and Firefox 67+.

The method returns an iterator and is used as follows:

_x000D_
_x000D_
const string = "something format_abc";_x000D_
const regexp = /(?:^|\s)format_(.*?)(?:\s|$)/g;_x000D_
const matches = string.matchAll(regexp);_x000D_
    _x000D_
for (const match of matches) {_x000D_
  console.log(match);_x000D_
  console.log(match.index)_x000D_
}
_x000D_
_x000D_
_x000D_

As it returns an iterator, we can say it's lazy, this is useful when handling particularly large numbers of capturing groups, or very large strings. But if you need, the result can be easily transformed into an Array by using the spread syntax or the Array.from method:

function getFirstGroup(regexp, str) {
  const array = [...str.matchAll(regexp)];
  return array.map(m => m[1]);
}

// or:
function getFirstGroup(regexp, str) {
  return Array.from(str.matchAll(regexp), m => m[1]);
}

In the meantime, while this proposal gets more wide support, you can use the official shim package.

Also, the internal workings of the method are simple. An equivalent implementation using a generator function would be as follows:

function* matchAll(str, regexp) {
  const flags = regexp.global ? regexp.flags : regexp.flags + "g";
  const re = new RegExp(regexp, flags);
  let match;
  while (match = re.exec(str)) {
    yield match;
  }
}

A copy of the original regexp is created; this is to avoid side-effects due to the mutation of the lastIndex property when going through the multple matches.

Also, we need to ensure the regexp has the global flag to avoid an infinite loop.

I'm also happy to see that even this StackOverflow question was referenced in the discussions of the proposal.

Update Eclipse with Android development tools v. 23

I was updating my build server today and came across the same issue. It has been reported here: https://code.google.com/p/android/issues/detail?id=72419

The fix is in progress and the work around according to the project manager is:

Please wait for an updated version within a day or two. Until then, your workaround is to do download one of

http://dl.google.com/android/android-sdk_r22.6.2-linux.tgz

http://dl.google.com/android/android-sdk_r22.6.2-windows.zip

http://dl.google.com/android/android-sdk_r22.6.2-macosx.zip

and copy over the following files:

    tools/hprof-conv
    tools/support/annotations.jar
    tools/proguard

[edit] zipalign was missing for me too, check to see if you need to copy this as well

Javax.net.ssl.SSLHandshakeException: javax.net.ssl.SSLProtocolException: SSL handshake aborted: Failure in SSL library, usually a protocol error

Previously, I've also solved this problem with custom SSLFactory implementation, but according to OkHttp docs the solution is much easier.

My final solution with needed TLS ciphers for 4.2+ devices looks like this:

public UsersApi provideUsersApi() {

    private ConnectionSpec spec = new ConnectionSpec.Builder(ConnectionSpec.COMPATIBLE_TLS)
        .supportsTlsExtensions(true)
        .tlsVersions(TlsVersion.TLS_1_2, TlsVersion.TLS_1_1, TlsVersion.TLS_1_0)
        .cipherSuites(
                CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
                CipherSuite.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
                CipherSuite.TLS_DHE_RSA_WITH_AES_128_GCM_SHA256,
                CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA,
                CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA,
                CipherSuite.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA,
                CipherSuite.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA,
                CipherSuite.TLS_ECDHE_ECDSA_WITH_RC4_128_SHA,
                CipherSuite.TLS_ECDHE_RSA_WITH_RC4_128_SHA,
                CipherSuite.TLS_DHE_RSA_WITH_AES_128_CBC_SHA,
                CipherSuite.TLS_DHE_DSS_WITH_AES_128_CBC_SHA,
                CipherSuite.TLS_DHE_RSA_WITH_AES_256_CBC_SHA)
        .build();

    OkHttpClient client = new OkHttpClient.Builder()
            .connectionSpecs(Collections.singletonList(spec))
            .build();

    return new Retrofit.Builder()
            .baseUrl(USERS_URL)
            .addConverterFactory(GsonConverterFactory.create())
            .client(client)
            .build()
            .create(UsersApi.class);
}

Note that set of supported protocols depends on configured on your server.

Custom Listview Adapter with filter Android

please check below code it will help you

DrawerActivity.userListview
            .setOnItemClickListener(new OnItemClickListener() {

                @Override
                public void onItemClick(AdapterView<?> parent, View view,
                        int position, long id) {

                    int pos = position;
                    Intent intent = new Intent(getContext(),
                            UserDetail.class);
                    intent.putExtra("model", list.get(position));
                    context.startActivity(intent);
                }
            });
    return convertView;
}

@Override
public android.widget.Filter getFilter() {

    return new android.widget.Filter() {

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

            ArrayList<UserListModel> updatelist = (ArrayList<UserListModel>) results.values;
            UserListCustomAdaptor newadaptor = new UserListCustomAdaptor(
                    getContext(), getCount(), updatelist);

            if (results.equals(constraint)) {
                updatelist.add(modelobj);
            }
            if (results.count > 0) {
                notifyDataSetChanged();
            } else {

                notifyDataSetInvalidated();
            }
        }

        @Override
        protected FilterResults performFiltering(CharSequence constraint) {

            FilterResults filterResults = new FilterResults();
            list = new ArrayList<UserListModel>();

            if (constraint != null && DrawerActivity.userlist != null) {

                constraint = constraint.toString().toLowerCase();
                int length = DrawerActivity.userlist.size();
                int i = 0;
                while (i < length) {

                    UserListModel modelobj = DrawerActivity.userlist.get(i);
                    String data = modelobj.getFirstName() + " "
                            + modelobj.getLastName();
                    if (data.toLowerCase().contains(constraint.toString())) {
                        list.add(modelobj);
                    }

                    i++;
                }
                filterResults.values = list;
                filterResults.count = list.size();
            }
            return filterResults;
        }
    };
}

@Override
public int getCount() {
    return list.size();
}

@Override
public UserListModel getItem(int position) {

    return list.get(position);
}

get current page from url

The class you need is System.Uri

Dim url As System.Uri = Request.UrlReferrer 
Debug.WriteLine(url.AbsoluteUri)   ' => http://www.mysite.com/default.aspx
Debug.WriteLine(url.AbsolutePath)  ' => /default.aspx
Debug.WriteLine(url.Host)          ' => http:/www.mysite.com
Debug.WriteLine(url.Port)          ' => 80
Debug.WriteLine(url.IsLoopback)    ' => False

http://www.devx.com/vb2themax/Tip/18709

How to enable GZIP compression in IIS 7.5

This is more an add-on to the best answer above (GZip Compression can be enabled directly through IIS) which is correct if your running IIS on Windows desktop however...

If your running IIS on Windows Server, this content compression feature is found in a different place to desktop Windows (not in programs and features in Control Panel). First open "Server Manager" then click Manage -> "Add Roles & Features" then keep clicking NEXT (make sure you select the correct server when you see the list of servers if your managing multiple servers from this instance) until you get to SERVER ROLES, scroll down to and open "Web Server (IIS)..." then "Web Server" then "Performance" then tick "Dynamic Content Compression" then click INSTALL. I tested this on Server 2016 Standard so there may be slight differences if your on an earlier version of Server.

Then follow the instructions from Testing - Check if GZIP Compression is Enabled

How to make a 3D scatter plot in Python?

You can use matplotlib for this. matplotlib has a mplot3d module that will do exactly what you want.

from matplotlib import pyplot
from mpl_toolkits.mplot3d import Axes3D
import random


fig = pyplot.figure()
ax = Axes3D(fig)

sequence_containing_x_vals = list(range(0, 100))
sequence_containing_y_vals = list(range(0, 100))
sequence_containing_z_vals = list(range(0, 100))

random.shuffle(sequence_containing_x_vals)
random.shuffle(sequence_containing_y_vals)
random.shuffle(sequence_containing_z_vals)

ax.scatter(sequence_containing_x_vals, sequence_containing_y_vals, sequence_containing_z_vals)
pyplot.show()

The code above generates a figure like:

matplotlib 3D image

How to Create a script via batch file that will uninstall a program if it was installed on windows 7 64-bit or 32-bit

wmic can call an uninstaller. I haven't tried this, but I think it might work.

wmic /node:computername /user:adminuser /password:password product where name="name of application" call uninstall

If you don't know exactly what the program calls itself, do

wmic product get name | sort

and look for it. You can also uninstall using SQL-ish wildcards.

wmic /node:computername /user:adminuser /password:password product where "name like '%j2se%'" call uninstall

... for example would perform a case-insensitive search for *j2se* and uninstall "J2SE Runtime Environment 5.0 Update 12". (Note that in the example above, %j2se% is not an environment variable, but simply the word "j2se" with a SQL-ish wildcard on each end. If your search string could conflict with an environment or script variable, use double percents to specify literal percent signs, like %%j2se%%.)

If wmic prompts for y/n confirmation before completing the uninstall, try this:

echo y | wmic /node:computername /user:adminuser /password:password product where name="whatever" call uninstall

... to pass a y to it before it even asks.

I haven't tested this, but it's worth a shot anyway. If it works on one computer, then you can just loop through a text file containing all the computer names within your organization using a for loop, or put it in a domain policy logon script.

Import a custom class in Java

If your classes are in the same package, you won't need to import. To call a method from class B in class A, you should use classB.methodName(arg)

Improving bulk insert performance in Entity framework

 Use : db.Set<tale>.AddRange(list); 
Ref :
TESTEntities db = new TESTEntities();
List<Person> persons = new List<Person> { 
new  Person{Name="p1",Place="palce"},
new  Person{Name="p2",Place="palce"},
new  Person{Name="p3",Place="palce"},
new  Person{Name="p4",Place="palce"},
new  Person{Name="p5",Place="palce"}
};
db.Set<Person>().AddRange(persons);
db.SaveChanges();

Editing specific line in text file in Python

You want to do something like this:

# with is like your try .. finally block in this case
with open('stats.txt', 'r') as file:
    # read a list of lines into data
    data = file.readlines()

print data
print "Your name: " + data[0]

# now change the 2nd line, note that you have to add a newline
data[1] = 'Mage\n'

# and write everything back
with open('stats.txt', 'w') as file:
    file.writelines( data )

The reason for this is that you can't do something like "change line 2" directly in a file. You can only overwrite (not delete) parts of a file - that means that the new content just covers the old content. So, if you wrote 'Mage' over line 2, the resulting line would be 'Mageior'.

What's the algorithm to calculate aspect ratio?

You can always start by making a lookup table based on common aspect ratios. Check https://en.wikipedia.org/wiki/Display_aspect_ratio Then you can simply do the division

For real life problems, you can do something like below

let ERROR_ALLOWED = 0.05
let STANDARD_ASPECT_RATIOS = [
  [1, '1:1'],
  [4/3, '4:3'],
  [5/4, '5:4'],
  [3/2, '3:2'],
  [16/10, '16:10'],
  [16/9, '16:9'],
  [21/9, '21:9'],
  [32/9, '32:9'],
]
let RATIOS = STANDARD_ASPECT_RATIOS.map(function(tpl){return tpl[0]}).sort()
let LOOKUP = Object()
for (let i=0; i < STANDARD_ASPECT_RATIOS.length; i++){
  LOOKUP[STANDARD_ASPECT_RATIOS[i][0]] = STANDARD_ASPECT_RATIOS[i][1]
}

/*
Find the closest value in a sorted array
*/
function findClosest(arrSorted, value){
  closest = arrSorted[0]
  closestDiff = Math.abs(arrSorted[0] - value)
  for (let i=1; i<arrSorted.length; i++){
    let diff = Math.abs(arrSorted[i] - value)
    if (diff < closestDiff){
      closestDiff = diff
      closest = arrSorted[i]
    } else {
      return closest
    }
  }
  return arrSorted[arrSorted.length-1]
}

/*
Estimate the aspect ratio based on width x height (order doesn't matter)
*/
function estimateAspectRatio(dim1, dim2){
  let ratio = Math.max(dim1, dim2) / Math.min(dim1, dim2)
  if (ratio in LOOKUP){
    return LOOKUP[ratio]
  }

  // Look by approximation
  closest = findClosest(RATIOS, ratio)
  if (Math.abs(closest - ratio) <= ERROR_ALLOWED){
    return '~' + LOOKUP[closest]
  }

  return 'non standard ratio: ' + Math.round(ratio * 100) / 100 + ':1'
}

Then you simply give the dimensions in any order

estimateAspectRatio(1920, 1080) // 16:9
estimateAspectRatio(1920, 1085) // ~16:9
estimateAspectRatio(1920, 1150) // non standard ratio: 1.65:1
estimateAspectRatio(1920, 1200) // 16:10
estimateAspectRatio(1920, 1220) // ~16:10

Applying Comic Sans Ms font style

The font may exist with different names, and not at all on some systems, so you need to use different variations and fallback to get the closest possible look on all systems:

font-family: "Comic Sans MS", "Comic Sans", cursive;

Be careful what you use this font for, though. Many consider it as ugly and overused, so it should not be use for something that should look professional.

Sort arrays of primitive types in descending order

You cannot use Comparators for sorting primitive arrays.

Your best bet is to implement (or borrow an implementation) of a sorting algorithm that is appropriate for your use case to sort the array (in reverse order in your case).

How can I split a delimited string into an array in PHP?

explode has some very big problems in real life usage:

count(explode(',', null)); // 1 !! 
explode(',', null); // [""] not an empty array, but an array with one empty string!
explode(',', ""); // [""]
explode(',', "1,"); // ["1",""] ending commas are also unsupported, kinda like IE8

this is why i prefer preg_split

preg_split('@,@', $string, NULL, PREG_SPLIT_NO_EMPTY)

the entire boilerplate:

/** @brief wrapper for explode
 * @param string|int|array $val string will explode. '' return []. int return string in array (1 returns ['1']). array return itself. for other types - see $as_is
 * @param bool $as_is false (default): bool/null return []. true: bool/null return itself.
 * @param string $delimiter default ','
 * @return array|mixed
 */
public static function explode($val, $as_is = false, $delimiter = ',')
{
    // using preg_split (instead of explode) because it is the best way to handle ending comma and avoid empty string converted to ['']
    return (is_string($val) || is_int($val)) ?
        preg_split('@' . preg_quote($delimiter, '@') . '@', $val, NULL, PREG_SPLIT_NO_EMPTY)
        :
        ($as_is ? $val : (is_array($val) ? $val : []));
}

Shrinking navigation bar when scrolling down (bootstrap3)

You can combine "scroll" and "scrollstop" events in order to achieve desired result:

$(window).on("scroll",function(){
   $('nav').addClass('shrink');
}); 
$(window).on("scrollstop",function(){
   $('nav').removeClass('shrink');
}); 

How to read if a checkbox is checked in PHP?

<?php

  if (isset($_POST['add'])) {

    $nama      = $_POST['name'];
    $subscribe = isset($_POST['subscribe']) ? $_POST['subscribe'] : "Not Checked";

    echo "Name: {$nama} <br />";
    echo "Subscribe: {$subscribe}";

    echo "<hr />";   

  }

?>

<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="POST" >

  <input type="text" name="name" /> <br />
  <input type="checkbox" name="subscribe" value="news" /> News <br />

  <input type="submit" name="add" value="Save" />

</form>

How to get input type using jquery?

The best place to start looking is http://api.jquery.com/category/selectors/

This will give you a good set of examples.

Ultamatly the selecting of elements in the DOM is achived using CSS selectors so if you think about getting an element by id you will want to use $('#elementId'), if you want all the input tags use $('input') and finaly the part i think you'll want if you want all input tags with a type of checkbox use $('input, [type=checkbox])

Note: You'll find most of the values you want are on attributes so the css selector for attributes is: [attributeName=value]

Just because you asked for the dropdown as aposed to a listbox try the following:


$('select, [size]).each(function(){
  var selectedItem = $('select, [select]', this).first();
});

The code was from memory so please accound for small errors

Replacing characters in Ant property

Or... You can also to try Your Own Task

JAVA CODE:

class CustomString extends Task{

private String type, string, before, after, returnValue;

public void execute() {
    if (getType().equals("replace")) {
        replace(getString(), getBefore(), getAfter());
    }
}

private void replace(String str, String a, String b){
    String results = str.replace(a, b);
    Project project = getProject();
    project.setProperty(getReturnValue(), results);
}

..all getter and setter..

ANT SCRIPT

...
<project name="ant-test" default="build">

<target name="build" depends="compile, run"/>

<target name="clean">
    <delete dir="build" />
</target>

<target name="compile" depends="clean">
    <mkdir dir="build/classes"/>
    <javac srcdir="src" destdir="build/classes" includeantruntime="true"/>
</target>

<target name="declare" depends="compile">
    <taskdef name="string" classname="CustomString" classpath="build/classes" />
</target>

<!-- Replacing characters in Ant property -->
<target name="run" depends="declare">
    <property name="propA" value="This is a value"/>
    <echo message="propA=${propA}" />
    <string type="replace" string="${propA}" before=" " after="_" returnvalue="propB"/>
    <echo message="propB=${propB}" />
</target>

CONSOLE:

run:
     [echo] propA=This is a value
     [echo] propB=This_is_a_value

Concatenating strings doesn't work as expected

std::string a = "Hello ";
std::string b = "World ";
std::string c = a;
c.append(b);

How do I stop/start a scheduled task on a remote computer programmatically?

schtasks /change /disable /tn "Name Of Task" /s REMOTEMACHINENAME /u mydomain\administrator /p adminpassword 

angular js unknown provider

To add my own experience in here, I was trying to inject a service into one of my module config functions. This paragraph from the docs which I eventually found explains why that doesn't work:

During application bootstrap, before Angular goes off creating all services, it configures and instantiates all providers. We call this the configuration phase of the application life-cycle. During this phase, services aren't accessible because they haven't been created yet.

Meaning you can inject providers into module.config(...) functions, but you can't inject services, for that you need to wait until module.run(...), or expose a provider you can inject to module.config

Checking if a list is empty with LINQ

If I check with Count() Linq executes a "SELECT COUNT(*).." in the database, but I need to check if the results contains data, I resolved to introducing FirstOrDefault() instead of Count();

Before

var cfop = from tabelaCFOPs in ERPDAOManager.GetTable<TabelaCFOPs>()

if (cfop.Count() > 0)
{
    var itemCfop = cfop.First();
    //....
}

After

var cfop = from tabelaCFOPs in ERPDAOManager.GetTable<TabelaCFOPs>()

var itemCfop = cfop.FirstOrDefault();

if (itemCfop != null)
{
    //....
}

"The stylesheet was not loaded because its MIME type, "text/html" is not "text/css"

This is more likely an issue at your server side. you request style sheet page "Styles/Site.css" from the server of type "text/css", but your server might be responding to this request with "test/html". I had this issue when my server was running in python and it was replying to requested css files with header text/html (as that of my index.html file). I re-arranged my server code and assigned the correct headers to its corresponding pages and my issue got resolved.

Bold words in a string of strings.xml in Android

You could basically use html tags in your string resource like:

<resource>
    <string name="styled_welcome_message">We are <b><i>so</i></b> glad to see you.</string>
</resources>

And use Html.fromHtml or use spannable, check the link I posted.

Old similar question: Is it possible to have multiple styles inside a TextView?

*.h or *.hpp for your class definitions

I use .hpp because I want the user to differentiate what headers are C++ headers, and what headers are C headers.

This can be important when your project is using both C and C++ modules: Like someone else explained before me, you should do it very carefully, and its starts by the "contract" you offer through the extension

.hpp : C++ Headers

(Or .hxx, or .hh, or whatever)

This header is for C++ only.

If you're in a C module, don't even try to include it. You won't like it, because no effort is done to make it C-friendly (too much would be lost, like function overloading, namespaces, etc. etc.).

.h : C/C++ compatible or pure C Headers

This header can be included by both a C source, and a C++ source, directly or indirectly.

It can included directly, being protected by the __cplusplus macro:

  • Which mean that, from a C++ viewpoint, the C-compatible code will be defined as extern "C".
  • From a C viewpoint, all the C code will be plainly visible, but the C++ code will be hidden (because it won't compile in a C compiler).

For example:

#ifndef MY_HEADER_H
#define MY_HEADER_H

   #ifdef __cplusplus
      extern "C"
      {
   #endif

   void myCFunction() ;

   #ifdef __cplusplus
      } // extern "C"
   #endif

#endif // MY_HEADER_H

Or it could be included indirectly by the corresponding .hpp header enclosing it with the extern "C" declaration.

For example:

#ifndef MY_HEADER_HPP
#define MY_HEADER_HPP

extern "C"
{
#include "my_header.h"
}

#endif // MY_HEADER_HPP

and:

#ifndef MY_HEADER_H
#define MY_HEADER_H

void myCFunction() ;

#endif // MY_HEADER_H

Force GUI update from UI Thread

After updating the UI, start a task to perform with the long running operation:

label.Text = "Please Wait...";

Task<string> task = Task<string>.Factory.StartNew(() =>
{
    try
    {
        SomewhatLongRunningOperation();
        return "Success!";
    }
    catch (Exception e)
    {
        return "Error: " + e.Message;
    }
});
Task UITask = task.ContinueWith((ret) =>
{
    label.Text = ret.Result;
}, TaskScheduler.FromCurrentSynchronizationContext());

This works in .NET 3.5 and later.

Creating stored procedure with declare and set variables

I assume you want to pass the Order ID in. So:

CREATE PROCEDURE [dbo].[Procedure_Name]
(
    @OrderID INT
) AS
BEGIN
    Declare @OrderItemID AS INT
    DECLARE @AppointmentID AS INT
    DECLARE @PurchaseOrderID AS INT
    DECLARE @PurchaseOrderItemID AS INT
    DECLARE @SalesOrderID AS INT
    DECLARE @SalesOrderItemID AS INT

    SET @OrderItemID = (SELECT OrderItemID FROM [OrderItem] WHERE OrderID = @OrderID)
    SET @AppointmentID = (SELECT AppoinmentID FROM [Appointment] WHERE OrderID = @OrderID)
    SET @PurchaseOrderID = (SELECT PurchaseOrderID FROM [PurchaseOrder] WHERE OrderID = @OrderID)
END

Add rows to CSV File in powershell

Create a new custom object and add it to the object array that Import-Csv creates.

$fileContent = Import-csv $file -header "Date", "Description"
$newRow = New-Object PsObject -Property @{ Date = 'Text4' ; Description = 'Text5' }
$fileContent += $newRow

Twitter bootstrap progress bar animation on page load

While Tats_innit's answer has a nice touch to it, I had to do it a bit differently since I have more than one progress bar on the page.

here's my solution:

JSfiddle: http://jsfiddle.net/vacNJ/

HTML (example):

<div class="progress progress-success">
<div class="bar" style="float: left; width: 0%; " data-percentage="60"></div>
</div>

<div class="progress progress-success">
<div class="bar" style="float: left; width: 0%; " data-percentage="50"></div>
</div>

<div class="progress progress-success">
<div class="bar" style="float: left; width: 0%; " data-percentage="40"></div>
</div>

?

JavaScript:

setTimeout(function(){

    $('.progress .bar').each(function() {
        var me = $(this);
        var perc = me.attr("data-percentage");

        var current_perc = 0;

        var progress = setInterval(function() {
            if (current_perc>=perc) {
                clearInterval(progress);
            } else {
                current_perc +=1;
                me.css('width', (current_perc)+'%');
            }

            me.text((current_perc)+'%');

        }, 50);

    });

},300);

@Tats_innit: Using setInterval() to dynamically recalc the progress is a nice solution, thx mate! ;)

EDIT:

A friend of mine wrote a nice jquery plugin for custom twitter bootstrap progress bars. Here's a demo: http://minddust.github.com/bootstrap-progressbar/

Here's the Github repo: https://github.com/minddust/bootstrap-progressbar

Can I access variables from another file?

This is quite an old question, but I'm going to provide a modern solution that's been available since ES6 - export and import:

In first.js:

let colorcodes = <whatever>;
export default colorcodes //or a different export statement

In second.js:

import colorcodes from <path-to-first.js> //or a matching import statement

How to pass a function as a parameter in Java?

You could use Java reflection to do this. The method would be represented as an instance of java.lang.reflect.Method.

import java.lang.reflect.Method;

public class Demo {

    public static void main(String[] args) throws Exception{
        Class[] parameterTypes = new Class[1];
        parameterTypes[0] = String.class;
        Method method1 = Demo.class.getMethod("method1", parameterTypes);

        Demo demo = new Demo();
        demo.method2(demo, method1, "Hello World");
    }

    public void method1(String message) {
        System.out.println(message);
    }

    public void method2(Object object, Method method, String message) throws Exception {
        Object[] parameters = new Object[1];
        parameters[0] = message;
        method.invoke(object, parameters);
    }

}

Convert Java object to XML string

Here is a util class for marshaling and unmarshaling objects. In my case it was a nested class, so I made it static JAXBUtils.

import javax.xml.bind.JAXB;
import java.io.StringReader;
import java.io.StringWriter;

public class JAXBUtils
{
    /**
     * Unmarshal an XML string
     * @param xml     The XML string
     * @param type    The JAXB class type.
     * @return The unmarshalled object.
     */
    public <T> T unmarshal(String xml, Class<T> type)
    {
        StringReader reader = new StringReader(xml);
        return javax.xml.bind.JAXB.unmarshal(reader, type);
    }

    /**
     * Marshal an Object to XML.
     * @param object    The object to marshal.
     * @return The XML string representation of the object.
     */
    public String marshal(Object object)
    {
        StringWriter stringWriter = new StringWriter();
        JAXB.marshal(object, stringWriter);
        return stringWriter.toString();
    }
}

How to create user for a db in postgresql?

From CLI:

$ su - postgres 
$ psql template1
template1=# CREATE USER tester WITH PASSWORD 'test_password';
template1=# GRANT ALL PRIVILEGES ON DATABASE "test_database" to tester;
template1=# \q

PHP (as tested on localhost, it works as expected):

  $connString = 'port=5432 dbname=test_database user=tester password=test_password';
  $connHandler = pg_connect($connString);
  echo 'Connected to '.pg_dbname($connHandler);

Nesting optgroups in a dropdownlist/select

I think if you have something that structured and complex, you might consider something other than a single drop-down box.

What is the difference between Python's list methods append and extend?

What is the difference between the list methods append and extend?

  • append adds its argument as a single element to the end of a list. The length of the list itself will increase by one.
  • extend iterates over its argument adding each element to the list, extending the list. The length of the list will increase by however many elements were in the iterable argument.

append

The list.append method appends an object to the end of the list.

my_list.append(object) 

Whatever the object is, whether a number, a string, another list, or something else, it gets added onto the end of my_list as a single entry on the list.

>>> my_list
['foo', 'bar']
>>> my_list.append('baz')
>>> my_list
['foo', 'bar', 'baz']

So keep in mind that a list is an object. If you append another list onto a list, the first list will be a single object at the end of the list (which may not be what you want):

>>> another_list = [1, 2, 3]
>>> my_list.append(another_list)
>>> my_list
['foo', 'bar', 'baz', [1, 2, 3]]
                     #^^^^^^^^^--- single item at the end of the list.

extend

The list.extend method extends a list by appending elements from an iterable:

my_list.extend(iterable)

So with extend, each element of the iterable gets appended onto the list. For example:

>>> my_list
['foo', 'bar']
>>> another_list = [1, 2, 3]
>>> my_list.extend(another_list)
>>> my_list
['foo', 'bar', 1, 2, 3]

Keep in mind that a string is an iterable, so if you extend a list with a string, you'll append each character as you iterate over the string (which may not be what you want):

>>> my_list.extend('baz')
>>> my_list
['foo', 'bar', 1, 2, 3, 'b', 'a', 'z']

Operator Overload, __add__ (+) and __iadd__ (+=)

Both + and += operators are defined for list. They are semantically similar to extend.

my_list + another_list creates a third list in memory, so you can return the result of it, but it requires that the second iterable be a list.

my_list += another_list modifies the list in-place (it is the in-place operator, and lists are mutable objects, as we've seen) so it does not create a new list. It also works like extend, in that the second iterable can be any kind of iterable.

Don't get confused - my_list = my_list + another_list is not equivalent to += - it gives you a brand new list assigned to my_list.

Time Complexity

Append has constant time complexity, O(1).

Extend has time complexity, O(k).

Iterating through the multiple calls to append adds to the complexity, making it equivalent to that of extend, and since extend's iteration is implemented in C, it will always be faster if you intend to append successive items from an iterable onto a list.

Performance

You may wonder what is more performant, since append can be used to achieve the same outcome as extend. The following functions do the same thing:

def append(alist, iterable):
    for item in iterable:
        alist.append(item)

def extend(alist, iterable):
    alist.extend(iterable)

So let's time them:

import timeit

>>> min(timeit.repeat(lambda: append([], "abcdefghijklmnopqrstuvwxyz")))
2.867846965789795
>>> min(timeit.repeat(lambda: extend([], "abcdefghijklmnopqrstuvwxyz")))
0.8060121536254883

Addressing a comment on timings

A commenter said:

Perfect answer, I just miss the timing of comparing adding only one element

Do the semantically correct thing. If you want to append all elements in an iterable, use extend. If you're just adding one element, use append.

Ok, so let's create an experiment to see how this works out in time:

def append_one(a_list, element):
    a_list.append(element)

def extend_one(a_list, element):
    """creating a new list is semantically the most direct
    way to create an iterable to give to extend"""
    a_list.extend([element])

import timeit

And we see that going out of our way to create an iterable just to use extend is a (minor) waste of time:

>>> min(timeit.repeat(lambda: append_one([], 0)))
0.2082819009956438
>>> min(timeit.repeat(lambda: extend_one([], 0)))
0.2397019260097295

We learn from this that there's nothing gained from using extend when we have only one element to append.

Also, these timings are not that important. I am just showing them to make the point that, in Python, doing the semantically correct thing is doing things the Right Way™.

It's conceivable that you might test timings on two comparable operations and get an ambiguous or inverse result. Just focus on doing the semantically correct thing.

Conclusion

We see that extend is semantically clearer, and that it can run much faster than append, when you intend to append each element in an iterable to a list.

If you only have a single element (not in an iterable) to add to the list, use append.

Can we add div inside table above every <tr>?

You can't put a div directly inside a table but you can put div inside td or th element.

For that you need to do is make sure the div is inside an actual table cell, a td or th element, so do that:

HTML:-

<tr>
  <td>
    <div>
      <p>I'm text in a div.</p>
    </div>
  </td>
</tr>

For more information :-

http://css-tricks.com/using-divs-inside-tables/

Difference between e.target and e.currentTarget

e.currentTarget would always return the component onto which the event listener is added.

On the other hand, e.target can be the component itself or any direct child or grand child or grand-grand-child and so on who received the event. In other words, e.target returns the component which is on top in the Display List hierarchy and must be in the child hierarchy or the component itself.

One use can be when you have several Image in Canvas and you want to drag Images inside the component but Canvas. You can add a listener on Canvas and in that listener you can write the following code to make sure that Canvas wouldn't get dragged.

function dragImageOnly(e:MouseEvent):void
{
    if(e.target==e.currentTarget)
    {
        return;
     }
     else
     {
        Image(e.target).startDrag();
     }
}

Batch Script to Run as Administrator

@echo off

 call :isAdmin

 if %errorlevel% == 0 (
    goto :run
 ) else (
    echo Requesting administrative privileges...
    goto :UACPrompt
 )

 exit /b

 :isAdmin
    fsutil dirty query %systemdrive% >nul
 exit /b

 :run
  <YOUR BATCH SCRIPT HERE>
 exit /b

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

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

How to rename HTML "browse" button of an input type=file?

  1. Wrap the <input type="file"> with a <label> tag;
  2. Add a tag (with the text that you need) inside the label, like a <span> or <a>;
  3. Make this tag look like a button;
  4. Make input[type="file"] invisible via display: none.

What Process is using all of my disk IO

You're looking for iotop (assuming you've got kernel >2.6.20 and Python 2.5). Failing that, you're looking into hooking into the filesystem. I recommend the former.

What is WEB-INF used for in a Java EE web application?

There is a convention (not necessary) of placing jsp pages under WEB-INF directory so that they cannot be deep linked or bookmarked to. This way all requests to jsp page must be directed through our application, so that user experience is guaranteed.

Why are there two ways to unstage a file in Git?

For versions 2.23 and above only,

Instead of these suggestions, you could use git restore --staged <file> in order to unstage the file(s).

Your project path contains non-ASCII characters android studio

I solved this issue by adding this line

android.overridePathCheck=true

to

gradle.properties

As this message said

This warning can be disabled by using 
the command line flag -Dcom.android.build.gradle.overridePathCheck=true,
 or adding the line 
'com.android.build.gradle.overridePathCheck=true'
 to gradle.properties file in the project directory.

Getting indices of True values in a boolean list

Using element-wise multiplication and a set:

>>> states = [False, False, False, False, True, True, False, True, False, False, False, False, False, False, False, False]
>>> set(multiply(states,range(1,len(states)+1))-1).difference({-1})

Output: {4, 5, 7}

Angular 2 Dropdown Options Default Value

Fully fleshing out other posts, here is what works in Angular2 quickstart,

To set the DOM default: along with *ngFor, use a conditional statement in the <option>'s selected attribute.

To set the Control's default: use its constructor argument. Otherwise before an onchange when the user re-selects an option, which sets the control's value with the selected option's value attribute, the control value will be null.

script:

import {ControlGroup,Control} from '@angular/common';
...
export class MyComponent{
  myForm: ControlGroup;
  myArray: Array<Object> = [obj1,obj2,obj3];
  myDefault: Object = myArray[1]; //or obj2

  ngOnInit(){ //override
    this.myForm = new ControlGroup({'myDropdown': new Control(this.myDefault)});
  }
  myOnSubmit(){
    console.log(this.myForm.value.myDropdown); //returns the control's value 
  }
}

markup:

<form [ngFormModel]="myForm" (ngSubmit)="myOnSubmit()">
  <select ngControl="myDropdown">
    <option *ngFor="let eachObj of myArray" selected="eachObj==={{myDefault}}"
            value="{{eachObj}}">{{eachObj.myText}}</option>
  </select>
  <br>
  <button type="submit">Save</button>
</form>

Spring MVC - How to get all request params in a map in Spring controller?

you can simply use this:

Map<String, String[]> parameters = request.getParameterMap();

That should work fine

Remove all special characters except space from a string using JavaScript

search all not (word characters || space):

str.replace(/[^\w ]/, '')

What is the question mark for in a Typescript parameter name

The ? in the parameters is to denote an optional parameter. The Typescript compiler does not require this parameter to be filled in. See the code example below for more details:

// baz: number | undefined means: the second argument baz can be a number or undefined

// = undefined, is default parameter syntax, 
// if the parameter is not filled in it will default to undefined

// Although default JS behaviour is to set every non filled in argument to undefined 
// we need this default argument so that the typescript compiler
// doesn't require the second argument to be filled in
function fn1 (bar: string, baz: number | undefined = undefined) {
    // do stuff
}

// All the above code can be simplified using the ? operator after the parameter
// In other words fn1 and fn2 are equivalent in behaviour
function fn2 (bar: string, baz?: number) {
    // do stuff
}



fn2('foo', 3); // works
fn2('foo'); // works

fn2();
// Compile time error: Expected 1-2 arguments, but got 0
// An argument for 'bar' was not provided.


fn1('foo', 3); // works
fn1('foo'); // works

fn1();
// Compile time error: Expected 1-2 arguments, but got 0
// An argument for 'bar' was not provided.

Using BeautifulSoup to search HTML for string

The following line is looking for the exact NavigableString 'Python':

>>> soup.body.findAll(text='Python')
[]

Note that the following NavigableString is found:

>>> soup.body.findAll(text='Python Jobs') 
[u'Python Jobs']

Note this behaviour:

>>> import re
>>> soup.body.findAll(text=re.compile('^Python$'))
[]

So your regexp is looking for an occurrence of 'Python' not the exact match to the NavigableString 'Python'.

how to convert 2d list to 2d numpy array?

np.array() is even more powerful than what unutbu said above. You also could use it to convert a list of np arrays to a higher dimention array, the following is a simple example:

aArray=np.array([1,1,1])

bArray=np.array([2,2,2])

aList=[aArray, bArray]

xArray=np.array(aList)

xArray's shape is (2,3), it's a standard np array. This operation avoids a loop programming.

Connecting to local SQL Server database using C#

In Data Source (on the left of Visual Studio) right click on the database, then Configure Data Source With Wizard. A new window will appear, expand the Connection string, you can find the connection string in there

How to prove that a problem is NP complete?

You need to reduce an NP-Complete problem to the problem you have. If the reduction can be done in polynomial time then you have proven that your problem is NP-complete, if the problem is already in NP, because:

It is not easier than the NP-complete problem, since it can be reduced to it in polynomial time which makes the problem NP-Hard.

See the end of http://www.ics.uci.edu/~eppstein/161/960312.html for more.

Spark Kill Running Application

First use:

yarn application -list

Note down the application id Then to kill use:

yarn application -kill application_id

Can we update primary key values of a table?

You can as long as

  • The value is unique
  • No existing foreign keys are violated

Getting a link to go to a specific section on another page

To link from a page to another section of the page, I navigate through the page depending on the page's location to the other, at the URL bar, and add the #id. So what I mean;

<a href = "../#the_part_that_you_want">This takes you #the_part_that_you_want at the page before</a>

Validate phone number with JavaScript

Simple Regular expression: /\b\d{3}[-.]?\d{3}[-.]?\d{4}\b/g

Check out the format, hope it works :
444-555-1234
f:246.555.8888
m:1235554567

Could not establish trust relationship for SSL/TLS secure channel -- SOAP

The following snippets will fix the case where there is something wrong with the SSL certificate on the server you are calling. For example, it may be self-signed or the host name between the certificate and the server may not match.

This is dangerous if you are calling a server outside of your direct control, since you can no longer be as sure that you are talking to the server you think you're connected to. However, if you are dealing with internal servers and getting a "correct" certificate is not practical, use the following to tell the web service to ignore the certificate problems and bravely soldier on.

The first two use lambda expressions, the third uses regular code. The first accepts any certificate. The last two at least check that the host name in the certificate is the one you expect.
... hope you find it helpful

//Trust all certificates
System.Net.ServicePointManager.ServerCertificateValidationCallback =
    ((sender, certificate, chain, sslPolicyErrors) => true);

// trust sender
System.Net.ServicePointManager.ServerCertificateValidationCallback
                = ((sender, cert, chain, errors) => cert.Subject.Contains("YourServerName"));

// validate cert by calling a function
ServicePointManager.ServerCertificateValidationCallback += new RemoteCertificateValidationCallback(ValidateRemoteCertificate);

// callback used to validate the certificate in an SSL conversation
private static bool ValidateRemoteCertificate(object sender, X509Certificate cert, X509Chain chain, SslPolicyErrors policyErrors)
{
    bool result = cert.Subject.Contains("YourServerName");
    return result;
}

How do I make a JSON object with multiple arrays?

Using below method pass any value which is any array:

Input parameter: url, like Example: "/node/[any int value of array]/anyKeyWhichInArray" Example: "cars/Nissan/[0]/model"

It can be used for any response:

    public String getResponseParameterThroughUrl(Response r, String url) throws JsonProcessingException, IOException {
    String value = "";
    String[] xpathOrder = url.split("/");
    ObjectMapper objectMapper = new ObjectMapper();
    String responseData = r.getBody().asString();       
    JSONObject jsonObject = new JSONObject(responseData);
    byte[] jsonData = jsonObject.toString().getBytes();
    JsonNode rootNode = objectMapper.readTree(jsonData);
    JsonNode node = null;
    for(int i=1;i<xpathOrder.length;i++) {
        if(node==null)
            node = rootNode;
        if(xpathOrder[i].contains("[")){
            xpathOrder[i] = xpathOrder[i].replace("[", "");
            xpathOrder[i] = xpathOrder[i].replace("]", "");
            node = node.get(Integer.parseInt(xpathOrder[i]));
        }
        else
            node = node.path(xpathOrder[i]);
    }
    value = node.asText();
    return value;
}

Check if a parameter is null or empty in a stored procedure

I recommend checking for invalid dates too:

set @PreviousStartDate=case ISDATE(@PreviousStartDate) 
    when 1 then @PreviousStartDate 
        else '1/1/2010'
    end

How do I simulate placeholder functionality on input date field?

As i mentioned here

initially set the field type to text.

on focus change it to type date

Installing OpenCV for Python on Ubuntu, getting ImportError: No module named cv2.cv

Find where the cv2.so is, for example /usr/local/lib/python2.7/dist-packages, then add this into your ~/.bashrc by doing:

sudo gedit ~/.bashrc

and add

export PYTHONPATH=/usr/local/lib/python2.7/dist-packages:$PYTHONPATH

In the last line

And then remember to open another terminal, this can be work, and I have solve my problem. Hope it can help you.

System.Collections.Generic.List does not contain a definition for 'Select'

This question's bit old, but, there's a tricky scenario which also leads to this error:

In controller:

ViewBag.id = //id from querystring
List<string> = GrabDataFromDBByID(ViewBag.id).Select(a=>a.ToString());

The above code will lead to an error in this part: .Select(a=>a.ToString()) because of the below reason: You're passing a ViewBag.id to a method which in compiler, it doesn't know the type, so there might be several methods with the same name and different parameters let's say:

GrabDataFromDBByID(string)
GrabDataFromDBByID(int)
GrabDataFromDBByID(whateverType)

So to prevent this case, either explicitly cast the ViewBag or create another variable storing it.

How to include another XHTML in XHTML using JSF 2.0 Facelets?

<ui:include>

Most basic way is <ui:include>. The included content must be placed inside <ui:composition>.

Kickoff example of the master page /page.xhtml:

<!DOCTYPE html>
<html lang="en"
    xmlns="http://www.w3.org/1999/xhtml"
    xmlns:f="http://xmlns.jcp.org/jsf/core"
    xmlns:h="http://xmlns.jcp.org/jsf/html"
    xmlns:ui="http://xmlns.jcp.org/jsf/facelets">
    <h:head>
        <title>Include demo</title>
    </h:head>
    <h:body>
        <h1>Master page</h1>
        <p>Master page blah blah lorem ipsum</p>
        <ui:include src="/WEB-INF/include.xhtml" />
    </h:body>
</html>

The include page /WEB-INF/include.xhtml (yes, this is the file in its entirety, any tags outside <ui:composition> are unnecessary as they are ignored by Facelets anyway):

<ui:composition 
    xmlns="http://www.w3.org/1999/xhtml"
    xmlns:f="http://xmlns.jcp.org/jsf/core"
    xmlns:h="http://xmlns.jcp.org/jsf/html"
    xmlns:ui="http://xmlns.jcp.org/jsf/facelets">
    <h2>Include page</h2>
    <p>Include page blah blah lorem ipsum</p>
</ui:composition>
  

This needs to be opened by /page.xhtml. Do note that you don't need to repeat <html>, <h:head> and <h:body> inside the include file as that would otherwise result in invalid HTML.

You can use a dynamic EL expression in <ui:include src>. See also How to ajax-refresh dynamic include content by navigation menu? (JSF SPA).


<ui:define>/<ui:insert>

A more advanced way of including is templating. This includes basically the other way round. The master template page should use <ui:insert> to declare places to insert defined template content. The template client page which is using the master template page should use <ui:define> to define the template content which is to be inserted.

Master template page /WEB-INF/template.xhtml (as a design hint: the header, menu and footer can in turn even be <ui:include> files):

<!DOCTYPE html>
<html lang="en"
    xmlns="http://www.w3.org/1999/xhtml"
    xmlns:f="http://xmlns.jcp.org/jsf/core"
    xmlns:h="http://xmlns.jcp.org/jsf/html"
    xmlns:ui="http://xmlns.jcp.org/jsf/facelets">
    <h:head>
        <title><ui:insert name="title">Default title</ui:insert></title>
    </h:head>
    <h:body>
        <div id="header">Header</div>
        <div id="menu">Menu</div>
        <div id="content"><ui:insert name="content">Default content</ui:insert></div>
        <div id="footer">Footer</div>
    </h:body>
</html>

Template client page /page.xhtml (note the template attribute; also here, this is the file in its entirety):

<ui:composition template="/WEB-INF/template.xhtml"
    xmlns="http://www.w3.org/1999/xhtml"
    xmlns:f="http://xmlns.jcp.org/jsf/core"
    xmlns:h="http://xmlns.jcp.org/jsf/html"
    xmlns:ui="http://xmlns.jcp.org/jsf/facelets">

    <ui:define name="title">
        New page title here
    </ui:define>

    <ui:define name="content">
        <h1>New content here</h1>
        <p>Blah blah</p>
    </ui:define>
</ui:composition>

This needs to be opened by /page.xhtml. If there is no <ui:define>, then the default content inside <ui:insert> will be displayed instead, if any.


<ui:param>

You can pass parameters to <ui:include> or <ui:composition template> by <ui:param>.

<ui:include ...>
    <ui:param name="foo" value="#{bean.foo}" />
</ui:include>
<ui:composition template="...">
    <ui:param name="foo" value="#{bean.foo}" />
    ...
</ui:composition >

Inside the include/template file, it'll be available as #{foo}. In case you need to pass "many" parameters to <ui:include>, then you'd better consider registering the include file as a tagfile, so that you can ultimately use it like so <my:tagname foo="#{bean.foo}">. See also When to use <ui:include>, tag files, composite components and/or custom components?

You can even pass whole beans, methods and parameters via <ui:param>. See also JSF 2: how to pass an action including an argument to be invoked to a Facelets sub view (using ui:include and ui:param)?


Design hints

The files which aren't supposed to be publicly accessible by just entering/guessing its URL, need to be placed in /WEB-INF folder, like as the include file and the template file in above example. See also Which XHTML files do I need to put in /WEB-INF and which not?

There doesn't need to be any markup (HTML code) outside <ui:composition> and <ui:define>. You can put any, but they will be ignored by Facelets. Putting markup in there is only useful for web designers. See also Is there a way to run a JSF page without building the whole project?

The HTML5 doctype is the recommended doctype these days, "in spite of" that it's a XHTML file. You should see XHTML as a language which allows you to produce HTML output using a XML based tool. See also Is it possible to use JSF+Facelets with HTML 4/5? and JavaServer Faces 2.2 and HTML5 support, why is XHTML still being used.

CSS/JS/image files can be included as dynamically relocatable/localized/versioned resources. See also How to reference CSS / JS / image resource in Facelets template?

You can put Facelets files in a reusable JAR file. See also Structure for multiple JSF projects with shared code.

For real world examples of advanced Facelets templating, check the src/main/webapp folder of Java EE Kickoff App source code and OmniFaces showcase site source code.

Laravel update model with unique validation rule for attribute

A simple example for roles update


// model/User.php
class User extends Eloquent
{

    public static function rolesUpdate($id)
    {
        return array(
            'username'              => 'required|alpha_dash|unique:users,username,' . $id,
            'email'                 => 'required|email|unique:users,email,'. $id,
            'password'              => 'between:4,11',
        );
    }
}       

.

// controllers/UsersControllers.php
class UsersController extends Controller
{

    public function update($id)
    {
        $user = User::find($id);
        $validation = Validator::make($input, User::rolesUpdate($user->id));

        if ($validation->passes())
        {
            $user->update($input);

            return Redirect::route('admin.user.show', $id);
        }

        return Redirect::route('admin.user.edit', $id)->withInput()->withErrors($validation);
    }

}

Sending email from Command-line via outlook without having to click send

You can use cURL and CRON to run .php files at set times.

Here's an example of what cURL needs to run the .php file:

curl http://localhost/myscript.php

Then setup the CRON job to run the above cURL:

nano -w /var/spool/cron/root
or
crontab -e

Followed by:

01 * * * * /usr/bin/curl http://www.yoursite.com/script.php

For more info about, check out this post: https://www.scalescale.com/tips/nginx/execute-php-scripts-automatically-using-cron-curl/

For more info about cURL: What is cURL in PHP?

For more info about CRON: http://code.tutsplus.com/tutorials/scheduling-tasks-with-cron-jobs--net-8800

Also, if you would like to learn about setting up a CRON job on your hosted server, just inquire with your host provider, and they may have a GUI for setting it up in the c-panel (such as http://godaddy.com, or http://1and1.com/ )

NOTE: Technically I believe you can setup a CRON job to run the .php file directly, but I'm not certain.

Best of luck with the automatic PHP running :-)