Programs & Examples On #Pst

File format used by Microsoft Outlook to store data locally.

Access blocked by CORS policy: Response to preflight request doesn't pass access control check

You have to set the http header at the http response of your resource. So it needs to be set serverside, you can remove the "HTTP_OPTIONS"-header from your angular HTTP-Post request.

Uncaught Invariant Violation: Too many re-renders. React limits the number of renders to prevent an infinite loop

You must link an event in your onClick. Additionally, the click function must receive the event. See the example

export default function Component(props) {

    function clickEvent (event, variable){
        console.log(variable);
    }

    return (
        <div>
            <IconButton
                key="close"
                aria-label="Close"
                color="inherit"
                onClick={e => clickEvent(e, 10)}
            >
        </div>
    )
}

Gradle: Could not determine java version from '11.0.2'

I've had the same issue. Upgrading to gradle 5.0 did the trick for me.

This link provides detailed steps on how install gradle 5.0: https://linuxize.com/post/how-to-install-gradle-on-ubuntu-18-04/

Xcode 10, Command CodeSign failed with a nonzero exit code

For me the solution was the following, having the "Automatically manage sign" flag on:

  1. in the team drop-down of the target, select "None"

  2. re-select the correct development team

After trying almost every suggestion, I found that this works, I guess because Xcode sets up the signing stuff from scratch.

Execution failed for task ':app:compileDebugJavaWithJavac' Android Studio 3.1 Update

Try updating your buildToolVersion to 27.0.2 instead of 27.0.3

The error probably occurring because of compatibility issue with build tools

Could not resolve com.android.support:appcompat-v7:26.1.0 in Android Studio new project

This work for me. In the android\app\build.gradle file you need to specify the following

compileSdkVersion 26
buildToolsVersion "26.0.1"

and then find this

compile "com.android.support:appcompat-v7"

and make sure it says

compile "com.android.support:appcompat-v7:26.0.1"

Distribution certificate / private key not installed

i tried all mentioned solutions available on the internet but no solution working on my Mac, then i created a provisioning profile manually on apple developer website from certificates and identifiers. By importing that file manually app successfully uploaded on appStore follow below steps

On Developer website

1-go to this link https://developer.apple.com/account/resources/certificates

2- In profile Section create new profile by using app bundle identifier

3-Download it and save it an where

On Xcode

1-Go to Signing and certificates

2-Disable automatically manage signing

3- Select provisioning profile in its section

4- Archive the app

5-Click Distribute App ->ApStore connect ->Upload->Next-> Then Select Profile from XXXX-app section when it download it show inside this section and now upload it

Java.lang.NoClassDefFoundError: com/fasterxml/jackson/databind/exc/InvalidDefinitionException

Use all the jackson dependencies(databind,core, annotations, scala(if you are using spark and scala)) with the same version.. and upgrade the versions to the latest releases..

<dependency>
            <groupId>com.fasterxml.jackson.module</groupId>
            <artifactId>jackson-module-scala_2.11</artifactId>
            <version>2.9.4</version>
        </dependency>

        <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.9.4</version>
        <exclusions>
            <exclusion>
                <groupId>com.fasterxml.jackson.core</groupId>
                <artifactId>jackson-core</artifactId>
            </exclusion>
            <exclusion>
                <groupId>com.fasterxml.jackson.core</groupId>
                <artifactId>jackson-annotations</artifactId>
            </exclusion>
        </exclusions>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-core</artifactId>
        <version>2.9.4</version>
    </dependency>

        <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-annotations</artifactId>
        <version>2.9.4</version>

        </dependency>

Note: Use Scala dependency only if you are working with scala. Otherwise it is not needed.

Cast object to interface in TypeScript

If it helps anyone, I was having an issue where I wanted to treat an object as another type with a similar interface. I attempted the following:

Didn't pass linting

const x = new Obj(a as b);

The linter was complaining that a was missing properties that existed on b. In other words, a had some properties and methods of b, but not all. To work around this, I followed VS Code's suggestion:

Passed linting and testing

const x = new Obj(a as unknown as b);

Note that if your code attempts to call one of the properties that exists on type b that is not implemented on type a, you should realize a runtime fault.

How to print a Groovy variable in Jenkins?

You shouldn't use ${varName} when you're outside of strings, you should just use varName. Inside strings you use it like this; echo "this is a string ${someVariable}";. Infact you can place an general java expression inside of ${...}; echo "this is a string ${func(arg1, arg2)}.

Gradle error: Minimum supported Gradle version is 3.3. Current version is 3.2

In my case, I was missing the setting.gradle file.

NVIDIA NVML Driver/library version mismatch

These answers not worked for me:

https://stackoverflow.com/a/43023000/1179925

https://stackoverflow.com/a/45319156/1179925

https://stackoverflow.com/a/54349675/1179925

dmesg

NVRM: API mismatch: the client has the version 418.67, but
NVRM: this kernel module has the version 430.26.  Please
NVRM: make sure that this kernel module and all NVIDIA driver
NVRM: components have the same version.

Uninstall old driver 418.67 and install new driver 430.26 (download NVIDIA-Linux-x86_64-430.26.run):

sudo apt-get --purge remove "*nvidia*"
sudo /usr/bin/nvidia-uninstall
chmod +x NVIDIA-Linux-x86_64-430.26.run
sudo ./NVIDIA-Linux-x86_64-430.26.run
[ignore abort]

cat /proc/driver/nvidia/version

NVRM version: NVIDIA UNIX x86_64 Kernel Module  430.26  Tue Jun  4 17:40:52 CDT 2019
GCC version:  gcc version 7.4.0 (Ubuntu 7.4.0-1ubuntu1~18.04.1)

Return file in ASP.Net Core Web API

If this is ASP.net-Core then you are mixing web API versions. Have the action return a derived IActionResult because in your current code the framework is treating HttpResponseMessage as a model.

[Route("api/[controller]")]
public class DownloadController : Controller {
    //GET api/download/12345abc
    [HttpGet("{id}"]
    public async Task<IActionResult> Download(string id) {
        Stream stream = await {{__get_stream_based_on_id_here__}}

        if(stream == null)
            return NotFound(); // returns a NotFoundResult with Status404NotFound response.

        return File(stream, "application/octet-stream"); // returns a FileStreamResult
    }    
}

ASP.NET Core return JSON with status code

Controller action return types in ASP.NET Core web API 02/03/2020

6 minutes to read +2

By Scott Addie Link

Synchronous action

[HttpGet("{id}")]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public ActionResult<Product> GetById(int id)
{
    if (!_repository.TryGetProduct(id, out var product))
    {
        return NotFound();
    }

    return product;
}

Asynchronous action

[HttpPost]
[Consumes(MediaTypeNames.Application.Json)]
[ProducesResponseType(StatusCodes.Status201Created)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
public async Task<ActionResult<Product>> CreateAsync(Product product)
{
    if (product.Description.Contains("XYZ Widget"))
    {
        return BadRequest();
    }

    await _repository.AddProductAsync(product);

    return CreatedAtAction(nameof(GetById), new { id = product.Id }, product);
}

Deserialize Java 8 LocalDateTime with JacksonMapper

The date time you're passing is not a iso local date time format.

Change to

@Column(name = "start_date")
@DateTimeFormat(iso = DateTimeFormatter.ISO_LOCAL_DATE_TIME)
@JsonFormat(pattern = "YYYY-MM-dd HH:mm")
private LocalDateTime startDate;

and pass date string in the format '2011-12-03T10:15:30'.

But if you still want to pass your custom format, use just have to specify the right formatter.

Change to

@Column(name = "start_date")
@DateTimeFormat(iso = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm"))
@JsonFormat(pattern = "YYYY-MM-dd HH:mm")
private LocalDateTime startDate;

I think your problem is the @DateTimeFormat has no effect at all. As the jackson is doing the deseralization and it doesnt know anything about spring annotation and I dont see spring scanning this annotation in the deserialization context.

Alternatively, you can try setting the formatter while registering the java time module.

LocalDateTimeDeserializer localDateTimeDeserializer = new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm"));
module.addDeserializer(LocalDateTime.class, localDateTimeDeserializer);

Here is the test case with the deseralizer which works fine. May be try to get rid of that DateTimeFormat annotation altogether.

@RunWith(JUnit4.class)
public class JacksonLocalDateTimeTest {

    private ObjectMapper objectMapper;

    @Before
    public void init() {
        JavaTimeModule module = new JavaTimeModule();
        LocalDateTimeDeserializer localDateTimeDeserializer =  new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm"));
        module.addDeserializer(LocalDateTime.class, localDateTimeDeserializer);
        objectMapper = Jackson2ObjectMapperBuilder.json()
                .modules(module)
                .featuresToDisable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
                .build();
    }

    @Test
    public void test() throws IOException {
        final String json = "{ \"date\": \"2016-11-08 12:00\" }";
        final JsonType instance = objectMapper.readValue(json, JsonType.class);

        assertEquals(LocalDateTime.parse("2016-11-08 12:00",DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm") ), instance.getDate());
    }
}


class JsonType {
    private LocalDateTime date;

    public LocalDateTime getDate() {
        return date;
    }

    public void setDate(LocalDateTime date) {
        this.date = date;
    }
}

Disable nginx cache for JavaScript files

The expires and add_header directives have no impact on NGINX caching the files, those are purely about what the browser sees.

What you likely want instead is:

location stuffyoudontwanttocache {
    # don't cache it
    proxy_no_cache 1;
    # even if cached, don't try to use it
    proxy_cache_bypass 1; 
}

Though usually .js etc is the thing you would cache, so perhaps you should just disable caching entirely?

What is mapDispatchToProps?

mapStateToProps receives the state and props and allows you to extract props from the state to pass to the component.

mapDispatchToProps receives dispatch and props and is meant for you to bind action creators to dispatch so when you execute the resulting function the action gets dispatched.

I find this only saves you from having to do dispatch(actionCreator()) within your component thus making it a bit easier to read.

https://github.com/reactjs/react-redux/blob/master/docs/api.md#arguments

Updates were rejected because the tip of your current branch is behind its remote counterpart

The command I used with Azure DevOps when I encountered the message "updates were rejected because the tip of your current branch is behind" was/is this command:

git pull origin master

(or can start with a new folder and do a Clone) ..

This answer doesn't address the question posed, specifically, Keif has answered this above, but it does answer the question's title/heading text and this will be a common question for Azure DevOps users.

I noted comment: "You'd always want to make sure that you do a pull before pushing" in answer from Keif above !

I have also used Git Gui tool in addition to Git command line tool.

(I wasn't sure how to do the equivalent of the command line command "git pull origin master" within Git Gui so I'm back to command line to do this).

A diagram that shows various git commands for various actions that you might want to undertake is this one:

enter image description here

How to convert JSON object to an Typescript array?

You have a JSON object that contains an Array. You need to access the array results. Change your code to:

this.data = res.json().results

No assembly found containing an OwinStartupAttribute Error

just paste this code <add key="owin:AutomaticAppStartup" value="false" /> in Web.config Not In web.config there is two webconfig so be sure that it will been paste in Web.Config

docker entrypoint running bash script gets "permission denied"

This is a bit stupid maybe but the error message I got was Permission denied and it sent me spiralling down in a very wrong direction to attempt to solve it. (Here for example)

I haven't even added any bash script myself, I think one is added by nodejs image which I use.

FROM node:14.9.0

I was wrongly running to expose/connect the port on my local:

docker run -p 80:80 [name] . # this is wrong!

which gives

/usr/local/bin/docker-entrypoint.sh: 8: exec: .: Permission denied

But you shouldn't even have a dot in the end, it was added to documentation of another projects docker image by misstake. You should simply run:

docker run -p 80:80 [name]

I like Docker a lot but it's sad it has so many gotchas like this and not always very clear error messages...

ASP.NET Core Web API exception handling

A simple way to handle an exception on any particular method is:

using Microsoft.AspNetCore.Http;
...

public ActionResult MyAPIMethod()
{
    try
    {
       var myObject = ... something;

       return Json(myObject);
    }
    catch (Exception ex)
    {
        Log.Error($"Error: {ex.Message}");
        return StatusCode(StatusCodes.Status500InternalServerError);
    }         
}

Understanding React-Redux and mapStateToProps()

You got the first part right:

Yes mapStateToProps has the Store state as an argument/param (provided by react-redux::connect) and its used to link the component with certain part of the store state.

By linking I mean the object returned by mapStateToProps will be provided at construction time as props and any subsequent change will be available through componentWillReceiveProps.

If you know the Observer design pattern it's exactly that or small variation of it.

An example would help make things clearer:

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

class ItemsContainer extends Component {
    constructor(props) {
        super(props);

        this.state = {
            items: props.items, //provided by connect@mapStateToProps
            filteredItems: this.filterItems(props.items, props.filters),
        };
    }

    componentWillReceiveProps(nextProps) {
        this.setState({
            filteredItems: this.filterItems(this.state.items, nextProps.filters),
        });
    }

    filterItems = (items, filters) => { /* return filtered list */ }

    render() {
        return (
            <View>
                // display the filtered items
            </View>
        );
    }
}

module.exports = connect(
    //mapStateToProps,
    (state) => ({
        items: state.App.Items.List,
        filters: state.App.Items.Filters,
        //the State.App & state.App.Items.List/Filters are reducers used as an example.
    })
    // mapDispatchToProps,  that's another subject
)(ItemsContainer);

There can be another react component called itemsFilters that handle the display and persisting the filter state into Redux Store state, the Demo component is "listening" or "subscribed" to Redux Store state filters so whenever filters store state changes (with the help of filtersComponent) react-redux detect that there was a change and notify or "publish" all the listening/subscribed components by sending the changes to their componentWillReceiveProps which in this example will trigger a refilter of the items and refresh the display due to the fact that react state has changed.

Let me know if the example is confusing or not clear enough to provide a better explanation.

As for: This means that the state as consumed by your target component can have a wildly different structure from the state as it is stored on your store.

I didn't get the question, but just know that the react state (this.setState) is totally different from the Redux Store state!

The react state is used to handle the redraw and behavior of the react component. The react state is contained to the component exclusively.

The Redux Store state is a combination of Redux reducers states, each is responsible of managing a small portion app logic. Those reducers attributes can be accessed with the help of react-redux::connect@mapStateToProps by any component! Which make the Redux store state accessible app wide while component state is exclusive to itself.

How to return HTTP 500 from ASP.NET Core RC2 Web Api?

From what I can see there are helper methods inside the ControllerBase class. Just use the StatusCode method:

[HttpPost]
public IActionResult Post([FromBody] string something)
{    
    //...
    try
    {
        DoSomething();
    }
    catch(Exception e)
    {
         LogException(e);
         return StatusCode(500);
    }
}

You may also use the StatusCode(int statusCode, object value) overload which also negotiates the content.

Why do I have to "git push --set-upstream origin <branch>"?

A basically full command is like git push <remote> <local_ref>:<remote_ref>. If you run just git push, git does not know what to do exactly unless you have made some config that helps git to make a decision. In a git repo, we can setup multiple remotes. Also we can push a local ref to any remote ref. The full command is the most straightforward way to make a push. If you want to type fewer words, you have to config first, like --set-upstream.

Adb install failure: INSTALL_CANCELED_BY_USER

For MIUI OS Device

1) Go to Setting

2) Scroll down to Additional Setting

3) You will find Developer option at bottom

4) Turn this on - Install via USB: Toggle On

By turning this on, It is working charm in my MIUI8 device.

React.js, wait for setState to finish before triggering a function?

Why not one more answer? setState() and the setState()-triggered render() have both completed executing when you call componentDidMount() (the first time render() is executed) and/or componentDidUpdate() (any time after render() is executed). (Links are to ReactJS.org docs.)

Example with componentDidUpdate()

Caller, set reference and set state...

<Cmp ref={(inst) => {this.parent=inst}}>;
this.parent.setState({'data':'hello!'});

Render parent...

componentDidMount() {           // componentDidMount() gets called after first state set
    console.log(this.state.data);   // output: "hello!"
}
componentDidUpdate() {          // componentDidUpdate() gets called after all other states set
    console.log(this.state.data);   // output: "hello!"
}

Example with componentDidMount()

Caller, set reference and set state...

<Cmp ref={(inst) => {this.parent=inst}}>
this.parent.setState({'data':'hello!'});

Render parent...

render() {              // render() gets called anytime setState() is called
    return (
        <ChildComponent
            state={this.state}
        />
    );
}

After parent rerenders child, see state in componentDidUpdate().

componentDidMount() {           // componentDidMount() gets called anytime setState()/render() finish
console.log(this.props.state.data); // output: "hello!"
}

Launch an event when checking a checkbox in Angular2

You can use ngModel like

<input type="checkbox" [ngModel]="checkboxValue" (ngModelChange)="addProp($event)" data-md-icheck/>

To update the checkbox state by updating the property checkboxValue in your code and when the checkbox is changed by the user addProp() is called.

Re-render React component when prop changes

ComponentWillReceiveProps() is going to be deprecated in the future due to bugs and inconsistencies. An alternative solution for re-rendering a component on props change is to use ComponentDidUpdate() and ShouldComponentUpdate().

ComponentDidUpdate() is called whenever the component updates AND if ShouldComponentUpdate() returns true (If ShouldComponentUpdate() is not defined it returns true by default).

shouldComponentUpdate(nextProps){
    return nextProps.changedProp !== this.state.changedProp;
}

componentDidUpdate(props){
    // Desired operations: ex setting state
}

This same behavior can be accomplished using only the ComponentDidUpdate() method by including the conditional statement inside of it.

componentDidUpdate(prevProps){
    if(prevProps.changedProp !== this.props.changedProp){
        this.setState({          
            changedProp: this.props.changedProp
        });
    }
}

If one attempts to set the state without a conditional or without defining ShouldComponentUpdate() the component will infinitely re-render

The number of method references in a .dex file cannot exceed 64k API 17

For me Upgrading Gradle works.Look for update at Android Website then add it in your build.gradle (Project) like this

 dependencies {
        classpath 'com.android.tools.build:gradle:2.2.0-alpha4'   
          ....
    }

then sync project with gradle file plus it might be happened sometimes because of java.exe (in my case) just force kill java.exe from task manager in windows then re run program

Delete an element in a JSON object

with open('writing_file.json', 'w') as w:
    with open('reading_file.json', 'r') as r:
        for line in r:
            element = json.loads(line.strip())
            if 'hours' in element:
                del element['hours']
            w.write(json.dumps(element))

this is the method i use..

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

I solved this by setting a higher timeout value for the proxy:

location / {
    proxy_read_timeout 300s;
    proxy_connect_timeout 75s;
    proxy_pass http://localhost:3000;
}

Documentation: https://nginx.org/en/docs/http/ngx_http_proxy_module.html

Why Is `Export Default Const` invalid?

If the component name is explained in the file name MyComponent.js, just don't name the component, keeps code slim.

import React from 'react'

export default (props) =>
    <div id='static-page-template'>
        {props.children}
    </div>

Update: Since this labels it as unknown in stack tracing, it isn't recommended

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

make sure ,use this 404 route wrote on the bottom of the code.

syntax will be like

{
    path: 'page-not-found', 
    component: PagenotfoundComponent
},
{
    path: '**', 
    redirectTo: '/page-not-found'
},

Thank you

Git pushing to remote branch

git push --set-upstream origin <branch_name>_test

--set-upstream sets the association between your local branch and the remote. You only have to do it the first time. On subsequent pushes you can just do:

git push

If you don't have origin set yet, use:

git remote add origin <repository_url> then retry the above command.

How to show uncommitted changes in Git and some Git diffs in detail

You have already staged the changes (presumably by running git add), so in order to get their diff, you need to run:

git diff --cached

(A plain git diff will only show unstaged changes.)

For example: Example git diff cached use

How to use a client certificate to authenticate and authorize in a Web API

I came upon a similar issue recently and following Fabian's advice actually led me to the solution. Turns out with client certs you have to ensure two things:

  1. The private key is actually being exported as part of the cert.

  2. The application pool identity running the app has access to said private key.

In our case I had to:

  1. Import the pfx file into the local server store while checking the export checkbox to ensure the private key was sent out.
  2. Using MMC console, grant the service account used access to the private key for the cert.

The trusted root issue explained in other answers is a valid one, it was just not the issue in our case.

Android Studio Gradle: Error:Execution failed for task ':app:processDebugGoogleServices'. > No matching client found for package

if you run the other type of build(for example sign apk or etc), you must select app type of build then run the projects.

please seen the following image. for run this project we must select "app" in run configuration popup. enter image description here

HTTP 415 unsupported media type error when calling Web API 2 endpoint

I was trying to write a code that would work on both Mac and Windows. The code was working fine on Windows, but was giving the response as 'Unsupported Media Type' on Mac. Here is the code I used and the following line made the code work on Mac as well:

Request.AddHeader "Content-Type", "application/json"

Here is the snippet of my code:

Dim Client As New WebClient
Dim Request As New WebRequest
Dim Response As WebResponse
Dim Distance As String

Client.BaseUrl = "http://1.1.1.1:8080/config"
Request.AddHeader "Content-Type", "application/json" *** The line that made the code work on mac

Set Response = Client.Execute(Request)

Could not determine the dependencies of task ':app:crashlyticsStoreDeobsDebug' if I enable the proguard

You can run this command in your project directory. Basically it just cleans the build and gradle.

   cd android && rm -R .gradle && cd app && rm -R build

In my case, I was using react-native using this as a script in package.json

"scripts": { "clean-android": "cd android && rm -R .gradle && cd app && rm -R build" }

How to use refs in React with Typescript

If you wont to forward your ref, in Props interface you need to use RefObject<CmpType> type from import React, { RefObject } from 'react';

Spring Boot - How to log all requests and responses with exceptions in single place?

If you are seeing only part of your request payload, you need to call the setMaxPayloadLength function as it defaults to showing only 50 characters in your request body. Also, setting setIncludeHeaders to false is a good idea if you don't want to log your auth headers!

@Bean
public CommonsRequestLoggingFilter requestLoggingFilter() {
    CommonsRequestLoggingFilter loggingFilter = new CommonsRequestLoggingFilter();
    loggingFilter.setIncludeClientInfo(false);
    loggingFilter.setIncludeQueryString(false);
    loggingFilter.setIncludePayload(true);
    loggingFilter.setIncludeHeaders(false);
    loggingFilter.setMaxPayloadLength(500);
    return loggingFilter;
}

npm install -g less does not work: EACCES: permission denied

enter image description hereUse sudo -i to switch to $root, then execute npm install -g xxxx

Docker Networking - nginx: [emerg] host not found in upstream

Two things worth to mention:

  • Using same network bridge
  • Using links to add hosts resol

My example:

version: '3'
services:
  mysql:
    image: mysql:5.7
    restart: always
    container_name: mysql
    volumes:
      - ./mysql-data:/var/lib/mysql
    environment:
      MYSQL_ROOT_PASSWORD: tima@123
    network_mode: bridge
  ghost:
    image: ghost:2
    restart: always
    container_name: ghost
    depends_on:
      - mysql
    links:
      - mysql
    environment:
      database__client: mysql
      database__connection__host: mysql
      database__connection__user: root
      database__connection__password: xxxxxxxxx
      database__connection__database: ghost
      url: https://www.itsfun.tk
    volumes:
      - ./ghost-data:/var/lib/ghost/content
    network_mode: bridge
  nginx:
    image: nginx
    restart: always
    container_name: nginx
    depends_on:
      - ghost
    links:
      - ghost
    ports:
      - "80:80"
      - "443:443"
    volumes:
       - ./nginx/nginx.conf:/etc/nginx/nginx.conf
       - ./nginx/conf.d:/etc/nginx/conf.d
       - ./nginx/letsencrypt:/etc/letsencrypt
    network_mode: bridge

If you don't specify a special network bridge, all of them will use the same default one.

Error LNK2019 unresolved external symbol _main referenced in function "int __cdecl invoke_main(void)" (?invoke_main@@YAHXZ)

Right click on project. Properties->Configuration Properties->General->Linker.

I found two options needed to be set. Under System: SubSystem = Windows (/SUBSYSTEM:WINDOWS) Under Advanced: EntryPoint = main

How to handle errors with boto3?

Just an update to the 'no exceptions on resources' problem as pointed to by @jarmod (do please feel free to update your answer if below seems applicable)

I have tested the below code and it runs fine. It uses 'resources' for doing things, but catches the client.exceptions - although it 'looks' somewhat wrong... it tests good, the exception classes are showing and matching when looked into using debugger at exception time...

It may not be applicable to all resources and clients, but works for data folders (aka s3 buckets).

lab_session = boto3.Session() 
c = lab_session.client('s3') #this client is only for exception catching

try:
    b = s3.Bucket(bucket)
    b.delete()
except c.exceptions.NoSuchBucket as e:
    #ignoring no such bucket exceptions
    logger.debug("Failed deleting bucket. Continuing. {}".format(e))
except Exception as e:
    #logging all the others as warning
    logger.warning("Failed deleting bucket. Continuing. {}".format(e))

Hope this helps...

Xcode 7 error: "Missing iOS Distribution signing identity for ..."

I kept running into the issue and saw that all my certs were invalidated -- oh no!

It turns out I never deleted the expired cert. It was not showing up for me, until I selected from Keychain Access application:

View->Show Expired Certificates

then

System->All Items

will finally display that gnarly expired cert. Delete that and retry from XCode will pick up the new valid certs.

Just make sure you search "All Items" in the Keychain Access app. The invalidated certs are a result of pointing to the expired certificate that has not been deleted yet.

How return error message in spring mvc @Controller

Evaluating the error response from another service invocated...

This was my solution for evaluating the error:

try {
        return authenticationFeign.signIn(userDto, dataRequest);
    }catch(FeignException ex){

        //ex.status();

        if(ex.status() == HttpStatus.UNAUTHORIZED.value()){
            System.out.println("is a error 401");
            return new ResponseEntity<>(HttpStatus.UNAUTHORIZED);
        }
        return new ResponseEntity<>(HttpStatus.OK);

    }

There is no tracking information for the current branch

I run into this exact message often because I create a local branches via git checkout -b <feature-branch-name> without first creating the remote branch.

After all the work was finished and committed locally the fix was git push -u which created the remote branch, pushed all my work, and then the merge-request URL.

SQLSTATE[HY000] [1045] Access denied for user 'username'@'localhost' using CakePHP

That error message usually means that either the password we are using doesn't match what MySQL thinks the password should be for the user we're connecting as, or a matching MySQL user doesn't exist (hasn't been created).

In MySQL, a user is identified by both a username ("test2") and a host ("localhost").

The error message identifies the user ("test2") and the host ("localhost") values...

  'test2'@'localhost'

We can check to see if the user exists, using this query from a client we can connect from:

 SELECT user, host FROM mysql.user

We're looking for a row that has "test2" for user, and "localhost" for host.

 user     host       
 -------  -----------
 test2     127.0.0.1  cleanup
 test2     ::1        
 test2     localhost  

If that row doesn't exist, then the host may be set to wildcard value of %, to match any other host that isn't a match.

If the row exists, then the password may not match. We can change the password (if we're connected as a user with sufficient privileges, e.g. root

 SET PASSWORD FOR 'test2'@'localhost' = PASSWORD('mysecretcleartextpassword')

We can also verify that the user has privileges on objects in the database.

 GRANT SELECT ON jobs.* TO 'test2'@'localhost' 

EDIT

If we make changes to mysql privilege tables with DML operations (INSERT,UPDATE,DELETE), those changes will not take effect until MySQL re-reads the tables. We can make changes effective by forcing a re-read with a FLUSH PRIVILEGES statement, executed by a privileged user.

Using `window.location.hash.includes` throws “Object doesn't support property or method 'includes'” in IE11

This question and its answers led me to my own solution (with help from SO), though some say you shouldn't tamper with native prototypes:

  // IE does not support .includes() so I'm making my own:
  String.prototype.doesInclude=function(needle){
    return this.substring(needle) != -1;
  }

Then I just replaced all .includes() with .doesInclude() and my problem was solved.

Impact of Xcode build options "Enable bitcode" Yes/No

  • What does the ENABLE_BITCODE actually do, will it be a non-optional requirement in the future?

I'm not sure at what level you are looking for an answer at, so let's take a little trip. Some of this you may already know.

When you build your project, Xcode invokes clang for Objective-C targets and swift/swiftc for Swift targets. Both of these compilers compile the app to an intermediate representation (IR), one of these IRs is bitcode. From this IR, a program called LLVM takes over and creates the binaries needed for x86 32 and 64 bit modes (for the simulator) and arm6/arm7/arm7s/arm64 (for the device). Normally, all of these different binaries are lumped together in a single file called a fat binary.

The ENABLE_BITCODE option cuts out this final step. It creates a version of the app with an IR bitcode binary. This has a number of nice features, but one giant drawback: it can't run anywhere. In order to get an app with a bitcode binary to run, the bitcode needs to be recompiled (maybe assembled or transcoded… I'm not sure of the correct verb) into an x86 or ARM binary.

When a bitcode app is submitted to the App Store, Apple will do this final step and create the finished binaries.

Right now, bitcode apps are optional, but history has shown Apple turns optional things into requirements (like 64 bit support). This usually takes a few years, so third party developers (like Parse) have time to update.

  • can I use the above method without any negative impact and without compromising a future appstore submission?

Yes, you can turn off ENABLE_BITCODE and everything will work just like before. Until Apple makes bitcode apps a requirement for the App Store, you will be fine.

  • Are there any performance impacts if I enable / disable it?

There will never be negative performance impacts for enabling it, but internal distribution of an app for testing may get more complicated.

As for positive impacts… well that's complicated.

For distribution in the App Store, Apple will create separate versions of your app for each machine architecture (arm6/arm7/arm7s/arm64) instead of one app with a fat binary. This means the app installed on iOS devices will be smaller.

In addition, when bitcode is recompiled (maybe assembled or transcoded… again, I'm not sure of the correct verb), it is optimized. LLVM is always working on creating new a better optimizations. In theory, the App Store could recreate the separate version of the app in the App Store with each new release of LLVM, so your app could be re-optimized with the latest LLVM technology.

Maven- No plugin found for prefix 'spring-boot' in the current project and in the plugin groups

Make sure pom.xml exist in the directory, when using the mvn spring-boot:run command. No need to add any thing in the pom.xml file.

Where is the kibana error log? Is there a kibana error log?

It seems that you need to pass a flag "-l, --log-file"

https://github.com/elastic/kibana/issues/3407

Usage: kibana [options]

Kibana is an open source (Apache Licensed), browser based analytics and search dashboard for Elasticsearch.

Options:

    -h, --help                 output usage information
    -V, --version              output the version number
    -e, --elasticsearch <uri>  Elasticsearch instance
    -c, --config <path>        Path to the config file
    -p, --port <port>          The port to bind to
    -q, --quiet                Turns off logging
    -H, --host <host>          The host to bind to
    -l, --log-file <path>      The file to log to
    --plugins <path>           Path to scan for plugins

If you use the init script to run as a service, maybe you will need to customize it.

Remove "Using default security password" on Spring Boot

It didn't work for me when I excluded SecurityAutoConfiguration using @SpringBootApplication annotation, but did work when I excluded it in @EnableAutoConfiguration:

@EnableAutoConfiguration(exclude = { SecurityAutoConfiguration.class })

How do I draw a circle in iOS Swift?

I find Core Graphics to be pretty simple for Swift 3:

if let cgcontext = UIGraphicsGetCurrentContext() {
    cgcontext.strokeEllipse(in: CGRect(x: center.x-diameter/2, y: center.y-diameter/2, width: diameter, height: diameter))
}

No resource identifier found for attribute '...' in package 'com.app....'

I solved is by using android:background instead of app:srcCompact.

This is caused by xmlns:app="http://schemas.android.com/apk/res-auto". As people have suggested above, you could use /lib-auto or /lib/your-package but I got suspicious namespace error when I tried using /lib-auto and unexpected namespace prefix error with /lib/my-package .

No connection could be made because the target machine actively refused it 127.0.0.1

The exception message says you're trying to connect to the same host (127.0.0.1), while you're stating that your server is running on a different host. Besides the obvious bugs like having "localhost" in the url, or maybe some you might want to check your DNS settings.

Executing a batch file in a remote machine through PsExec

You have an extra -c you need to get rid of:

psexec -u administrator -p force \\135.20.230.160 -s -d cmd.exe /c "C:\Amitra\bogus.bat"

JS - window.history - Delete a state

There is no way to delete or read the past history.

You could try going around it by emulating history in your own memory and calling history.pushState everytime window popstate event is emitted (which is proposed by the currently accepted Mike's answer), but it has a lot of disadvantages that will result in even worse UX than not supporting the browser history at all in your dynamic web app, because:

  • popstate event can happen when user goes back ~2-3 states to the past
  • popstate event can happen when user goes forward

So even if you try going around it by building virtual history, it's very likely that it can also lead into a situation where you have blank history states (to which going back/forward does nothing), or where that going back/forward skips some of your history states totally.

How to configure Docker port mapping to use Nginx as an upstream proxy?

I tried using the popular Jason Wilder reverse proxy that code-magically works for everyone, and learned that it doesn't work for everyone (ie: me). And I'm brand new to NGINX, and didn't like that I didn't understand the technologies I was trying to use.

Wanted to add my 2 cents, because the discussion above around linking containers together is now dated since it is a deprecated feature. So here's an explanation on how to do it using networks. This answer is a full example of setting up nginx as a reverse proxy to a statically paged website using Docker Compose and nginx configuration.

TL;DR;

Add the services that need to talk to each other onto a predefined network. For a step-by-step discussion on Docker networks, I learned some things here: https://technologyconversations.com/2016/04/25/docker-networking-and-dns-the-good-the-bad-and-the-ugly/

Define the Network

First of all, we need a network upon which all your backend services can talk on. I called mine web but it can be whatever you want.

docker network create web

Build the App

We'll just do a simple website app. The website is a simple index.html page being served by an nginx container. The content is a mounted volume to the host under a folder content

DockerFile:

FROM nginx
COPY default.conf /etc/nginx/conf.d/default.conf

default.conf

server {
    listen       80;
    server_name  localhost;

    location / {
        root   /var/www/html;
        index  index.html index.htm;
    }

    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   /usr/share/nginx/html;
    }
}

docker-compose.yml

version: "2"

networks:
  mynetwork:
    external:
      name: web

services:
  nginx:
    container_name: sample-site
    build: .
    expose:
      - "80"
    volumes:
      - "./content/:/var/www/html/"
    networks:
      default: {}
      mynetwork:
        aliases:
          - sample-site

Note that we no longer need port mapping here. We simple expose port 80. This is handy for avoiding port collisions.

Run the App

Fire this website up with

docker-compose up -d

Some fun checks regarding the dns mappings for your container:

docker exec -it sample-site bash
ping sample-site

This ping should work, inside your container.

Build the Proxy

Nginx Reverse Proxy:

Dockerfile

FROM nginx

RUN rm /etc/nginx/conf.d/*

We reset all the virtual host config, since we're going to customize it.

docker-compose.yml

version: "2"

networks:
  mynetwork:
    external:
      name: web


services:
  nginx:
    container_name: nginx-proxy
    build: .
    ports:
      - "80:80"
      - "443:443"
    volumes:
      - ./conf.d/:/etc/nginx/conf.d/:ro
      - ./sites/:/var/www/
    networks:
      default: {}
      mynetwork:
        aliases:
          - nginx-proxy

Run the Proxy

Fire up the proxy using our trusty

docker-compose up -d

Assuming no issues, then you have two containers running that can talk to each other using their names. Let's test it.

docker exec -it nginx-proxy bash
ping sample-site
ping nginx-proxy

Set up Virtual Host

Last detail is to set up the virtual hosting file so the proxy can direct traffic based on however you want to set up your matching:

sample-site.conf for our virtual hosting config:

  server {
    listen 80;
    listen [::]:80;

    server_name my.domain.com;

    location / {
      proxy_pass http://sample-site;
    }

  }

Based on how the proxy was set up, you'll need this file stored under your local conf.d folder which we mounted via the volumes declaration in the docker-compose file.

Last but not least, tell nginx to reload it's config.

docker exec nginx-proxy service nginx reload

These sequence of steps is the culmination of hours of pounding head-aches as I struggled with the ever painful 502 Bad Gateway error, and learning nginx for the first time, since most of my experience was with Apache.

This answer is to demonstrate how to kill the 502 Bad Gateway error that results from containers not being able to talk to one another.

I hope this answer saves someone out there hours of pain, since getting containers to talk to each other was really hard to figure out for some reason, despite it being what I expected to be an obvious use-case. But then again, me dumb. And please let me know how I can improve this approach.

Why does git status show branch is up-to-date when changes exist upstream?

While these are all viable answers, I decided to give my way of checking if local repo is in line with the remote, whithout fetching or pulling. In order to see where my branches are I use simply:

git remote show origin

What it does is return all the current tracked branches and most importantly - the info whether they are up to date, ahead or behind the remote origin ones. After the above command, this is an example of what is returned:

  * remote origin
  Fetch URL: https://github.com/xxxx/xxxx.git
  Push  URL: https://github.com/xxxx/xxxx.git
  HEAD branch: master
  Remote branches:
    master      tracked
    no-payments tracked
  Local branches configured for 'git pull':
    master      merges with remote master
    no-payments merges with remote no-payments
  Local refs configured for 'git push':
    master      pushes to master      (local out of date)
    no-payments pushes to no-payments (local out of date)

Hope this helps someone.

Android Studio update -Error:Could not run build action using Gradle distribution

I had the same problem and I Just Invalidate caches/restart

Multipart File Upload Using Spring Rest Template + Spring Web MVC

Here are my working example

@RequestMapping(value = "/api/v1/files/upload", method =RequestMethod.POST)
public ResponseEntity<?> upload(@RequestParam("files") MultipartFile[] files) {
    LinkedMultiValueMap<String, Object> map = new LinkedMultiValueMap<>();
    List<String> tempFileNames = new ArrayList<>();
    String tempFileName;
    FileOutputStream fo;

    try {
        for (MultipartFile file : files) {
            tempFileName = "/tmp/" + file.getOriginalFilename();
            tempFileNames.add(tempFileName);
            fo = new FileOutputStream(tempFileName);
            fo.write(file.getBytes());
            fo.close();
            map.add("files", new FileSystemResource(tempFileName));
        }

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);

        HttpEntity<LinkedMultiValueMap<String, Object>> requestEntity = new HttpEntity<>(map, headers);
        String response = restTemplate.postForObject(uploadFilesUrl, requestEntity, String.class);

    } catch (IOException e) {
        e.printStackTrace();
    }

    for (String fileName : tempFileNames) {
        File f = new File(fileName);
        f.delete();
    }
    return new ResponseEntity<Object>(HttpStatus.OK);
}

sudo service mongodb restart gives "unrecognized service error" in ubuntu 14.0.4

For me nothing have helped, I've ended up with a solution:

create /lib/systemd/system/mongod.service file with content

[Unit]
Description=High-performance, schema-free document-oriented database
After=network.target
Documentation=https://docs.mongodb.org/manual

[Service]
User=mongodb
Group=mongodb
ExecStart=/usr/bin/mongod --quiet --config /etc/mongod.conf

[Install]
WantedBy=multi-user.target

then start/stop commands should work

$ sudo service mongod start

For reference - I have Ubuntu 14.04 LTS, MongoDB 3.2.9 installed from

deb http://repo.mongodb.org/apt/ubuntu trusty/mongodb-org/3.2 multiverse

Return HTML from ASP.NET Web API

Starting with AspNetCore 2.0, it's recommended to use ContentResult instead of the Produce attribute in this case. See: https://github.com/aspnet/Mvc/issues/6657#issuecomment-322586885

This doesn't rely on serialization nor on content negotiation.

[HttpGet]
public ContentResult Index() {
    return new ContentResult {
        ContentType = "text/html",
        StatusCode = (int)HttpStatusCode.OK,
        Content = "<html><body>Hello World</body></html>"
    };
}

Multiple scenarios @RequestMapping produces JSON/XML together with Accept or ResponseEntity

All your problems are that you are mixing content type negotiation with parameter passing. They are things at different levels. More specific, for your question 2, you constructed the response header with the media type your want to return. The actual content negotiation is based on the accept media type in your request header, not response header. At the point the execution reaches the implementation of the method getPersonFormat, I am not sure whether the content negotiation has been done or not. Depends on the implementation. If not and you want to make the thing work, you can overwrite the request header accept type with what you want to return.

return new ResponseEntity<>(PersonFactory.createPerson(), httpHeaders, HttpStatus.OK);

Jquery Ajax, return success/error from mvc.net controller

Use Json class instead of Content as shown following:

    //  When I want to return an error:
    if (!isFileSupported)
    {
        Response.StatusCode = (int) HttpStatusCode.BadRequest;
        return Json("The attached file is not supported", MediaTypeNames.Text.Plain);
    }
    else
    {
        //  When I want to return sucess:
        Response.StatusCode = (int)HttpStatusCode.OK; 
        return Json("Message sent!", MediaTypeNames.Text.Plain);
    }

Also set contentType:

contentType: 'application/json; charset=utf-8',

Spring: Returning empty HTTP Responses with ResponseEntity<Void> doesn't work

You can also not specify the type parameter which seems a bit cleaner and what Spring intended when looking at the docs:

@RequestMapping(method = RequestMethod.HEAD, value = Constants.KEY )
public ResponseEntity taxonomyPackageExists( @PathVariable final String key ){
    // ...
    return new ResponseEntity(HttpStatus.NO_CONTENT);
}

When use ResponseEntity<T> and @RestController for Spring RESTful applications

ResponseEntity is meant to represent the entire HTTP response. You can control anything that goes into it: status code, headers, and body.

@ResponseBody is a marker for the HTTP response body and @ResponseStatus declares the status code of the HTTP response.

@ResponseStatus isn't very flexible. It marks the entire method so you have to be sure that your handler method will always behave the same way. And you still can't set the headers. You'd need the HttpServletResponse or a HttpHeaders parameter.

Basically, ResponseEntity lets you do more.

Spring: return @ResponseBody "ResponseEntity<List<JSONObject>>"

I have no idea why the other answers didn't work for me (error 500) but this works

@GetMapping("")
public String getAll() {
    List<Entity> entityList = entityManager.findAll();
    List<JSONObject> entities = new ArrayList<JSONObject>();
    for (Entity n : entityList) {
        JSONObject Entity = new JSONObject();
        entity.put("id", n.getId());
        entity.put("address", n.getAddress());
        entities.add(entity);
    }
    return entities.toString();
}

Starting Docker as Daemon on Ubuntu

This problem really cost me some hours.

My system is Ubuntu 14.04, I installed docker by sudo apt-get install docker, and typed some other commands that caused the problem.

  1. I google "unknown job: docker.io", answers did not take effect.

  2. I looked for reasons of "unknown job" in /etc/init.d/, found no proper answer .

  3. I looked for way to debug script in /etc/init.d/, found no proper answer.

  4. Then, I did a clean:

    1. sudo apt-get remove docker.io
    2. rm every suspicious file by find / -name "*docker*", such as /etc/init/docker.io.conf, /etc/init.d/docker.io .
  5. Follow the latest official document: https://docs.docker.com/installation/, there is a lot of outdated documentation which can be misleading.

Finally, it fixed the problem.

Note: If you are in China, because of the GFW, you may need to set the https_proxy to install docker from https://get.docker.com/ .

How to Migrate to WKWebView?

Swift is not a requirement, everything works fine with Objective-C. UIWebView will continue to be supported, so there is no rush to migrate if you want to take your time. However, it will not get the javascript and scrolling performance enhancements of WKWebView.

For backwards compatibility, I have two properties for my view controller: a UIWebView and a WKWebView. I use the WKWebview only if the class exists:

if ([WKWebView class]) {
    // do new webview stuff
} else {
    // do old webview stuff
}

Whereas I used to have a UIWebViewDelegate, I also made it a WKNavigationDelegate and created the necessary methods.

Difference between WebStorm and PHPStorm

In my own experience, even though theoretically many JetBrains products share the same functionalities, the new features that get introduced in some apps don't get immediately introduced in the others. In particular, IntelliJ IDEA has a new version once per year, while WebStorm and PHPStorm get 2 to 3 per year I think. Keep that in mind when choosing an IDE. :)

Forwarding port 80 to 8080 using NGINX

As simple as like this,

make sure to change example.com to your domain (or IP), and 8080 to your Node.js application port:

server {
    listen 80;
    server_name example.com;

    location / {
        proxy_set_header   X-Forwarded-For $remote_addr;
        proxy_set_header   Host $http_host;
        proxy_pass         "http://127.0.0.1:8080";
    }
}

Source: https://eladnava.com/binding-nodejs-port-80-using-nginx/

Why am I getting a "401 Unauthorized" error in Maven?

If you were like me, running maven compile deploy from eclipse's maven run configuration, the issue could be related to eclipse's own embedded maven as described in https://bugs.eclipse.org/bugs/show_bug.cgi?id=562847

The workaround is to run mvn compile deploy from CLI such as bash, or to NOT use embedded maven in the eclipse's maven run configuration, and add an external maven (mine is in /usr/share/mvn), and voila, it'll say BUILD SUCCESS.

Nginx reverse proxy causing 504 Gateway Timeout

Had the same problem. Turned out it was caused by iptables connection tracking on the upstream server. After removing --state NEW,ESTABLISHED,RELATED from the firewall script and flushing with conntrack -F the problem was gone.

AppStore - App status is ready for sale, but not in app store

I published an update to my app yesterday noon(I have selected Manual release instead of Automatic) and Today early morning App store review was completed and after I release the build manually, the App shows Ready for sale in iTunesConect immediately. After 45mins I got the update on the App store.

how to set ulimit / file descriptor on docker container the image tag is phusion/baseimage-docker

The latest docker supports setting ulimits through the command line and the API. For instance, docker run takes --ulimit <type>=<soft>:<hard> and there can be as many of these as you like. So, for your nofile, an example would be --ulimit nofile=262144:262144

Spring Boot Rest Controller how to return different HTTP status codes?

There are different ways to return status code, 1 : RestController class should extends BaseRest class, in BaseRest class we can handle exception and return expected error codes. for example :

@RestController
@RequestMapping
class RestController extends BaseRest{

}

@ControllerAdvice
public class BaseRest {
@ExceptionHandler({Exception.class,...})
    @ResponseStatus(value=HttpStatus.INTERNAL_SERVER_ERROR)
    public ErrorModel genericError(HttpServletRequest request, 
            HttpServletResponse response, Exception exception) {
        
        ErrorModel error = new ErrorModel();
        resource.addError("error code", exception.getLocalizedMessage());
        return error;
    }

Can't update: no tracked branch

git branch --set-upstream-to=origin/master master

Worked for me....where I have a single branch in my repo called master. The response was "Branch master set up to track remote branch master from origin."

Download file from an ASP.NET Web API method using AngularJS

Support for downloading binary files in using ajax is not great, it is very much still under development as working drafts.

Simple download method:

You can have the browser download the requested file simply by using the code below, and this is supported in all browsers, and will obviously trigger the WebApi request just the same.

$scope.downloadFile = function(downloadPath) { 
    window.open(downloadPath, '_blank', '');  
}

Ajax binary download method:

Using ajax to download the binary file can be done in some browsers and below is an implementation that will work in the latest flavours of Chrome, Internet Explorer, FireFox and Safari.

It uses an arraybuffer response type, which is then converted into a JavaScript blob, which is then either presented to save using the saveBlob method - though this is only currently present in Internet Explorer - or turned into a blob data URL which is opened by the browser, triggering the download dialog if the mime type is supported for viewing in the browser.

Internet Explorer 11 Support (Fixed)

Note: Internet Explorer 11 did not like using the msSaveBlob function if it had been aliased - perhaps a security feature, but more likely a flaw, So using var saveBlob = navigator.msSaveBlob || navigator.webkitSaveBlob ... etc. to determine the available saveBlob support caused an exception; hence why the code below now tests for navigator.msSaveBlob separately. Thanks? Microsoft

// Based on an implementation here: web.student.tuwien.ac.at/~e0427417/jsdownload.html
$scope.downloadFile = function(httpPath) {
    // Use an arraybuffer
    $http.get(httpPath, { responseType: 'arraybuffer' })
    .success( function(data, status, headers) {

        var octetStreamMime = 'application/octet-stream';
        var success = false;

        // Get the headers
        headers = headers();

        // Get the filename from the x-filename header or default to "download.bin"
        var filename = headers['x-filename'] || 'download.bin';

        // Determine the content type from the header or default to "application/octet-stream"
        var contentType = headers['content-type'] || octetStreamMime;

        try
        {
            // Try using msSaveBlob if supported
            console.log("Trying saveBlob method ...");
            var blob = new Blob([data], { type: contentType });
            if(navigator.msSaveBlob)
                navigator.msSaveBlob(blob, filename);
            else {
                // Try using other saveBlob implementations, if available
                var saveBlob = navigator.webkitSaveBlob || navigator.mozSaveBlob || navigator.saveBlob;
                if(saveBlob === undefined) throw "Not supported";
                saveBlob(blob, filename);
            }
            console.log("saveBlob succeeded");
            success = true;
        } catch(ex)
        {
            console.log("saveBlob method failed with the following exception:");
            console.log(ex);
        }

        if(!success)
        {
            // Get the blob url creator
            var urlCreator = window.URL || window.webkitURL || window.mozURL || window.msURL;
            if(urlCreator)
            {
                // Try to use a download link
                var link = document.createElement('a');
                if('download' in link)
                {
                    // Try to simulate a click
                    try
                    {
                        // Prepare a blob URL
                        console.log("Trying download link method with simulated click ...");
                        var blob = new Blob([data], { type: contentType });
                        var url = urlCreator.createObjectURL(blob);
                        link.setAttribute('href', url);

                        // Set the download attribute (Supported in Chrome 14+ / Firefox 20+)
                        link.setAttribute("download", filename);

                        // Simulate clicking the download link
                        var event = document.createEvent('MouseEvents');
                        event.initMouseEvent('click', true, true, window, 1, 0, 0, 0, 0, false, false, false, false, 0, null);
                        link.dispatchEvent(event);
                        console.log("Download link method with simulated click succeeded");
                        success = true;

                    } catch(ex) {
                        console.log("Download link method with simulated click failed with the following exception:");
                        console.log(ex);
                    }
                }

                if(!success)
                {
                    // Fallback to window.location method
                    try
                    {
                        // Prepare a blob URL
                        // Use application/octet-stream when using window.location to force download
                        console.log("Trying download link method with window.location ...");
                        var blob = new Blob([data], { type: octetStreamMime });
                        var url = urlCreator.createObjectURL(blob);
                        window.location = url;
                        console.log("Download link method with window.location succeeded");
                        success = true;
                    } catch(ex) {
                        console.log("Download link method with window.location failed with the following exception:");
                        console.log(ex);
                    }
                }

            }
        }

        if(!success)
        {
            // Fallback to window.open method
            console.log("No methods worked for saving the arraybuffer, using last resort window.open");
            window.open(httpPath, '_blank', '');
        }
    })
    .error(function(data, status) {
        console.log("Request failed with status: " + status);

        // Optionally write the error out to scope
        $scope.errorDetails = "Request failed with status: " + status;
    });
};

Usage:

var downloadPath = "/files/instructions.pdf";
$scope.downloadFile(downloadPath);

Notes:

You should modify your WebApi method to return the following headers:

  • I have used the x-filename header to send the filename. This is a custom header for convenience, you could however extract the filename from the content-disposition header using regular expressions.

  • You should set the content-type mime header for your response too, so the browser knows the data format.

I hope this helps.

(13: Permission denied) while connecting to upstream:[nginx]

I have solved my problem by running my Nginx as the user I'm currently logged in with, mulagala.

By default the user as nginx is defined at the very top section of the nginx.conf file as seen below;

user nginx; # Default Nginx user

Change nginx to the name of your current user - here, mulagala.

user mulagala; # Custom Nginx user (as username of the current logged in user)

However, this may not address the actual problem and may actually have casual side effect(s).

For an effective solution, please refer to Joseph Barbere's solution.

upstream sent too big header while reading response header from upstream

Add:

fastcgi_buffers 16 16k;
fastcgi_buffer_size 32k;
proxy_buffer_size   128k;
proxy_buffers   4 256k;
proxy_busy_buffers_size   256k;

To server{} in nginx.conf

Works for me.

phpMyAdmin allow remote users

Replace the contents of the first <directory> tag.

Remove:

<Directory /usr/share/phpMyAdmin/>
 <IfModule mod_authz_core.c>
  # Apache 2.4
  <RequireAny>
    Require ip 127.0.0.1
    Require ip ::1
  </RequireAny>
 </IfModule>
 <IfModule !mod_authz_core.c>
  # Apache 2.2
  Order Deny,Allow
  Deny from All
  Allow from 127.0.0.1
  Allow from ::1
 </IfModule>
</Directory>

And place this instead:

<Directory /usr/share/phpMyAdmin/>
 Order allow,deny
 Allow from all
</Directory>

Don't forget to restart Apache afterwards.

nginx error connect to php5-fpm.sock failed (13: Permission denied)

Consideration must also be given to your individual FPM pools, if any.

I couldn't figure out why none of these answers was working for me today. This had been a set-and-forget scenario for me, where I had forgotten that listen.user and listen.group were duplicated on a per-pool basis.

If you used pools for different user accounts like I did, where each user account owns their FPM processes and sockets, setting only the default listen.owner and listen.group configuration options to 'nginx' will simply not work. And obviously, letting 'nginx' own them all is not acceptable either.

For each pool, make sure that

listen.group = nginx

Otherwise, you can leave the pool's ownership and such alone.

fatal: The current branch master has no upstream branch

To resolve this issue, while checking out the code from git itself, u need to give the command like below:

git checkout -b branchname origin/branchname

Here, by default we are setting the upstream branch, so you will not be facing the mentioned issue.

There isn't anything to compare. Nothing to compare, branches are entirely different commit histories

Top guy is probably right that you downloaded instead of cloning the repo at start. Here is a easy solution without getting too technical.

  • In a new editor window, clone your repo in another directory.
  • Make a new branch.
  • Then copy from your your edited editor window into your new repo by copy paste.

Make sure that all your edits are copied over by looking at your older github branch.

Forbidden :You don't have permission to access /phpmyadmin on this server

None of the configuration above worked for me on my CentOS 7 server. After hours of searching, that what worked for me:

Edit file phpMyAdmin.conf

sudo nano /etc/httpd/conf.d/phpMyAdmin.conf

And replace the existing <Directory> ... </Directory> node with the following:

<Directory /usr/share/phpMyAdmin/>
   AddDefaultCharset UTF-8

   <IfModule mod_authz_core.c>
     # Apache 2.4
     <RequireAny>
       #Require ip 127.0.0.1
       #Require ip ::1
       Require all granted
     </RequireAny>
   </IfModule>
   <IfModule !mod_authz_core.c>
     # Apache 2.2
     Order Deny,Allow
     Deny from All
     Allow from 127.0.0.1
     Allow from ::1
   </IfModule>
</Directory>

ASP.NET MVC - Attaching an entity of type 'MODELNAME' failed because another entity of the same type already has the same primary key value

Reasons I've encountered this error:

  1. Did not use .AsNoTracking() when querying for existing entities. Especially when calling a helper function to check permissions.
  2. Calling .Include() on a query and then trying to edit the parent. Example: var ent = repo.Query<Ent>().Include(e=>e.Ent2).First(); ...repo.Edit(e.Ent2); repo.Edit(e); If I'm going to edit a nested object, I try to separate these into separate query calls now. If you can't do that, set the child object to null and iterate through lists, detaching objects like this
  3. Editing an old entity in a Put web call. The new item is already added to the repo, so modify that one and have it be saved in super.Put(). Example of what will throw an error: public void Put(key, newItem){ var old = repo.Query<Entity>().Where(e=>Id==key).First(); ... repo.Edit(old); super.Put(key,newItem); ... }
  4. Multiple helper functions edit the same entity. Instead of passing the ID as a parameter into each function, pass a reference to the entity. Error solved!

web-api POST body object always null

After Three days of searching and none of above solutions worked for me , I found another approach to this problem in this Link: HttpRequestMessage

I used one of the solutions in this site

[HttpPost]
public async System.Threading.Tasks.Task<string> Post(HttpRequestMessage request)
{
    string body = await request.Content.ReadAsStringAsync();
    return body;
}

Could not load file or assembly 'Newtonsoft.Json' or one of its dependencies. Manifest definition does not match the assembly reference

None of the answers, including the checked one did not work for me.

The solution was far more simple. I first removed the references from my BUS layer. Then deleted the dll's from the project (to make sure it's gone), then reinstalled JSON.NET from nuget packeges. And, the tricky part was, "turning it off and on again".

I just restarted visual studio, and there it worked!

So, if you try everything possible and still can't solve the problem, just try turning visual studio off and on again, it might help.

Various ways to remove local Git changes

For discard all i like to stash and drop that stash, it's the fastest way to discard all, especially if you work between multiple repos.

This will stash all changes in {0} key and instantly drop it from {0}

git stash && git stash drop

Error sending json in POST to web API service

  1. You have to must add header property Content-Type:application/json
  2. When you define any POST request method input parameter that should be annotated as [FromBody], e.g.:

    [HttpPost]
    public HttpResponseMessage Post([FromBody]ActivityResult ar)
    {
      return new HttpResponseMessage(HttpStatusCode.OK);
    }
    
  3. Any JSON input data must be raw data.

Spring: How to get parameters from POST body?

You can get entire post body into a POJO. Following is something similar

@RequestMapping(
    value = { "/api/pojo/edit" }, 
    method = RequestMethod.POST, 
    produces = "application/json", 
    consumes = ["application/json"])
@ResponseBody
public Boolean editWinner( @RequestBody Pojo pojo) { 

Where each field in Pojo (Including getter/setters) should match the Json request object that the controller receives..

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

Transaction count after EXECUTE indicates a mismatching number of BEGIN and COMMIT statements. Previous count = 1, current count = 0

This can also depend on the way you are invoking the SP from your C# code. If the SP returns some table type value then invoke the SP with ExecuteStoreQuery, and if the SP doesn't returns any value invoke the SP with ExecuteStoreCommand

Getting first and last day of the current month

DateTime now = DateTime.Now;
var startDate = new DateTime(now.Year, now.Month, 1);
var endDate = startDate.AddMonths(1).AddDays(-1);

Why should I use IHttpActionResult instead of HttpResponseMessage?

// this will return HttpResponseMessage as IHttpActionResult
return ResponseMessage(httpResponseMessage); 

PUT and POST getting 405 Method Not Allowed Error for Restful Web Services

In my case the form (which I cannot modify) was always sending POST.
While in my Web Service I tried to implement GET method (due to lack of documentation I expected that both are allowed).

Thus, it was failing as "Not allowed", since there was no method with POST type on my end.

Changing @GET to @POST above my WS method fixed the issue.

return error message with actionResult

IN your view insert

@Html.ValidationMessage("Error")

then in the controller after you use new in your model

var model = new yourmodel();
try{
[...]
}catch(Exception ex){
ModelState.AddModelError("Error", ex.Message);
return View(model);
}

Why call git branch --unset-upstream to fixup?

I had this question twice, and it was always caused by the corruption of the git cache file at my local branch. I fixed it by writing the missing commit hash into that file. I got the right commit hash from the server and ran the following command locally:

cat .git/refs/remotes/origin/feature/mybranch \
echo 1edf9668426de67ab764af138a98342787dc87fe \
>> .git/refs/remotes/origin/feature/mybranch

How to resolve conflicts in EGit

GIT has the most irritating way of resolving conflicts (Unlike svn where you can simply compare and do the changes). I strongly feel git has complex conflict resolution process. If I were to resolve, I would simply take another code from GIT as fresh, add my changes and commit them. It simple and not so process oriented.

nginx: connect() failed (111: Connection refused) while connecting to upstream

I had the same problem when I wrote two upstreams in NGINX conf

upstream php_upstream {
    server unix:/var/run/php/my.site.sock;
    server 127.0.0.1:9000;
}

...

fastcgi_pass php_upstream;

but in /etc/php/7.3/fpm/pool.d/www.conf I listened the socket only

listen = /var/run/php/my.site.sock

So I need just socket, no any 127.0.0.1:9000, and I just removed IP+port upstream

upstream php_upstream {
    server unix:/var/run/php/my.site.sock;
}

This could be rewritten without an upstream

fastcgi_pass unix:/var/run/php/my.site.sock;

insert data into database using servlet and jsp in eclipse

Same problem fetch main problem in PreparedStatement use simple statement then you successfully insert record same use below.

String  st2="insert into 
user(gender,name,address,telephone,fax,email,
     destination,sdate,edate,Participant,hcategory,
     Culture,Nature,People,Cities,Beaches,Festivals,username,password) 
values('"+gender+"','"+name+"','"+address+"','"+phone+"','"+fax+"',
       '"+email+"','"+desti+"','"+sdate+"','"+edate+"','"+parti+"',
       '"+hotel+"','"+chk1+"','"+chk2+"','"+chk3+"','"+chk4+"',
       '"+chk5+"','"+chk6+"','"+user+"','"+password+"')";


int i=stm.executeUpdate(st2);

How to delete an app from iTunesConnect / App Store Connect

Apps can’t be deleted if they are part of a Game Center group, in an app bundle, or currently displayed on a store. You’ll want to remove the app from sale or from the group if you want to delete it.

Source: iTunes Connect Developer Guide - Transferring and Deleting Apps

Cannot install packages using node package manager in Ubuntu

for me problem was solved by,

sudo apt-get remove node
sudo apt-get remove nodejs
curl -sL https://deb.nodesource.com/setup_8.x | sudo -E bash -
sudo apt-get install -y nodejs
sudo ln -s /usr/bin/nodejs /usr/bin/node
alias node=nodejs
rm -r /usr/local/lib/python2.7/dist-packages/localstack/node_modules
npm install -g npm@latest || sudo npm install -g npm@latest

Why is it common to put CSRF prevention tokens in cookies?

A good reason, which you have sort of touched on, is that once the CSRF cookie has been received, it is then available for use throughout the application in client script for use in both regular forms and AJAX POSTs. This will make sense in a JavaScript heavy application such as one employed by AngularJS (using AngularJS doesn't require that the application will be a single page app, so it would be useful where state needs to flow between different page requests where the CSRF value cannot normally persist in the browser).

Consider the following scenarios and processes in a typical application for some pros and cons of each approach you describe. These are based on the Synchronizer Token Pattern.

Request Body Approach

  1. User successfully logs in.
  2. Server issues auth cookie.
  3. User clicks to navigate to a form.
  4. If not yet generated for this session, server generates CSRF token, stores it against the user session and outputs it to a hidden field.
  5. User submits form.
  6. Server checks hidden field matches session stored token.

Advantages:

  • Simple to implement.
  • Works with AJAX.
  • Works with forms.
  • Cookie can actually be HTTP Only.

Disadvantages:

  • All forms must output the hidden field in HTML.
  • Any AJAX POSTs must also include the value.
  • The page must know in advance that it requires the CSRF token so it can include it in the page content so all pages must contain the token value somewhere, which could make it time consuming to implement for a large site.

Custom HTTP Header (downstream)

  1. User successfully logs in.
  2. Server issues auth cookie.
  3. User clicks to navigate to a form.
  4. Page loads in browser, then an AJAX request is made to retrieve the CSRF token.
  5. Server generates CSRF token (if not already generated for session), stores it against the user session and outputs it to a header.
  6. User submits form (token is sent via hidden field).
  7. Server checks hidden field matches session stored token.

Advantages:

Disadvantages:

  • Doesn't work without an AJAX request to get the header value.
  • All forms must have the value added to its HTML dynamically.
  • Any AJAX POSTs must also include the value.
  • The page must make an AJAX request first to get the CSRF token, so it will mean an extra round trip each time.
  • Might as well have simply output the token to the page which would save the extra request.

Custom HTTP Header (upstream)

  1. User successfully logs in.
  2. Server issues auth cookie.
  3. User clicks to navigate to a form.
  4. If not yet generated for this session, server generates CSRF token, stores it against the user session and outputs it in the page content somewhere.
  5. User submits form via AJAX (token is sent via header).
  6. Server checks custom header matches session stored token.

Advantages:

Disadvantages:

  • Doesn't work with forms.
  • All AJAX POSTs must include the header.

Custom HTTP Header (upstream & downstream)

  1. User successfully logs in.
  2. Server issues auth cookie.
  3. User clicks to navigate to a form.
  4. Page loads in browser, then an AJAX request is made to retrieve the CSRF token.
  5. Server generates CSRF token (if not already generated for session), stores it against the user session and outputs it to a header.
  6. User submits form via AJAX (token is sent via header) .
  7. Server checks custom header matches session stored token.

Advantages:

Disadvantages:

  • Doesn't work with forms.
  • All AJAX POSTs must also include the value.
  • The page must make an AJAX request first to get the CRSF token, so it will mean an extra round trip each time.

Set-Cookie

  1. User successfully logs in.
  2. Server issues auth cookie.
  3. User clicks to navigate to a form.
  4. Server generates CSRF token, stores it against the user session and outputs it to a cookie.
  5. User submits form via AJAX or via HTML form.
  6. Server checks custom header (or hidden form field) matches session stored token.
  7. Cookie is available in browser for use in additional AJAX and form requests without additional requests to server to retrieve the CSRF token.

Advantages:

  • Simple to implement.
  • Works with AJAX.
  • Works with forms.
  • Doesn't necessarily require an AJAX request to get the cookie value. Any HTTP request can retrieve it and it can be appended to all forms/AJAX requests via JavaScript.
  • Once the CSRF token has been retrieved, as it is stored in a cookie the value can be reused without additional requests.

Disadvantages:

  • All forms must have the value added to its HTML dynamically.
  • Any AJAX POSTs must also include the value.
  • The cookie will be submitted for every request (i.e. all GETs for images, CSS, JS, etc, that are not involved in the CSRF process) increasing request size.
  • Cookie cannot be HTTP Only.

So the cookie approach is fairly dynamic offering an easy way to retrieve the cookie value (any HTTP request) and to use it (JS can add the value to any form automatically and it can be employed in AJAX requests either as a header or as a form value). Once the CSRF token has been received for the session, there is no need to regenerate it as an attacker employing a CSRF exploit has no method of retrieving this token. If a malicious user tries to read the user's CSRF token in any of the above methods then this will be prevented by the Same Origin Policy. If a malicious user tries to retrieve the CSRF token server side (e.g. via curl) then this token will not be associated to the same user account as the victim's auth session cookie will be missing from the request (it would be the attacker's - therefore it won't be associated server side with the victim's session).

As well as the Synchronizer Token Pattern there is also the Double Submit Cookie CSRF prevention method, which of course uses cookies to store a type of CSRF token. This is easier to implement as it does not require any server side state for the CSRF token. The CSRF token in fact could be the standard authentication cookie when using this method, and this value is submitted via cookies as usual with the request, but the value is also repeated in either a hidden field or header, of which an attacker cannot replicate as they cannot read the value in the first place. It would be recommended to choose another cookie however, other than the authentication cookie so that the authentication cookie can be secured by being marked HttpOnly. So this is another common reason why you'd find CSRF prevention using a cookie based method.

Proxy Error 502 : The proxy server received an invalid response from an upstream server

Add this into your httpd.conf file

Timeout 2400
ProxyTimeout 2400
ProxyBadHeader Ignore 

Add context path to Spring Boot application

You can do it by adding the port and contextpath easily to add the configuration in [src\main\resources] .properties file and also .yml file

application.porperties file configuration

server.port = 8084
server.contextPath = /context-path

application.yml file configuration

server:
port: 8084
contextPath: /context-path

We can also change it programmatically in spring boot.

@Component
public class ServerPortCustomizer implements     WebServerFactoryCustomizer<EmbeddedServletContainerCustomizer > {

@Override
public void customize(EmbeddedServletContainerCustomizer factory) {
    factory.setContextPath("/context-path");
    factory.setPort(8084);
}

}

We can also add an other way

@SpringBootApplication
public class MyApplication {
public static void main(String[] args) {SpringApplication application =     new pringApplication(MyApplication.class);
    Map<String, Object> map = new HashMap<>();
    map.put("server.servlet.context-path", "/context-path");
    map.put("server.port", "808");
    application.setDefaultProperties(map);
    application.run(args);
    }       
}

using java command spring boot 1.X

java -jar my-app.jar --server.contextPath=/spring-boot-app     --server.port=8585 

using java command spring boot 2.X

java -jar my-app.jar --server.servlet.context-path=/spring-boot-app --server.port=8585 

download csv file from web api in angular js

The a.download is not supported by IE. At least at the HTML5 "supported" pages. :(

How to git clone a specific tag

git clone -b 13.1rc1-Gotham  --depth 1  https://github.com/xbmc/xbmc.git
Cloning into 'xbmc'...
remote: Counting objects: 17977, done.
remote: Compressing objects: 100% (13473/13473), done.
Receiving objects:  36% (6554/17977), 19.21 MiB | 469 KiB/s    

Will be faster than :

git clone https://github.com/xbmc/xbmc.git
Cloning into 'xbmc'...
remote: Reusing existing pack: 281705, done.
remote: Counting objects: 533, done.
remote: Compressing objects: 100% (177/177), done.
Receiving objects:  14% (40643/282238), 55.46 MiB | 578 KiB/s

Or

git clone -b 13.1rc1-Gotham  https://github.com/xbmc/xbmc.git
Cloning into 'xbmc'...
remote: Reusing existing pack: 281705, done.
remote: Counting objects: 533, done.
remote: Compressing objects: 100% (177/177), done.
Receiving objects:  12% (34441/282238), 20.25 MiB | 461 KiB/s

How to pass json POST data to Web API method as an object?

Microsoft gave a good example of doing this:

https://docs.microsoft.com/en-us/aspnet/web-api/overview/advanced/sending-html-form-data-part-1

First validate the request

if (ModelState.IsValid)

and than use the serialized data.

Content = new StringContent(update.Status)

Here 'Status' is a field in the complex type. Serializing is done by .NET, no need to worry about that.

OwinStartup not firing

Alternative answer to the original problem discussed - Owin "not firing." In my case I spent hours thinking it wasn't firing due to being unable to set a breakpoint in it.

When debugging OWIN startup in visual studio

  • IIS Express - Running "F5" will break on the OWIN startup code

  • IIS - Running "F5" will not break until after OWIN (and global.asax) code is loaded. If you attach to W3P.exe you will be able to step into it.

What is IllegalStateException?

package com.concepttimes.java;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class IllegalStateExceptionDemo {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        List al = new ArrayList();
        al.add("Sachin");
        al.add("Rahul");
        al.add("saurav");
        Iterator itr = al.iterator();  
        while (itr.hasNext()) {           
            itr.remove();
        }
    }
}

IllegalStateException signals that method has been invoked at the wrong time. In this below example, we can see that. remove() method is called at the same time element is being used in while loop.

Please refer to below link for more details. http://www.elitmuszone.com/elitmus/illegalstateexception-in-java/

OWIN Startup Class Missing

In my case, I had renamed the project and changed it's folder structure. I found that updating the RootNameSpace and AssemblyName in the .csproj file where the error was being thrown resolved the error. If you have modified paths of your project I'd recommend checking this as well.

<RootNamespace>Company.Product.WebAPI</RootNamespace>
<AssemblyName>Company.Product.WebAPI</AssemblyName>

How to include libraries in Visual Studio 2012?

In code level also, you could add your lib to the project using the compiler directives #pragma.

example:

#pragma comment( lib, "yourLibrary.lib" )

Cannot ignore .idea/workspace.xml - keeps popping up

If you have multiple projects in your git repo, .idea/workspace.xml will not match to any files.

Instead, do the following:

$ git rm -f **/.idea/workspace.xml

And make your .gitignore look something like this:

# User-specific stuff:
**/.idea/workspace.xml
**/.idea/tasks.xml
**/.idea/dictionaries
**/.idea/vcs.xml
**/.idea/jsLibraryMappings.xml

# Sensitive or high-churn files:
**/.idea/dataSources.ids
**/.idea/dataSources.xml
**/.idea/dataSources.local.xml
**/.idea/sqlDataSources.xml
**/.idea/dynamic.xml
**/.idea/uiDesigner.xml

## File-based project format:
*.iws

# IntelliJ
/out/

Runtime error: Could not load file or assembly 'System.Web.WebPages.Razor, Version=3.0.0.0

I got this error because such DLL (and many others) were missing in bin folder when I pubished the web application. It seemed like a bug in Visual Studio publish function. Cleaning, recompiling and publishing it again, made such DLLs to be published correctly.

Error: The processing instruction target matching "[xX][mM][lL]" is not allowed

For PHP, put this line of code before you start printing your XML:

while(ob_get_level()) ob_end_clean();

Git removing upstream from local repository

git remote manpage is pretty straightforward:

Use

Older (backwards-compatible) syntax:
$ git remote rm upstream
Newer syntax for newer git versions: (* see below)
$ git remote remove upstream

Then do:    
$ git remote add upstream https://github.com/Foo/repos.git

or just update the URL directly:

$ git remote set-url upstream https://github.com/Foo/repos.git

or if you are comfortable with it, just update the .git/config directly - you can probably figure out what you need to change (left as exercise for the reader).

...
[remote "upstream"]
    fetch = +refs/heads/*:refs/remotes/upstream/*
    url = https://github.com/foo/repos.git
...

===

* Regarding 'git remote rm' vs 'git remote remove' - this changed around git 1.7.10.3 / 1.7.12 2 - see

https://code.google.com/p/git-core/source/detail?spec=svne17dba8fe15028425acd6a4ebebf1b8e9377d3c6&r=e17dba8fe15028425acd6a4ebebf1b8e9377d3c6

Log message

remote: prefer subcommand name 'remove' to 'rm'

All remote subcommands are spelled out words except 'rm'. 'rm', being a
popular UNIX command name, may mislead users that there are also 'ls' or
'mv'. Use 'remove' to fit with the rest of subcommands.

'rm' is still supported and used in the test suite. It's just not
widely advertised.

Handle spring security authentication exceptions with @ExceptionHandler

I'm using the objectMapper. Every Rest Service is mostly working with json, and in one of your configs you have already configured an object mapper.

Code is written in Kotlin, hopefully it will be ok.

@Bean
fun objectMapper(): ObjectMapper {
    val objectMapper = ObjectMapper()
    objectMapper.registerModule(JodaModule())
    objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false)

    return objectMapper
}

class UnauthorizedAuthenticationEntryPoint : BasicAuthenticationEntryPoint() {

    @Autowired
    lateinit var objectMapper: ObjectMapper

    @Throws(IOException::class, ServletException::class)
    override fun commence(request: HttpServletRequest, response: HttpServletResponse, authException: AuthenticationException) {
        response.addHeader("Content-Type", "application/json")
        response.status = HttpServletResponse.SC_UNAUTHORIZED

        val responseError = ResponseError(
            message = "${authException.message}",
        )

        objectMapper.writeValue(response.writer, responseError)
     }}

Could not load file or assembly 'System.Web.Http 4.0.0 after update from 2012 to 2013

I fixed this by reinstalling the NuGet package, which corrects broken dependencies. From the package manager, run:

Update-Package Microsoft.AspNet.WebApi -reinstall

Web API Put Request generates an Http 405 Method Not Allowed error

Another cause of this could be if you don't use the default variable name for the "id" which is actually: id.

How to support HTTP OPTIONS verb in ASP.NET MVC/WebAPI application

I had this same problem. For me the fix was to remove the custom content type from the jQuery AJAX call. Custom content types trigger the pre-flight request. I found this:

The browser can skip the preflight request if the following conditions are true:

The request method is GET, HEAD, or POST, and

The application does not set any request headers other than Accept, Accept-Language, Content-Language, Content-Type, or Last-Event-ID, and

The Content-Type header (if set) is one of the following:

  • application/x-www-form-urlencoded
  • multipart/form-data
  • text/plain

From this page: http://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api (under "Preflight Requests")

Please enter a commit message to explain why this merge is necessary, especially if it merges an updated upstream into a topic branch

It's not a Git error message, it's the editor as git uses your default editor.

To solve this:

  1. press "i" (i for insert)
  2. write your merge message
  3. press "esc" (escape)
  4. write ":wq" (write & quit)
  5. then press enter

Can I safely delete contents of Xcode Derived data folder?

Yes, you can delete all files from DerivedData sub-folder (Not DerivedData Folder) directly.

That will not affect your project work. Contents of DerivedData folder is generated during the build time and you can delete them if you want. It's not an issue.

The contents of DerivedData will be recreated when you build your projects again.

Xcode8+ Update

From the Xcode8 that removed project option from the window tab so you can still use first way:

Xcode -> Preferences -> location -> click on small arrow button as i explain in my first answer.

Xcode7.3 Update For remove particular project's DeriveData you just need to follow the following steps:

Go to Window -> Project:

enter image description here

You can find the list of project and you can either go the DerivedData Folder or you can direct delete individual Project's DerivedData

enter image description here


I am not working on Xcode5 but in 4.6.3 you can find DerivedData folder as found in the below image:

enter image description here

After clicking on Preferences..

enter image description here

You get this window

enter image description here

Changing the Git remote 'push to' default

If you did git push origin -u localBranchName:remoteBranchName and on sequentially git push commands, you get errors that then origin doesn't exist, then follow these steps:

  1. git remote -v

Check if there is any remote that I don't care. Delete them with git remote remove 'name'

  1. git config --edit

Look for possible signs of a old/non-existent remote. Look for pushdefault:

[remote]
  pushdefault = oldremote

Update oldremote value and save.

git push should work now.

NGINX: upstream timed out (110: Connection timed out) while reading response header from upstream

I think this error can happen for various reasons, but it can be specific to the module you're using. For example I saw this using the uwsgi module, so had to set "uwsgi_read_timeout".

Return JSON for ResponseEntity<String>

This is a String, not a json structure(key, value), try:

return new ResponseEntity("{"vale" : "This is a String"}", HttpStatus.OK);

Get the current date in java.sql.Date format

Simply in one line:

java.sql.Date date = new java.sql.Date(Calendar.getInstance().getTime().getTime());

ASP.NET jQuery Ajax Calling Code-Behind Method

Firstly, you probably want to add a return false; to the bottom of your Submit() method in JavaScript (so it stops the submit, since you're handling it in AJAX).

You're connecting to the complete event, not the success event - there's a significant difference and that's why your debugging results aren't as expected. Also, I've never made the signature methods match yours, and I've always provided a contentType and dataType. For example:

$.ajax({
        type: "POST",
        url: "Default.aspx/OnSubmit",
        data: dataValue,                
        contentType: 'application/json; charset=utf-8',
        dataType: 'json',
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            alert("Request: " + XMLHttpRequest.toString() + "\n\nStatus: " + textStatus + "\n\nError: " + errorThrown);
        },
        success: function (result) {
            alert("We returned: " + result);
        }
    });

What does '--set-upstream' do?

When you push to a remote and you use the --set-upstream flag git sets the branch you are pushing to as the remote tracking branch of the branch you are pushing.

Adding a remote tracking branch means that git then knows what you want to do when you git fetch, git pull or git push in future. It assumes that you want to keep the local branch and the remote branch it is tracking in sync and does the appropriate thing to achieve this.

You could achieve the same thing with git branch --set-upstream-to or git checkout --track. See the git help pages on tracking branches for more information.

Mock MVC - Add Request Parameter to test

When i analyzed your code. I have also faced the same problem but my problem is if i give value for both first and last name means it is working fine. but when i give only one value means it says 400. anyway use the .andDo(print()) method to find out the error

public void testGetUserByName() throws Exception {
    String firstName = "Jack";
    String lastName = "s";       
    this.userClientObject = client.createClient();
    mockMvc.perform(get("/byName")
            .sessionAttr("userClientObject", this.userClientObject)
            .param("firstName", firstName)
            .param("lastName", lastName)               
    ).andDo(print())
     .andExpect(status().isOk())
            .andExpect(content().contentType("application/json"))
            .andExpect(jsonPath("$[0].id").exists())
            .andExpect(jsonPath("$[0].fn").value("Marge"));
}

If your problem is org.springframework.web.bind.missingservletrequestparameterexception you have to change your code to

@RequestMapping(value = "/byName", method = RequestMethod.GET)
    @ResponseStatus(HttpStatus.OK)
    public
    @ResponseBody
    String getUserByName(
        @RequestParam( value="firstName",required = false) String firstName,
        @RequestParam(value="lastName",required = false) String lastName, 
        @ModelAttribute("userClientObject") UserClient userClient)
    {

        return client.getUserByName(userClient, firstName, lastName);
    }

Programmatically Creating UILabel

In Swift -

var label:UILabel = UILabel(frame: CGRectMake(0, 0, 70, 20))
label.center = CGPointMake(50, 70)
label.textAlignment = NSTextAlignment.Center
label.text = "message"
label.textColor = UIColor.blackColor()
self.view.addSubview(label)

File Not Found when running PHP with Nginx

I had the "file not found" problem, so I moved the "root" definition up into the "server" bracket to provide a default value for all the locations. You can always override this by giving any location it's own root.

server {
    root /usr/share/nginx/www;
    location / {
            #root /usr/share/nginx/www;
    }

    location ~ \.php$ {
            try_files $uri =404;
            fastcgi_split_path_info ^(.+\.php)(/.+)$;
            fastcgi_pass 127.0.0.1:9000;
            fastcgi_index index.php;
            include fastcgi_params;
    }
}

Alternatively, I could have defined root in both my locations.

How to get current location in Android

You need to write code in the OnLocationChanged method, because this method is called when the location has changed. I.e. you need to save the new location to return it if getLocation is called.

If you don't use the onLocationChanged it always will be the old location.

Using Get-childitem to get a list of files modified in the last 3 days

Here's a minor update to the solution provided by Dave Sexton. Many times you need multiple filters. The Filter parameter can only take a single string whereas the -Include parameter can take a string array. if you have a large file tree it also makes sense to only get the date to compare with once, not for each file. Here's my updated version:

$compareDate = (Get-Date).AddDays(-3)    
@(Get-ChildItem -Path c:\pstbak\*.* -Filter '*.pst','*.mdb' -Recurse | Where-Object { $_.LastWriteTime -gt $compareDate}).Count

Error LNK2019: Unresolved External Symbol in Visual Studio

I was getting this error after adding the include files and linking the library. It was because the lib was built with non-unicode and my application was unicode. Matching them fixed it.

Find specific string in a text file with VBS script

Wow, after few attempts I finally figured out how to deal with my text edits in vbs. The code works perfectly, it gives me the result I was expecting. Maybe it's not the best way to do this, but it does its job. Here's the code:

Option Explicit

Dim StdIn:  Set StdIn = WScript.StdIn
Dim StdOut: Set StdOut = WScript


Main()

Sub Main()

Dim objFSO, filepath, objInputFile, tmpStr, ForWriting, ForReading, count, text, objOutputFile, index, TSGlobalPath, foundFirstMatch
Set objFSO = CreateObject("Scripting.FileSystemObject")
TSGlobalPath = "C:\VBS\TestSuiteGlobal\Test suite Dispatch Decimal - Global.txt"
ForReading = 1
ForWriting = 2
Set objInputFile = objFSO.OpenTextFile(TSGlobalPath, ForReading, False)
count = 7
text=""
foundFirstMatch = false

Do until objInputFile.AtEndOfStream
    tmpStr = objInputFile.ReadLine
    If foundStrMatch(tmpStr)=true Then
        If foundFirstMatch = false Then
            index = getIndex(tmpStr)
            foundFirstMatch = true
            text = text & vbCrLf & textSubstitution(tmpStr,index,"true")
        End If
        If index = getIndex(tmpStr) Then
            text = text & vbCrLf & textSubstitution(tmpStr,index,"false")
        ElseIf index < getIndex(tmpStr) Then
            index = getIndex(tmpStr)
            text = text & vbCrLf & textSubstitution(tmpStr,index,"true")
        End If
    Else
        text = text & vbCrLf & textSubstitution(tmpStr,index,"false")
    End If
Loop
Set objOutputFile = objFSO.CreateTextFile("C:\VBS\NuovaProva.txt", ForWriting, true)
objOutputFile.Write(text)
End Sub


Function textSubstitution(tmpStr,index,foundMatch)
Dim strToAdd
strToAdd = "<tr><td><a href=" & chr(34) & "../../Logs/CF5.0_Features/Beginning_of_CF5.0_Features_TC" & CStr(index) & ".html" & chr(34) & ">Beginning_of_CF5.0_Features_TC" & CStr(index) & "</a></td></tr>"
If foundMatch = "false" Then
    textSubstitution = tmpStr
ElseIf foundMatch = "true" Then
    textSubstitution = strToAdd & vbCrLf & tmpStr
End If
End Function


Function getIndex(tmpStr)
Dim substrToFind, charAtPos, char1, char2
substrToFind = "<tr><td><a href=" & chr(34) & "../Test case "
charAtPos = len(substrToFind) + 1
char1 = Mid(tmpStr, charAtPos, 1)
char2 = Mid(tmpStr, charAtPos+1, 1)
If IsNumeric(char2) Then
    getIndex = CInt(char1 & char2)
Else
    getIndex = CInt(char1)
End If
End Function

Function foundStrMatch(tmpStr)
Dim substrToFind
substrToFind = "<tr><td><a href=" & chr(34) & "../Test case "
If InStr(tmpStr, substrToFind) > 0 Then
    foundStrMatch = true
Else
    foundStrMatch = false
End If
End Function

This is the original txt file

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
  <meta content="text/html; charset=UTF-8" http-equiv="content-type" />
  <title>Test Suite</title>
</head>
<body>
<table id="suiteTable" cellpadding="1" cellspacing="1" border="1" class="selenium"><tbody>
<tr><td><b>Test Suite</b></td></tr>
<tr><td><a href="../../Component/TC_Environment_setting">TC_Environment_setting</a></td></tr>
<tr><td><a href="../../Component/TC_Set_variables">TC_Set_variables</a></td></tr>
<tr><td><a href="../../Component/TC_Set_ID">TC_Set_ID</a></td></tr>
<tr><td><a href="../../Login/Log_in_Admin">Log_in_Admin</a></td></tr>
<tr><td><a href="../../Component/Set_Roles_Dispatch_Decimal">Set_Roles_Dispatch_Decimal</a></td></tr>
<tr><td><a href="../../Login/Log_ in_U1A1">Log_ in_U1A1</a></td></tr>
<tr><td><a href="../Test case 5 DD/Form1">Form1</a></td></tr>
<tr><td><a href="../Test case 5 DD/contrD1">contrD1</a></td></tr>
<tr><td><a href="../../Login/Logout">Logout</a></td></tr>
<tr><td><a href="../../Login/Log_ in_U1B1">Log_ in_U1B1</a></td></tr>
<tr><td><a href="../../Component/Search&OpenApp">Search&OpenApp</a></td></tr>
<tr><td><a href="../Test case 5 DD/FormEND">FormEND</a></td></tr>
<tr><td><a href="../../Component/Controllo END">Controllo END</a></td></tr>
<tr><td><a href="../../Login/Logout">Logout</a></td></tr>
<tr><td><a href="../../Login/Log_ in_U1A1">Log_ in_U1A1</a></td></tr>
<tr><td><a href="../Test case 6 DD/Form1">Form1</a></td></tr>
<tr><td><a href="../Test case 6 DD/contrD1">contrD1</a></td></tr>
<tr><td><a href="../../Login/Logout">Logout</a></td></tr>
<tr><td><a href="../../Login/Log_ in_U1B1">Log_ in_U1B1</a></td></tr>
<tr><td><a href="../../Component/Search&OpenApp">Search&OpenApp</a></td></tr>
<tr><td><a href="../Test case 5 DD/FormEND">FormEND</a></td></tr>
<tr><td><a href="../../Component/Controllo END">Controllo END</a></td></tr>
<tr><td><a href="../../Login/Logout">Logout</a></td></tr>
<tr><td><a href="../../Login/Log_ in_U1A1">Log_ in_U1A1</a></td></tr>
<tr><td><a href="../Test case 7 DD/Form1">Form1</a></td></tr>
<tr><td><a href="../../Component/Controllo DeadLetter">Controllo DeadLetter</a></td></tr>
<tr><td><a href="../../Login/Logout">Logout</a></td></tr>
<tr><td><a href="../../Component/Set_Roles_Dispatch_Decimal">Set_Roles_Dispatch_Decimal</a></td></tr>
<tr><td><a href="../../Login/Logout_BAC">Logout_BAC</a></td></tr>
</tbody></table>
</body>
</html>

And this is the result I'm expecting

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
  <meta content="text/html; charset=UTF-8" http-equiv="content-type" />
  <title>Test Suite</title>
</head>
<body>
<table id="suiteTable" cellpadding="1" cellspacing="1" border="1" class="selenium"><tbody>
<tr><td><b>Test Suite</b></td></tr>
<tr><td><a href="../../Component/TC_Environment_setting">TC_Environment_setting</a></td></tr>
<tr><td><a href="../../Component/TC_Set_variables">TC_Set_variables</a></td></tr>
<tr><td><a href="../../Component/TC_Set_ID">TC_Set_ID</a></td></tr>
<tr><td><a href="../../Login/Log_in_Admin">Log_in_Admin</a></td></tr>
<tr><td><a href="../../Component/Set_Roles_Dispatch_Decimal">Set_Roles_Dispatch_Decimal</a></td></tr>
<tr><td><a href="../../Login/Log_ in_U1A1">Log_ in_U1A1</a></td></tr>
<tr><td><a href="../../Logs/CF5.0_Features/Beginning_of_CF5.0_Features_TC5.html">Beginning_of_CF5.0_Features_TC5</a></td></tr>
<tr><td><a href="../Test case 5 DD/Form1">Form1</a></td></tr>
<tr><td><a href="../Test case 5 DD/Form1">Form1</a></td></tr>
<tr><td><a href="../Test case 5 DD/contrD1">contrD1</a></td></tr>
<tr><td><a href="../../Login/Logout">Logout</a></td></tr>
<tr><td><a href="../../Login/Log_ in_U1B1">Log_ in_U1B1</a></td></tr>
<tr><td><a href="../../Component/Search&OpenApp">Search&OpenApp</a></td></tr>
<tr><td><a href="../Test case 5 DD/FormEND">FormEND</a></td></tr>
<tr><td><a href="../../Component/Controllo END">Controllo END</a></td></tr>
<tr><td><a href="../../Login/Logout">Logout</a></td></tr>
<tr><td><a href="../../Login/Log_ in_U1A1">Log_ in_U1A1</a></td></tr>
<tr><td><a href="../../Logs/CF5.0_Features/Beginning_of_CF5.0_Features_TC6.html">Beginning_of_CF5.0_Features_TC6</a></td></tr>
<tr><td><a href="../Test case 6 DD/Form1">Form1</a></td></tr>
<tr><td><a href="../Test case 6 DD/contrD1">contrD1</a></td></tr>
<tr><td><a href="../../Login/Logout">Logout</a></td></tr>
<tr><td><a href="../../Login/Log_ in_U1B1">Log_ in_U1B1</a></td></tr>
<tr><td><a href="../../Component/Search&OpenApp">Search&OpenApp</a></td></tr>
<tr><td><a href="../../Component/Controllo END">Controllo END</a></td></tr>
<tr><td><a href="../../Login/Logout">Logout</a></td></tr>
<tr><td><a href="../../Login/Log_ in_U1A1">Log_ in_U1A1</a></td></tr>
<tr><td><a href="../../Logs/CF5.0_Features/Beginning_of_CF5.0_Features_TC7.html">Beginning_of_CF5.0_Features_TC7</a></td></tr>
<tr><td><a href="../Test case 7 DD/Form1">Form1</a></td></tr>
<tr><td><a href="../../Component/Controllo DeadLetter">Controllo DeadLetter</a></td></tr>
<tr><td><a href="../../Login/Logout">Logout</a></td></tr>
<tr><td><a href="../../Component/Set_Roles_Dispatch_Decimal">Set_Roles_Dispatch_Decimal</a></td></tr>
<tr><td><a href="../../Login/Logout_BAC">Logout_BAC</a></td></tr>
</tbody></table>
</body>
</html>

android.os.NetworkOnMainThreadException with android 4.2

This is the correct way:

public class JSONParser extends AsyncTask <String, Void, String>{

    static InputStream is = null;

static JSONObject jObj = null;
static String json = "";

// constructor
public JSONParser() {

}
@Override
protected String doInBackground(String... params) {


    // Making HTTP request
    try {
        // defaultHttpClient
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpGet httpPost = new HttpGet(url);

            HttpResponse getResponse = httpClient.execute(httpPost);
           final int statusCode = getResponse.getStatusLine().getStatusCode();

           if (statusCode != HttpStatus.SC_OK) { 
              Log.w(getClass().getSimpleName(), 
                  "Error " + statusCode + " for URL " + url); 
              return null;
           }

           HttpEntity getResponseEntity = getResponse.getEntity();

        //HttpResponse httpResponse = httpClient.execute(httpPost);
        //HttpEntity httpEntity = httpResponse.getEntity();
        is = getResponseEntity.getContent();            

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        Log.d("IO", e.getMessage().toString());
        e.printStackTrace();

    }

    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                is, "iso-8859-1"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        is.close();
        json = sb.toString();
    } catch (Exception e) {
        Log.e("Buffer Error", "Error converting result " + e.toString());
    }

    // try parse the string to a JSON object
    try {
        jObj = new JSONObject(json);
    } catch (JSONException e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString());
    }

    // return JSON String
    return jObj;


}
protected void onPostExecute(String page)
{   
    //onPostExecute
}   
}

To call it (from main):

mJSONParser = new JSONParser();
mJSONParser.execute();

How to respond with HTTP 400 error in a Spring MVC @ResponseBody method returning String?

As mentioned in some answers, there is the ability to create an exception class for each HTTP status that you want to return. I don't like the idea of having to create a class per status for each project. Here is what I came up with instead.

  • Create a generic exception that accepts an HTTP status
  • Create an Controller Advice exception handler

Let's get to the code

package com.javaninja.cam.exception;

import org.springframework.http.HttpStatus;


/**
 * The exception used to return a status and a message to the calling system.
 * @author norrisshelton
 */
@SuppressWarnings("ClassWithoutNoArgConstructor")
public class ResourceException extends RuntimeException {

    private HttpStatus httpStatus = HttpStatus.INTERNAL_SERVER_ERROR;

    /**
     * Gets the HTTP status code to be returned to the calling system.
     * @return http status code.  Defaults to HttpStatus.INTERNAL_SERVER_ERROR (500).
     * @see HttpStatus
     */
    public HttpStatus getHttpStatus() {
        return httpStatus;
    }

    /**
     * Constructs a new runtime exception with the specified HttpStatus code and detail message.
     * The cause is not initialized, and may subsequently be initialized by a call to {@link #initCause}.
     * @param httpStatus the http status.  The detail message is saved for later retrieval by the {@link
     *                   #getHttpStatus()} method.
     * @param message    the detail message. The detail message is saved for later retrieval by the {@link
     *                   #getMessage()} method.
     * @see HttpStatus
     */
    public ResourceException(HttpStatus httpStatus, String message) {
        super(message);
        this.httpStatus = httpStatus;
    }
}

Then I create a controller advice class

package com.javaninja.cam.spring;


import com.javaninja.cam.exception.ResourceException;

import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;


/**
 * Exception handler advice class for all SpringMVC controllers.
 * @author norrisshelton
 * @see org.springframework.web.bind.annotation.ControllerAdvice
 */
@org.springframework.web.bind.annotation.ControllerAdvice
public class ControllerAdvice {

    /**
     * Handles ResourceExceptions for the SpringMVC controllers.
     * @param e SpringMVC controller exception.
     * @return http response entity
     * @see ExceptionHandler
     */
    @ExceptionHandler(ResourceException.class)
    public ResponseEntity handleException(ResourceException e) {
        return ResponseEntity.status(e.getHttpStatus()).body(e.getMessage());
    }
}

To use it

throw new ResourceException(HttpStatus.BAD_REQUEST, "My message");

http://javaninja.net/2016/06/throwing-exceptions-messages-spring-mvc-controller/

Django DoesNotExist

This line

 except Vehicle.vehicledevice.device.DoesNotExist

means look for device instance for DoesNotExist exception, but there's none, because it's on class level, you want something like

 except Device.DoesNotExist

How to generate and auto increment Id with Entity Framework

This is a guess :)

Is it because the ID is a string? What happens if you change it to int?

I mean:

 public int Id { get; set; }

Android how to convert int to String?

Normal ways would be Integer.toString(i) or String.valueOf(i).

int i = 5;
String strI = String.valueOf(i);

Or

int aInt = 1;    
String aString = Integer.toString(aInt);

Read Content from Files which are inside Zip file

Because of the condition in while, the loop might never break:

while (entry != null) {
  // If entry never becomes null here, loop will never break.
}

Instead of the null check there, you can try this:

ZipEntry entry = null;
while ((entry = zip.getNextEntry()) != null) {
  // Rest of your code
}

fatal: 'origin' does not appear to be a git repository

This does not answer your question, but I faced a similar error message but due to a different reason. Allow me to make my post for the sake of information collection.

I have a git repo on a network drive. Let's call this network drive RAID. I cloned this repo on my local machine (LOCAL) and on my number crunching cluster (CRUNCHER). For convenience I mounted the user directory of my account on CRUNCHER on my local machine. So, I can manipulate files on CRUNCHER without the need to do the work in an SSH terminal.

Today, I was modifying files in the repo on CRUNCHER via my local machine. At some point I decided to commit the files, so a did a commit. Adding the modified files and doing the commit worked as I expected, but when I called git push I got an error message similar to the one posted in the question.

The reason was, that I called push from within the repo on CRUNCHER on LOCAL. So, all paths in the config file were plain wrong.

When I realized my fault, I logged onto CRUNCHER via Terminal and was able to push the commit.

Feel free to comment if my explanation can't be understood, or you find my post superfluous.

Why does Git say my master branch is "already up to date" even though it is not?

I think your basic issue here is that you're misinterpreting and/or misunderstanding what git does and why it does it.

When you clone some other repository, git makes a copy of whatever is "over there". It also takes "their" branch labels, such as master, and makes a copy of that label whose "full name" in your git tree is (normally) remotes/origin/master (but in your case, remotes/upstream/master). Most of the time you get to omit the remotes/ part too, so you can refer to that original copy as upstream/master.

If you now make and commit some change(s) to some file(s), you're the only one with those changes. Meanwhile other people may use the original repository (from which you made your clone) to make other clones and change those clones. They are the only ones with their changes, of course. Eventually though, someone may have changes they send back to the original owner (via "push" or patches or whatever).

The git pull command is mostly just shorthand for git fetch followed by git merge. This is important because it means you need to understand what those two operations actually do.

The git fetch command says to go back to wherever you cloned from (or have otherwise set up as a place to fetch from) and find "new stuff someone else added or changed or removed". Those changes are copied over and applied to your copy of what you got from them earlier. They are not applied to your own work, only to theirs.

The git merge command is more complicated and is where you are going awry. What it does, oversimplified a bit, is compare "what you changed in your copy" to "changes you fetched from someone-else and thus got added to your-copy-of-the-someone-else's-work". If your changes and their changes don't seem to conflict, the merge operation mushes them together and gives you a "merge commit" that ties your development and their development together (though there is a very common "easy" case in which you have no changes and you get a "fast forward").

The situation you're encountering now is one in which you have made changes and committed them—nine times, in fact, hence the "ahead 9"—and they have made no changes. So, fetch dutifully fetches nothing, and then merge takes their lack-of-changes and also does nothing.

What you want is to look at, or maybe even "reset" to, "their" version of the code.

If you merely want to look at it, you can simply check out that version:

git checkout upstream/master

That tells git that you want to move the current directory to the branch whose full name is actually remotes/upstream/master. You'll see their code as of the last time you ran git fetch and got their latest code.

If you want to abandon all your own changes, what you need to do is change git's idea of which revision your label, master, should name. Currently it names your most recent commit. If you get back onto that branch:

git checkout master

then the git reset command will allow you to "move the label", as it were. The only remaining problem (assuming you're really ready to abandon everything you've don) is finding where the label should point.

git log will let you find the numeric names—those things like 7cfcb29—which are permanent (never changing) names, and there are a ridiculous number of other ways to name them, but in this case you just want the name upstream/master.

To move the label, wiping out your own changes (any that you have committed are actually recoverable for quite a while but it's a lot harder after this so be very sure):

git reset --hard upstream/master

The --hard tells git to wipe out what you have been doing, move the current branch label, and then check out the given commit.

It's not super-common to really want to git reset --hard and wipe out a bunch of work. A safer method (making it a lot easier to recover that work if you decide some of it was worthwhile after all) is to rename your existing branch:

git branch -m master bunchofhacks

and then make a new local branch named master that "tracks" (I don't really like this term as I think it confuses people but that's the git term :-) ) the origin (or upstream) master:

git branch -t master upstream/master

which you can then get yourself on with:

git checkout master

What the last three commands do (there's shortcuts to make it just two commands) is to change the name pasted on the existing label, then make a new label, then switch to it:

before doing anything:

C0 -    "remotes/upstream/master"
    \
     \- C1 --- C2 --- C3 --- C4 --- C5 --- C6 --- C7 --- C8 --- C9    "master"

after git branch -m:

C0 -    "remotes/upstream/master"
    \
     \- C1 --- C2 --- C3 --- C4 --- C5 --- C6 --- C7 --- C8 --- C9    "bunchofhacks"

after git branch -t master upstream/master:

C0 -    "remotes/upstream/master", "master"
    \
     \- C1 --- C2 --- C3 --- C4 --- C5 --- C6 --- C7 --- C8 --- C9    "bunchofhacks"

Here C0 is the latest commit (a complete source tree) that you got when you first did your git clone. C1 through C9 are your commits.

Note that if you were to git checkout bunchofhacks and then git reset --hard HEAD^^, this would change the last picture to:

C0 -    "remotes/upstream/master", "master"
    \
     \- C1 --- C2 --- C3 --- C4 --- C5 --- C6 --- C7 -    "bunchofhacks"
                                                      \
                                                       \- C8 --- C9

The reason is that HEAD^^ names the revision two up from the head of the current branch (which just before the reset would be bunchofhacks), and reset --hard then moves the label. Commits C8 and C9 are now mostly invisible (you can use things like the reflog and git fsck to find them but it's no longer trivial). Your labels are yours to move however you like. The fetch command takes care of the ones that start with remotes/. It's conventional to match "yours" with "theirs" (so if they have a remotes/origin/mauve you'd name yours mauve too), but you can type in "theirs" whenever you want to name/see commits you got "from them". (Remember that "one commit" is an entire source tree. You can pick out one specific file from one commit, with git show for instance, if and when you want that.)

What is the default Jenkins password?

I was running Jenkins executing java -jar jenkins.war.

In my case Jenkins wrote webroot in an stdout: webroot: $user.home/.jenkins. So admin secret key was placed in a ~/.jenkins/secrets/initialAdminPassword.

Git Pull is Not Possible, Unmerged Files

There is a solution even if you don't want to remove your local changes. Just fix the unmerged files (by git add or git remove). Then do git pull.

nginx - nginx: [emerg] bind() to [::]:80 failed (98: Address already in use)

I had several *.save files (emergency dumps from nano) from different NGINX config files in my sites-avilable dir. Once I deleted these .save files, NGINX restarted fine. I assumed these were harmless since there were no corresponding symlinks, but I guess I was wrong.

WebAPI Multiple Put/Post parameters

If attribute routing is being used, you can use the [FromUri] and [FromBody] attributes.

Example:

[HttpPost()]
[Route("api/products/{id:int}")]
public HttpResponseMessage AddProduct([FromUri()] int id,  [FromBody()] Product product)
{
  // Add product
}

how to download file using AngularJS and calling MVC API?

using FileSaver.js solved my issue thanks for help, below code helped me

'$'

 DownloadClaimForm: function (claim) 
{
 url = baseAddress + "DownLoadFile";
 return  $http.post(baseAddress + "DownLoadFile", claim, {responseType: 'arraybuffer' })
                            .success(function (data) {
                                var file = new Blob([data], { type: 'application/pdf' });
                                saveAs(file, 'Claims.pdf');
                            });


    }

Can IntelliJ IDEA encapsulate all of the functionality of WebStorm and PHPStorm through plugins?

I regularly use IntelliJ, PHPStorm and WebStorm. Would love to only use IntelliJ. As pointed out by the vendor the "Open Directory" functionality not being in IntelliJ is painful.

Now for the rub part; I have tried using IntelliJ as my single IDE and have found performance to be terrible compared to the lighter weight versions. Intellisense is almost useless in IntelliJ compared to WebStorm.

git discard all changes and pull from upstream

You can do it in a single command:

git fetch --all && git reset --hard origin/master

Or in a pair of commands:

git fetch --all
git reset --hard origin/master

Note than you will lose ALL your local changes

How to change TIMEZONE for a java.util.Calendar/Date

  1. The class Date/Timestamp represents a specific instant in time, with millisecond precision, since January 1, 1970, 00:00:00 GMT. So this time difference (from epoch to current time) will be same in all computers across the world with irrespective of Timezone.

  2. Date/Timestamp doesn't know about the given time is on which timezone.

  3. If we want the time based on timezone we should go for the Calendar or SimpleDateFormat classes in java.

  4. If you try to print a Date/Timestamp object using toString(), it will convert and print the time with the default timezone of your machine.

  5. So we can say (Date/Timestamp).getTime() object will always have UTC (time in milliseconds)

  6. To conclude Date.getTime() will give UTC time, but toString() is on locale specific timezone, not UTC.

Now how will I create/change time on specified timezone?

The below code gives you a date (time in milliseconds) with specified timezones. The only problem here is you have to give date in string format.

   DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd HH:mm:ss");
   dateFormatLocal.setTimeZone(timeZone);
   java.util.Date parsedDate = dateFormatLocal.parse(date);

Use dateFormat.format for taking input Date (which is always UTC), timezone and return date as String.

How to store UTC/GMT time in DB:

If you print the parsedDate object, the time will be in default timezone. But you can store the UTC time in DB like below.

        Calendar calGMT = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
        Timestamp tsSchedStartTime = new Timestamp (parsedDate.getTime());
        if (tsSchedStartTime != null) {
            stmt.setTimestamp(11, tsSchedStartTime, calGMT );
        } else {
            stmt.setNull(11, java.sql.Types.DATE);
        }

Insert into C# with SQLCommand

you can use implicit casting AddWithValue

cmd.Parameters.AddWithValue("@param1", klantId);
cmd.Parameters.AddWithValue("@param2", klantNaam);
cmd.Parameters.AddWithValue("@param3", klantVoornaam);

sample code,

using (SqlConnection conn = new SqlConnection("connectionString")) 
{
    using (SqlCommand cmd = new SqlCommand()) 
    { 
        cmd.Connection = conn;
        cmd.CommandType = CommandType.Text;
        cmd.CommandText = @"INSERT INTO klant(klant_id,naam,voornaam) 
                            VALUES(@param1,@param2,@param3)";  

        cmd.Parameters.AddWithValue("@param1", klantId);  
        cmd.Parameters.AddWithValue("@param2", klantNaam);  
        cmd.Parameters.AddWithValue("@param3", klantVoornaam);  

        try
        {
            conn.Open();
            cmd.ExecuteNonQuery(); 
        }
        catch(SqlException e)
        {
            MessgeBox.Show(e.Message.ToString(), "Error Message");
        }

    } 
}

Cannot open Windows.h in Microsoft Visual Studio

The right combination of Windows SDK Version and Platform Toolset needs to be selected Depends of course what toolset you have currently installed

SDK Version and Platform Toolset

Spring REST Service: how to configure to remove null objects in json response

Since version 1.6 we have new annotation JsonSerialize (in version 1.9.9 for example).

Example:

@JsonSerialize(include=Inclusion.NON_NULL)
public class Test{
...
}

Default value is ALWAYS.

In old versions you can use JsonWriteNullProperties, which is deprecated in new versions. Example:

@JsonWriteNullProperties(false)
public class Test{
    ...
}

Throw HttpResponseException or return Request.CreateErrorResponse?

As far as I can tell, whether you throw an exception, or you return Request.CreateErrorResponse, the result is the same. If you look at the source code for System.Web.Http.dll, you will see as much. Take a look at this general summary, and a very similar solution that I have made: Web Api, HttpError, and the behavior of exceptions

nginx - read custom header from upstream server

$http_name_of_the_header_key

i.e if you have origin = domain.com in header, you can use $http_origin to get "domain.com"

In nginx does support arbitrary request header field. In the above example last part of a variable name is the field name converted to lower case with dashes replaced by underscores

Reference doc here: http://nginx.org/en/docs/http/ngx_http_core_module.html#var_http_

For your example the variable would be $http_my_custom_header.

The module was expected to contain an assembly manifest

I found another strange reason and i thought maybe another developer confused as me. I did run install.bat that created to install my service in developer Command Prompt of VS2010 but my service generated in VS2012. it was going to this error and drives me to crazy but i try VS2012 Developer Command Prompt tools and everything gone to be OK. I don't no why but my problem was solved. so you can test it and if anyone know reason of that please share with us. Thanks.

java.sql.SQLException: - ORA-01000: maximum open cursors exceeded

Using batch processing will result in less overhead. See the following link for examples: http://www.tutorialspoint.com/jdbc/jdbc-batch-processing.htm

How to set downloading file name in ASP.NET Web API

If you want to ensure that the file name is properly encoded but also avoid the WebApi HttpResponseMessage you can use the following:

Response.AddHeader("Content-Disposition", new System.Net.Mime.ContentDisposition("attachment") { FileName = "foo.txt" }.ToString());

You may use either ContentDisposition or ContentDispositionHeaderValue. Calling ToString on an instance of either will do the encoding of file names for you.

Adding and using header (HTTP) in nginx

To add a header just add the following code to the location block where you want to add the header:

location some-location {
  add_header X-my-header my-header-content;      
}

Obviously, replace the x-my-header and my-header-content with what you want to add. And that's all there is to it.

prevent property from being serialized in web API

ASP.NET Web API uses Json.Net as default formatter, so if your application just only uses JSON as data format, you can use [JsonIgnore] to ignore property for serialization:

public class Foo
{
    public int Id { get; set; }
    public string Name { get; set; }

    [JsonIgnore]
    public List<Something> Somethings { get; set; }
}

But, this way does not support XML format. So, in case your application has to support XML format more (or only support XML), instead of using Json.Net, you should use [DataContract] which supports both JSON and XML:

[DataContract]
public class Foo
{
    [DataMember]
    public int Id { get; set; }
    [DataMember]
    public string Name { get; set; }

    //Ignore by default
    public List<Something> Somethings { get; set; }
}

For more understanding, you can read the official article.

Rollback a Git merge

git revert -m 1 88113a64a21bf8a51409ee2a1321442fd08db705

But may have unexpected side-effects. See --mainline parent-number option in git-scm.com/docs/git-revert

Perhaps a brute but effective way would be to check out the left parent of that commit, make a copy of all the files, checkout HEAD again, and replace all the contents with the old files. Then git will tell you what is being rolled back and you create your own revert commit :) !

How can I send JSON response in symfony2 controller

Symfony 2.1 has a JsonResponse class.

return new JsonResponse(array('name' => $name));

The passed in array will be JSON encoded the status code will default to 200 and the content type will be set to application/json.

There is also a handy setCallback function for JSONP.

git rebase merge conflict

When you have a conflict during rebase you have three options:

  • You can run git rebase --abort to completely undo the rebase. Git will return you to your branch's state as it was before git rebase was called.

  • You can run git rebase --skip to completely skip the commit. That means that none of the changes introduced by the problematic commit will be included. It is very rare that you would choose this option.

  • You can fix the conflict as iltempo said. When you're finished, you'll need to call git rebase --continue. My mergetool is kdiff3 but there are many more which you can use to solve conflicts. You only need to set your merge tool in git's settings so it can be invoked when you call git mergetool https://git-scm.com/docs/git-mergetool

If none of the above works for you, then go for a walk and try again :)

How to dynamically set bootstrap-datepicker's date value?

For Bootstrap 4

If you are using input group in Bootstrap, you need to attach the new date to parent of the textbox, otherwise if you click on the calendar icon and click outside the date will be cleared.

<div class="input-group date" id="my-date-component">
   <input type="text" />
    <div class="input-group-append">
      <span class="input-group-text"><i class="fa fa-calendar"></i></span>
    </div>
</div>

You need to set date to input-group.date.

$('#my-date-component').datepicker("update", new Date("01/10/2014"));

Also check datepicker update method

How to import a csv file into MySQL workbench?

In case you have smaller data set, a way to achieve it by GUI is:

  1. Open a query window
  2. SELECT * FROM [table_name]
  3. Select Import from the menu bar
  4. Press Apply on the bottom right below the Result Grid

enter image description here

Reference: http://www.youtube.com/watch?v=tnhJa_zYNVY

How to POST request using RestSharp

My RestSharp POST method:

var client = new RestClient(ServiceUrl);

var request = new RestRequest("/resource/", Method.POST);

// Json to post.
string jsonToSend = JsonHelper.ToJson(json);

request.AddParameter("application/json; charset=utf-8", jsonToSend, ParameterType.RequestBody);
request.RequestFormat = DataFormat.Json;

try
{
    client.ExecuteAsync(request, response =>
    {
        if (response.StatusCode == HttpStatusCode.OK)
        {
            // OK
        }
        else
        {
            // NOK
        }
    });
}
catch (Exception error)
{
    // Log
}

Get TimeZone offset value from TimeZone without TimeZone name

ZoneId here = ZoneId.of("Europe/Kiev");
ZonedDateTime hereAndNow = Instant.now().atZone(here);
String.format("%tz", hereAndNow);

will give you a standardized string representation like "+0300"

Return JSON with error status code MVC

The neatest solution I've found is to create your own JsonResult that extends the original implementation and allows you to specify a HttpStatusCode:

public class JsonHttpStatusResult : JsonResult
{
    private readonly HttpStatusCode _httpStatus;

    public JsonHttpStatusResult(object data, HttpStatusCode httpStatus)
    {
        Data = data;
        _httpStatus = httpStatus;
    }

    public override void ExecuteResult(ControllerContext context)
    {
        context.RequestContext.HttpContext.Response.StatusCode = (int)_httpStatus;
        base.ExecuteResult(context);
    }
}

You can then use this in your controller action like so:

if(thereWereErrors)
{
    var errorModel = new { error = "There was an error" };
    return new JsonHttpStatusResult(errorModel, HttpStatusCode.InternalServerError);
}

Bad File Descriptor with Linux Socket write() Bad File Descriptor C

I had this error too, my problem was in some part of code I didn't close file descriptor and in other part, I tried to open that file!! use close(fd) system call after you finished working on a file.

How do I completely uninstall Node.js, and reinstall from beginning (Mac OS X)

  • Delete node and/or node_modules from /usr/local/lib

          ex code:
          cd /usr/local/lib
          sudo rm -rf node
          sudo rm -rf node_modules
    
  • Delete node and/or node_modules from /usr/local/include

  • Delete node, node-debug, and node-gyp from /usr/local/bin
  • Delete .npmrc from your home directory (these are your npm settings, don't delete this if you plan on re-installing Node right away)
  • Delete .npm from your home directory
  • Delete .node-gyp from your home directory
  • Delete .node_repl_history from your home directory
  • Delete node* from /usr/local/share/man/man1/
  • Delete npm* from /usr/local/share/man/man1/
  • Delete node.d from /usr/local/lib/dtrace/
  • Delete node from /usr/local/opt/local/bin/
  • Delete node from /usr/local/opt/local/include/
  • Delete node_modules from /usr/local/opt/local/lib/
  • Delete node from /usr/local/share/doc/
  • Delete node.stp from /usr/local/share/systemtap/tapset/

How to remove MySQL completely with config and library files?

Just a little addition to the answer of @dAm2k :

In addition to sudo apt-get remove --purge mysql\*

I've done a sudo apt-get remove --purge mariadb\*.

I seems that in the new release of debian (stretch), when you install mysql it install mariadb package with it.

Hope it helps.

Best practice to return errors in ASP.NET Web API

Building up upon Manish Jain's answer (which is meant for Web API 2 which simplifies things):

1) Use validation structures to response as many validation errors as possible. These structures can also be used to response to requests coming from forms.

public class FieldError
{
    public String FieldName { get; set; }
    public String FieldMessage { get; set; }
}

// a result will be able to inform API client about some general error/information and details information (related to invalid parameter values etc.)
public class ValidationResult<T>
{
    public bool IsError { get; set; }

    /// <summary>
    /// validation message. It is used as a success message if IsError is false, otherwise it is an error message
    /// </summary>
    public string Message { get; set; } = string.Empty;

    public List<FieldError> FieldErrors { get; set; } = new List<FieldError>();

    public T Payload { get; set; }

    public void AddFieldError(string fieldName, string fieldMessage)
    {
        if (string.IsNullOrWhiteSpace(fieldName))
            throw new ArgumentException("Empty field name");

        if (string.IsNullOrWhiteSpace(fieldMessage))
            throw new ArgumentException("Empty field message");

        // appending error to existing one, if field already contains a message
        var existingFieldError = FieldErrors.FirstOrDefault(e => e.FieldName.Equals(fieldName));
        if (existingFieldError == null)
            FieldErrors.Add(new FieldError {FieldName = fieldName, FieldMessage = fieldMessage});
        else
            existingFieldError.FieldMessage = $"{existingFieldError.FieldMessage}. {fieldMessage}";

        IsError = true;
    }

    public void AddEmptyFieldError(string fieldName, string contextInfo = null)
    {
        AddFieldError(fieldName, $"No value provided for field. Context info: {contextInfo}");
    }
}

public class ValidationResult : ValidationResult<object>
{

}

2) Service layer will return ValidationResults, regardless of operation being successful or not. E.g:

    public ValidationResult DoSomeAction(RequestFilters filters)
    {
        var ret = new ValidationResult();

        if (filters.SomeProp1 == null) ret.AddEmptyFieldError(nameof(filters.SomeProp1));
        if (filters.SomeOtherProp2 == null) ret.AddFieldError(nameof(filters.SomeOtherProp2 ), $"Failed to parse {filters.SomeOtherProp2} into integer list");

        if (filters.MinProp == null) ret.AddEmptyFieldError(nameof(filters.MinProp));
        if (filters.MaxProp == null) ret.AddEmptyFieldError(nameof(filters.MaxProp));


        // validation affecting multiple input parameters
        if (filters.MinProp > filters.MaxProp)
        {
            ret.AddFieldError(nameof(filters.MinProp, "Min prop cannot be greater than max prop"));
            ret.AddFieldError(nameof(filters.MaxProp, "Check"));
        }

        // also specify a global error message, if we have at least one error
        if (ret.IsError)
        {
            ret.Message = "Failed to perform DoSomeAction";
            return ret;
        }

        ret.Message = "Successfully performed DoSomeAction";
        return ret;
    }

3) API Controller will construct the response based on service function result

One option is to put virtually all parameters as optional and perform custom validation which return a more meaningful response. Also, I am taking care not to allow any exception to go beyond the service boundary.

    [Route("DoSomeAction")]
    [HttpPost]
    public HttpResponseMessage DoSomeAction(int? someProp1 = null, string someOtherProp2 = null, int? minProp = null, int? maxProp = null)
    {
        try
        {
            var filters = new RequestFilters 
            {
                SomeProp1 = someProp1 ,
                SomeOtherProp2 = someOtherProp2.TrySplitIntegerList() ,
                MinProp = minProp, 
                MaxProp = maxProp
            };

            var result = theService.DoSomeAction(filters);
            return !result.IsError ? Request.CreateResponse(HttpStatusCode.OK, result) : Request.CreateResponse(HttpStatusCode.BadRequest, result);
        }
        catch (Exception exc)
        {
            Logger.Log(LogLevel.Error, exc, "Failed to DoSomeAction");
            return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, new HttpError("Failed to DoSomeAction - internal error"));
        }
    }

Where's my invalid character (ORA-00911)

If you use the string literal exactly as you have shown us, the problem is the ; character at the end. You may not include that in the query string in the JDBC calls.

As you are inserting only a single row, a regular INSERT should be just fine even when inserting multiple rows. Using a batched statement is probable more efficient anywy. No need for INSERT ALL. Additionally you don't need the temporary clob and all that. You can simplify your method to something like this (assuming I got the parameters right):

String query1 = "select substr(to_char(max_data),1,4) as year, " + 
  "substr(to_char(max_data),5,6) as month, max_data " +
  "from dss_fin_user.acq_dashboard_src_load_success " + 
  "where source = 'CHQ PeopleSoft FS'";

String query2 = ".....";

String sql = "insert into domo_queries (clob_column) values (?)";
PreparedStatement pstmt = con.prepareStatement(sql);
StringReader reader = new StringReader(query1);
pstmt.setCharacterStream(1, reader, query1.length());
pstmt.addBatch();

reader = new StringReader(query2);
pstmt.setCharacterStream(1, reader, query2.length());
pstmt.addBatch();

pstmt.executeBatch();   
con.commit();

Returning http status code from Web Api controller

.net core 2.2 returning 304 status code. This is using an ApiController.

    [HttpGet]
    public ActionResult<YOUROBJECT> Get()
    {
        return StatusCode(304);
    }

Optionally you can return an object with the response

    [HttpGet]
    public ActionResult<YOUROBJECT> Get()
    {
        return StatusCode(304, YOUROBJECT); 
    }

Counter increment in Bash loop not working

It seems that you didn't update the counter is the script, use counter++

git pull keeping local changes

Update: this literally answers the question asked, but I think KurzedMetal's answer is really what you want.

Assuming that:

  1. You're on the branch master
  2. The upstream branch is master in origin
  3. You have no uncommitted changes

.... you could do:

# Do a pull as usual, but don't commit the result:
git pull --no-commit

# Overwrite config/config.php with the version that was there before the merge
# and also stage that version:
git checkout HEAD config/config.php

# Create the commit:
git commit -F .git/MERGE_MSG

You could create an alias for that if you need to do it frequently. Note that if you have uncommitted changes to config/config.php, this would throw them away.

configure: error: C compiler cannot create executables

If anyone is coming here because RVM / Ruby is creating issues (Middleman/Grunt) I've solved my issue.

PS. The answer by steroscott fixed my issue a while back...this time around not the case.

In my case rvm is trying to use a downloaded gcc via homebrew. I ran a brew uninstall of gcc (gcc46 for me) and reran the code for the ruby installation (old project old ruby v)

$ brew uninstall gcc46

$ rvm install 1.9.3

during that process of checking for requirements it automatically fetched a newer gcc for me and boom, all is working now. Oh a big note, the gcc install from the rvm command can take around 10-15 minutes without throwing out any text, it's not frozen :) Good luck

Word wrapping in phpstorm

For Word Wrapping in Php Storm 2019.1.3 Just follow below steps:

from top nagivation menu

View -> Active Editor -> Soft-Wrap

that's it so simple.

How To Accept a File POST

The ASP.NET Core way is now here:

[HttpPost("UploadFiles")]
public async Task<IActionResult> Post(List<IFormFile> files)
{
    long size = files.Sum(f => f.Length);

    // full path to file in temp location
    var filePath = Path.GetTempFileName();

    foreach (var formFile in files)
    {
        if (formFile.Length > 0)
        {
            using (var stream = new FileStream(filePath, FileMode.Create))
            {
                await formFile.CopyToAsync(stream);
            }
        }
    }

    // process uploaded files
    // Don't rely on or trust the FileName property without validation.

    return Ok(new { count = files.Count, size, filePath});
}

HttpClient does not exist in .net 4.0: what can I do?

Referring to the answers above, I am only adding this to help clarify things. It is possible to use HttpClient from .Net 4.0, and you have to install the package from here

However, the text is very confusion and contradicts itself.

This package is not supported in Visual Studio 2010, and is only required for projects targeting .NET Framework 4.5, Windows 8, or Windows Phone 8.1 when consuming a library that uses this package.

But underneath it states that these are the supported platforms.

Supported Platforms:

  • .NET Framework 4

  • Windows 8

  • Windows Phone 8.1

  • Windows Phone Silverlight 7.5

  • Silverlight 4

  • Portable Class Libraries

Ignore what it ways about targeting .Net 4.5. This is wrong. The package is all about using HttpClient in .Net 4.0. However, you may need to use VS2012 or higher. Not sure if it works in VS2010, but that may be worth testing.

How to use System.Net.HttpClient to post a complex type?

I think you can do this:

var client = new HttpClient();
HttpContent content = new Widget();
client.PostAsync<Widget>("http://localhost:44268/api/test", content, new FormUrlEncodedMediaTypeFormatter())
    .ContinueWith((postTask) => { postTask.Result.EnsureSuccessStatusCode(); });

git checkout tag, git pull fails in branch

What worked for me was: git branch --set-upstream-to=origin master When I did a pull again I only got the updates from master and the warning went away.

Improve SQL Server query performance on large tables

Simple Answer: NO. You cannot help ad hoc queries on a 238 column table with a 50% Fill Factor on the Clustered Index.

Detailed Answer:

As I have stated in other answers on this topic, Index design is both Art and Science and there are so many factors to consider that there are few, if any, hard and fast rules. You need to consider: the volume of DML operations vs SELECTs, disk subsystem, other indexes / triggers on the table, distribution of data within the table, are queries using SARGable WHERE conditions, and several other things that I can't even remember right now.

I can say that no help can be given for questions on this topic without an understanding of the Table itself, its indexes, triggers, etc. Now that you have posted the table definition (still waiting on the Indexes but the Table definition alone points to 99% of the issue) I can offer some suggestions.

First, if the table definition is accurate (238 columns, 50% Fill Factor) then you can pretty much ignore the rest of the answers / advice here ;-). Sorry to be less-than-political here, but seriously, it's a wild goose chase without knowing the specifics. And now that we see the table definition it becomes quite a bit clearer as to why a simple query would take so long, even when the test queries (Update #1) ran so quickly.

The main problem here (and in many poor-performance situations) is bad data modeling. 238 columns is not prohibited just like having 999 indexes is not prohibited, but it is also generally not very wise.

Recommendations:

  1. First, this table really needs to be remodeled. If this is a data warehouse table then maybe, but if not then these fields really need to be broken up into several tables which can all have the same PK. You would have a master record table and the child tables are just dependent info based on commonly associated attributes and the PK of those tables is the same as the PK of the master table and hence also FK to the master table. There will be a 1-to-1 relationship between master and all child tables.
  2. The use of ANSI_PADDING OFF is disturbing, not to mention inconsistent within the table due to the various column additions over time. Not sure if you can fix that now, but ideally you would always have ANSI_PADDING ON, or at the very least have the same setting across all ALTER TABLE statements.
  3. Consider creating 2 additional File Groups: Tables and Indexes. It is best not to put your stuff in PRIMARY as that is where SQL SERVER stores all of its data and meta-data about your objects. You create your Table and Clustered Index (as that is the data for the table) on [Tables] and all Non-Clustered indexes on [Indexes]
  4. Increase the Fill Factor from 50%. This low number is likely why your index space is larger than your data space. Doing an Index Rebuild will recreate the data pages with a max of 4k (out of the total 8k page size) used for your data so your table is spread out over a wide area.
  5. If most or all queries have "ER101_ORG_CODE" in the WHERE condition, then consider moving that to the leading column of the clustered index. Assuming that it is used more often than "ER101_ORD_NBR". If "ER101_ORD_NBR" is used more often then keep it. It just seems, assuming that the field names mean "OrganizationCode" and "OrderNumber", that "OrgCode" is a better grouping that might have multiple "OrderNumbers" within it.
  6. Minor point, but if "ER101_ORG_CODE" is always 2 characters, then use CHAR(2) instead of VARCHAR(2) as it will save a byte in the row header which tracks variable width sizes and adds up over millions of rows.
  7. As others here have mentioned, using SELECT * will hurt performance. Not only due to it requiring SQL Server to return all columns and hence be more likely to do a Clustered Index Scan regardless of your other indexes, but it also takes SQL Server time to go to the table definition and translate * into all of the column names. It should be slightly faster to specify all 238 column names in the SELECT list though that won't help the Scan issue. But do you ever really need all 238 columns at the same time anyway?

Good luck!

UPDATE
For the sake of completeness to the question "how to improve performance on a large table for ad-hoc queries", it should be noted that while it will not help for this specific case, IF someone is using SQL Server 2012 (or newer when that time comes) and IF the table is not being updated, then using Columnstore Indexes is an option. For more details on that new feature, look here: http://msdn.microsoft.com/en-us/library/gg492088.aspx (I believe these were made to be updateable starting in SQL Server 2014).

UPDATE 2
Additional considerations are:

  • Enable compression on the Clustered Index. This option became available in SQL Server 2008, but as an Enterprise Edition-only feature. However, as of SQL Server 2016 SP1, Data Compression was made available in all editions! Please see the MSDN page for Data Compression for details on Row and Page Compression.
  • If you cannot use Data Compression, or if it won't provide much benefit for a particular table, then IF you have a column of a fixed-length type (INT, BIGINT, TINYINT, SMALLINT, CHAR, NCHAR, BINARY, DATETIME, SMALLDATETIME, MONEY, etc) and well over 50% of the rows are NULL, then consider enabling the SPARSE option which became available in SQL Server 2008. Please see the MSDN page for Use Sparse Columns for details.

The proxy server received an invalid response from an upstream server

This is not mentioned in you post but I suspect you are initiating an SSL connection from the browser to Apache, where VirtualHosts are configured, and Apache does a revese proxy to your Tomcat.

There is a serious bug in (some versions ?) of IE that sends the 'wrong' host information in an SSL connection (see EDIT below) and confuses the Apache VirtualHosts. In short the server name presented is the one of the reverse DNS resolution of the IP, not the one in the URL.

The workaround is to have one IP address per SSL virtual hosts/server name. Is short, you must end up with something like

1 server name == 1 IP address == 1 certificate == 1 Apache Virtual Host

EDIT

Though the conclusion is correct, the identification of the problem is better described here http://en.wikipedia.org/wiki/Server_Name_Indication

Why is nginx responding to any domain name?

The first server block in the nginx config is the default for all requests that hit the server for which there is no specific server block.

So in your config, assuming your real domain is REAL.COM, when a user types that in, it will resolve to your server, and since there is no server block for this setup, the server block for FAKE.COM, being the first server block (only server block in your case), will process that request.

This is why proper Nginx configs have a specific server block for defaults before following with others for specific domains.

# Default server
server {
    return 404;
}

server {
    server_name domain_1;
    [...]
}

server {
    server_name domain_2;
    [...]
}

etc

** EDIT **

It seems some users are a bit confused by this example and think it is limited to a single conf file etc.

Please note that the above is a simple example for the OP to develop as required.

I personally use separate vhost conf files with this as so (CentOS/RHEL):

http {
    [...]
    # Default server
    server {
        return 404;
    }
    # Other servers
    include /etc/nginx/conf.d/*.conf;
}

/etc/nginx/conf.d/ will contain domain_1.conf, domain_2.conf... domain_n.conf which will be included after the server block in the main nginx.conf file which will always be the first and will always be the default unless it is overridden it with the default_server directive elsewhere.

The alphabetical order of the file names of the conf files for the other servers becomes irrelevant in this case.

In addition, this arrangement gives a lot of flexibility in that it is possible to define multiple defaults.

In my specific case, I have Apache listening on Port 8080 on the internal interface only and I proxy PHP and Perl scripts to Apache.

However, I run two separate applications that both return links with ":8080" in the output html attached as they detect that Apache is not running on the standard Port 80 and try to "help" me out.

This causes an issue in that the links become invalid as Apache cannot be reached from the external interface and the links should point at Port 80.

I resolve this by creating a default server for Port 8080 to redirect such requests.

http {
    [...]
    # Default server block for undefined domains
    server {
        listen 80;
        return 404;
    }
    # Default server block to redirect Port 8080 for all domains
    server {
        listen my.external.ip.addr:8080;
        return 301 http://$host$request_uri;
    }
    # Other servers
    include /etc/nginx/conf.d/*.conf;
}

As nothing in the regular server blocks listens on Port 8080, the redirect default server block transparently handles such requests by virtue of its position in nginx.conf.

I actually have four of such server blocks and this is a simplified use case.

Show ProgressDialog Android

I am using the following code in one of my current projects where i download data from the internet. It is all inside my activity class.

private class GetData extends AsyncTask<String, Void, JSONObject> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();

            progressDialog = ProgressDialog.show(Calendar.this,
                    "", "");

        }

        @Override
        protected JSONObject doInBackground(String... params) {

            String response;

            try {

                HttpClient httpclient = new DefaultHttpClient();

                HttpPost httppost = new HttpPost(url);

                HttpResponse responce = httpclient.execute(httppost);

                HttpEntity httpEntity = responce.getEntity();

                response = EntityUtils.toString(httpEntity);

                Log.d("response is", response);

                return new JSONObject(response);

            } catch (Exception ex) {

                ex.printStackTrace();

            }

            return null;
        }

        @Override
        protected void onPostExecute(JSONObject result) 
        {
            super.onPostExecute(result);

            progressDialog.dismiss();

            if(result != null)
            {
                try
                {
                    JSONObject jobj = result.getJSONObject("result");

                    String status = jobj.getString("status");

                    if(status.equals("true"))
                    {
                        JSONArray array = jobj.getJSONArray("data");

                        for(int x = 0; x < array.length(); x++)
                        {
                            HashMap<String, String> map = new HashMap<String, String>();

                            map.put("name", array.getJSONObject(x).getString("name"));

                            map.put("date", array.getJSONObject(x).getString("date"));

                            map.put("description", array.getJSONObject(x).getString("description"));

                            list.add(map);
                        }

                        CalendarAdapter adapter = new CalendarAdapter(Calendar.this, list);

                        list_of_calendar.setAdapter(adapter);
                    }
                }
                catch (Exception e) 
                {
                    e.printStackTrace();
                }
            }
            else
            {
                Toast.makeText(Calendar.this, "Network Problem", Toast.LENGTH_LONG).show();
            }
        }

    }

and execute it in OnCreate Method like new GetData().execute();

where Calendar is my calendarActivity and i have also created a CalendarAdapter to set these values to a list view.

What's the best way to add a drop shadow to my UIView

Wasabii's answer in Swift 2.3:

let shadowPath = UIBezierPath(rect: view.bounds)
view.layer.masksToBounds = false
view.layer.shadowColor = UIColor.blackColor().CGColor
view.layer.shadowOffset = CGSize(width: 0, height: 0.5)
view.layer.shadowOpacity = 0.2
view.layer.shadowPath = shadowPath.CGPath

And in Swift 3/4/5:

let shadowPath = UIBezierPath(rect: view.bounds)
view.layer.masksToBounds = false
view.layer.shadowColor = UIColor.black.cgColor
view.layer.shadowOffset = CGSize(width: 0, height: 0.5)
view.layer.shadowOpacity = 0.2
view.layer.shadowPath = shadowPath.cgPath

Put this code in layoutSubviews() if you're using AutoLayout.

In SwiftUI, this is all much easier:

Color.yellow  // or whatever your view
    .shadow(radius: 3)
    .frame(width: 200, height: 100)

Clean up a fork and restart it from the upstream

Love VonC's answer. Here's an easy version of it for beginners.

There is a git remote called origin which I am sure you are all aware of. Basically, you can add as many remotes to a git repo as you want. So, what we can do is introduce a new remote which is the original repo not the fork. I like to call it original

Let's add original repo's to our fork as a remote.

git remote add original https://git-repo/original/original.git

Now let's fetch the original repo to make sure we have the latest coded

git fetch original

As, VonC suggested, make sure we are on the master.

git checkout master

Now to bring our fork up to speed with the latest code on original repo, all we have to do is hard reset our master branch in accordance with the original remote.

git reset --hard original/master

And you are done :)

What is the difference between origin and upstream on GitHub?

after cloning a fork you have to explicitly add a remote upstream, with git add remote "the original repo you forked from". This becomes your upstream, you mostly fetch and merge from your upstream. Any other business such as pushing from your local to upstream should be done using pull request.

git cherry-pick says "...38c74d is a merge but no -m option was given"

-m means the parent number.

From the git doc:

Usually you cannot cherry-pick a merge because you do not know which side of the merge should be considered the mainline. This option specifies the parent number (starting from 1) of the mainline and allows cherry-pick to replay the change relative to the specified parent.

For example, if your commit tree is like below:

- A - D - E - F -   master
   \     /
    B - C           branch one

then git cherry-pick E will produce the issue you faced.

git cherry-pick E -m 1 means using D-E, while git cherry-pick E -m 2 means using B-C-E.

Understanding the Linux oom-killer's logs

Sum of total_vm is 847170 and sum of rss is 214726, these two values are counted in 4kB pages, which means when oom-killer was running, you had used 214726*4kB=858904kB physical memory and swap space.

Since your physical memory is 1GB and ~200MB was used for memory mapping, it's reasonable for invoking oom-killer when 858904kB was used.

rss for process 2603 is 181503, which means 181503*4KB=726012 rss, was equal to sum of anon-rss and file-rss.

[11686.043647] Killed process 2603 (flasherav) total-vm:1498536kB, anon-rss:721784kB, file-rss:4228kB

'Microsoft.ACE.OLEDB.12.0' provider is not registered on the local machine

First verify which version of microsoft.ace.oledb.12.0 is installed in your system.

Check in below path C:\Program Files\Common Files\Microsoft Shared\OFFICE14\ACEOLEDB.DLL --64 bit is installed

Check in below path C:\Program Files (x86)\Common Files\Microsoft Shared\OFFICE14\ACEOLEDB.DLL --x86 bit is installed

If (x86) is installed then using configuration manager change solution platform to x86, for x64 change to x64.

If not available then install using below link

https://www.microsoft.com/en-us/download/details.aspx?id=23734

Laravel - Eloquent "Has", "With", "WhereHas" - What do they mean?

With

with() is for eager loading. That basically means, along the main model, Laravel will preload the relationship(s) you specify. This is especially helpful if you have a collection of models and you want to load a relation for all of them. Because with eager loading you run only one additional DB query instead of one for every model in the collection.

Example:

User > hasMany > Post

$users = User::with('posts')->get();
foreach($users as $user){
    $users->posts; // posts is already loaded and no additional DB query is run
}

Has

has() is to filter the selecting model based on a relationship. So it acts very similarly to a normal WHERE condition. If you just use has('relation') that means you only want to get the models that have at least one related model in this relation.

Example:

User > hasMany > Post

$users = User::has('posts')->get();
// only users that have at least one post are contained in the collection

WhereHas

whereHas() works basically the same as has() but allows you to specify additional filters for the related model to check.

Example:

User > hasMany > Post

$users = User::whereHas('posts', function($q){
    $q->where('created_at', '>=', '2015-01-01 00:00:00');
})->get();
// only users that have posts from 2015 on forward are returned

Save PL/pgSQL output from PostgreSQL to a CSV file

In terminal (while connected to the db) set output to the cvs file

1) Set field seperator to ',':

\f ','

2) Set output format unaligned:

\a

3) Show only tuples:

\t

4) Set output:

\o '/tmp/yourOutputFile.csv'

5) Execute your query:

:select * from YOUR_TABLE

6) Output:

\o

You will then be able to find your csv file in this location:

cd /tmp

Copy it using the scp command or edit using nano:

nano /tmp/yourOutputFile.csv

How can I change image tintColor in iOS and WatchKit

Also, for the above answers, in iOS 13 and later there is a clean way

let image = UIImage(named: "imageName")?.withTintColor(.white, renderingMode: .alwaysTemplate)

Align text in a table header

If you want to center the th of all tables:
table th{ text-align: center; }

If you only want to center the th of a table with a determined id:
table#tableId th{ text-align: center; }

Make elasticsearch only return certain fields?

In java you can use setFetchSource like this :

client.prepareSearch(index).setTypes(type)
            .setFetchSource(new String[] { "field1", "field2" }, null)

How to update MySql timestamp column to current timestamp on PHP?

Use this query:

UPDATE `table` SET date_date=now();

Sample code can be:

<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }

mysql_select_db("my_db", $con);

mysql_query("UPDATE `table` SET date_date=now()");

mysql_close($con);
?>

How can I be notified when an element is added to the page?

Between the deprecation of mutation events and the emergence of MutationObserver, an efficent way to be notified when a specific element was added to the DOM was to exploit CSS3 animation events.

To quote the blog post:

Setup a CSS keyframe sequence that targets (via your choice of CSS selector) whatever DOM elements you want to receive a DOM node insertion event for. I used a relatively benign and little used css property, clip I used outline-color in an attempt to avoid messing with intended page styles – the code once targeted the clip property, but it is no longer animatable in IE as of version 11. That said, any property that can be animated will work, choose whichever one you like.

Next I added a document-wide animationstart listener that I use as a delegate to process the node insertions. The animation event has a property called animationName on it that tells you which keyframe sequence kicked off the animation. Just make sure the animationName property is the same as the keyframe sequence name you added for node insertions and you’re good to go.

Copy data from one column to other column (which is in a different table)

Hope you have key field is two tables.

 UPDATE tblindiantime t
   SET CountryName = (SELECT c.BusinessCountry 
                     FROM contacts c WHERE c.Key = t.Key 
                     )

How can you get the active users connected to a postgreSQL database via SQL?

Using balexandre's info:

SELECT usesysid, usename FROM pg_stat_activity;

WAMP server, localhost is not working

If you have skype installed, close it completely.

If you have sql server installed, go to:

Control panel -> Administrative Tools -> Services

And stop SQL Server Reporting Services

Port 80 must be free now. Click on Wamp icon -> Restart All Services

What is the difference between bottom-up and top-down?

rev4: A very eloquent comment by user Sammaron has noted that, perhaps, this answer previously confused top-down and bottom-up. While originally this answer (rev3) and other answers said that "bottom-up is memoization" ("assume the subproblems"), it may be the inverse (that is, "top-down" may be "assume the subproblems" and "bottom-up" may be "compose the subproblems"). Previously, I have read on memoization being a different kind of dynamic programming as opposed to a subtype of dynamic programming. I was quoting that viewpoint despite not subscribing to it. I have rewritten this answer to be agnostic of the terminology until proper references can be found in the literature. I have also converted this answer to a community wiki. Please prefer academic sources. List of references: {Web: 1,2} {Literature: 5}

Recap

Dynamic programming is all about ordering your computations in a way that avoids recalculating duplicate work. You have a main problem (the root of your tree of subproblems), and subproblems (subtrees). The subproblems typically repeat and overlap.

For example, consider your favorite example of Fibonnaci. This is the full tree of subproblems, if we did a naive recursive call:

TOP of the tree
fib(4)
 fib(3)...................... + fib(2)
  fib(2)......... + fib(1)       fib(1)........... + fib(0)
   fib(1) + fib(0)   fib(1)       fib(1)              fib(0)
    fib(1)   fib(0)
BOTTOM of the tree

(In some other rare problems, this tree could be infinite in some branches, representing non-termination, and thus the bottom of the tree may be infinitely large. Furthermore, in some problems you might not know what the full tree looks like ahead of time. Thus, you might need a strategy/algorithm to decide which subproblems to reveal.)


Memoization, Tabulation

There are at least two main techniques of dynamic programming which are not mutually exclusive:

  • Memoization - This is a laissez-faire approach: You assume that you have already computed all subproblems and that you have no idea what the optimal evaluation order is. Typically, you would perform a recursive call (or some iterative equivalent) from the root, and either hope you will get close to the optimal evaluation order, or obtain a proof that you will help you arrive at the optimal evaluation order. You would ensure that the recursive call never recomputes a subproblem because you cache the results, and thus duplicate sub-trees are not recomputed.

    • example: If you are calculating the Fibonacci sequence fib(100), you would just call this, and it would call fib(100)=fib(99)+fib(98), which would call fib(99)=fib(98)+fib(97), ...etc..., which would call fib(2)=fib(1)+fib(0)=1+0=1. Then it would finally resolve fib(3)=fib(2)+fib(1), but it doesn't need to recalculate fib(2), because we cached it.
    • This starts at the top of the tree and evaluates the subproblems from the leaves/subtrees back up towards the root.
  • Tabulation - You can also think of dynamic programming as a "table-filling" algorithm (though usually multidimensional, this 'table' may have non-Euclidean geometry in very rare cases*). This is like memoization but more active, and involves one additional step: You must pick, ahead of time, the exact order in which you will do your computations. This should not imply that the order must be static, but that you have much more flexibility than memoization.

    • example: If you are performing fibonacci, you might choose to calculate the numbers in this order: fib(2),fib(3),fib(4)... caching every value so you can compute the next ones more easily. You can also think of it as filling up a table (another form of caching).
    • I personally do not hear the word 'tabulation' a lot, but it's a very decent term. Some people consider this "dynamic programming".
    • Before running the algorithm, the programmer considers the whole tree, then writes an algorithm to evaluate the subproblems in a particular order towards the root, generally filling in a table.
    • *footnote: Sometimes the 'table' is not a rectangular table with grid-like connectivity, per se. Rather, it may have a more complicated structure, such as a tree, or a structure specific to the problem domain (e.g. cities within flying distance on a map), or even a trellis diagram, which, while grid-like, does not have a up-down-left-right connectivity structure, etc. For example, user3290797 linked a dynamic programming example of finding the maximum independent set in a tree, which corresponds to filling in the blanks in a tree.

(At it's most general, in a "dynamic programming" paradigm, I would say the programmer considers the whole tree, then writes an algorithm that implements a strategy for evaluating subproblems which can optimize whatever properties you want (usually a combination of time-complexity and space-complexity). Your strategy must start somewhere, with some particular subproblem, and perhaps may adapt itself based on the results of those evaluations. In the general sense of "dynamic programming", you might try to cache these subproblems, and more generally, try avoid revisiting subproblems with a subtle distinction perhaps being the case of graphs in various data structures. Very often, these data structures are at their core like arrays or tables. Solutions to subproblems can be thrown away if we don't need them anymore.)

[Previously, this answer made a statement about the top-down vs bottom-up terminology; there are clearly two main approaches called Memoization and Tabulation that may be in bijection with those terms (though not entirely). The general term most people use is still "Dynamic Programming" and some people say "Memoization" to refer to that particular subtype of "Dynamic Programming." This answer declines to say which is top-down and bottom-up until the community can find proper references in academic papers. Ultimately, it is important to understand the distinction rather than the terminology.]


Pros and cons

Ease of coding

Memoization is very easy to code (you can generally* write a "memoizer" annotation or wrapper function that automatically does it for you), and should be your first line of approach. The downside of tabulation is that you have to come up with an ordering.

*(this is actually only easy if you are writing the function yourself, and/or coding in an impure/non-functional programming language... for example if someone already wrote a precompiled fib function, it necessarily makes recursive calls to itself, and you can't magically memoize the function without ensuring those recursive calls call your new memoized function (and not the original unmemoized function))

Recursiveness

Note that both top-down and bottom-up can be implemented with recursion or iterative table-filling, though it may not be natural.

Practical concerns

With memoization, if the tree is very deep (e.g. fib(10^6)), you will run out of stack space, because each delayed computation must be put on the stack, and you will have 10^6 of them.

Optimality

Either approach may not be time-optimal if the order you happen (or try to) visit subproblems is not optimal, specifically if there is more than one way to calculate a subproblem (normally caching would resolve this, but it's theoretically possible that caching might not in some exotic cases). Memoization will usually add on your time-complexity to your space-complexity (e.g. with tabulation you have more liberty to throw away calculations, like using tabulation with Fib lets you use O(1) space, but memoization with Fib uses O(N) stack space).

Advanced optimizations

If you are also doing a extremely complicated problems, you might have no choice but to do tabulation (or at least take a more active role in steering the memoization where you want it to go). Also if you are in a situation where optimization is absolutely critical and you must optimize, tabulation will allow you to do optimizations which memoization would not otherwise let you do in a sane way. In my humble opinion, in normal software engineering, neither of these two cases ever come up, so I would just use memoization ("a function which caches its answers") unless something (such as stack space) makes tabulation necessary... though technically to avoid a stack blowout you can 1) increase the stack size limit in languages which allow it, or 2) eat a constant factor of extra work to virtualize your stack (ick), or 3) program in continuation-passing style, which in effect also virtualizes your stack (not sure the complexity of this, but basically you will effectively take the deferred call chain from the stack of size N and de-facto stick it in N successively nested thunk functions... though in some languages without tail-call optimization you may have to trampoline things to avoid a stack blowout).


More complicated examples

Here we list examples of particular interest, that are not just general DP problems, but interestingly distinguish memoization and tabulation. For example, one formulation might be much easier than the other, or there may be an optimization which basically requires tabulation:

  • the algorithm to calculate edit-distance[4], interesting as a non-trivial example of a two-dimensional table-filling algorithm

How to add "Maven Managed Dependencies" library in build path eclipse?

If you have removed Maven dependency from Library accidentally. Add below in pom.xml

<build>     
        <plugins>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.3</version>
                <configuration>
                    <source>1.7</source>
                    <target>1.7</target>
                </configuration>
            </plugin>
        </plugins>
</build>

mailto link with HTML body

As you can see in RFC 6068, this is not possible at all:

The special <hfname> "body" indicates that the associated <hfvalue> is the body of the message. The "body" field value is intended to contain the content for the first text/plain body part of the message. The "body" pseudo header field is primarily intended for the generation of short text messages for automatic processing (such as "subscribe" messages for mailing lists), not for general MIME bodies.

no module named zlib

After running configure, you can change the config option in the file Modules/Setup as below:

zlib zlibmodule.c -I$(prefix)/include -L$(exec_prefix)/lib -lz

Or you can uncomment the zlib line as-is.

What's the difference between size_t and int in C++?

The size_t type is defined as the unsigned integral type of the sizeof operator. In the real world, you will often see int defined as 32 bits (for backward compatibility) but size_t defined as 64 bits (so you can declare arrays and structures more than 4 GiB in size) on 64-bit platforms. If a long int is also 64-bits, this is called the LP64 convention; if long int is 32 bits but long long int and pointers are 64 bits, that’s LLP64. You also might get the reverse, a program that uses 64-bit instructions for speed, but 32-bit pointers to save memory. Also, int is signed and size_t is unsigned.

There were historically a number of other platforms where addresses were wider or shorter than the native size of int. In fact, in the ’70s and early ’80s, this was more common than not: all the popular 8-bit microcomputers had 8-bit registers and 16-bit addresses, and the transition between 16 and 32 bits also produced many machines that had addresses wider than their registers. I occasionally still see questions here about Borland Turbo C for MS-DOS, whose Huge memory mode had 20-bit addresses stored in 32 bits on a 16-bit CPU (but which could support the 32-bit instruction set of the 80386); the Motorola 68000 had a 16-bit ALU with 32-bit registers and addresses; there were IBM mainframes with 15-bit, 24-bit or 31-bit addresses. You also still see different ALU and address-bus sizes in embedded systems.

Any time int is smaller than size_t, and you try to store the size or offset of a very large file or object in an unsigned int, there is the possibility that it could overflow and cause a bug. With an int, there is also the possibility of getting a negative number. If an int or unsigned int is wider, the program will run correctly but waste memory.

You should generally use the correct type for the purpose if you want portability. A lot of people will recommend that you use signed math instead of unsigned (to avoid nasty, subtle bugs like 1U < -3). For that purpose, the standard library defines ptrdiff_t in <stddef.h> as the signed type of the result of subtracting a pointer from another.

That said, a workaround might be to bounds-check all addresses and offsets against INT_MAX and either 0 or INT_MIN as appropriate, and turn on the compiler warnings about comparing signed and unsigned quantities in case you miss any. You should always, always, always be checking your array accesses for overflow in C anyway.

Set markers for individual points on a line in Matplotlib

A simple trick to change a particular point marker shape, size... is to first plot it with all the other data then plot one more plot only with that point (or set of points if you want to change the style of multiple points). Suppose we want to change the marker shape of second point:

x = [1,2,3,4,5]
y = [2,1,3,6,7]

plt.plot(x, y, "-o")
x0 = [2]
y0 = [1]
plt.plot(x0, y0, "s")

plt.show()

Result is: Plot with multiple markers

enter image description here

How to parse XML in Bash?

After some research for translation between Linux and Windows formats of the file paths in XML files I found interesting tutorials and solutions on:

How to run a javascript function during a mouseover on a div

the prototype way

<div id="sub1" title="some text on mouse over">some text</div>


<script type="text/javascript">//<![CDATA[
  $("sub1").observe("mouseover", function() {
    alert(this.readAttribute("title"));
  });
//]]></script>

include Prototype Lib for testing

<script type="text/javascript" 
  src="http://ajax.googleapis.com/ajax/libs/prototype/1.6.0.2/prototype.js"></script>

How to read data of an Excel file using C#?

I'd recommend you to use Bytescout Spreadsheet.

https://bytescout.com/products/developer/spreadsheetsdk/bytescoutspreadsheetsdk.html

I tried it with Monodevelop in Unity3D and it is pretty straight forward. Check this sample code to see how the library works:

https://bytescout.com/products/developer/spreadsheetsdk/read-write-excel.html

What's the best way to send a signal to all members of a process group?

Kill all the processes belonging to the same process tree using the Process Group ID (PGID)

  • kill -- -$PGID     Use default signal (TERM = 15)
  • kill -9 -$PGID     Use the signal KILL (9)

You can retrieve the PGID from any Process-ID (PID) of the same process tree

  • kill -- -$(ps -o pgid= $PID | grep -o '[0-9]*')   (signal TERM)
  • kill -9 -$(ps -o pgid= $PID | grep -o '[0-9]*')   (signal KILL)

Special thanks to tanager and Speakus for contributions on $PID remaining spaces and OSX compatibility.

Explanation

  • kill -9 -"$PGID" => Send signal 9 (KILL) to all child and grandchild...
  • PGID=$(ps opgid= "$PID") => Retrieve the Process-Group-ID from any Process-ID of the tree, not only the Process-Parent-ID. A variation of ps opgid= $PID is ps -o pgid --no-headers $PID where pgid can be replaced by pgrp.
    But:
    • ps inserts leading spaces when PID is less than five digits and right aligned as noticed by tanager. You can use:
      PGID=$(ps opgid= "$PID" | tr -d ' ')
    • ps from OSX always print the header, therefore Speakus proposes:
      PGID="$( ps -o pgid "$PID" | grep [0-9] | tr -d ' ' )"
  • grep -o [0-9]* prints successive digits only (does not print spaces or alphabetical headers).

Further command lines

PGID=$(ps -o pgid= $PID | grep -o [0-9]*)
kill -TERM -"$PGID"  # kill -15
kill -INT  -"$PGID"  # correspond to [CRTL+C] from keyboard
kill -QUIT -"$PGID"  # correspond to [CRTL+\] from keyboard
kill -CONT -"$PGID"  # restart a stopped process (above signals do not kill it)
sleep 2              # wait terminate process (more time if required)
kill -KILL -"$PGID"  # kill -9 if it does not intercept signals (or buggy)

Limitation

  • As noticed by davide and Hubert Kario, when kill is invoked by a process belonging to the same tree, kill risks to kill itself before terminating the whole tree killing.
  • Therefore, be sure to run the command using a process having a different Process-Group-ID.

Long story

> cat run-many-processes.sh
#!/bin/sh
echo "ProcessID=$$ begins ($0)"
./child.sh background &
./child.sh foreground
echo "ProcessID=$$ ends ($0)"

> cat child.sh
#!/bin/sh
echo "ProcessID=$$ begins ($0)"
./grandchild.sh background &
./grandchild.sh foreground
echo "ProcessID=$$ ends ($0)"

> cat grandchild.sh
#!/bin/sh
echo "ProcessID=$$ begins ($0)"
sleep 9999
echo "ProcessID=$$ ends ($0)"

Run the process tree in background using '&'

> ./run-many-processes.sh &    
ProcessID=28957 begins (./run-many-processes.sh)
ProcessID=28959 begins (./child.sh)
ProcessID=28958 begins (./child.sh)
ProcessID=28960 begins (./grandchild.sh)
ProcessID=28961 begins (./grandchild.sh)
ProcessID=28962 begins (./grandchild.sh)
ProcessID=28963 begins (./grandchild.sh)

> PID=$!                    # get the Parent Process ID
> PGID=$(ps opgid= "$PID")  # get the Process Group ID

> ps fj
 PPID   PID  PGID   SID TTY      TPGID STAT   UID   TIME COMMAND
28348 28349 28349 28349 pts/3    28969 Ss   33021   0:00 -bash
28349 28957 28957 28349 pts/3    28969 S    33021   0:00  \_ /bin/sh ./run-many-processes.sh
28957 28958 28957 28349 pts/3    28969 S    33021   0:00  |   \_ /bin/sh ./child.sh background
28958 28961 28957 28349 pts/3    28969 S    33021   0:00  |   |   \_ /bin/sh ./grandchild.sh background
28961 28965 28957 28349 pts/3    28969 S    33021   0:00  |   |   |   \_ sleep 9999
28958 28963 28957 28349 pts/3    28969 S    33021   0:00  |   |   \_ /bin/sh ./grandchild.sh foreground
28963 28967 28957 28349 pts/3    28969 S    33021   0:00  |   |       \_ sleep 9999
28957 28959 28957 28349 pts/3    28969 S    33021   0:00  |   \_ /bin/sh ./child.sh foreground
28959 28960 28957 28349 pts/3    28969 S    33021   0:00  |       \_ /bin/sh ./grandchild.sh background
28960 28964 28957 28349 pts/3    28969 S    33021   0:00  |       |   \_ sleep 9999
28959 28962 28957 28349 pts/3    28969 S    33021   0:00  |       \_ /bin/sh ./grandchild.sh foreground
28962 28966 28957 28349 pts/3    28969 S    33021   0:00  |           \_ sleep 9999
28349 28969 28969 28349 pts/3    28969 R+   33021   0:00  \_ ps fj

The command pkill -P $PID does not kill the grandchild:

> pkill -P "$PID"
./run-many-processes.sh: line 4: 28958 Terminated              ./child.sh background
./run-many-processes.sh: line 4: 28959 Terminated              ./child.sh foreground
ProcessID=28957 ends (./run-many-processes.sh)
[1]+  Done                    ./run-many-processes.sh

> ps fj
 PPID   PID  PGID   SID TTY      TPGID STAT   UID   TIME COMMAND
28348 28349 28349 28349 pts/3    28987 Ss   33021   0:00 -bash
28349 28987 28987 28349 pts/3    28987 R+   33021   0:00  \_ ps fj
    1 28963 28957 28349 pts/3    28987 S    33021   0:00 /bin/sh ./grandchild.sh foreground
28963 28967 28957 28349 pts/3    28987 S    33021   0:00  \_ sleep 9999
    1 28962 28957 28349 pts/3    28987 S    33021   0:00 /bin/sh ./grandchild.sh foreground
28962 28966 28957 28349 pts/3    28987 S    33021   0:00  \_ sleep 9999
    1 28961 28957 28349 pts/3    28987 S    33021   0:00 /bin/sh ./grandchild.sh background
28961 28965 28957 28349 pts/3    28987 S    33021   0:00  \_ sleep 9999
    1 28960 28957 28349 pts/3    28987 S    33021   0:00 /bin/sh ./grandchild.sh background
28960 28964 28957 28349 pts/3    28987 S    33021   0:00  \_ sleep 9999

The command kill -- -$PGID kills all processes including the grandchild.

> kill --    -"$PGID"  # default signal is TERM (kill -15)
> kill -CONT -"$PGID"  # awake stopped processes
> kill -KILL -"$PGID"  # kill -9 to be sure

> ps fj
 PPID   PID  PGID   SID TTY      TPGID STAT   UID   TIME COMMAND
28348 28349 28349 28349 pts/3    29039 Ss   33021   0:00 -bash
28349 29039 29039 28349 pts/3    29039 R+   33021   0:00  \_ ps fj

Conclusion

I notice in this example PID and PGID are equal (28957).
This is why I originally thought kill -- -$PID was enough. But in the case the process is spawn within a Makefile the Process ID is different from the Group ID.

I think kill -- -$(ps -o pgid= $PID | grep -o [0-9]*) is the best simple trick to kill a whole process tree when called from a different Group ID (another process tree).

mysqldump with create database line

Here is how to do dump the database (with just the schema):

mysqldump -u root -p"passwd" --no-data --add-drop-database --databases my_db_name | sed 's#/[*]!40000 DROP DATABASE IF EXISTS my_db_name;#' >my_db_name.sql

If you also want the data, remove the --no-data option.

How to rebuild docker container in docker-compose.yml?

Maybe these steps are not quite correct, but I do like this:

stop docker compose: $ docker-compose down

remove the container: $ docker system prune -a

start docker compose: $ docker-compose up -d

How do I determine k when using k-means clustering?

Hi I'll make it simple and straight to explain, I like to determine clusters using 'NbClust' library.

Now, how to use the 'NbClust' function to determine the right number of clusters: You can check the actual project in Github with actual data and clusters - Extention to this 'kmeans' algorithm also performed using the right number of 'centers'.

Github Project Link: https://github.com/RutvijBhutaiya/Thailand-Customer-Engagement-Facebook

How to pass an object from one activity to another on Android

Use gson to convert your object to JSON and pass it through intent. In the new Activity convert the JSON to an object.

In your build.gradle, add this to your dependencies

implementation 'com.google.code.gson:gson:2.8.4'

In your Activity, convert the object to json-string:

Gson gson = new Gson();
String myJson = gson.toJson(vp);
intent.putExtra("myjson", myjson);

In your receiving Activity, convert the json-string back to the original object:

Gson gson = new Gson();
YourObject ob = gson.fromJson(getIntent().getStringExtra("myjson"), YourObject.class);

For Kotlin it's quite the same

Pass the data

val gson = Gson()
val intent = Intent(this, YourActivity::class.java)
intent.putExtra("identifier", gson.toJson(your_object))
startActivity(intent)

Receive the data

val gson = Gson()
val yourObject = gson.fromJson<YourObject>(intent.getStringExtra("identifier"), YourObject::class.java)

An established connection was aborted by the software in your host machine

I was getting these errors too and was stumped. After reading and trying the two answers above, I was still getting the error.

However,I checked the processes tab of Task Manager to find a rogue copy of 'eclipse.exe *32' that the UI didn' t show as running. I guess this should have been obvious as the error does suggest that the reason the emulator/phone cannot connect is because it's already established a connection with the second copy.

Long story short, make sure via Task Manager that no other Eclipse instances are running before resorting to a PC restart!

MySQL Error 1093 - Can't specify target table for update in FROM clause

Try to save result of Select statement in separate variable and then use that for delete query.

MS-DOS Batch file pause with enter key

There's a pause command that does just that, though it's not specifically the enter key.

If you really want to wait for only the enter key, you can use the set command to ask for user input with a dummy variable, something like:

set /p DUMMY=Hit ENTER to continue...

Creating a Facebook share button with customized url, title and image

Unfortunately, it appears that we can't post shares for individual topics or articles within a page. It appears Facebook just wants us to share entire pages (based on url only).

There's also their new share dialog, but even though they claim it can do all of what the old sharer.php could do, that doesn't appear to be true.

And here's Facebooks 'best practices' for sharing.

Android Paint: .measureText() vs .getTextBounds()

This is how I calculated the real dimensions for the first letter (you can change the method header to suit your needs, i.e. instead of char[] use String):

private void calculateTextSize(char[] text, PointF outSize) {
    // use measureText to calculate width
    float width = mPaint.measureText(text, 0, 1);

    // use height from getTextBounds()
    Rect textBounds = new Rect();
    mPaint.getTextBounds(text, 0, 1, textBounds);
    float height = textBounds.height();
    outSize.x = width;
    outSize.y = height;
}

Note that I'm using TextPaint instead of the original Paint class.

Which SchemaType in Mongoose is Best for Timestamp?

First : npm install mongoose-timestamp

Next: let Timestamps = require('mongoose-timestamp')

Next: let MySchema = new Schema

Next: MySchema.plugin(Timestamps)

Next : const Collection = mongoose.model('Collection',MySchema)

Then you can use the Collection.createdAt or Collection.updatedAt anywhere your want.

Created on: Date Of The Week Month Date Year 00:00:00 GMT

Time is in this format.

"pip install json" fails on Ubuntu

json is a built-in module, you don't need to install it with pip.

String.Replace(char, char) method in C#

@gnomixa - What do you mean in your comment about not achieving anything? The following works for me in VS2005.

If your goal is to remove the newline characters, thereby shortening the string, look at this:

        string originalStringWithNewline = "12\n345"; // length is 6
        System.Diagnostics.Debug.Assert(originalStringWithNewline.Length == 6);
        string newStringWithoutNewline = originalStringWithNewline.Replace("\n", ""); // new length is 5
        System.Diagnostics.Debug.Assert(newStringWithoutNewline.Length == 5);

If your goal is to replace the newline characters with a space character, leaving the string length the same, look at this example:

        string originalStringWithNewline = "12\n345"; // length is 6
        System.Diagnostics.Debug.Assert(originalStringWithNewline.Length == 6);
        string newStringWithoutNewline = originalStringWithNewline.Replace("\n", " "); // new length is still 6
        System.Diagnostics.Debug.Assert(newStringWithoutNewline.Length == 6);

And you have to replace single-character strings instead of characters because '' is not a valid character to be passed to Replace(string,char)

How to send post request to the below post method using postman rest client

The Interface of Postman is changing acccording to the updates.

So You can get full information about postman can get Here.

https://www.getpostman.com/docs/requests

Set width to match constraints in ConstraintLayout

If you want TextView in the center of parent..
Your main layout is Constraint Layout

<androidx.appcompat.widget.AppCompatTextView
     android:layout_width="0dp"
     android:layout_height="wrap_content"
     android:text="@string/logout"
     app:layout_constraintLeft_toLeftOf="parent"
     app:layout_constraintRight_toRightOf="parent"
     android:gravity="center">
</androidx.appcompat.widget.AppCompatTextView>

Create table with jQuery - append

Following is done for multiple file uploads using jquery:

File input button:

<div>
 <input type="file" name="uploadFiles" id="uploadFiles" multiple="multiple" class="input-xlarge" onchange="getFileSizeandName(this);"/> 
</div>

Displaying File name and File size in a table:

<div id="uploadMultipleFilediv">
<table id="uploadTable" class="table table-striped table-bordered table-condensed"></table></div>

Javascript for getting the file name and file size:

function getFileSizeandName(input)
{
    var select = $('#uploadTable');
    //select.empty();
    var totalsizeOfUploadFiles = "";
    for(var i =0; i<input.files.length; i++)
    {
        var filesizeInBytes = input.files[i].size; // file size in bytes
        var filesizeInMB = (filesizeInBytes / (1024*1024)).toFixed(2); // convert the file size from bytes to mb
        var filename = input.files[i].name;
        select.append($('<tr><td>'+filename+'</td><td>'+filesizeInMB+'</td></tr>'));
        totalsizeOfUploadFiles = totalsizeOfUploadFiles+filesizeInMB;
        //alert("File name is : "+filename+" || size : "+filesizeInMB+" MB || size : "+filesizeInBytes+" Bytes");               
    }           
}

WARNING: Exception encountered during context initialization - cancelling refresh attempt

This was my stupidity, but a stupidity that was not easy to identify :).

Problem:

  1. My code is compiled on Jdk 1.8.
  2. My eclipse, had JDK 1.8 as the compiler.
  3. My tomcat in eclipse was using Java 1.7 for its container, hence it was not able to understand the .class files which were compiled using 1.8.
  4. To avoid the problem, ensure in your eclipse, double click on your server -> Open Launch configuration -> Classpath -> JRE System Library -> Give the JDK/JRE of the compiled version of java class, in my case, it had to be JDK 1.8
    1. Post this, clean the server, build and redeploy, start the tomcat.

If you are deploying manually into your server, ensure your JAVA_HOME, JDK_HOME points to the correct JDK which you used to compile the project and build the war.

If you do not like to change JAVA_HOME, JDK_HOME, you can always change the JAVA_HOME and JDK_HOME in catalina.bat(for tomcat server) and that'll enable your life to be easy!

Failed linking file resources

I was doing Temperatur Converter App.I was facing same error while running the app as: Android Studio linking failed. In String.xml a line was missed, I included the line. It went fine without any errors.

Before Correction

<resources>
<color name="myColor">#FFE4E1</color>
<string name="Celsius">To Celsius</string>
<string name="fahrenheit">To Fahrenheit</string>
<string name="calc">Calculate</string>
</resources>

After editing:

<resources>
<string name="app_name">Temp Converter</string>
<color name="myColor">#FFE4E1</color>
<string name="Celsius">To Celsius</string>
<string name="fahrenheit">To Fahrenheit</string>
<string name="calc">Calculate</string>
</resources>

Jquery assiging class to th in a table

You had thead in your selector, but there is no thead in your table. Also you had your selectors backwards. As you mentioned above, you wanted to be adding the tr class to the th, not vice-versa (although your comment seems to contradict what you wrote up above).

$('tr th').each(function(index){     if($('tr td').eq(index).attr('class') != ''){         // get the class of the td         var tdClass = $('tr td').eq(index).attr('class');         // add it to this th         $(this).addClass(tdClass );     } }); 

Fiddle

Java Comparator class to sort arrays

[...] How should Java Comparator class be declared to sort the arrays by their first elements in decreasing order [...]

Here's a complete example using Java 8:

import java.util.*;

public class Test {

    public static void main(String args[]) {

        int[][] twoDim = { {1, 2}, {3, 7}, {8, 9}, {4, 2}, {5, 3} };

        Arrays.sort(twoDim, Comparator.comparingInt(a -> a[0])
                                      .reversed());

        System.out.println(Arrays.deepToString(twoDim));
    }
}

Output:

[[8, 9], [5, 3], [4, 2], [3, 7], [1, 2]]

For Java 7 you can do:

Arrays.sort(twoDim, new Comparator<int[]>() {
    @Override
    public int compare(int[] o1, int[] o2) {
        return Integer.compare(o2[0], o1[0]);
    }
});

If you unfortunate enough to work on Java 6 or older, you'd do:

Arrays.sort(twoDim, new Comparator<int[]>() {
    @Override
    public int compare(int[] o1, int[] o2) {
        return ((Integer) o2[0]).compareTo(o1[0]);
    }
});

Html- how to disable <a href>?

I created a button...

This is where you've gone wrong. You haven't created a button, you've created an anchor element. If you had used a button element instead, you wouldn't have this problem:

<button type="button" data-toggle="modal" data-target="#myModal" data-role="disabled">
    Connect
</button>

If you are going to continue using an a element instead, at the very least you should give it a role attribute set to "button" and drop the href attribute altogether:

<a role="button" ...>

Once you've done that you can introduce a piece of JavaScript which calls event.preventDefault() - here with event being your click event.

How to get my project path?

var requiredPath = Path.GetDirectoryName(Path.GetDirectoryName(
System.IO.Path.GetDirectoryName( 
      System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase )));

How to write a PHP ternary operator

How to write a basic PHP Ternary Operator:

($your_boolean) ? 'This is returned if true' : 'This is returned if false';

Example:

$myboolean = true;
echo ($myboolean) ? 'foobar' : "penguin";
foobar

echo (!$myboolean) ? 'foobar' : "penguin";
penguin

A PHP ternary operator with an 'elseif' crammed in there:

$chow = 3;
echo ($chow == 1) ? "one" : ($chow == 2) ? "two" : "three";
three

But please don't nest ternary operators except for parlor tricks. It's a bad code smell.

How to hide navigation bar permanently in android activity?

The other answers mostly use the flags for setSystemUiVisibility() method in View. However, this API is deprecated since Android 11. Check my article about modifying the system UI visibility for more information. The article also explains how to handle the cutouts properly or how to listen to the visibility changes.

Here are code snippets for showing / hiding system bars with the new API as well as the deprecated one for backward compatibility:

/**
 * Hides the system bars and makes the Activity "fullscreen". If this should be the default
 * state it should be called from [Activity.onWindowFocusChanged] if hasFocus is true.
 * It is also recommended to take care of cutout areas. The default behavior is that the app shows
 * in the cutout area in portrait mode if not in fullscreen mode. This can cause "jumping" if the
 * user swipes a system bar to show it. It is recommended to set [WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_NEVER],
 * call [showBelowCutout] from [Activity.onCreate]
 * (see [Android Developers article about cutouts](https://developer.android.com/guide/topics/display-cutout#never_render_content_in_the_display_cutout_area)).
 * @see showSystemUI
 * @see addSystemUIVisibilityListener
 */
fun Activity.hideSystemUI() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
        window.insetsController?.let {
            // Default behavior is that if navigation bar is hidden, the system will "steal" touches
            // and show it again upon user's touch. We just want the user to be able to show the
            // navigation bar by swipe, touches are handled by custom code -> change system bar behavior.
            // Alternative to deprecated SYSTEM_UI_FLAG_IMMERSIVE.
            it.systemBarsBehavior = WindowInsetsController.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE
            // make navigation bar translucent (alternative to deprecated
            // WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION)
            // - do this already in hideSystemUI() so that the bar
            // is translucent if user swipes it up
            window.navigationBarColor = getColor(R.color.internal_black_semitransparent_light)
            // Finally, hide the system bars, alternative to View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
            // and SYSTEM_UI_FLAG_FULLSCREEN.
            it.hide(WindowInsets.Type.systemBars())
        }
    } else {
        // Enables regular immersive mode.
        // For "lean back" mode, remove SYSTEM_UI_FLAG_IMMERSIVE.
        // Or for "sticky immersive," replace it with SYSTEM_UI_FLAG_IMMERSIVE_STICKY
        @Suppress("DEPRECATION")
        window.decorView.systemUiVisibility = (
                // Do not let system steal touches for showing the navigation bar
                View.SYSTEM_UI_FLAG_IMMERSIVE
                        // Hide the nav bar and status bar
                        or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                        or View.SYSTEM_UI_FLAG_FULLSCREEN
                        // Keep the app content behind the bars even if user swipes them up
                        or View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                        or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN)
        // make navbar translucent - do this already in hideSystemUI() so that the bar
        // is translucent if user swipes it up
        @Suppress("DEPRECATION")
        window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION)
    }
}

/**
 * Shows the system bars and returns back from fullscreen.
 * @see hideSystemUI
 * @see addSystemUIVisibilityListener
 */
fun Activity.showSystemUI() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
        // show app content in fullscreen, i. e. behind the bars when they are shown (alternative to
        // deprecated View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION and View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN)
        window.setDecorFitsSystemWindows(false)
        // finally, show the system bars
        window.insetsController?.show(WindowInsets.Type.systemBars())
    } else {
        // Shows the system bars by removing all the flags
        // except for the ones that make the content appear under the system bars.
        @Suppress("DEPRECATION")
        window.decorView.systemUiVisibility = (
                View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                        or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN)
    }
}

How to make a DIV not wrap?

The min-width property does not work correctly in Internet Explorer, which is most likely the cause of your problems.

Read info and a brilliant script that fixes many IE CSS problems.

How to print float to n decimal places including trailing 0s?

Floating point numbers lack precision to accurately represent "1.6" out to that many decimal places. The rounding errors are real. Your number is not actually 1.6.

Check out: http://docs.python.org/library/decimal.html

Android: Expand/collapse animation

Based on solutions by @Tom Esterez and @Seth Nelson (top 2) I simlified them. As well as original solutions it doesn't depend on Developer options (animation settings).

private void resizeWithAnimation(final View view, int duration, final int targetHeight) {
    final int initialHeight = view.getMeasuredHeight();
    final int distance = targetHeight - initialHeight;

    view.setVisibility(View.VISIBLE);

    Animation a = new Animation() {
        @Override
        protected void applyTransformation(float interpolatedTime, Transformation t) {
            if (interpolatedTime == 1 && targetHeight == 0) {
                view.setVisibility(View.GONE);
            }
            view.getLayoutParams().height = (int) (initialHeight + distance * interpolatedTime);
            view.requestLayout();
        }

        @Override
        public boolean willChangeBounds() {
            return true;
        }
    };

    a.setDuration(duration);
    view.startAnimation(a);
}

Eclipse CDT project built but "Launch Failed. Binary Not Found"

You need to click on the MinGW compiler when running the code. Failure to do this will cause the launch failed binary not found error.

How do I style appcompat-v7 Toolbar like Theme.AppCompat.Light.DarkActionBar?

Similar to Arnav Rao's, but with a different parent:

    <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <!-- Customize your theme here. -->
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>

    <item name="toolbarStyle">@style/MyToolbar</item>
</style>

<style name="MyToolbar" parent="ThemeOverlay.AppCompat.Dark.ActionBar">
    <item name="android:background">#ff0000</item>
</style>

With this approach, the appearance of the Toolbar is entirely defined in the app styles, so you don't need to place any styling on each toolbar.

Finding row index containing maximum value using R

See ?which.max

> which.max( matrix[,2] )
[1] 2

How does "304 Not Modified" work exactly?

When the browser puts something in its cache, it also stores the Last-Modified or ETag header from the server.

The browser then sends a request with the If-Modified-Since or If-None-Match header, telling the server to send a 304 if the content still has that date or ETag.

The server needs some way of calculating a date-modified or ETag for each version of each resource; this typically comes from the filesystem or a separate database column.

How to correct indentation in IntelliJ

In Android Studio this works: Go to File->Settings->Editor->CodeStyle->Java. Under Wrapping and Braces uncheck "Comment at first Column" Then formatting shortcut will indent the comment lines as well.

How to convert latitude or longitude to meters?

There are many tools that will make this easy. See monjardin's answer for more details about what's involved.

However, doing this isn't necessarily difficult. It sounds like you're using Java, so I would recommend looking into something like GDAL. It provides java wrappers for their routines, and they have all the tools required to convert from Lat/Lon (geographic coordinates) to UTM (projected coordinate system) or some other reasonable map projection.

UTM is nice, because it's meters, so easy to work with. However, you will need to get the appropriate UTM zone for it to do a good job. There are some simple codes available via googling to find an appropriate zone for a lat/long pair.

Use Font Awesome Icon in Placeholder

If you can / want to use Bootstrap the solution would be input-groups:

<div class="input-group">
 <div class="input-group-prepend">
  <span class="input-group-text"><i class="fa fa-search"></i></span>
  </div>
 <input type="text" class="form-control" placeholder="-">
</div>

Looks about like this:input with text-prepend and search symbol

How to execute a MySQL command from a shell script?

The core of the question has been answered several times already, I just thought I'd add that backticks (`s) have beaning in both shell scripting and SQL. If you need to use them in SQL for specifying a table or database name you'll need to escape them in the shell script like so:

mysql -p=password -u "root" -Bse "CREATE DATABASE \`${1}_database\`;
CREATE USER '$1'@'%' IDENTIFIED BY '$2';
GRANT ALL PRIVILEGES ON `${1}_database`.* TO '$1'@'%' WITH GRANT OPTION;"

Of course, generating SQL through concatenated user input (passed arguments) shouldn't be done unless you trust the user input.It'd be a lot more secure to put it in another scripting language with support for parameters / correctly escaping strings for insertion into MySQL.

How to Detect cause of 503 Service Temporarily Unavailable error and handle it?

There is of course some apache log files. Search in your apache configuration files for 'Log' keyword, you'll certainly find plenty of them. Depending on your OS and installation places may vary (in a Typical Linux server it would be /var/log/apache2/[access|error].log).

Having a 503 error in Apache usually means the proxied page/service is not available. I assume you're using tomcat and that means tomcat is either not responding to apache (timeout?) or not even available (down? crashed?). So chances are that it's a configuration error in the way to connect apache and tomcat or an application inside tomcat that is not even sending a response for apache.

Sometimes, in production servers, it can as well be that you get too much traffic for the tomcat server, apache handle more request than the proxyied service (tomcat) can accept so the backend became unavailable.

How do I strip all spaces out of a string in PHP?

If you want to remove all whitespace:

$str = preg_replace('/\s+/', '', $str);

See the 5th example on the preg_replace documentation. (Note I originally copied that here.)

Edit: commenters pointed out, and are correct, that str_replace is better than preg_replace if you really just want to remove the space character. The reason to use preg_replace would be to remove all whitespace (including tabs, etc.).

Laravel Request getting current path with query string

Get the current URL including the query string.

echo url()->full();

Should I put input elements inside a label element?

See http://www.w3.org/TR/html401/interact/forms.html#h-17.9 for the W3 recommendations.

They say it can be done either way. They describe the two methods as explicit (using "for" with the element's id) and implicit (embedding the element in the label):

Explicit:

The for attribute associates a label with another control explicitly: the value of the for attribute must be the same as the value of the id attribute of the associated control element.

Implicit:

To associate a label with another control implicitly, the control element must be within the contents of the LABEL element. In this case, the LABEL may only contain one control element.

How to return dictionary keys as a list in Python?

Try list(newdict.keys()).

This will convert the dict_keys object to a list.

On the other hand, you should ask yourself whether or not it matters. The Pythonic way to code is to assume duck typing (if it looks like a duck and it quacks like a duck, it's a duck). The dict_keys object will act like a list for most purposes. For instance:

for key in newdict.keys():
  print(key)

Obviously, insertion operators may not work, but that doesn't make much sense for a list of dictionary keys anyway.

How do I see if Wi-Fi is connected on Android?

Try

wifiManager.getConnectionInfo().getIpAddress()

This returns 0 until the device has a usable connection (on my machine, a Samsung SM-T280, Android 5.1.1).

Failed to load ApplicationContext for JUnit test of Spring controller

Solved by adding the following dependency into pom.xml file :

<dependency>
        <groupId>com.h2database</groupId>
        <artifactId>h2</artifactId>
        <scope>test</scope>
</dependency>

unsigned int vs. size_t

The size_t type is the unsigned integer type that is the result of the sizeof operator (and the offsetof operator), so it is guaranteed to be big enough to contain the size of the biggest object your system can handle (e.g., a static array of 8Gb).

The size_t type may be bigger than, equal to, or smaller than an unsigned int, and your compiler might make assumptions about it for optimization.

You may find more precise information in the C99 standard, section 7.17, a draft of which is available on the Internet in pdf format, or in the C11 standard, section 7.19, also available as a pdf draft.

How to get a substring between two strings in PHP?

function getBetween($string, $start = "", $end = ""){
    if (strpos($string, $start)) { // required if $start not exist in $string
        $startCharCount = strpos($string, $start) + strlen($start);
        $firstSubStr = substr($string, $startCharCount, strlen($string));
        $endCharCount = strpos($firstSubStr, $end);
        if ($endCharCount == 0) {
            $endCharCount = strlen($firstSubStr);
        }
        return substr($firstSubStr, 0, $endCharCount);
    } else {
        return '';
    }
}

Sample use:

echo getBetween("abc","a","c"); // returns: 'b'

echo getBetween("hello","h","o"); // returns: 'ell'

echo getBetween("World","a","r"); // returns: ''

Is there a cross-domain iframe height auto-resizer that works?

You have three alternatives:

1. Use iFrame-resizer

This is a simple library for keeping iFrames sized to their content. It uses the PostMessage and MutationObserver APIs, with fall backs for IE8-10. It also has options for the content page to request the containing iFrame is a certain size and can also close the iFrame when your done with it.

https://github.com/davidjbradshaw/iframe-resizer

2. Use Easy XDM (PostMessage + Flash combo)

Easy XDM uses a collection of tricks for enabling cross-domain communication between different windows in a number of browsers, and there are examples for using it for iframe resizing:

http://easyxdm.net/wp/2010/03/17/resize-iframe-based-on-content/

http://kinsey.no/blog/index.php/2010/02/19/resizing-iframes-using-easyxdm/

Easy XDM works by using PostMessage on modern browsers and a Flash based solution as fallback for older browsers.

See also this thread on Stackoverflow (there are also others, this is a commonly asked question). Also, Facebook would seem to use a similar approach.

3. Communicate via a server

Another option would be to send the iframe height to your server and then poll from that server from the parent web page with JSONP (or use a long poll if possible).

Heroku 'Permission denied (publickey) fatal: Could not read from remote repository' woes

I had the same issue. And I tried to reset my keys as everyone said, but it still didn't worked. For was because I renamed the app.

So what I did was to reset my keys and also rename app from console. Check this question for more information: Heroku push app problem

How can I get all the request headers in Django?

For what it's worth, it appears your intent is to use the incoming HTTP request to form another HTTP request. Sort of like a gateway. There is an excellent module django-revproxy that accomplishes exactly this.

The source is a pretty good reference on how to accomplish what you are trying to do.

How to get a variable name as a string in PHP?

From php.net

@Alexandre - short solution

<?php
function vname(&$var, $scope=0)
{
    $old = $var;
    if (($key = array_search($var = 'unique'.rand().'value', !$scope ? $GLOBALS : $scope)) && $var = $old) return $key;  
}
?>

@Lucas - usage

<?php
//1.  Use of a variable contained in the global scope (default):
  $my_global_variable = "My global string.";
  echo vname($my_global_variable); // Outputs:  my_global_variable

//2.  Use of a local variable:
  function my_local_func()
  {
    $my_local_variable = "My local string.";
    return vname($my_local_variable, get_defined_vars());
  }
  echo my_local_func(); // Outputs: my_local_variable

//3.  Use of an object property:
  class myclass
  {
    public function __constructor()
    {
      $this->my_object_property = "My object property  string.";
    }
  }
  $obj = new myclass;
  echo vname($obj->my_object_property, $obj); // Outputs: my_object_property
?>

Moment.js get day name from date

With moment you can parse the date string you have:

var dt = moment(myDate.date, "YYYY-MM-DD HH:mm:ss")

That's for UTC, you'll have to convert the time zone from that point if you so desire.

Then you can get the day of the week:

dt.format('dddd');

Write string to output stream

You can create a PrintStream wrapping around your OutputStream and then just call it's print(String):

final OutputStream os = new FileOutputStream("/tmp/out");
final PrintStream printStream = new PrintStream(os);
printStream.print("String");
printStream.close();

SQL Query To Obtain Value that Occurs more than once

For MySQL:

SELECT lastname AS ln 
    FROM 
    (SELECT lastname, count(*) as Counter 
     FROM `students` 
     GROUP BY `lastname`) AS tbl WHERE Counter > 2

Detecting iOS orientation change instantly

Try making your changes in:

- (void) viewWillLayoutSubviews {}

The code will run at every orientation change as the subviews get laid out again.

Bootstrap Carousel : Remove auto slide

From the official docs:

interval The amount of time to delay between automatically cycling an item. If false, carousel will not automatically cycle.

You can either pass this value with javascript or using a data-interval="false" attribute.

How to make a countdown timer in Android?

public class Scan extends AppCompatActivity {
int minute;
long min;
TextView tv_timer;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_scan2);
    tv_timer=findViewById(R.id.tv_timer);
    minute=Integer.parseInt("Your time in string form like 10");
    min= minute*60*1000;
    counter(min);
}
private void counter(long min) {
    CountDownTimer timer = new CountDownTimer(min, 1000) {
        public void onTick(long millisUntilFinished) {
            int seconds = (int) (millisUntilFinished / 1000) % 60;
            int minutes = (int) ((millisUntilFinished / (1000 * 60)) % 60);
            int hours = (int) ((millisUntilFinished / (1000 * 60 * 60)) % 24);
            tv_timer.setText(String.format("%d:%d:%d", hours, minutes, seconds));
        }
        public void onFinish() {
            Toast.makeText(getApplicationContext(), "Your time has been completed",
                    Toast.LENGTH_LONG).show();
        }
    };
    timer.start();
}

}

PHP Session data not being saved

I had session cookie path set to "//" instead of "/". Firebug is awesome. Hope it helps somebody.

Naming Conventions: What to name a boolean variable?

Haskell uses init to refer to all but the last element of a list (the inverse of tail, basically); would isInInit work, or is that too opaque?

How to set focus to a button widget programmatically?

Yeah it's possible.

Button myBtn = (Button)findViewById(R.id.myButtonId);
myBtn.requestFocus();

or in XML

<Button ...><requestFocus /></Button>

Important Note: The button widget needs to be focusable and focusableInTouchMode. Most widgets are focusable but not focusableInTouchMode by default. So make sure to either set it in code

myBtn.setFocusableInTouchMode(true);

or in XML

android:focusableInTouchMode="true"

How I can check if an object is null in ruby on rails 2?

In your example, you can simply replace null with `nil and it will work fine.

require 'erb'

template = <<EOS
<% if (@objectname != nil) then %>
  @objectname is not nil
<% else %>
  @objectname is nil
<% end %>
EOS

@objectname = nil
ERB.new(template, nil, '>').result # => "  @objectname is nil\n"

@objectname = 'some name'
ERB.new(template, nil, '>').result # => "  @objectname is not nil\n"

Contrary to what the other poster said, you can see above that then works fine in Ruby. It's not common, but it is fine.

#blank? and #present? have other implications. Specifically, if the object responds to #empty?, they will check whether it is empty. If you go to http://api.rubyonrails.org/ and search for "blank?", you will see what objects it is defined on and how it works. Looking at the definition on Object, we see "An object is blank if it’s false, empty, or a whitespace string. For example, “”, “ ”, nil, [], and {} are all blank." You should make sure that this is what you want.

Also, nil is considered false, and anything other than false and nil is considered true. This means you can directly place the object in the if statement, so a more canonical way of writing the above would be

require 'erb'

template = <<EOS
<% if @objectname %>
  @objectname is not nil
<% else %>
  @objectname is nil
<% end %>
EOS

@objectname = nil
ERB.new(template, nil, '>').result # => "  @objectname is nil\n"

@objectname = 'some name'
ERB.new(template, nil, '>').result # => "  @objectname is not nil\n"

If you explicitly need to check nil and not false, you can use the #nil? method, for which nil is the only object that will cause this to return true.

nil.nil?          # => true
false.nil?        # => false
Object.new.nil?   # => false

Easiest way to detect Internet connection on iOS?

I currently use this simple synchronous method which requires no extra files in your projects or delegates.

Import:

#import <SystemConfiguration/SCNetworkReachability.h>

Create this method:

+(bool)isNetworkAvailable
{
    SCNetworkReachabilityFlags flags;
    SCNetworkReachabilityRef address;
    address = SCNetworkReachabilityCreateWithName(NULL, "www.apple.com" );
    Boolean success = SCNetworkReachabilityGetFlags(address, &flags);
    CFRelease(address);

    bool canReach = success
                    && !(flags & kSCNetworkReachabilityFlagsConnectionRequired)
                    && (flags & kSCNetworkReachabilityFlagsReachable);

    return canReach;
}

Then, if you've put this in a MyNetworkClass:

if( [MyNetworkClass isNetworkAvailable] )
{
   // do something networky.
}

If you are testing in the simulator, turn your Mac's wifi on and off, as it appears the simulator will ignore the phone setting.

Update:

  1. In the end I used a thread/asynchronous callback to avoid blocking the main thread; and regularly re-testing so I could use a cached result - although you should avoid keeping data connections open unnecessarily.

  2. As @thunk described, there are better URLs to use, which Apple themselves use. http://cadinc.com/blog/why-your-apple-ios-7-device-wont-connect-to-the-wifi-network

Cookies vs. sessions

Short answer

Rules ordered by priority:

  • Rule 1. Never trust user input : cookies are not safe. Use sessions for sensitive data.
  • Rule 2. If persistent data must remain when the user closes the browser, use cookies.
  • Rule 3. If persistent data does not have to remain when the user closes the browser, use sessions.
  • Rule 4. Read the detailed answer!

Source : https://www.lucidar.me/en/web-dev/sessions-or-cookies/


Detailed answer

Cookies

  • Cookies are stored on the client side (in the visitor's browser).
  • Cookies are not safe: it's quite easy to read and write cookie contents.
  • When using cookies, you have to notify visitors according to european laws (GDPR).
  • Expiration can be set, but user or browser can change it.
  • Users (or browser) can (be set to) decline the use of cookies.

Sessions

  • Sessions are stored on the server side.
  • Sessions use cookies (see below).
  • Sessions are safer than cookies, but not invulnarable.
  • Expiration is set in server configuration (php.ini for example).
  • Default expiration time is 24 minutes or when the browser is closed.
  • Expiration is reset when the user refreshes or loads a new page.
  • Users (or browser) can (be set to) decline the use of cookies, therefore sessions.
  • Legally, you also have to notify visitors for the cookie, but the lack of precedent is not clear yet.

The appropriate choice

Sessions use a cookie! Session data is stored on the server side, but a UID is stored on client side in a cookie. It allows the server to match a given user with the right session data. UID is protected and hard to hack, but not invulnarable. For sensitive actions (changing email or resetting password), do not rely on sessions neither cookies : ask for the user password to confirm the action.

Sensitive data should never be stored in cookies (emails, encrypted passwords, personal data ...). Keep in mind the data are stored on a foreign computer, and if the computer is not private (classroom or public computers) someone else can potentially read the cookies content.

Remember-me data must be stored in cookies, otherwise data will be lost when the user closes the browser. However, don't save password or user personal data in the 'remember-me' cookie. Store user data in database and link this data with an encrypted pair of ID / key stored in a cookie.

After considering the previous recommandations, the following question is finally what helps you choosing between cookies and sessions:

Must persistent data remain when the user closes the browser ?

  • If the answer is yes, use cookies.
  • If the answer is no, use sessions.

Pagination using MySQL LIMIT, OFFSET

Use .. LIMIT :pageSize OFFSET :pageStart

Where :pageStart is bound to the_page_index (i.e. 0 for the first page) * number_of_items_per_pages (e.g. 4) and :pageSize is bound to number_of_items_per_pages.

To detect for "has more pages", either use SQL_CALC_FOUND_ROWS or use .. LIMIT :pageSize OFFSET :pageStart + 1 and detect a missing last (pageSize+1) record. Needless to say, for pages with an index > 0, there exists a previous page.

If the page index value is embedded in the URL (e.g. in "prev page" and "next page" links) then it can be obtained via the appropriate $_GET item.

How do I wait for a promise to finish before returning the variable of a function?

You don't want to make the function wait, because JavaScript is intended to be non-blocking. Rather return the promise at the end of the function, then the calling function can use the promise to get the server response.

var promise = query.find(); 
return promise; 

//Or return query.find(); 

How to create Java gradle project

The gradle guys are doing their best to solve all (y)our problems ;-). They recently (since 1.9) added a new feature (incubating): the "build init" plugin.

See: build init plugin documentation

Foreach loop in C++ equivalent of C#

using C++ 14:

#include <string>
#include <vector>


std::vector<std::string> listbox;
...
std::vector<std::string> strarr {"ram","mohan","sita"};    
for (const auto &str : strarr)
{
    listbox.push_back(str);
}

Javascript: How to check if a string is empty?

If you want to know if it's an empty string use === instead of ==.

if(variable === "") {
}

This is because === will only return true if the values on both sides are of the same type, in this case a string.

for example: (false == "") will return true, and (false === "") will return false.

#1045 - Access denied for user 'root'@'localhost' (using password: YES)

Try the following code:

$cfg['Servers'][$i]['password'] = '';

if you see Password column field as 'No' for the 'root' user in Users Overview page of phpMyAdmin.

How to concatenate two strings in C++?

C++14

std::string great = "Hello"s + " World"; // concatenation easy!

Answer on the question:

auto fname = ""s + name + ".txt";

High Quality Image Scaling Library

This might help

    public Image ResizeImage(Image source, RectangleF destinationBounds)
    {
        RectangleF sourceBounds = new RectangleF(0.0f,0.0f,(float)source.Width, (float)source.Height);
        RectangleF scaleBounds = new RectangleF();

        Image destinationImage = new Bitmap((int)destinationBounds.Width, (int)destinationBounds.Height);
        Graphics graph = Graphics.FromImage(destinationImage);
        graph.InterpolationMode =
            System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;

        // Fill with background color
        graph.FillRectangle(new SolidBrush(System.Drawing.Color.White), destinationBounds);

        float resizeRatio, sourceRatio;
        float scaleWidth, scaleHeight;

        sourceRatio = (float)source.Width / (float)source.Height;

        if (sourceRatio >= 1.0f)
        {
            //landscape
            resizeRatio = destinationBounds.Width / sourceBounds.Width;
            scaleWidth = destinationBounds.Width;
            scaleHeight = sourceBounds.Height * resizeRatio;
            float trimValue = destinationBounds.Height - scaleHeight;
            graph.DrawImage(source, 0, (trimValue / 2), destinationBounds.Width, scaleHeight);
        }
        else
        {
            //portrait
            resizeRatio = destinationBounds.Height/sourceBounds.Height;
            scaleWidth = sourceBounds.Width * resizeRatio;
            scaleHeight = destinationBounds.Height;
            float trimValue = destinationBounds.Width - scaleWidth;
            graph.DrawImage(source, (trimValue / 2), 0, scaleWidth, destinationBounds.Height);
        }

        return destinationImage;

    }

Note the InterpolationMode.HighQualityBicubic -> this is generally a good tradeoff between performance and results.

Which programming languages can be used to develop in Android?

Scala is supported. See example.

Support for other languages is problematic:

7) Something like the dx tool can be forced into the phone, so that Java code could in principle continue to generate bytecodes, yet have them be translated into a VM-runnable form. But, at present, Java code cannot be generated on the fly. This means Dalvik cannot run dynamic languages (JRuby, Jython, Groovy). Yet. (Perhaps the dex format needs a detuned variant which can be easily generated from bytecodes.)

How do I negate a condition in PowerShell?

If you are like me and dislike the double parenthesis, you can use a function

function not ($cm, $pm) {
  if (& $cm $pm) {0} else {1}
}

if (not Test-Path C:\Code) {'it does not exist!'}

Example

iPhone Debugging: How to resolve 'failed to get the task for process'?

I just changed my bundleIdentifier name, that seemed to do the trick.

Remove duplicate values from JS array

The top answers have complexity of O(n²), but this can be done with just O(n) by using an object as a hash:

function getDistinctArray(arr) {
    var dups = {};
    return arr.filter(function(el) {
        var hash = el.valueOf();
        var isDup = dups[hash];
        dups[hash] = true;
        return !isDup;
    });
}

This will work for strings, numbers, and dates. If your array contains objects, the above solution won't work because when coerced to a string, they will all have a value of "[object Object]" (or something similar) and that isn't suitable as a lookup value. You can get an O(n) implementation for objects by setting a flag on the object itself:

function getDistinctObjArray(arr) {
    var distinctArr = arr.filter(function(el) {
        var isDup = el.inArray;
        el.inArray = true;
        return !isDup;
    });
    distinctArr.forEach(function(el) {
        delete el.inArray;
    });
    return distinctArr;
}

2019 edit: Modern versions of JavaScript make this a much easier problem to solve. Using Set will work, regardless of whether your array contains objects, strings, numbers, or any other type.

function getDistinctArray(arr) {
    return [...new Set(arr)];
}

The implementation is so simple, defining a function is no longer warranted.

How do I create a self-signed certificate for code signing on Windows?

It's fairly easy using the New-SelfSignedCertificate command in Powershell. Open powershell and run these 3 commands.

1) Create certificate:
$cert = New-SelfSignedCertificate -DnsName www.yourwebsite.com -Type CodeSigning -CertStoreLocation Cert:\CurrentUser\My

2) set the password for it:
$CertPassword = ConvertTo-SecureString -String "my_passowrd" -Force –AsPlainText

3) Export it:
Export-PfxCertificate -Cert "cert:\CurrentUser\My\$($cert.Thumbprint)" -FilePath "d:\selfsigncert.pfx" -Password $CertPassword

Your certificate selfsigncert.pfx will be located @ D:/


Optional step: You would also require to add certificate password to system environment variables. do so by entering below in cmd: setx CSC_KEY_PASSWORD "my_password"

Check if value exists in enum in TypeScript

According to sandersn the best way to do this would be:

Object.values(MESSAGE_TYPE).includes(type as MESSAGE_TYPE)

ShowAllData method of Worksheet class failed

The simple way to avoid this is not to use the worksheet method ShowAllData

Autofilter has the same ShowAllData method which doesn't throw an error when the filter is enabled but no filter is set

If ActiveSheet.AutoFilterMode Then ActiveSheet.AutoFilter.ShowAllData

Downloading an entire S3 bucket?

Try this command:

aws s3 sync yourBucketnameDirectory yourLocalDirectory

For example, if your bucket name is myBucket and local directory is c:\local, then:

aws s3 sync s3://myBucket c:\local

For more informations about awscli check this aws cli installation

Difference between save and saveAndFlush in Spring data jpa

On saveAndFlush, changes will be flushed to DB immediately in this command. With save, this is not necessarily true, and might stay just in memory, until flush or commit commands are issued.

But be aware, that even if you flush the changes in transaction and do not commit them, the changes still won't be visible to the outside transactions until the commit in this transaction.

In your case, you probably use some sort of transactions mechanism, which issues commit command for you if everything works out fine.

Simple way to sort strings in the (case sensitive) alphabetical order

If you don't want to add a dependency on Guava (per Michael's answer) then this comparator is equivalent:

private static Comparator<String> ALPHABETICAL_ORDER = new Comparator<String>() {
    public int compare(String str1, String str2) {
        int res = String.CASE_INSENSITIVE_ORDER.compare(str1, str2);
        if (res == 0) {
            res = str1.compareTo(str2);
        }
        return res;
    }
};

Collections.sort(list, ALPHABETICAL_ORDER);

And I think it is just as easy to understand and code ...

The last 4 lines of the method can written more concisely as follows:

        return (res != 0) ? res : str1.compareTo(str2);

Redirecting to previous page after login? PHP

You should try something like $_SERVER['HTTP_REFERER'].

Speed tradeoff of Java's -Xms and -Xmx options

This was always the question I had when I was working on one of my application which created massive number of threads per request.

So this is a really good question and there are two aspects of this:
1. Whether my Xms and Xmx value should be same
       - Most websites and even oracle docs suggest it to be the same. However, I suggest to have some 10-20% of buffer between those values to give heap resizing an option to your application in case sudden high traffic spikes OR a incidental memory leak.

2. Whether I should start my Application with lower heap size
       - So here's the thing - no matter what GC Algo you use (even G1), large heap always has some trade off. The goal is to identify the behavior of your application to what heap size you can allow your GC pauses in terms of latency and throughput.
              - For example, if your application has lot of threads (each thread has 1 MB stack in native memory and not in heap) but does not occupy heavy object space, then I suggest have a lower value of Xms.
              - If your application creates lot of objects with increasing number of threads, then identify to what value of Xms you can set to tolerate those STW pauses. This means identify the max response time of your incoming requests you can tolerate and according tune the minimum heap size.

How can I refresh c# dataGridView after update ?

BindingSource is the only way without going for a 3rd party ORM, it may seem long winded at first but the benefits of one update method on the BindingSource are so helpful.

If your source is say for example a list of user strings

List<string> users = GetUsers();
BindingSource source = new BindingSource();
source.DataSource = users;
dataGridView1.DataSource = source;

then when your done editing just update your data object whether that be a DataTable or List of user strings like here and ResetBindings on the BindingSource;

users = GetUsers(); //Update your data object
source.ResetBindings(false);

How to get status code from webclient?

If you are using .Net 4.0 (or less):

class BetterWebClient : WebClient
{
        private WebRequest _Request = null;

        protected override WebRequest GetWebRequest(Uri address)
        {
            this._Request = base.GetWebRequest(address);

            if (this._Request is HttpWebRequest)
            {
                ((HttpWebRequest)this._Request).AllowAutoRedirect = false;
            }

            return this._Request;
        } 

        public HttpStatusCode StatusCode()
        {
            HttpStatusCode result;

            if (this._Request == null)
            {
                throw (new InvalidOperationException("Unable to retrieve the status 
                       code, maybe you haven't made a request yet."));
            }

            HttpWebResponse response = base.GetWebResponse(this._Request) 
                                       as HttpWebResponse;

            if (response != null)
            {
                result = response.StatusCode;
            }
            else
            {
                throw (new InvalidOperationException("Unable to retrieve the status 
                       code, maybe you haven't made a request yet."));
            }

            return result;
        }
    }

If you are using .Net 4.5.X or newer, switch to HttpClient:

var response = await client.GetAsync("http://www.contoso.com/");
var statusCode = response.StatusCode;

How can I write data attributes using Angular?

Use attribute binding syntax instead

<ol class="viewer-nav"><li *ngFor="let section of sections" 
    [attr.data-sectionvalue]="section.value">{{ section.text }}</li>  
</ol>

or

<ol class="viewer-nav"><li *ngFor="let section of sections" 
    attr.data-sectionvalue="{{section.value}}">{{ section.text }}</li>  
</ol>

See also :

How to run a cron job inside a docker container?

The adopted solution may be dangerous in a production environment.

In docker you should only execute one process per container because if you don't, the process that forked and went background is not monitored and may stop without you knowing it.

When you use CMD cron && tail -f /var/log/cron.log the cron process basically fork in order to execute cron in background, the main process exits and let you execute tailf in foreground. The background cron process could stop or fail you won't notice, your container will still run silently and your orchestration tool will not restart it.

You can avoid such a thing by redirecting directly the cron's commands output into your docker stdout and stderr which are located respectively in /proc/1/fd/1 and /proc/1/fd/2.

Using basic shell redirects you may want to do something like this :

* * * * * root echo hello > /proc/1/fd/1 2>/proc/1/fd/2

And your CMD will be : CMD ["cron", "-f"]

How to add include path in Qt Creator?

If you are using qmake, the standard Qt build system, just add a line to the .pro file as documented in the qmake Variable Reference:

INCLUDEPATH += <your path>

If you are using your own build system, you create a project by selecting "Import of Makefile-based project". This will create some files in your project directory including a file named <your project name>.includes. In that file, simply list the paths you want to include, one per line. Really all this does is tell Qt Creator where to look for files to index for auto completion. Your own build system will have to handle the include paths in its own way.

As explained in the Qt Creator Manual, <your path> must be an absolute path, but you can avoid OS-, host- or user-specific entries in your .pro file by using $$PWD which refers to the folder that contains your .pro file, e.g.

INCLUDEPATH += $$PWD/code/include

Hide div after a few seconds

You can try the .delay()

$(".formSentMsg").delay(3200).fadeOut(300);

call the div set the delay time in milliseconds and set the property you want to change, in this case I used .fadeOut() so it could be animated, but you can use .hide() as well.

http://api.jquery.com/delay/

How to keep an iPhone app running on background fully operational

From ioS 7 onwards, there are newer ways for apps to run in background. Apple now recognizes that apps have to constantly download and process data constantly.

Here is the new list of all the apps which can run in background.

  1. Apps that play audible content to the user while in the background, such as a music player app
  2. Apps that record audio content while in the background.
  3. Apps that keep users informed of their location at all times, such as a navigation app
  4. Apps that support Voice over Internet Protocol (VoIP)
  5. Apps that need to download and process new content regularly
  6. Apps that receive regular updates from external accessories

You can declare app's supported background tasks in Info.plist using X Code 5+. For eg. adding UIBackgroundModes key to your app’s Info.plist file and adding a value of 'fetch' to the array allows your app to regularly download and processes small amounts of content from the network. You can do the same in the 'capabilities' tab of Application properties in XCode 5 (attaching a snapshot)

Capabilities tab in XCode 5 You can find more about this in Apple documentation

How to order by with union in SQL?

To apply an ORDER BY or LIMIT clause to an individual SELECT, parenthesize the SELECT and place the clause inside the parentheses:

(SELECT a FROM t1 WHERE a=10 AND B=1 ORDER BY a LIMIT 10)
UNION
(SELECT a FROM t2 WHERE a=11 AND B=2 ORDER BY a LIMIT 10);

Phone number validation Android

We can use pattern to validate it.

android.util.Patterns.PHONE

public class GeneralUtils {

    private static boolean isValidPhoneNumber(String phoneNumber) {
        return !TextUtils.isEmpty(phoneNumber) && android.util.Patterns.PHONE.matcher(phoneNumber).matches();
    }

}

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

Please take a look at ack, which is designed for exactly these situations. Your example of

grep -ircl --exclude=*.{png,jpg} "foo=" *

is done with ack as

ack -icl "foo="

because ack never looks in binary files by default, and -r is on by default. And if you want only CPP and H files, then just do

ack -icl --cpp "foo="

Retrieve a Fragment from a ViewPager

In Fragment

public int getArgument(){
   return mPage;
{
public void update(){

}

In FragmentActivity

List<Fragment> fragments = getSupportFragmentManager().getFragments();
for(Fragment f:fragments){
    if((f instanceof PageFragment)&&(!f.isDetached())){
          PageFragment pf = (PageFragment)f;   
          if(pf.getArgument()==pager.getCurrentItem())pf.update();
    }
}

Convert dictionary to list collection in C#

If you want to pass the Dictionary keys collection into one method argument.

List<string> lstKeys = Dict.Keys;
Methodname(lstKeys);
-------------------
void MethodName(List<String> lstkeys)
{
    `enter code here`
    //Do ur task
}

Hide password with "•••••••" in a textField

For SwiftUI, try

TextField ("Email", text: $email)
    .textFieldStyle(RoundedBorderTextFieldStyle()).padding()
SecureField ("Password", text: $password)
    .textFieldStyle(RoundedBorderTextFieldStyle()).padding()

Font.createFont(..) set color and size (java.awt.Font)

Well, once you have your font, you can invoke deriveFont. For example,

helvetica = helvetica.deriveFont(Font.BOLD, 12f);

Changes the font's style to bold and its size to 12 points.

Array of an unknown length in C#

In a nutshell, please use Collections and Generics.

It's a must for any C# developer, it's worth spending time to learn :)

How can I show a message box with two buttons?

It can be done, I found it elsewhere on the web...this is no way my work ! :)

    Option Explicit
' Import
Private Declare Function GetCurrentThreadId Lib "kernel32" () As Long

Private Declare Function SetDlgItemText Lib "user32" _
    Alias "SetDlgItemTextA" _
    (ByVal hDlg As Long, _
     ByVal nIDDlgItem As Long, _
     ByVal lpString As String) As Long

Private Declare Function SetWindowsHookEx Lib "user32" _
    Alias "SetWindowsHookExA" _
    (ByVal idHook As Long, _
     ByVal lpfn As Long, _
     ByVal hmod As Long, _
     ByVal dwThreadId As Long) As Long

Private Declare Function UnhookWindowsHookEx Lib "user32" _
    (ByVal hHook As Long) As Long

' Handle to the Hook procedure
Private hHook As Long

' Hook type
Private Const WH_CBT = 5
Private Const HCBT_ACTIVATE = 5

' Constants
Public Const IDOK = 1
Public Const IDCANCEL = 2
Public Const IDABORT = 3
Public Const IDRETRY = 4
Public Const IDIGNORE = 5
Public Const IDYES = 6
Public Const IDNO = 7

Public Sub MsgBoxSmile()
    ' Set Hook
    hHook = SetWindowsHookEx(WH_CBT, _
                             AddressOf MsgBoxHookProc, _
                             0, _
                             GetCurrentThreadId)

    ' Run MessageBox
    MsgBox "Smiling Message Box", vbYesNo, "Message Box Hooking"
End Sub

Private Function MsgBoxHookProc(ByVal lMsg As Long, _
                                ByVal wParam As Long, _
                                ByVal lParam As Long) As Long

    If lMsg = HCBT_ACTIVATE Then
        SetDlgItemText wParam, IDYES, "Yes   :-)"
        SetDlgItemText wParam, IDNO, "No   :-("

        ' Release the Hook
        UnhookWindowsHookEx hHook
    End If

    MsgBoxHookProc = False
End Function

How to solve "Plugin execution not covered by lifecycle configuration" for Spring Data Maven Builds

I followed the GUI hint to finding any connector, and then I found AspectJ Integrator from SpringSource Team. After installation, it was settled.

How to center horizontally div inside parent div

<div id='child' style='width: 50px; height: 100px; margin:0 auto;'>Text</div>

Add values to app.config and retrieve them

sorry for late answer but may be my code may help u.

I placed 3 buttons on the winform surface. button1 & 2 will set different value and button3 will retrieve current value. so when run my code first add the reference System.configuration

and click on first button and then click on 3rd button to see what value has been set. next time again click on second & 3rd button to see again what value has been set after change.

so here is the code.

using System.Configuration;

 private void button1_Click(object sender, EventArgs e)
{
    Configuration config = ConfigurationManager.OpenExeConfiguration(Application.ExecutablePath);
    config.AppSettings.Settings.Remove("DBServerName");
    config.AppSettings.Settings.Add("DBServerName", "FirstAddedValue1");
    config.Save(ConfigurationSaveMode.Modified);
}

private void button2_Click(object sender, EventArgs e)
{
    Configuration config = ConfigurationManager.OpenExeConfiguration(Application.ExecutablePath);
    config.AppSettings.Settings.Remove("DBServerName");
    config.AppSettings.Settings.Add("DBServerName", "SecondAddedValue1");
    config.Save(ConfigurationSaveMode.Modified);
}

private void button3_Click(object sender, EventArgs e)
{
    Configuration config = ConfigurationManager.OpenExeConfiguration(Application.ExecutablePath);
          MessageBox.Show(config.AppSettings.Settings["DBServerName"].Value);
}

Using "margin: 0 auto;" in Internet Explorer 8

It is a bug in IE8.

Starting with your second question: “margin: 0 auto” centers a block, but only when width of the block is set to be less that width of parent. Usually, they get to be the same. That is why text in the example below is not centered.

<div style="height: 100px; width: 500px; background-color: Yellow;">    
    <b style="display: block; margin: 0 auto; ">text</b>
</div>

Once the display style of the b element is set to block, its width defaults to the parents width. CSS spec 10.3.3 Block-level, non-replaced elements in normal flow describes how: “If 'width' is set to 'auto', any other 'auto' values become '0' and 'width' follows from the resulting equality.” The equality mentioned there is

'margin-left' + 'border-left-width' + 'padding-left' + 'width' + 'padding-right' + 'border-right-width' + 'margin-right' = width of containing block

So, normally all autos result in a block width being equal to the width of containing block.

However, this calculation should not be applied to INPUT, which is a replaced element. Replaced elements are covered by 10.3.4 Block-level, replaced elements in normal flow. Text there says: “The used value of 'width' is determined as for inline replaced elements.” The relevant part of 10.3.2 Inline, replaced elements is: “if 'width' has a computed value of 'auto', and the element has an intrinsic width, then that intrinsic width is the used value of 'width'”.

I guess that the scenario CSS cares about is IMG element. Stackoverflow logo in this example will be centered by all browsers.

<div style="height: 100px; width: 500px; background-color: Yellow;">    
    <img style="display: block; margin: 0 auto; " border="0" src="http://stackoverflow.com/content/img/so/logo.png" alt="">
</div>

INPUT element should behave the same way.

css h1 - only as wide as the text

You could use a <span> instead of an <h1>.

How to reset db in Django? I get a command 'reset' not found error

If you want to clean the whole database, you can use: python manage.py flush If you want to clean database table of a Django app, you can use: python manage.py migrate appname zero

Django DateField default options

You could also use lambda. Useful if you're using django.utils.timezone.now

date = models.DateField(_("Date"), default=lambda: now().date())

How to show a GUI message box from a bash script in linux?

I believe Zenity will do what you want. It's specifically designed for displaying GTK dialogs from the command line, and it's available as an Ubuntu package.

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

Making the iPhone vibrate

You can use

1) AudioServicesPlayAlertSound(kSystemSoundID_Vibrate);

for iPhone and few newer iPods.

2) AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);

for iPads.

How to install an apk on the emulator in Android Studio?

enter image description here

When you start Android studio Look for Profile or Debug apk.

After clicking you get the option to browse for the saved apk and you will be bale to later run it using emulator

How to clone git repository with specific revision/changeset?

To clone only one single specific commit on a particular branch or tag use:

git clone --depth=1 --branch NAME https://github.com/your/repo.git

Unfortunately, NAME can only be branch name or tag name (not commit SHA).

Omit the --depth flag to download the whole history and then checkout that branch or tag:

git clone --branch NAME https://github.com/your/repo.git

This works with recent version of git (I did it with version 2.18.0).

How to center a table of the screen (vertically and horizontally)

I tried above align attribute in HTML5. It is not supported. Also I tried flex-align and vertival-align with style attributes. Still not able to place TABLE in center of screen. The following style place table in center horizontally.

style="margin:auto;"

Java and unlimited decimal places?

I believe that you are looking for the java.lang.BigDecimal class.

Exclude all transitive dependencies of a single dependency

Currently, there's no way to exclude more than one transitive dependency at a time, but there is a feature request for this on the Maven JIRA site:

https://issues.apache.org/jira/browse/MNG-2315

Does hosts file exist on the iPhone? How to change it?

This doesn't directly answer your question, but it does solve your problem...

What make of router do you have? Your router firmware may allow you to set DNS records for your local network. This is what I do with the Tomato firmware

How to convert jsonString to JSONObject in Java

Better Go with more simpler way by using org.json lib. Just do a very simple approach as below:

JSONObject obj = new JSONObject();
obj.put("phonetype", "N95");
obj.put("cat", "WP");

Now obj is your converted JSONObject form of your respective String. This is in case if you have name-value pairs.

For a string you can directly pass to the constructor of JSONObject. If it'll be a valid json String, then okay otherwise it'll throw an exception.

Get last field using awk substr

Use the fact that awk splits the lines in fields based on a field separator, that you can define. Hence, defining the field separator to / you can say:

awk -F "/" '{print $NF}' input

as NF refers to the number of fields of the current record, printing $NF means printing the last one.

So given a file like this:

/home/parent/child1/child2/child3/filename
/home/parent/child1/child2/filename
/home/parent/child1/filename

This would be the output:

$ awk -F"/" '{print $NF}' file
filename
filename
filename

How to detect a USB drive has been plugged in?

Microsoft API Code Pack. ShellObjectWatcher class.

Javascript - How to detect if document has loaded (IE 7/Firefox 3)

No need for a library. jQuery used this script for a while, btw.

http://dean.edwards.name/weblog/2006/06/again/

// Dean Edwards/Matthias Miller/John Resig

function init() {
  // quit if this function has already been called
  if (arguments.callee.done) return;

  // flag this function so we don't do the same thing twice
  arguments.callee.done = true;

  // kill the timer
  if (_timer) clearInterval(_timer);

  // do stuff
};

/* for Mozilla/Opera9 */
if (document.addEventListener) {
  document.addEventListener("DOMContentLoaded", init, false);
}

/* for Internet Explorer */
/*@cc_on @*/
/*@if (@_win32)
  document.write("<script id=__ie_onload defer src=javascript:void(0)><\/script>");
  var script = document.getElementById("__ie_onload");
  script.onreadystatechange = function() {
    if (this.readyState == "complete") {
      init(); // call the onload handler
    }
  };
/*@end @*/

/* for Safari */
if (/WebKit/i.test(navigator.userAgent)) { // sniff
  var _timer = setInterval(function() {
    if (/loaded|complete/.test(document.readyState)) {
      init(); // call the onload handler
    }
  }, 10);
}

/* for other browsers */
window.onload = init;

Numpy AttributeError: 'float' object has no attribute 'exp'

Probably there's something wrong with the input values for X and/or T. The function from the question works ok:

import numpy as np
from math import e

def sigmoid(X, T):
  return 1.0 / (1.0 + np.exp(-1.0 * np.dot(X, T)))

X = np.array([[1, 2, 3], [5, 0, 0]])
T = np.array([[1, 2], [1, 1], [4, 4]])

print(X.dot(T))
# Just to see if values are ok
print([1. / (1. + e ** el) for el in [-5, -10, -15, -16]])
print()
print(sigmoid(X, T))

Result:

[[15 16]
 [ 5 10]]

[0.9933071490757153, 0.9999546021312976, 0.999999694097773, 0.9999998874648379]

[[ 0.99999969  0.99999989]
 [ 0.99330715  0.9999546 ]]

Probably it's the dtype of your input arrays. Changing X to:

X = np.array([[1, 2, 3], [5, 0, 0]], dtype=object)

Gives:

Traceback (most recent call last):
  File "/[...]/stackoverflow_sigmoid.py", line 24, in <module>
    print sigmoid(X, T)
  File "/[...]/stackoverflow_sigmoid.py", line 14, in sigmoid
    return 1.0 / (1.0 + np.exp(-1.0 * np.dot(X, T)))
AttributeError: exp

How to automatically import data from uploaded CSV or XLS file into Google Sheets

In case anyone would be searching - I created utility for automated import of xlsx files into google spreadsheet: xls2sheets. One can do it automatically via setting up the cronjob for ./cmd/sheets-refresh, readme describes it all. Hope that would be of use.

How to programmatically send a 404 response with Express/Node?

According to the site I'll post below, it's all how you set up your server. One example they show is this:

var http = require("http");
var url = require("url");

function start(route, handle) {
  function onRequest(request, response) {
    var pathname = url.parse(request.url).pathname;
    console.log("Request for " + pathname + " received.");

    route(handle, pathname, response);
  }

  http.createServer(onRequest).listen(8888);
  console.log("Server has started.");
}

exports.start = start;

and their route function:

function route(handle, pathname, response) {
  console.log("About to route a request for " + pathname);
  if (typeof handle[pathname] === 'function') {
    handle[pathname](response);
  } else {
    console.log("No request handler found for " + pathname);
    response.writeHead(404, {"Content-Type": "text/plain"});
    response.write("404 Not found");
    response.end();
  }
}

exports.route = route;

This is one way. http://www.nodebeginner.org/

From another site, they create a page and then load it. This might be more of what you're looking for.

fs.readFile('www/404.html', function(error2, data) {
            response.writeHead(404, {'content-type': 'text/html'});
            response.end(data);
        });

http://blog.poweredbyalt.net/?p=81

WebAPI to Return XML

Here's another way to be compatible with an IHttpActionResult return type. In this case I am asking it to use the XML Serializer(optional) instead of Data Contract serializer, I'm using return ResponseMessage( so that I get a return compatible with IHttpActionResult:

return ResponseMessage(new HttpResponseMessage(HttpStatusCode.OK)
       {
           Content = new ObjectContent<SomeType>(objectToSerialize, 
              new System.Net.Http.Formatting.XmlMediaTypeFormatter { 
                  UseXmlSerializer = true 
              })
       });

Android: How to Programmatically set the size of a Layout

Java

This should work:

// Gets linearlayout
LinearLayout layout = findViewById(R.id.numberPadLayout);
// Gets the layout params that will allow you to resize the layout
LayoutParams params = layout.getLayoutParams();
// Changes the height and width to the specified *pixels*
params.height = 100;
params.width = 100;
layout.setLayoutParams(params);

If you want to convert dip to pixels, use this:

int height = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, <HEIGHT>, getResources().getDisplayMetrics());

Kotlin

How to split/partition a dataset into training and test datasets for, e.g., cross validation?

Thanks pberkes for your answer. I just modified it to avoid (1) replacement while sampling (2) duplicated instances occurred in both training and testing:

training_idx = np.random.choice(X.shape[0], int(np.round(X.shape[0] * 0.8)),replace=False)
training_idx = np.random.permutation(np.arange(X.shape[0]))[:np.round(X.shape[0] * 0.8)]
    test_idx = np.setdiff1d( np.arange(0,X.shape[0]), training_idx)

- java.lang.NullPointerException - setText on null object reference

Here lies your problem:

private void fillTextView (int id, String text) {
    TextView tv = (TextView) findViewById(id);
    tv.setText(text); // tv is null
}

--> (TextView) findViewById(id); // returns null But from your code, I can't find why this method returns null. Try to track down, what id you give as a parameter and if this view with the specified id exists.

The error message is very clear and even tells you at what method. From the documentation:

public final View findViewById (int id)
    Look for a child view with the given id. If this view has the given id, return this view.
    Parameters
        id  The id to search for.
    Returns
        The view that has the given id in the hierarchy or null

http://developer.android.com/reference/android/view/View.html#findViewById%28int%29

In other words: You have no view with the id you give as a parameter.

How to import a JSON file in ECMAScript 6?

I'm using babel+browserify and I have a JSON file in a directory ./i18n/locale-en.json with translations namespace (to be used with ngTranslate).

Without having to export anything from the JSON file (which btw is not possible), I could make a default import of its content with this syntax:

import translationsJSON from './i18n/locale-en';

upgade python version using pip

pip is designed to upgrade python packages and not to upgrade python itself. pip shouldn't try to upgrade python when you ask it to do so.

Don't type pip install python but use an installer instead.

Comparing two dictionaries and checking how many (key, value) pairs are equal

If you want to know how many values match in both the dictionaries, you should have said that :)

Maybe something like this:

shared_items = {k: x[k] for k in x if k in y and x[k] == y[k]}
print len(shared_items)

Boolean Field in Oracle

The best option is 0 and 1 (as numbers - another answer suggests 0 and 1 as CHAR for space-efficiency but that's a bit too twisted for me), using NOT NULL and a check constraint to limit contents to those values. (If you need the column to be nullable, then it's not a boolean you're dealing with but an enumeration with three values...)

Advantages of 0/1:

  • Language independent. 'Y' and 'N' would be fine if everyone used it. But they don't. In France they use 'O' and 'N' (I have seen this with my own eyes). I haven't programmed in Finland to see whether they use 'E' and 'K' there - no doubt they're smarter than that, but you can't be sure.
  • Congruent with practice in widely-used programming languages (C, C++, Perl, Javascript)
  • Plays better with the application layer e.g. Hibernate
  • Leads to more succinct SQL, for example, to find out how many bananas are ready to eat select sum(is_ripe) from bananas instead of select count(*) from bananas where is_ripe = 'Y' or even (yuk) select sum(case is_ripe when 'Y' then 1 else 0) from bananas

Advantages of 'Y'/'N':

  • Takes up less space than 0/1
  • It's what Oracle suggests, so might be what some people are more used to

Another poster suggested 'Y'/null for performance gains. If you've proven that you need the performance, then fair enough, but otherwise avoid since it makes querying less natural (some_column is null instead of some_column = 0) and in a left join you'll conflate falseness with nonexistent records.

How to parse/read a YAML file into a Python object?

Here is one way to test which YAML implementation the user has selected on the virtualenv (or the system) and then define load_yaml_file appropriately:

load_yaml_file = None

if not load_yaml_file:
    try:
        import yaml
        load_yaml_file = lambda fn: yaml.load(open(fn))
    except:
        pass

if not load_yaml_file:
    import commands, json
    if commands.getstatusoutput('ruby --version')[0] == 0:
        def load_yaml_file(fn):
            ruby = "puts YAML.load_file('%s').to_json" % fn
            j = commands.getstatusoutput('ruby -ryaml -rjson -e "%s"' % ruby)
            return json.loads(j[1])

if not load_yaml_file:
    import os, sys
    print """
ERROR: %s requires ruby or python-yaml  to be installed.

apt-get install ruby

  OR

apt-get install python-yaml

  OR

Demonstrate your mastery of Python by using pip.
Please research the latest pip-based install steps for python-yaml.
Usually something like this works:
   apt-get install epel-release
   apt-get install python-pip
   apt-get install libyaml-cpp-dev
   python2.7 /usr/bin/pip install pyyaml
Notes:
Non-base library (yaml) should never be installed outside a virtualenv.
"pip install" is permanent:
  https://stackoverflow.com/questions/1550226/python-setup-py-uninstall
Beware when using pip within an aptitude or RPM script.
  Pip might not play by all the rules.
  Your installation may be permanent.
Ruby is 7X faster at loading large YAML files.
pip could ruin your life.
  https://stackoverflow.com/questions/46326059/
  https://stackoverflow.com/questions/36410756/
  https://stackoverflow.com/questions/8022240/
Never use PyYaml in numerical applications.
  https://stackoverflow.com/questions/30458977/
If you are working for a Fortune 500 company, your choices are
1. Ask for either the "ruby" package or the "python-yaml"
package. Asking for Ruby is more likely to get a fast answer.
2. Work in a VM. I highly recommend Vagrant for setting it up.

""" % sys.argv[0]
    os._exit(4)


# test
import sys
print load_yaml_file(sys.argv[1])

How do I run PHP code when a user clicks on a link?

If you haven't yet installed jquery (because you're just a beginner or something), use this bit of code:

<a href="#" onclick="thisfunction()">link</a>

<script type="text/javascript">
function thisfunction(){
    var x = new XMLHttpRequest();
    x.open("GET","function.php",true);
    x.send();
    return false;
}
</script>

How to use a variable inside a regular expression?

From python 3.6 on you can also use Literal String Interpolation, "f-strings". In your particular case the solution would be:

if re.search(rf"\b(?=\w){TEXTO}\b(?!\w)", subject, re.IGNORECASE):
    ...do something

EDIT:

Since there have been some questions in the comment on how to deal with special characters I'd like to extend my answer:

raw strings ('r'):

One of the main concepts you have to understand when dealing with special characters in regular expressions is to distinguish between string literals and the regular expression itself. It is very well explained here:

In short:

Let's say instead of finding a word boundary \b after TEXTO you want to match the string \boundary. The you have to write:

TEXTO = "Var"
subject = r"Var\boundary"

if re.search(rf"\b(?=\w){TEXTO}\\boundary(?!\w)", subject, re.IGNORECASE):
    print("match")

This only works because we are using a raw-string (the regex is preceded by 'r'), otherwise we must write "\\\\boundary" in the regex (four backslashes). Additionally, without '\r', \b' would not converted to a word boundary anymore but to a backspace!

re.escape:

Basically puts a backspace in front of any special character. Hence, if you expect a special character in TEXTO, you need to write:

if re.search(rf"\b(?=\w){re.escape(TEXTO)}\b(?!\w)", subject, re.IGNORECASE):
    print("match")

NOTE: For any version >= python 3.7: !, ", %, ', ,, /, :, ;, <, =, >, @, and ` are not escaped. Only special characters with meaning in a regex are still escaped. _ is not escaped since Python 3.3.(s. here)

Curly braces:

If you want to use quantifiers within the regular expression using f-strings, you have to use double curly braces. Let's say you want to match TEXTO followed by exactly 2 digits:

if re.search(rf"\b(?=\w){re.escape(TEXTO)}\d{{2}}\b(?!\w)", subject, re.IGNORECASE):
    print("match")

C#, Looping through dataset and show each record from a dataset column

DateTime TaskStart = DateTime.Parse(dr["TaskStart"].ToString());

When and where to use GetType() or typeof()?

You may find it easier to use the is keyword:

if (mycontrol is TextBox)

How to check existence of user-define table type in SQL Server 2008?

IF EXISTS(SELECT 1 FROM sys.types WHERE name = 'Person' AND is_table_type = 1 AND SCHEMA_ID('VAB') = schema_id)
DROP TYPE VAB.Person;
go
CREATE TYPE VAB.Person AS TABLE
(    PersonID               INT
    ,FirstName              VARCHAR(255)
    ,MiddleName             VARCHAR(255)
    ,LastName               VARCHAR(255)
    ,PreferredName          VARCHAR(255)
);

Vector of structs initialization

You cannot access elements of an empty vector by subscript.
Always check that the vector is not empty & the index is valid while using the [] operator on std::vector.
[] does not add elements if none exists, but it causes an Undefined Behavior if the index is invalid.

You should create a temporary object of your structure, fill it up and then add it to the vector, using vector::push_back()

subject subObj;
subObj.name = s1;
sub.push_back(subObj);

Jquery to get the id of selected value from dropdown

First set a custom attribute into your option for example nameid (you can set non-standardized attribute of an HTML element, it's allowed):

'<option nameid= "' + n.id + "' value="' + i + '">' + n.names + '</option>'

then you can easily get attribute value using jquery .attr() :

$('option:selected').attr("nameid")

For Example:

<select id="jobSel" class="longcombo" onchange="GetNameId">
    <option nameid="32" value="1">test1</option>
    <option nameid="67" value="1">test2</option>
    <option nameid="45" value="1">test3</option>    
    </select>    

Jquery:

function GetNameId(){
   alert($('#jobSel option:selected').attr("nameid"));
}

Why do 64-bit DLLs go to System32 and 32-bit DLLs to SysWoW64 on 64-bit Windows?

System32 is where Windows historically placed all 32bit DLLs, and System was for the 16bit DLLs. When microsoft created the 64 bit OS, everyone I know of expected the files to reside under System64, but Microsoft decided it made more sense to put 64bit files under System32. The only reasoning I have been able to find, is that they wanted everything that was 32bit to work in a 64bit Windows w/o having to change anything in the programs -- just recompile, and it's done. The way they solved this, so that 32bit applications could still run, was to create a 32bit windows subsystem called Windows32 On Windows64. As such, the acronym SysWOW64 was created for the System directory of the 32bit subsystem. The Sys is short for System, and WOW64 is short for Windows32OnWindows64.
Since windows 16 is already segregated from Windows 32, there was no need for a Windows 16 On Windows 64 equivalence. Within the 32bit subsystem, when a program goes to use files from the system32 directory, they actually get the files from the SysWOW64 directory. But the process is flawed.

It's a horrible design. And in my experience, I had to do a lot more changes for writing 64bit applications, that simply changing the System32 directory to read System64 would have been a very small change, and one that pre-compiler directives are intended to handle.

Does Java have something like C#'s ref and out keywords?

Direct answer: No

But you can simulate reference with wrappers.

And do the following:

void changeString( _<String> str ) {
    str.s("def");
}

void testRef() {
     _<String> abc = new _<String>("abc");
     changeString( abc );
     out.println( abc ); // prints def
}

Out

void setString( _<String> ref ) {
    str.s( "def" );
}
void testOut(){
    _<String> abc = _<String>();
    setString( abc );
    out.println(abc); // prints def
}

And basically any other type such as:

_<Integer> one = new <Integer>(1);
addOneTo( one );

out.println( one ); // May print 2

Set the maximum character length of a UITextField in Swift

Simply just check with the number of characters in the string

  1. Add a delegate to view controller ans asign delegate
    class YorsClassName : UITextFieldDelegate {

    }
  1. check the number of chars allowed for textfield
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    if textField.text?.count == 1 {
        return false
    }
    return true
}

Note: Here I checked for only char allowed in textField

How to connect access database in c#

Try this code,

public void ConnectToAccess()
{
    System.Data.OleDb.OleDbConnection conn = new 
        System.Data.OleDb.OleDbConnection();
    // TODO: Modify the connection string and include any
    // additional required properties for your database.
    conn.ConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;" +
        @"Data source= C:\Documents and Settings\username\" +
        @"My Documents\AccessFile.mdb";
    try
    {
        conn.Open();
        // Insert code to process data.
    }
        catch (Exception ex)
    {
        MessageBox.Show("Failed to connect to data source");
    }
    finally
    {
        conn.Close();
    }
}

http://msdn.microsoft.com/en-us/library/5ybdbtte(v=vs.71).aspx

Inconsistent accessibility: property type is less accessible

Your class Delivery has no access modifier, which means it defaults to internal. If you then try to expose a property of that type as public, it won't work. Your type (class) needs to have the same, or higher access as your property.

More about access modifiers: http://msdn.microsoft.com/en-us/library/ms173121.aspx

Scrolling an iframe with JavaScript?

Or, you can set a margin-top on the iframe...a bit of a hack but works in FF so far.

#frame {
margin-top:200px;
}

Failed to load ApplicationContext from Unit Test: FileNotFound

The problem is insufficient memory to load context.

Try to set VM options:

-da -Xmx2048m -Xms1024m -XX:MaxPermSize=2048m

nodemon not found in npm

I found a very easy solution. Simply delete the npm and npm cache folder from your pc. Reinstall it again, but the mistake that many of us make is not installing npm globally.So:

npm i -g npm

And then, install nodemon globally:

npm i -g nodemon

Now,nodemon works globally, even without using the command:

npx nodemon <yourfilename>.js

android - listview get item view by position

Use this :

public View getViewByPosition(int pos, ListView listView) {
    final int firstListItemPosition = listView.getFirstVisiblePosition();
    final int lastListItemPosition = firstListItemPosition + listView.getChildCount() - 1;

    if (pos < firstListItemPosition || pos > lastListItemPosition ) {
        return listView.getAdapter().getView(pos, null, listView);
    } else {
        final int childIndex = pos - firstListItemPosition;
        return listView.getChildAt(childIndex);
    }
}

SQL Server Creating a temp table for this query

If you want to create a temp table after check exist table.You can use the following code

DROP TABLE IF EXISTS tempdb.dbo.#temptable
CREATE TABLE #temptable
  (
   SiteName             NVARCHAR(50),
   BillingMonth         varchar(10),
   Consumption          INT,
  )

After creating the temporary table, you can insert data into this table as a regular table:

INSERT INTO #temptable
SELECT COLUMN1,...
FROM
(...)

or

INSERT INTO #temptable
VALUES (value1, value2, value3, ...);

The SELECT statement is used to select data from a temp table.

SELECT * FROM #temptable

you can manually remove the temporary table by using the DROP TABLE statement:

DROP TABLE #temptable;

Render Content Dynamically from an array map function in React Native

Try moving the lapsList function out of your class and into your render function:

render() {
  const lapsList = this.state.laps.map((data) => {
    return (
      <View><Text>{data.time}</Text></View>
    )
  })

  return (
    <View style={styles.container}>
      <View style={styles.footer}>
        <View><Text>coucou test</Text></View>
        {lapsList}
      </View>
    </View>
  )
}

What's a good IDE for Python on Mac OS X?

I use TextMate for all my Python programming needs. It's not an IDE per se, but it does a lot of stuff that an IDE does (without all the cruft of an IDE). It has syntax highlighting, code folding, integration with various SCMs through the use of additional bundles (I know it supports SVN, Git, Mercurial, Darcs, and probably a few others). It's also quite extensible and customizable (again, through the use of bundles). It also has a basic concept of projects. One place where it doesn't shine, though, is in code completion; some bundles have limited support for code completion, but it's generally not as amazing as that of most language-specific IDEs. Given how awesome TextMate is, though, I don't know sacrificing that. TextMate's definitely made me much more productive.

Does PHP have threading?

Ever heard about appserver from techdivision?

It is written in php and works as a appserver managing multithreads for high traffic php applications. Is still in beta but very promesing.

How to pass a datetime parameter?

The problem is twofold:

1. The . in the route

By default, IIS treats all URI's with a dot in them as static resource, tries to return it and skip further processing (by Web API) altogether. This is configured in your Web.config in the section system.webServer.handlers: the default handler handles path="*.". You won't find much documentation regarding the strange syntax in this path attribute (regex would have made more sense), but what this apparently means is "anything that doesn't contain a dot" (and any character from point 2 below). Hence the 'Extensionless' in the name ExtensionlessUrlHandler-Integrated-4.0.

Multiple solutions are possible, in my opinion in the order of 'correctness':

  • Add a new handler specifically for the routes that must allow a dot. Be sure to add it before the default. To do this, make sure you remove the default handler first, and add it back after yours.
  • Change the path="*." attribute to path="*". It will then catch everything. Note that from then on, your web api will no longer interpret incoming calls with dots as static resources! If you are hosting static resources on your web api, this is therefor not advised!
  • Add the following to your Web.config to unconditionally handle all requests: under <system.webserver>: <modules runAllManagedModulesForAllRequests="true">

2. The : in the route

After you've changed the above, by default, you'd get the following error:

A potentially dangerous Request.Path value was detected from the client (:).

You can change the predefined disallowed/invalid characters in your Web.config. Under <system.web>, add the following: <httpRuntime requestPathInvalidCharacters="&lt;,&gt;,%,&amp;,*,\,?" />. I've removed the : from the standard list of invalid characters.

Easier/safer solutions

Although not an answer to your question, a safer and easier solution would be to change the request so that all this is not required. This can be done in two ways:

  1. Pass the date as a query string parameter, like ?date=2012-12-31T22:00:00.000Z.
  2. Strip the .000 from every request. You'd still need to allow :'s (cfr point 2).

How do I perform an IF...THEN in an SQL SELECT?

The case statement is your friend in this situation, and takes one of two forms:

The simple case:

SELECT CASE <variable> WHEN <value>      THEN <returnvalue>
                       WHEN <othervalue> THEN <returnthis>
                                         ELSE <returndefaultcase>
       END AS <newcolumnname>
FROM <table>

The extended case:

SELECT CASE WHEN <test>      THEN <returnvalue>
            WHEN <othertest> THEN <returnthis>
                             ELSE <returndefaultcase>
       END AS <newcolumnname>
FROM <table>

You can even put case statements in an order by clause for really fancy ordering.

How to make URL/Phone-clickable UILabel?

You can make a custom UIButton and setText what ever you want and add a method with that.

UIButton *sampleButton = [UIButton buttonWithType:UIButtonTypeCustom];
[sampleButton setFrame:CGRectMake(kLeftMargin, 10, self.view.bounds.size.width - kLeftMargin - kRightMargin, 52)];
[sampleButton setTitle:@"URL Text" forState:UIControlStateNormal];
[sampleButton setFont:[UIFont boldSystemFontOfSize:20]];


[sampleButton addTarget:self action:@selector(buttonPressed) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:sampleButton];


-(void)buttonPressed:(id)sender{
  // open url
}

How to compare timestamp dates with date-only parameter in MySQL?

You can use the DATE() function to extract the date portion of the timestamp:

SELECT * FROM table
WHERE DATE(timestamp) = '2012-05-25'

Though, if you have an index on the timestamp column, this would be faster because it could utilize an index on the timestamp column if you have one:

SELECT * FROM table
WHERE timestamp BETWEEN '2012-05-25 00:00:00' AND '2012-05-25 23:59:59'

Summernote image upload

I tested this code and Works

Javascript

<script>
$(document).ready(function() {
  $('#summernote').summernote({
    height: 200,
    onImageUpload: function(files, editor, welEditable) {
      sendFile(files[0], editor, welEditable);
    }
  });

  function sendFile(file, editor, welEditable) {
    data = new FormData();
    data.append("file", file);
    $.ajax({
      data: data,
      type: "POST",
      url: "Your URL POST (php)",
      cache: false,
      contentType: false,
      processData: false,
      success: function(url) {
        editor.insertImage(welEditable, url);
      }
    });
  }
});
</script>

PHP

if ($_FILES['file']['name']) {
  if (!$_FILES['file']['error']) {
    $name = md5(rand(100, 200));
    $ext = pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION);
    $filename = $name.
    '.'.$ext;
    $destination = '/assets/images/'.$filename; //change this directory
    $location = $_FILES["file"]["tmp_name"];
    move_uploaded_file($location, $destination);
    echo 'http://test.yourdomain.al/images/'.$filename; //change this URL
  } else {
    echo $message = 'Ooops!  Your upload triggered the following error:  '.$_FILES['file']['error'];
  }
}

Update:

After 0.7.0 onImageUpload should be inside callbacks option as mentioned by @tugberk

$('#summernote').summernote({
    height: 200,
    callbacks: {
        onImageUpload: function(files, editor, welEditable) {
            sendFile(files[0], editor, welEditable);
        }
    }
});

jQuery if statement to check visibility

try

if ($('#column-left form:visible').length > 0) { ...

How to convert a PIL Image into a numpy array?

If your image is stored in a Blob format (i.e. in a database) you can use the same technique explained by Billal Begueradj to convert your image from Blobs to a byte array.

In my case, I needed my images where stored in a blob column in a db table:

def select_all_X_values(conn):
    cur = conn.cursor()
    cur.execute("SELECT ImageData from PiecesTable")    
    rows = cur.fetchall()    
    return rows

I then created a helper function to change my dataset into np.array:

X_dataset = select_all_X_values(conn)
imagesList = convertToByteIO(np.array(X_dataset))

def convertToByteIO(imagesArray):
    """
    # Converts an array of images into an array of Bytes
    """
    imagesList = []

    for i in range(len(imagesArray)):  
        img = Image.open(BytesIO(imagesArray[i])).convert("RGB")
        imagesList.insert(i, np.array(img))

    return imagesList

After this, I was able to use the byteArrays in my Neural Network.

plt.imshow(imagesList[0])

How do I use a custom Serializer with Jackson?

As mentioned, @JsonValue is a good way. But if you don't mind a custom serializer, there's no need to write one for Item but rather one for User -- if so, it'd be as simple as:

public void serialize(Item value, JsonGenerator jgen,
    SerializerProvider provider) throws IOException,
    JsonProcessingException {
  jgen.writeNumber(id);
}

Yet another possibility is to implement JsonSerializable, in which case no registration is needed.

As to error; that is weird -- you probably want to upgrade to a later version. But it is also safer to extend org.codehaus.jackson.map.ser.SerializerBase as it will have standard implementations of non-essential methods (i.e. everything but actual serialization call).

How do I create a file at a specific path?

where is the file created?

In the application's current working directory. You can use os.getcwd to check it, and os.chdir to change it.

Opening file in the root directory probably fails due to lack of privileges.

Ionic 2: Cordova is not available. Make sure to include cordova.js or run in a device/simulator (running in emulator)

In case anyone stumbles with this problem again, the accepted solution did work for older versions of ionic and app scripts, I had used it many times in the past, but last week, after I updated some stuff, it got broken again, and this fix wasn't working anymore as this was already solved on the current version of app-scripts, most of the info is referred on this post https://forum.ionicframework.com/t/ionic-cordova-run-android-livereload-cordova-not-available/116790/18 but I'll make it short here:

First make sure you have this versions on your system

cli packages: (xxxx\npm\node_modules)

@ionic/cli-utils  : 1.19.2
ionic (Ionic CLI) : 3.20.0

global packages:

cordova (Cordova CLI) : not installed

local packages:

@ionic/app-scripts : 3.1.9
Cordova Platforms  : android 7.0.0
Ionic Framework    : ionic-angular 3.9.2

System:

Node : v10.1.0
npm  : 5.6.0

An this on your package.json

"@angular/cli": "^6.0.3", "@ionic/app-scripts": "^3.1.9", "typescript": "~2.4.2"

Now remove your platform with ionic cordova platform rm what-ever Then DELETE the node_modules and plugins folder and MAKE SURE the platform was deleted inside the platforms folder.

Finally, run

npm install ionic cordova platform add what-ever ionic cordova run

And everything should be working again

MYSQL Sum Query with IF Condition

How about this?

SUM(IF(PaymentType = "credit card", totalamount, 0)) AS CreditCardTotal

What is the difference between match_parent and fill_parent?

match_parent, which means that the view wants to be as big as its parent (minus padding).

wrap_content, which means that the view wants to be just big enough to enclose its content (plus padding)

For sake of better illustration, I have created a sample layout that demonstrate this concept. To see it's effect, I added a border of each textView content.

In "Match parent" textView content, we can see it's layout width spread out of it's parent whole length.

But we can see in "Wrap Content" textView content, it's layout width wrapped in of it's content(Wrap Content) length.

Android Layout

Run chrome in fullscreen mode on Windows

I would like to share my way of starting chrome - specificaly youtube tv - in full screen mode automatically, without the need of pressing F11. kiosk/fullscreen options doesn't seem to work (Version 41.0.2272.89). It has some steps though...

  • Start chrome and navigate to page (www.youtube.com/tv)
  • Drag the address from the address bar (the lock icon) to the desktop. It will create a shortcut.
  • From chrome, open Apps (the icon with the multiple coloured dots)
  • From desktop, drag the shortcut into the Apps space
  • Right click on the new icon in Apps and select "Open fullscreen"
  • Right click again on the icon in Apps and select "Create shortcuts..."
  • Select for example Desktop and Create. A new shortcut will be created on desktop.

Now, whenever you click on this shortcut, chrome will start in fullscreen and at the page you defined. I guess you can put this shortcut in startup folder to run when windows starts, but I haven't tried it.

How to print a dictionary's key?

In Python 3:

# A simple dictionary
x = {'X':"yes", 'Y':"no", 'Z':"ok"}

# To print a specific key (for example key at index 1)
print([key for key in x.keys()][1])

# To print a specific value (for example value at index 1)
print([value for value in x.values()][1])

# To print a pair of a key with its value (for example pair at index 2)
print(([key for key in x.keys()][2], [value for value in x.values()][2]))

# To print a key and a different value (for example key at index 0 and value at index 1)
print(([key for key in x.keys()][0], [value for value in x.values()][1]))

# To print all keys and values concatenated together
print(''.join(str(key) + '' + str(value) for key, value in x.items()))

# To print all keys and values separated by commas
print(', '.join(str(key) + ', ' + str(value) for key, value in x.items()))

# To print all pairs of (key, value) one at a time
for e in range(len(x)):
    print(([key for key in x.keys()][e], [value for value in x.values()][e]))

# To print all pairs (key, value) in a tuple
print(tuple(([key for key in x.keys()][i], [value for value in x.values()][i]) for i in range(len(x))))

simulate background-size:cover on <video> or <img>

jsFiddle

Using background cover is fine for images, and so is width 100%. These are not optimal for <video>, and these answers are overly complicated. You do not need jQuery or JavaScript to accomplish a full width video background.

Keep in mind that my code will not cover a background completely with a video like cover will, but instead it will make the video as big as it needs to be to maintain aspect ratio and still cover the whole background. Any excess video will bleed off the page edge, which sides depend on where you anchor the video.

The answer is quite simple.

Just use this HTML5 video code, or something along these lines: (test in Full Page)

_x000D_
_x000D_
html, body {_x000D_
  width: 100%; _x000D_
  height:100%; _x000D_
  overflow:hidden;_x000D_
}_x000D_
_x000D_
#vid{_x000D_
  position: absolute;_x000D_
  top: 50%; _x000D_
  left: 50%;_x000D_
  -webkit-transform: translateX(-50%) translateY(-50%);_x000D_
  transform: translateX(-50%) translateY(-50%);_x000D_
  min-width: 100%; _x000D_
  min-height: 100%; _x000D_
  width: auto; _x000D_
  height: auto;_x000D_
  z-index: -1000; _x000D_
  overflow: hidden;_x000D_
}
_x000D_
<video id="vid" video autobuffer autoplay>_x000D_
  <source id="mp4" src="http://grochtdreis.de/fuer-jsfiddle/video/sintel_trailer-480.mp4" type="video/mp4">_x000D_
</video>
_x000D_
_x000D_
_x000D_

The min-height and min-width will allow the video to maintain the aspect ratio of the video, which is usually the aspect ratio of any normal browser at a normal resolution. Any excess video bleeds off the side of the page.

Is there a numpy builtin to reject outliers from a list

An alternative is to make a robust estimation of the standard deviation (assuming Gaussian statistics). Looking up online calculators, I see that the 90% percentile corresponds to 1.2815σ and the 95% is 1.645σ (http://vassarstats.net/tabs.html?#z)

As a simple example:

import numpy as np

# Create some random numbers
x = np.random.normal(5, 2, 1000)

# Calculate the statistics
print("Mean= ", np.mean(x))
print("Median= ", np.median(x))
print("Max/Min=", x.max(), " ", x.min())
print("StdDev=", np.std(x))
print("90th Percentile", np.percentile(x, 90))

# Add a few large points
x[10] += 1000
x[20] += 2000
x[30] += 1500

# Recalculate the statistics
print()
print("Mean= ", np.mean(x))
print("Median= ", np.median(x))
print("Max/Min=", x.max(), " ", x.min())
print("StdDev=", np.std(x))
print("90th Percentile", np.percentile(x, 90))

# Measure the percentile intervals and then estimate Standard Deviation of the distribution, both from median to the 90th percentile and from the 10th to 90th percentile
p90 = np.percentile(x, 90)
p10 = np.percentile(x, 10)
p50 = np.median(x)
# p50 to p90 is 1.2815 sigma
rSig = (p90-p50)/1.2815
print("Robust Sigma=", rSig)

rSig = (p90-p10)/(2*1.2815)
print("Robust Sigma=", rSig)

The output I get is:

Mean=  4.99760520022
Median=  4.95395274981
Max/Min= 11.1226494654   -2.15388472011
Sigma= 1.976629928
90th Percentile 7.52065379649

Mean=  9.64760520022
Median=  4.95667658782
Max/Min= 2205.43861943   -2.15388472011
Sigma= 88.6263902244
90th Percentile 7.60646688694

Robust Sigma= 2.06772555531
Robust Sigma= 1.99878292462

Which is close to the expected value of 2.

If we want to remove points above/below 5 standard deviations (with 1000 points we would expect 1 value > 3 standard deviations):

y = x[abs(x - p50) < rSig*5]

# Print the statistics again
print("Mean= ", np.mean(y))
print("Median= ", np.median(y))
print("Max/Min=", y.max(), " ", y.min())
print("StdDev=", np.std(y))

Which gives:

Mean=  4.99755359935
Median=  4.95213030447
Max/Min= 11.1226494654   -2.15388472011
StdDev= 1.97692712883

I have no idea which approach is the more efficent/robust

How to model type-safe enum types?

just discovered enumeratum. it's pretty amazing and equally amazing it's not more well known!

What is the difference between display: inline and display: inline-block?

One thing not mentioned in answers is inline element can break among lines while inline-block can't (and obviously block)! So inline elements can be useful to style sentences of text and blocks inside them, but as they can't be padded you can use line-height instead.

_x000D_
_x000D_
<div style="width: 350px">_x000D_
  Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua._x000D_
  <div style="display: inline; background: #F00; color: #FFF">_x000D_
    Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat._x000D_
  </div>_x000D_
  Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum._x000D_
</div>_x000D_
<hr/>_x000D_
<div style="width: 350px">_x000D_
  Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua._x000D_
  <div style="display: inline-block; background: #F00; color: #FFF">_x000D_
    Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat._x000D_
  </div>_x000D_
  Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum._x000D_
</div>
_x000D_
_x000D_
_x000D_

enter image description here

HTTP GET Request in Node.js Express

Here is a snippet of some code from a sample of mine. It's asynchronous and returns a JSON object. It can do any form of GET request.

Note that there are more optimal ways (just a sample) - for example, instead of concatenating the chunks you put into an array and join it etc... Hopefully, it gets you started in the right direction:

const http = require('http');
const https = require('https');

/**
 * getJSON:  RESTful GET request returning JSON object(s)
 * @param options: http options object
 * @param callback: callback to pass the results JSON object(s) back
 */

module.exports.getJSON = (options, onResult) => {
  console.log('rest::getJSON');
  const port = options.port == 443 ? https : http;

  let output = '';

  const req = port.request(options, (res) => {
    console.log(`${options.host} : ${res.statusCode}`);
    res.setEncoding('utf8');

    res.on('data', (chunk) => {
      output += chunk;
    });

    res.on('end', () => {
      let obj = JSON.parse(output);

      onResult(res.statusCode, obj);
    });
  });

  req.on('error', (err) => {
    // res.send('error: ' + err.message);
  });

  req.end();
};

It's called by creating an options object like:

const options = {
  host: 'somesite.com',
  port: 443,
  path: '/some/path',
  method: 'GET',
  headers: {
    'Content-Type': 'application/json'
  }
};

And providing a callback function.

For example, in a service, I require the REST module above and then do this:

rest.getJSON(options, (statusCode, result) => {
  // I could work with the resulting HTML/JSON here. I could also just return it
  console.log(`onResult: (${statusCode})\n\n${JSON.stringify(result)}`);

  res.statusCode = statusCode;

  res.send(result);
});

UPDATE

If you're looking for async/await (linear, no callback), promises, compile time support and intellisense, we created a lightweight HTTP and REST client that fits that bill:

Microsoft typed-rest-client

Rails 4: before_filter vs. before_action

It is just a name change. before_action is more specific, because it gets executed before an action.

Address in mailbox given [] does not comply with RFC 2822, 3.6.2. when email is in a variable

Your email variable is empty because of the scope, you should set a use clause such as:

Mail::send('emails.activation', $data, function($message) use ($email, $subject) {
    $message->to($email)->subject($subject);
});

Message: Trying to access array offset on value of type null

This happens because $cOTLdata is not null but the index 'char_data' does not exist. Previous versions of PHP may have been less strict on such mistakes and silently swallowed the error / notice while 7.4 does not do this anymore.

To check whether the index exists or not you can use isset():

isset($cOTLdata['char_data'])

Which means the line should look something like this:

$len = isset($cOTLdata['char_data']) ? count($cOTLdata['char_data']) : 0;

Note I switched the then and else cases of the ternary operator since === null is essentially what isset already does (but in the positive case).

Error message 'Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information.'

I encountered this error with an ASP.NET 4 + SQL Server 2008 R2 + Entity Framework 4 application.

It would work fine on my development machine (Windows Vista 64-bit). Then when deployed to the server (Windows Server 2008 R2 SP1), it would work until the session timed out. So we'd deploy the application and everything looked fine and then leave it for more than the 20 minute session timeout and then this error would be thrown.

To solve it, I used this code on Ken Cox's blog to retrieve the LoaderExceptions property.

For my situation the missing DLL was Microsoft.ReportViewer.ProcessingObjectModel (version 10). This DLL needs to be installed in the GAC of the machine the application runs on. You can find it in the Microsoft Report Viewer 2010 Redistributable Package available on the Microsoft download site.

apt-get for Cygwin?

No. The only officially supported tool for downloading and updating Cygwin packages is the setup.exe file you used for the initial install, although that can be invoked with command line arguments to help the process.

From that same page:

The basic reason for not having a more full-featured package manager is that such a program would need full access to all of Cygwin's POSIX functionality. That is, however, difficult to provide in a Cygwin-free environment, such as exists on first installation. Additionally, Windows does not easily allow overwriting of in-use executables so installing a new version of the Cygwin DLL while a package manager is using the DLL is problematic.

Using std::max_element on a vector<double>

min/max_element return the iterator to the min/max element, not the value of the min/max element. You have to dereference the iterator in order to get the value out and assign it to a double. That is:

cLower = *min_element(C.begin(), C.end());

ngModel cannot be used to register form controls with a parent formGroup directive

when you write formcontrolname Angular 2 do not accept. You have to write formControlName . it is about uppercase second words.

<input type="number" [(ngModel)]="myObject.name" formcontrolname="nameFormControl"/>

if the error still conitnue try to set form control for all of object(myObject) field.

between start <form> </form> for example: <form [formGroup]="myForm" (ngSubmit)="submitForm(myForm.value)"> set form control for all input field </form>.

How to build and fill pandas dataframe from for loop?

Make a list of tuples with your data and then create a DataFrame with it:

d = []
for p in game.players.passing():
    d.append((p, p.team, p.passer_rating()))

pd.DataFrame(d, columns=('Player', 'Team', 'Passer Rating'))

A list of tuples should have less overhead than a list dictionaries. I tested this below, but please remember to prioritize ease of code understanding over performance in most cases.

Testing functions:

def with_tuples(loop_size=1e5):
    res = []

    for x in range(int(loop_size)):
        res.append((x-1, x, x+1))

    return pd.DataFrame(res, columns=("a", "b", "c"))

def with_dict(loop_size=1e5):
    res = []

    for x in range(int(loop_size)):
        res.append({"a":x-1, "b":x, "c":x+1})

    return pd.DataFrame(res)

Results:

%timeit -n 10 with_tuples()
# 10 loops, best of 3: 55.2 ms per loop

%timeit -n 10 with_dict()
# 10 loops, best of 3: 130 ms per loop

How can I modify a saved Microsoft Access 2007 or 2010 Import Specification?

I have just discovered an apparent bug in the whole Saved Import/XML setup in Access. Also frustrated by the rigidity of the Saved Import system, I created forms and wrote code to pick apart the XML in which the Saved Import specs are stored, to the point that I could use this tool to actually create a Saved Import from scratch via coded examination of a source Excel workbook.

What I've found out is that, while Access correctly imports a worksheet per modifications of default settings by the user (for example, it likes to take any column with a header name ending with "ID" and make it an indexed field in the resulting table, but you can cancel this during the import process), and while it also correctly creates XML in accordance to the user changes, if you then drop the table and use the Saved Import to re-import the worksheet, it ignores the XML import spec and reverts back to using its own invented defaults, at least in the case of the "ID" columns.

You can try this on your own: import an worksheet Excel with at least one column header name ending with "ID" ("OrderID", "User ID", or just plain "ID"). During the process, be sure to set "Indexed" to No for those columns. Execute the import and check "Save import steps" in the final dialog window. If you inspect the resulting table design, you will see there is no index on the field(s) in question. Then delete the table, find the saved import and execute it again. This time, those fields will be set as Indexed in the table design, even though the XML still says no index.

I was pulling my hair out until I discovered what was going on, comparing the XML I built from scratch with examples created through the Access tool.

How to fetch the row count for all tables in a SQL SERVER database

Short and sweet

sp_MSForEachTable 'DECLARE @t AS VARCHAR(MAX); 
SELECT @t = CAST(COUNT(1) as VARCHAR(MAX)) 
+ CHAR(9) + CHAR(9) + ''?'' FROM ? ; PRINT @t'

Output:

enter image description here