Programs & Examples On #Shop

How to do perspective fixing?

The simple solution is to just remap coordinates from the original to the final image, copying pixels from one coordinate space to the other, rounding off as necessary -- which may result in some pixels being copied several times adjacent to each other, and other pixels being skipped, depending on whether you're stretching or shrinking (or both) in either dimension. Make sure your copying iterates through the destination space, so all pixels are covered there even if they're painted more than once, rather than thru the source which may skip pixels in the output.

The better solution involves calculating the corresponding source coordinate without rounding, and then using its fractional position between pixels to compute an appropriate average of the (typically) four pixels surrounding that location. This is essentially a filtering operation, so you lose some resolution -- but the result looks a LOT better to the human eye; it does a much better job of retaining small details and avoids creating straight-line artifacts which humans find objectionable.

Note that the same basic approach can be used to remap flat images onto any other shape, including 3D surface mapping.

Angular @ViewChild() error: Expected 2 arguments, but got 1

In Angular 8 , ViewChild takes 2 parameters

 @ViewChild(ChildDirective, {static: false}) Component

Typescript: Type X is missing the following properties from type Y length, pop, push, concat, and 26 more. [2740]

This error could also be because you are not subscribing to the Observable.

Example, instead of:

this.products = this.productService.getProducts();

do this:

   this.productService.getProducts().subscribe({
    next: products=>this.products = products,
    error: err=>this.errorMessage = err
   });

Flutter - The method was called on null

As stated in the above answers, it's always a good practice to initialize the variables, but if you have something which you don't know what value should it takes, and you want to leave it uninitialized so you have to make sure that you are updating it before using it.

For example: Assume we have double _bmi; and you don't know what value should it takes, so you can leave it as it is, but before using it, you have to update its value first like calling a function that calculating BMI like follows:

String calculateBMI (){
_bmi = weight / pow( height/100, 2);
return _bmi.toStringAsFixed(1);}

or whatever, what I mean is, you can leave the variable as it is, but before using it make sure you have initialized it using whatever the method you are using.

error: resource android:attr/fontVariationSettings not found

This is caused by an incompatibility with the android support library that changed to version 28. I solved the problem by forcing the build to use a lower support library. //like build gradle

configurations.all {
        resolutionStrategy {
                force 'com.android.support:support-v4:27.1.0'
    }
} 

My project built successfully immediately after I changed this. Hope this might help you too. I lost a day of development because of this!.

Getting Image from API in Angular 4/5+?

angular 5 :

 getImage(id: string): Observable<Blob> {
    return this.httpClient.get('http://myip/image/'+id, {responseType: "blob"});
}

Vue Js - Loop via v-for X times (in a range)

You can use an index in a range and then access the array via its index:

<ul>
  <li v-for="index in 10" :key="index">
    {{ shoppingItems[index].name }} - {{ shoppingItems[index].price }}
  </li>
</ul>

You can also check the Official Documentation for more information.

React.createElement: type is invalid -- expected a string

Array of components

A common way to get this error is using an array of components, with a positional index used to select the component to render from the array. I saw a code like this many times:

const checkoutSteps = [Address, Shipment, Payment]

export const Checkout = ({step}) => {

  const ToRender = checkoutSteps[step]

  return (
    <ToRender />
  )
}

This is not necessary bad code, but if you call it with a wrong index (eg -1, or 3 in this case), the ToRender component will be undefined, throwing the React.createElement: type is invalid... error:

<Checkout step={0} /> // <Address />
<Checkout step={1} /> // <Shipment />
<Checkout step={2} /> // <Payment />
<Checkout step={3} /> // undefined
<Checkout step={-1} /> // undefined

A rational solution

You should protect yourself and your collegues from this hard-to-debug code using a more explicit approach, avoiding magic numbers and using PropTypes:

const checkoutSteps = {
  address: Address,
  shipment Shipment,
  payment: Payment
}

const propTypes = {
  step: PropTypes.oneOf(['address', 'shipment', 'payment']),
}

/* TIP: easier to maintain
const propTypes = {
  step: PropTypes.oneOf(Object.keys(checkoutSteps)),
}
*/

const Checkout = ({step}) => {

  const ToRender = checkoutSteps[step]

  return (
    <ToRender />
  )
}

Checkout.propTypes = propTypes

export default Checkout

And your code will look like this:

// OK
<Checkout step="address" /> // <Address />
<Checkout step="shipment" /> // <Shipment />
<Checkout step="payment" /> // <Payment />

// Errors
<Checkout step="wrongstep" /> // explicit error "step must be one of..."
<Checkout step={3} /> // explicit error (same as above)
<Checkout step={myWrongVar} /> // explicit error (same as above)

Benefits of this approach

  • code is more explicit, you can clearly see what you want to render
  • you don't need to remember the numbers and their hidden meaning (1 is for Address, 2 is for...)
  • errors are explicit too
  • no headache for your peers :)

how to make a new line in a jupyter markdown cell

The double space generally works well. However, sometimes the lacking newline in the PDF still occurs to me when using four pound sign sub titles #### in Jupyter Notebook, as the next paragraph is put into the subtitle as a single paragraph. No amount of double spaces and returns fixed this, until I created a notebook copy 'v. PDF' and started using a single backslash '\' which also indents the next paragraph nicely:

#### 1.1 My Subtitle  \

1.1 My Subtitle
    Next paragraph text.

An alternative to this, is to upgrade the level of your four # titles to three # titles, etc. up the title chain, which will remove the next paragraph indent and format the indent of the title itself (#### My Subtitle ---> ### My Subtitle).

### My Subtitle


1.1 My Subtitle

Next paragraph text.

How to update the value of a key in a dictionary in Python?

Well you could directly substract from the value by just referencing the key. Which in my opinion is simpler.

>>> books = {}
>>> books['book'] = 3       
>>> books['book'] -= 1   
>>> books   
{'book': 2}   

In your case:

book_shop[ch1] -= 1

currently unable to handle this request HTTP ERROR 500

Have you included the statement include ("fileName.php"); ?

Are you sure that file is in the correct directory?

What's the source of Error: getaddrinfo EAI_AGAIN?

Enabled Blaze and it still doesn't work?

Most probably you need to set .env from the right path, require('dotenv').config({ path: __dirname + './../.env' }); won't work (or any other path). Simply put the .env file in the functions directory, from which you deploy to Firebase.

How do you programmatically update query params in react-router?

I prefer you to use below function that is ES6 style:

getQueryStringParams = query => {
    return query
        ? (/^[?#]/.test(query) ? query.slice(1) : query)
            .split('&')
            .reduce((params, param) => {
                    let [key, value] = param.split('=');
                    params[key] = value ? decodeURIComponent(value.replace(/\+/g, ' ')) : '';
                    return params;
                }, {}
            )
        : {}
};

How to import a CSS file in a React Component

  1. Install Style Loader and CSS Loader:

    npm install --save-dev style-loader
    npm install --save-dev css-loader
    
  2. Configure webpack

    module: {
            loaders: [
                {
                    test: /\.css$/,
                    loader: 'style-loader'
                }, {
                    test: /\.css$/,
                    loader: 'css-loader',
                    query: {
                        modules: true,
                        localIdentName: '[name]__[local]___[hash:base64:5]'
                    }
                }
            ]
        }
    

Vue equivalent of setTimeout?

There's no need for bind(this) when you are using arrow functions:

  setTimeout( ()=> {
    // some code
   }, 500)

The term "Add-Migration" is not recognized

I think the answer needs updating in 2017, as MS have made some (breaking) changes that is detailed here.

https://github.com/aspnet/EntityFramework/issues/7053

To summarise, you will now need a reference to EntityFrameWorkCore.Tools.DotNet in the Tools Section as below

"Microsoft.EntityFrameworkCore.Tools.DotNet": "1.0.0"

I have also posted a working project.json file below in case some one runs in problems.

{
  "dependencies": {
    "Microsoft.NETCore.App": {
      "version": "1.0.1",
      "type": "platform"
    },
    "Microsoft.AspNetCore.Diagnostics": "1.0.0",
    "Microsoft.AspNetCore.Server.IISIntegration": "1.0.0",
    "Microsoft.AspNetCore.Server.Kestrel": "1.0.1",
    "Microsoft.Extensions.Logging.Console": "1.0.0",
    "Microsoft.AspNetCore.Razor.Tools": {
      "version": "1.0.0-preview2-final",
      "type": "build"
    },
    "Microsoft.AspNetCore.StaticFiles": "1.0.0",
    "Microsoft.AspNetCore.Mvc": "1.0.1",
    "Microsoft.EntityFrameworkCore.SqlServer": "1.0.1",
    "Microsoft.Extensions.Configuration.Json": "1.0.1",
    "Microsoft.EntityFrameworkCore.Tools": {
      "version": "1.0.0-preview2-final",
      "type": "build"
    }
  },

  "tools": {
    "Microsoft.AspNetCore.Server.IISIntegration.Tools": "1.0.0-preview2-final",
    "Microsoft.AspNetCore.Razor.Tools": "1.0.0-preview2-final",
    "Microsoft.EntityFrameworkCore.Tools": "1.0.0-preview2-final",
    "Microsoft.EntityFrameworkCore.Tools.DotNet": "1.0.0"
  },

  "frameworks": {
    "netcoreapp1.0": {
      "imports": [
        "dotnet5.6",
        "portable-net45+win8"
      ]
    }
  },

  "buildOptions": {
    "emitEntryPoint": true,
    "preserveCompilationContext": true
  },

  "runtimeOptions": {
    "configProperties": {
      "System.GC.Server": true
    }
  },

  "publishOptions": {
    "include": [
      "wwwroot",
      "web.config"
    ]
  },

  "scripts": {
    "postpublish": [ "dotnet publish-iis --publish-folder %publish:OutputPath% --framework %publish:FullTargetFramework%" ]
  }
}

How to use npm with ASP.NET Core

Install the Bundler and Minifier into Visual Studio Extensions

Then you create a bundleconfig.json and enter the following like :

// Configure bundling and minification for the project.
// More info at https://go.microsoft.com/fwlink/?LinkId=808241
[
 {
    "outputFileName": "wwwroot/js/jquery.min.js",
    "inputFiles": [
      "node_modules/jquery/dist/jquery.js"
    ],
    // Optionally specify minification options
    "minify": {
      "enabled": true,
      "renameLocals": false
    },
    // Optionally generate .map file
    "sourceMap": false
  }
]

So the bundler and minifier (gulp based) has access to the source files (which should be excluded from Visual Studio and also excluded from GIT) and puts them into the wwwroot as specified

only side effect every time you save it will run this (but you can set it to run it manually)

How do I filter an array with TypeScript in Angular 2?

To filter an array irrespective of the property type (i.e. for all property types), we can create a custom filter pipe

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({ name: "filter" })
export class ManualFilterPipe implements PipeTransform {
  transform(itemList: any, searchKeyword: string) {
    if (!itemList)
      return [];
    if (!searchKeyword)
      return itemList;
    let filteredList = [];
    if (itemList.length > 0) {
      searchKeyword = searchKeyword.toLowerCase();
      itemList.forEach(item => {
        //Object.values(item) => gives the list of all the property values of the 'item' object
        let propValueList = Object.values(item);
        for(let i=0;i<propValueList.length;i++)
        {
          if (propValueList[i]) {
            if (propValueList[i].toString().toLowerCase().indexOf(searchKeyword) > -1)
            {
              filteredList.push(item);
              break;
            }
          }
        }
      });
    }
    return filteredList;
  }
}

//Usage

//<tr *ngFor="let company of companyList | filter: searchKeyword"></tr>

Don't forget to import the pipe in the app module

We might need to customize the logic to filer with dates.

When should I use curly braces for ES6 import?

  • If there is any default export in the file, there isn't any need to use the curly braces in the import statement.

  • if there are more than one export in the file then we need to use curly braces in the import file so that which are necessary we can import.

  • You can find the complete difference when to use curly braces and default statement in the below YouTube video (very heavy Indian accent, including rolling on the r's...).

    21. ES6 Modules. Different ways of using import/export, Default syntax in the code. ES6 | ES2015

Swift Error: Editor placeholder in source file

Clean Build folder + Build

will clear any error you may have even after fixing your code.

Cannot resolve symbol HttpGet,HttpClient,HttpResponce in Android Studio

HttpClient was deprecated in API Level 22 and removed in API Level 23. You have to use URLConnection.

WELD-001408: Unsatisfied dependencies for type Customer with qualifiers @Default

Your Customer class has to be discovered by CDI as a bean. For that you have two options:

  1. Put a bean defining annotation on it. As @Model is a stereotype it's why it does the trick. A qualifier like @Named is not a bean defining annotation, reason why it doesn't work

  2. Change the bean discovery mode in your bean archive from the default "annotated" to "all" by adding a beans.xml file in your jar.

Keep in mind that @Named has only one usage : expose your bean to the UI. Other usages are for bad practice or compatibility with legacy framework.

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

I've had a very similar issue using spring-boot-starter-data-redis. To my implementation there was offered a @Bean for RedisTemplate as follows:

@Bean
public RedisTemplate<String, List<RoutePlantCache>> redisTemplate(RedisConnectionFactory connectionFactory) {
    final RedisTemplate<String, List<RoutePlantCache>> template = new RedisTemplate<>();
    template.setConnectionFactory(connectionFactory);
    template.setKeySerializer(new StringRedisSerializer());
    template.setValueSerializer(new Jackson2JsonRedisSerializer<>(RoutePlantCache.class));

    // Add some specific configuration here. Key serializers, etc.
    return template;
}

The fix was to specify an array of RoutePlantCache as following:

template.setValueSerializer(new Jackson2JsonRedisSerializer<>(RoutePlantCache[].class));

Below the exception I had:

com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of `[...].RoutePlantCache` out of START_ARRAY token
 at [Source: (byte[])"[{ ... },{ ... [truncated 1478 bytes]; line: 1, column: 1]
    at com.fasterxml.jackson.databind.exc.MismatchedInputException.from(MismatchedInputException.java:59) ~[jackson-databind-2.11.4.jar:2.11.4]
    at com.fasterxml.jackson.databind.DeserializationContext.reportInputMismatch(DeserializationContext.java:1468) ~[jackson-databind-2.11.4.jar:2.11.4]
    at com.fasterxml.jackson.databind.DeserializationContext.handleUnexpectedToken(DeserializationContext.java:1242) ~[jackson-databind-2.11.4.jar:2.11.4]
    at com.fasterxml.jackson.databind.DeserializationContext.handleUnexpectedToken(DeserializationContext.java:1190) ~[jackson-databind-2.11.4.jar:2.11.4]
    at com.fasterxml.jackson.databind.deser.BeanDeserializer._deserializeFromArray(BeanDeserializer.java:604) ~[jackson-databind-2.11.4.jar:2.11.4]
    at com.fasterxml.jackson.databind.deser.BeanDeserializer._deserializeOther(BeanDeserializer.java:190) ~[jackson-databind-2.11.4.jar:2.11.4]
    at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:166) ~[jackson-databind-2.11.4.jar:2.11.4]
    at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:4526) ~[jackson-databind-2.11.4.jar:2.11.4]
    at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:3572) ~[jackson-databind-2.11.4.jar:2.11.4]

How to disable SSL certificate checking with Spring RestTemplate?

Please see below for a modest improvement on @Sled's code shown above, that turn-back-on method was missing one line, now it passes my tests. This disables HTTPS certificate and hostname spoofing when using RestTemplate in a Spring-Boot version 2 application that uses the default HTTP configuration, NOT configured to use Apache HTTP Client.

package org.my.little.spring-boot-v2.app;

import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

/**
 * Disables and enables certificate and host-name checking in
 * HttpsURLConnection, the default JVM implementation of the HTTPS/TLS protocol.
 * Has no effect on implementations such as Apache Http Client, Ok Http.
*/
public final class SSLUtils {

    private static final HostnameVerifier jvmHostnameVerifier = HttpsURLConnection.getDefaultHostnameVerifier();

    private static final HostnameVerifier trivialHostnameVerifier = new HostnameVerifier() {
        public boolean verify(String hostname, SSLSession sslSession) {
            return true;
        }
    };

    private static final TrustManager[] UNQUESTIONING_TRUST_MANAGER = new TrustManager[] { new X509TrustManager() {
        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return null;
        }

        public void checkClientTrusted(X509Certificate[] certs, String authType) {
        }

        public void checkServerTrusted(X509Certificate[] certs, String authType) {
        }
    } };

    public static void turnOffSslChecking() throws NoSuchAlgorithmException, KeyManagementException {
        HttpsURLConnection.setDefaultHostnameVerifier(trivialHostnameVerifier);
        // Install the all-trusting trust manager
        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, UNQUESTIONING_TRUST_MANAGER, null);
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
    }

    public static void turnOnSslChecking() throws KeyManagementException, NoSuchAlgorithmException {
        HttpsURLConnection.setDefaultHostnameVerifier(jvmHostnameVerifier);
        // Return it to the initial state (discovered by reflection, now hardcoded)
        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, null, null);
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
    }

    private SSLUtils() {
        throw new UnsupportedOperationException("Do not instantiate libraries.");
    }
}

How to add Button over image using CSS?

Adapt this example to your code

HTML

<div class="img-holder">
    <img src="images/img-1.png" alt="image description"/>
    <a class="link" href=""></a>
</div>

CSS

.img-holder {position: relative;}
.img-holder .link {
    position: absolute;
    bottom: 10px; /*your button position*/
    right: 10px; /*your button position*/
}

How to add image that is on my computer to a site in css or html?

The image needs to be in the same folder that your html page is in, then create a href to that folder with the picture name at the end. Example:

<img src="C:\users\home\pictures\picture.png"/>

Calculating sum of repeated elements in AngularJS ng-repeat

**Angular 6: Grand Total**       
 **<h2 align="center">Usage Details Of {{profile$.firstName}}</h2>
        <table align ="center">
          <tr>
            <th>Call Usage</th>
            <th>Data Usage</th>
            <th>SMS Usage</th>
            <th>Total Bill</th>
          </tr>
          <tr>
          <tr *ngFor="let user of bills$">
            <td>{{ user.callUsage}}</td>
            <td>{{ user.dataUsage }}</td>
            <td>{{ user.smsUsage }}</td>
       <td>{{user.callUsage *2 + user.dataUsage *1 + user.smsUsage *1}}</td>
          </tr>


          <tr>
            <th> </th>
            <th>Grand Total</th>
            <th></th>
            <td>{{total( bills$)}}</td>
          </tr>
        </table>**


    **Controller:**
        total(bills) {
            var total = 0;
            bills.forEach(element => {
total = total + (element.callUsage * 2 + element.dataUsage * 1 + element.smsUsage * 1);
            });
            return total;
        }

How to make a transparent HTML button?

Setting its background image to none also works:

button {
    background-image: none;
}

Can you blur the content beneath/behind a div?

you can do this with css3, this blurs the whole element

div (or whatever element) {
  -webkit-filter: blur(5px);
  -moz-filter: blur(5px);
  -o-filter: blur(5px);
  -ms-filter: blur(5px);
  filter: blur(5px);
}

Fiddle: http://jsfiddle.net/H4DU4/

Calculate summary statistics of columns in dataframe

To clarify one point in @EdChum's answer, per the documentation, you can include the object columns by using df.describe(include='all'). It won't provide many statistics, but will provide a few pieces of info, including count, number of unique values, top value. This may be a new feature, I don't know as I am a relatively new user.

Laravel Eloquent Sum of relation's column

I tried doing something similar, which took me a lot of time before I could figure out the collect() function. So you can have something this way:

collect($items)->sum('amount');

This will give you the sum total of all the items.

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException Error

NullPointerExceptions are among the easier exceptions to diagnose, frequently. Whenever you get an exception in Java and you see the stack trace ( that's what your second quote-block is called, by the way ), you read from top to bottom. Often, you will see exceptions that start in Java library code or in native implementations methods, for diagnosis you can just skip past those until you see a code file that you wrote.

Then you like at the line indicated and look at each of the objects ( instantiated classes ) on that line -- one of them was not created and you tried to use it. You can start by looking up in your code to see if you called the constructor on that object. If you didn't, then that's your problem, you need to instantiate that object by calling new Classname( arguments ). Another frequent cause of NullPointerExceptions is accidentally declaring an object with local scope when there is an instance variable with the same name.

In your case, the exception occurred in your constructor for Workshop on line 75. <init> means the constructor for a class. If you look on that line in your code, you'll see the line

denimjeansButton.addItemListener(this);

There are fairly clearly two objects on this line: denimjeansButton and this. this is synonymous with the class instance you are currently in and you're in the constructor, so it can't be this. denimjeansButton is your culprit. You never instantiated that object. Either remove the reference to the instance variable denimjeansButton or instantiate it.

How do I make an auto increment integer field in Django?

You can use default primary key (id) which auto increaments.

Note: When you use first design i.e. use default field (id) as a primary key, initialize object by mentioning column names. e.g.

class User(models.Model):
    user_name = models.CharField(max_length = 100)

then initialize,

user = User(user_name="XYZ")

if you initialize in following way,

user = User("XYZ")

then python will try to set id = "XYZ" which will give you error on data type.

Python json.loads shows ValueError: Extra data

I came across this because I was trying to load a JSON file dumped from MongoDB. It was giving me an error

JSONDecodeError: Extra data: line 2 column 1

The MongoDB JSON dump has one object per line, so what worked for me is:

import json
data = [json.loads(line) for line in open('data.json', 'r')]

How do you add input from user into list in Python

shopList = [] 
maxLengthList = 6
while len(shopList) < maxLengthList:
    item = input("Enter your Item to the List: ")
    shopList.append(item)
    print shopList
print "That's your Shopping List"
print shopList

Laravel Eloquent inner join with multiple conditions

You can simply add multiple conditions by adding them as where() inside the join closure

->leftJoin('table2 AS b', function($join){
        $join->on('a.field1', '=', 'b.field2')
        ->where('b.field3', '=', true)
        ->where('b.field4', '=', '1');
})

Bootstrap 3 Carousel Not Working

There are just two minor things here.

The first is in the following carousel indicator list items:

<li data-target="carousel" data-slide-to="0"></li>

You need to pass the data-target attribute a selector which means the ID must be prefixed with #. So change them to the following:

<li data-target="#carousel" data-slide-to="0"></li>

Secondly, you need to give the carousel a starting point so both the carousel indicator items and the carousel inner items must have one active class. Like this:

<ol class="carousel-indicators">
    <li data-target="#carousel" data-slide-to="0" class="active"></li>
    <!-- Other Items -->
</ol>
<div class="carousel-inner">
    <div class="item active">
        <img src="https://picsum.photos/1500/600?image=1" alt="Slide 1" />
    </div>
    <!-- Other Items -->
</div>

Working Demo in Fiddle

What is the difference between response.sendRedirect() and request.getRequestDispatcher().forward(request,response)

Redirect and Request dispatcher are two different methods to move form one page to another. if we are using redirect to a new page actually a new request is happening from the client side itself to the new page. so we can see the change in the URL. Since redirection is a new request the old request values are not available here.

could not extract ResultSet in hibernate

I had the same issue, when I tried to update a row:

@Query(value = "UPDATE data SET value = 'asdf'", nativeQuery = true)
void setValue();

My Problem was that I forgot to add the @Modifying annotation:

@Modifying    
@Query(value = "UPDATE data SET value = 'asdf'", nativeQuery = true)
void setValue();

Select2() is not a function

I was having this problem when I started using select2 with XCrud. I solved it by disabling XCrud from loading JQuery, it was it a second time, and loading it below the body tag. So make sure JQuery isn't getting loaded twice on your page.

Closing Bootstrap modal onclick

Close the modal box using javascript

$('#product-options').modal('hide');

Open the modal box using javascript

$('#product-options').modal('show');

Toggle the modal box using javascript

$('#myModal').modal('toggle');

Means close the modal if it's open and vice versa.

How to upload files on server folder using jsp

You can only use absolute path http://grand-shopping.com/<"some folder"> is not an absolute path.

Either you can use a path inside the application which is vurneable or you can use server specific path like in

windows -> C:/Users/puneet verma/Downloads/
linux -> /opt/Downloads/

Double border with different color

You can use the border and box-shadow properties along with CSS pseudo elements to achieve a triple-border sort of effect. See the example below for an idea of how to create three borders at the bottom of a div:

_x000D_
_x000D_
.triple-border:after {_x000D_
    content: " ";_x000D_
    display: block;_x000D_
    width: 100%;_x000D_
    background: #FFE962;_x000D_
    height: 9px;_x000D_
    padding-bottom: 8px;_x000D_
    border-bottom: 9px solid #A3C662;_x000D_
    box-shadow: -2px 11px 0 -1px #34b6af;_x000D_
}
_x000D_
<div class="triple-border">Triple border bottom with multiple colours</div>
_x000D_
_x000D_
_x000D_

You'll have to play around with the values to get the alignment correct. However, you can also achieve more flexibility, e.g. 4 borders if you put some of the attributes in the proper element rather than the pseudo selector.

Resize image with javascript canvas (smoothly)

Based on K3N answer, I rewrite code generally for anyone wants

var oc = document.createElement('canvas'), octx = oc.getContext('2d');
    oc.width = img.width;
    oc.height = img.height;
    octx.drawImage(img, 0, 0);
    while (oc.width * 0.5 > width) {
       oc.width *= 0.5;
       oc.height *= 0.5;
       octx.drawImage(oc, 0, 0, oc.width, oc.height);
    }
    oc.width = width;
    oc.height = oc.width * img.height / img.width;
    octx.drawImage(img, 0, 0, oc.width, oc.height);

UPDATE JSFIDDLE DEMO

Here is my ONLINE DEMO

How to query for Xml values and attributes from table in SQL Server?

Actually you're close to your goal, you just need to use nodes() method to split your rows and then get values:

select
    s.SqmId,
    m.c.value('@id', 'varchar(max)') as id,
    m.c.value('@type', 'varchar(max)') as type,
    m.c.value('@unit', 'varchar(max)') as unit,
    m.c.value('@sum', 'varchar(max)') as [sum],
    m.c.value('@count', 'varchar(max)') as [count],
    m.c.value('@minValue', 'varchar(max)') as minValue,
    m.c.value('@maxValue', 'varchar(max)') as maxValue,
    m.c.value('.', 'nvarchar(max)') as Value,
    m.c.value('(text())[1]', 'nvarchar(max)') as Value2
from sqm as s
    outer apply s.data.nodes('Sqm/Metrics/Metric') as m(c)

sql fiddle demo

Using Cookie in Asp.Net Mvc 4

We are using Response.SetCookie() for update the old one cookies and Response.Cookies.Add() are use to add the new cookies. Here below code CompanyId is update in old cookie[OldCookieName].

HttpCookie cookie = Request.Cookies["OldCookieName"];//Get the existing cookie by cookie name.
cookie.Values["CompanyID"] = Convert.ToString(CompanyId);
Response.SetCookie(cookie); //SetCookie() is used for update the cookie.
Response.Cookies.Add(cookie); //The Cookie.Add() used for Add the cookie.

How to call webmethod in Asp.net C#

This is a bit late, but I just stumbled on this problem, trying to resolve my own problem of this kind. I then realized that I had this line in the ajax post wrong:

data: "{'quantity' : " + total_qty + ",'itemId':" + itemId + "}",

It should be:

data: "{quantity : '" + total_qty + "',itemId: '" + itemId + "'}",

As well as the WebMethod to:

public static string AddTo_Cart(string quantity, string itemId)

And this resolved my problem.

Hope it may be of help to someone else as well.

HTML5 Canvas Resize (Downscale) Image High Quality?

Why use the canvas to resize images? Modern browsers all use bicubic interpolation — the same process used by Photoshop (if you're doing it right) — and they do it faster than the canvas process. Just specify the image size you want (use only one dimension, height or width, to resize proportionally).

This is supported by most browsers, including later versions of IE. Earlier versions may require browser-specific CSS.

A simple function (using jQuery) to resize an image would be like this:

function resizeImage(img, percentage) {
    var coeff = percentage/100,
        width = $(img).width(),
        height = $(img).height();

    return {"width": width*coeff, "height": height*coeff}           
}

Then just use the returned value to resize the image in one or both dimensions.

Obviously there are different refinements you could make, but this gets the job done.

Paste the following code into the console of this page and watch what happens to the gravatars:

function resizeImage(img, percentage) {
    var coeff = percentage/100,
        width = $(img).width(),
        height = $(img).height();

    return {"width": width*coeff, "height": height*coeff}           
}

$('.user-gravatar32 img').each(function(){
  var newDimensions = resizeImage( this, 150);
  this.style.width = newDimensions.width + "px";
  this.style.height = newDimensions.height + "px";
});

Draw an X in CSS

_x000D_
_x000D_
#x{_x000D_
    width: 20px;_x000D_
    height: 20px;_x000D_
    background-color:orange;_x000D_
    position:relative;_x000D_
    border-radius:2px;_x000D_
}_x000D_
#x::after,#x::before{_x000D_
    position:absolute;_x000D_
    top:9px;_x000D_
    left:0px;_x000D_
    content:'';_x000D_
    display:block;_x000D_
    width:20px;_x000D_
    height:2px;_x000D_
    background-color:red;_x000D_
    _x000D_
}_x000D_
#x::after{_x000D_
    -webkit-transform: rotate(45deg);_x000D_
    -moz-transform: rotate(45deg);_x000D_
    -ms-transform: rotate(45deg);_x000D_
    -o-transform: rotate(45deg);_x000D_
    transform: rotate(45deg);_x000D_
}_x000D_
#x::before{_x000D_
    -webkit-transform: rotate(-45deg);_x000D_
    -moz-transform: rotate(-45deg);_x000D_
    -ms-transform: rotate(-45deg);_x000D_
    -o-transform: rotate(-45deg);_x000D_
    transform: rotate(-45deg);_x000D_
}
_x000D_
<div id=x>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Receive JSON POST with PHP

Try;

$data = json_decode(file_get_contents('php://input'), true);
print_r($data);
echo $data["operacion"];

From your json and your code, it looks like you have spelled the word operation correctly on your end, but it isn't in the json.

EDIT

Maybe also worth trying to echo the json string from php://input.

echo file_get_contents('php://input');

Creating and Update Laravel Eloquent

firstOrNew will create record if not exist and updating a row if already exist. You can also use updateOrCreate here is the full example

$flight = App\Flight::updateOrCreate(
    ['departure' => 'Oakland', 'destination' => 'San Diego'],
    ['price' => 99]
); 

If there's a flight from Oakland to San Diego, set the price to $99. if not exist create new row

Reference Doc here: (https://laravel.com/docs/5.5/eloquent)

jquery beforeunload when closing (not leaving) the page?

As indicated here https://stackoverflow.com/a/1632004/330867, you can implement it by "filtering" what is originating the exit of this page.

As mentionned in the comments, here's a new version of the code in the other question, which also include the ajax request you make in your question :

var canExit = true;

// For every function that will call an ajax query, you need to set the var "canExit" to false, then set it to false once the ajax is finished.

function checkCart() {
  canExit = false;
  $.ajax({
    url : 'index.php?route=module/cart/check',
    type : 'POST',
    dataType : 'json',
    success : function (result) {
       if (result) {
        canExit = true;
       }
    }
  })
}

$(document).on('click', 'a', function() {canExit = true;}); // can exit if it's a link
$(window).on('beforeunload', function() {
    if (canExit) return null; // null will allow exit without a question
    // Else, just return the message you want to display
    return "Do you really want to close?";
});

Important: You shouldn't have a global variable defined (here canExit), this is here for simpler version.

Note that you can't override completely the confirm message (at least in chrome). The message you return will only be prepended to the one given by Chrome. Here's the reason : How can I override the OnBeforeUnload dialog and replace it with my own?

AngularJS Multiple ng-app within a page

In my case I had to wrap the bootstrapping of my second app in angular.element(document).ready for it to work:

angular.element(document).ready(function() {
  angular.bootstrap(document.getElementById("app2"), ["app2"]);
});   

How to change navbar/container width? Bootstrap 3

I just solved this issue myself. You were on the right track.

@media (min-width: 1200px) {
    .container{
        max-width: 970px;
    }
}

Here we say: On viewports 1200px or larger - set container max-width to 970px. This will overwrite the standard class that currently sets max-width to 1170px for that range.

NOTE: Make sure you include this AFTER the bootstrap.css stuff (everyone has made this little mistake in the past).

Hope this helps.. good luck!

How to create custom button in Android using XML Styles

Two things you need to do, if you want to make a custom button design.

1st is: create a xml resource file in drawable folder (Example: btn_shape_rectangle.xml) then copy and paste the code there.

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:padding="16dp"
android:shape="rectangle">
<solid
    android:color="#fff"/>
<stroke
    android:width="1dp"
    android:color="#000000"
    />
<corners android:radius="10dp" />
</shape>

2nd is go to your layout button where you want to implement this design. just link up it. Example: android:background="@drawable/btn_shape_rectangle"

You can change shape color radius what design you want can do.

Hope it will works and help you. Happy Coding

How to write connection string in web.config file and read from it?

try this

var configuration = WebConfigurationManager.OpenWebConfiguration("~");
var section = (ConnectionStringsSection)configuration.GetSection("connectionStrings");
section.ConnectionStrings["MyConnectionString"].ConnectionString = "Data Source=...";
configuration.Save();

Export pictures from excel file into jpg using VBA

This code:

Option Explicit

Sub ExportMyPicture()

     Dim MyChart As String, MyPicture As String
     Dim PicWidth As Long, PicHeight As Long

     Application.ScreenUpdating = False
     On Error GoTo Finish

     MyPicture = Selection.Name
     With Selection
           PicHeight = .ShapeRange.Height
           PicWidth = .ShapeRange.Width
     End With

     Charts.Add
     ActiveChart.Location Where:=xlLocationAsObject, Name:="Sheet1"
     Selection.Border.LineStyle = 0
     MyChart = Selection.Name & " " & Split(ActiveChart.Name, " ")(2)

     With ActiveSheet
           With .Shapes(MyChart)
                 .Width = PicWidth
                 .Height = PicHeight
           End With

           .Shapes(MyPicture).Copy

           With ActiveChart
                 .ChartArea.Select
                 .Paste
           End With

           .ChartObjects(1).Chart.Export Filename:="MyPic.jpg", FilterName:="jpg"
           .Shapes(MyChart).Cut
     End With

     Application.ScreenUpdating = True
     Exit Sub

Finish:
     MsgBox "You must select a picture"
End Sub

was copied directly from here, and works beautifully for the cases I tested.

Set Matplotlib colorbar size to match graph

This combination (and values near to these) seems to "magically" work for me to keep the colorbar scaled to the plot, no matter what size the display.

plt.colorbar(im,fraction=0.046, pad=0.04)

It also does not require sharing the axis which can get the plot out of square.

How to redirect single url in nginx?

location ~ /issue([0-9]+) {
    return 301 http://example.com/shop/issues/custom_isse_name$1;
}

How to apply font anti-alias effects in CSS?

here you go Sir :-)

1

.myElement{
    -webkit-font-smoothing: antialiased;
    -moz-osx-font-smoothing: grayscale;
    text-rendering: optimizeLegibility;
}

2

.myElement{
    text-shadow: rgba(0,0,0,.01) 0 0 1px;
}

Instagram: Share photo from webpage

Updated June 2020

It is no longer possible... allegedly. If you have a Facebook or Instagram dedicated contact (because you work in either a big agency or with a big client) it may potentially be possible depending on your use case, but it's highly discouraged.


Before December 2019:

It is now "possible":

https://developers.facebook.com/docs/instagram-api/content-publishing

The Content Publishing API is a subset of Instagram Graph API endpoints that allow you to publish media objects. Publishing media objects with this API is a two step process — you first create a media object container, then publish the container on your Business Account.

Its worth noting that "The Content Publishing API is in closed beta with Facebook Marketing Partners and Instagram Partners only. We are not accepting new applicants at this time." from https://stackoverflow.com/a/49677468/445887

JavaFX Location is not set error message

I converted a simple NetBeans 8 Java FXML application to the Maven-driven one. Then I got problems, because the getResource() methods weren't able to find the .fxml files. In mine original application the fxmls were scattered through the package tree - each beside its controller class file. After I made Clean and build in NetBeans, I checked the result .jar in the target folder - the .jar didn't contain any fxml at all. All the fxmls were strangely disappeared.

Then I put all fxmls into the resources/fxml folder and set the getResource method parameters accordingly, for example: FXMLLoader(App.class.getClassLoader().getResource("fxml/ObjOverview.fxml")); In this case everything went OK. The fxml folder appeared int the .jar's root and it contained all my fxmls. The program was working as expected.

How can I send cookies using PHP curl in addition to CURLOPT_COOKIEFILE?

I think the only cookie you need is JSESSIONID=xxx..

Also NEVER share your cookies, becasuse someone may access your personal data that way. Specially when the cookies are session. These cookies will stop working once you logout the site.

Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result, boolean given in

The problem is your query returned false meaning there was an error in your query. After your query you could do the following:

if (!$result) {
    die(mysqli_error($link));
}

Or you could combine it with your query:

$results = mysqli_query($link, $query) or die(mysqli_error($link));

That will print out your error.

Also... you need to sanitize your input. You can't just take user input and put that into a query. Try this:

$query = "SELECT * FROM shopsy_db WHERE name LIKE '%" . mysqli_real_escape_string($link, $searchTerm) . "%'";

In reply to: Table 'sookehhh_shopsy_db.sookehhh_shopsy_db' doesn't exist

Are you sure the table name is sookehhh_shopsy_db? maybe it's really like users or something.

Spring MVC + JSON = 406 Not Acceptable

I couldn't see it as an answer here so I thought I would mention that I recieved this error using spring 4.2 when I accidentally removed the getter/setter for the class I was expecting to be returned as Json.

Creating a Shopping Cart using only HTML/JavaScript

Here's a one page cart written in Javascript with localStorage. Here's a full working pen. Previously found on Codebox

cart.js

var cart = {
  // (A) PROPERTIES
  hPdt : null, // HTML products list
  hItems : null, // HTML current cart
  items : {}, // Current items in cart

  // (B) LOCALSTORAGE CART
  // (B1) SAVE CURRENT CART INTO LOCALSTORAGE
  save : function () {
    localStorage.setItem("cart", JSON.stringify(cart.items));
  },

  // (B2) LOAD CART FROM LOCALSTORAGE
  load : function () {
    cart.items = localStorage.getItem("cart");
    if (cart.items == null) { cart.items = {}; }
    else { cart.items = JSON.parse(cart.items); }
  },

  // (B3) EMPTY ENTIRE CART
  nuke : function () {
    if (confirm("Empty cart?")) {
      cart.items = {};
      localStorage.removeItem("cart");
      cart.list();
    }
  },

  // (C) INITIALIZE
  init : function () {
    // (C1) GET HTML ELEMENTS
    cart.hPdt = document.getElementById("cart-products");
    cart.hItems = document.getElementById("cart-items");

    // (C2) DRAW PRODUCTS LIST
    cart.hPdt.innerHTML = "";
    let p, item, part;
    for (let id in products) {
      // WRAPPER
      p = products[id];
      item = document.createElement("div");
      item.className = "p-item";
      cart.hPdt.appendChild(item);

      // PRODUCT IMAGE
      part = document.createElement("img");
      part.src = "images/" +p.img;
      part.className = "p-img";
      item.appendChild(part);

      // PRODUCT NAME
      part = document.createElement("div");
      part.innerHTML = p.name;
      part.className = "p-name";
      item.appendChild(part);

      // PRODUCT DESCRIPTION
      part = document.createElement("div");
      part.innerHTML = p.desc;
      part.className = "p-desc";
      item.appendChild(part);

      // PRODUCT PRICE
      part = document.createElement("div");
      part.innerHTML = "$" + p.price;
      part.className = "p-price";
      item.appendChild(part);

      // ADD TO CART
      part = document.createElement("input");
      part.type = "button";
      part.value = "Add to Cart";
      part.className = "cart p-add";
      part.onclick = cart.add;
      part.dataset.id = id;
      item.appendChild(part);
    }

    // (C3) LOAD CART FROM PREVIOUS SESSION
    cart.load();

    // (C4) LIST CURRENT CART ITEMS
    cart.list();
  },

  // (D) LIST CURRENT CART ITEMS (IN HTML)
  list : function () {
    // (D1) RESET
    cart.hItems.innerHTML = "";
    let item, part, pdt;
    let empty = true;
    for (let key in cart.items) {
      if(cart.items.hasOwnProperty(key)) { empty = false; break; }
    }

    // (D2) CART IS EMPTY
    if (empty) {
      item = document.createElement("div");
      item.innerHTML = "Cart is empty";
      cart.hItems.appendChild(item);
    }

    // (D3) CART IS NOT EMPTY - LIST ITEMS
    else {
      let p, total = 0, subtotal = 0;
      for (let id in cart.items) {
        // ITEM
        p = products[id];
        item = document.createElement("div");
        item.className = "c-item";
        cart.hItems.appendChild(item);

        // NAME
        part = document.createElement("div");
        part.innerHTML = p.name;
        part.className = "c-name";
        item.appendChild(part);

        // REMOVE
        part = document.createElement("input");
        part.type = "button";
        part.value = "X";
        part.dataset.id = id;
        part.className = "c-del cart";
        part.addEventListener("click", cart.remove);
        item.appendChild(part);

        // QUANTITY
        part = document.createElement("input");
        part.type = "number";
        part.value = cart.items[id];
        part.dataset.id = id;
        part.className = "c-qty";
        part.addEventListener("change", cart.change);
        item.appendChild(part);

        // SUBTOTAL
        subtotal = cart.items[id] * p.price;
        total += subtotal;
      }

      // EMPTY BUTTONS
      item = document.createElement("input");
      item.type = "button";
      item.value = "Empty";
      item.addEventListener("click", cart.nuke);
      item.className = "c-empty cart";
      cart.hItems.appendChild(item);

      // CHECKOUT BUTTONS
      item = document.createElement("input");
      item.type = "button";
      item.value = "Checkout - " + "$" + total;
      item.addEventListener("click", cart.checkout);
      item.className = "c-checkout cart";
      cart.hItems.appendChild(item);
    }
  },

  // (E) ADD ITEM INTO CART
  add : function () {
    if (cart.items[this.dataset.id] == undefined) {
      cart.items[this.dataset.id] = 1;
    } else {
      cart.items[this.dataset.id]++;
    }
    cart.save();
    cart.list();
  },

  // (F) CHANGE QUANTITY
  change : function () {
    if (this.value == 0) {
      delete cart.items[this.dataset.id];
    } else {
      cart.items[this.dataset.id] = this.value;
    }
    cart.save();
    cart.list();
  },
  
  // (G) REMOVE ITEM FROM CART
  remove : function () {
    delete cart.items[this.dataset.id];
    cart.save();
    cart.list();
  },
  
  // (H) CHECKOUT
  checkout : function () {
    // SEND DATA TO SERVER
    // CHECKS
    // SEND AN EMAIL
    // RECORD TO DATABASE
    // PAYMENT
    // WHATEVER IS REQUIRED
    alert("TO DO");

    /*
    var data = new FormData();
    data.append('cart', JSON.stringify(cart.items));
    data.append('products', JSON.stringify(products));
    var xhr = new XMLHttpRequest();
    xhr.open("POST", "SERVER-SCRIPT");
    xhr.onload = function(){ ... };
    xhr.send(data);
    */
  }
};
window.addEventListener("DOMContentLoaded", cart.init);

How to require a controller in an angularjs directive

I got lucky and answered this in a comment to the question, but I'm posting a full answer for the sake of completeness and so we can mark this question as "Answered".


It depends on what you want to accomplish by sharing a controller; you can either share the same controller (though have different instances), or you can share the same controller instance.

Share a Controller

Two directives can use the same controller by passing the same method to two directives, like so:

app.controller( 'MyCtrl', function ( $scope ) {
  // do stuff...
});

app.directive( 'directiveOne', function () {
  return {
    controller: 'MyCtrl'
  };
});

app.directive( 'directiveTwo', function () {
  return {
    controller: 'MyCtrl'
  };
});

Each directive will get its own instance of the controller, but this allows you to share the logic between as many components as you want.

Require a Controller

If you want to share the same instance of a controller, then you use require.

require ensures the presence of another directive and then includes its controller as a parameter to the link function. So if you have two directives on one element, your directive can require the presence of the other directive and gain access to its controller methods. A common use case for this is to require ngModel.

^require, with the addition of the caret, checks elements above directive in addition to the current element to try to find the other directive. This allows you to create complex components where "sub-components" can communicate with the parent component through its controller to great effect. Examples could include tabs, where each pane can communicate with the overall tabs to handle switching; an accordion set could ensure only one is open at a time; etc.

In either event, you have to use the two directives together for this to work. require is a way of communicating between components.

Check out the Guide page of directives for more info: http://docs.angularjs.org/guide/directive

notifyDataSetChange not working from custom adapter

class StudentAdapter extends BaseAdapter {
    ArrayList<LichHocDTO> studentList;

    private void capNhatDuLieu(ArrayList<LichHocDTO> list){
        this.studentList.clear();
        this.studentList.addAll(list);
        this.notifyDataSetChanged();
    }
}

You can try. It work for me

Photoshop text tool adds punctuation to the beginning of text

Select all text afected by this issue:

Window -> Character, click the icon next to hide the Character Window, Middle Western Features and select Left-to-right character direction.

How to force open links in Chrome not download them?

Great question.

It can be achieved via an extension:

Setting transparent images background in IrfanView

You were on the right track. IrfanView sets the background for transparency the same as the viewing color around the image.

You just need to re-open the image with IrfanView after changing the view color to white.

To change the viewing color in Irfanview go to:

Options > Properties/Settings > Viewing > Main window color

How To Make Circle Custom Progress Bar in Android

Circle Android Custom Progress Bar

for more information on How to create Circle Android Custom Progress Bar view this link

Step 01 You should create an xml file on drawable file for configure the appearance of progress bar . So Im creating my xml file as circular_progress_bar.xml.

<?xml version="1.0" encoding="UTF-8"?>

<layer-list xmlns:android="http://schemas.android.com/apk/res/android"
android:fromDegrees="120"
android:pivotX="50%"
android:pivotY="50%"
android:toDegrees="140">
<item android:id="@android:id/background">
<shape
    android:innerRadiusRatio="3"
    android:shape="ring"
    android:useLevel="false"
     android:angle="0"
     android:type="sweep"
    android:thicknessRatio="50.0">
    <solid android:color="#000000"/>
</shape>

 </item>
 <item android:id="@android:id/progress">
   <rotate
    android:fromDegrees="120"
    android:toDegrees="120">
<shape
    android:innerRadiusRatio="3"
    android:shape="ring"
     android:angle="0"
     android:type="sweep"
    android:thicknessRatio="50.0">
    <solid android:color="#ffffff"/>
</shape>
</rotate>
</item>
</layer-list>

Step 02 Then create progress bar on your xml file Then give the name of xml file on your drawable folder as the parth of android:progressDrawable

 <ProgressBar
            android:id="@+id/progressBar"
            style="?android:attr/progressBarStyleHorizontal"
            android:layout_width="150dp"
            android:layout_height="150dp"
            android:layout_marginLeft="0dp"
            android:layout_centerHorizontal="true"
            android:indeterminate="false"
            android:max="100"
            android:progressDrawable="@drawable/circular_progress_bar" />

Step 03 Visual the progress bar using thread

package com.example.progress;
import android.os.Bundle;
import android.os.Handler;
import android.app.Activity;
import android.view.Menu;
import android.view.animation.Animation;
 import android.view.animation.TranslateAnimation;
 import android.widget.ProgressBar;
 import android.widget.TextView;

 public class MainActivity extends Activity {

  private ProgressBar progBar;
  private TextView text;
     private Handler mHandler = new Handler();
     private int mProgressStatus=0;



@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    progBar= (ProgressBar)findViewById(R.id.progressBar);
    text = (TextView)findViewById(R.id.textView1);

    dosomething();
}



  public void dosomething() {

  new Thread(new Runnable() {
        public void run() {
        final int presentage=0;
            while (mProgressStatus < 63) {
                mProgressStatus += 1;
                // Update the progress bar
                mHandler.post(new Runnable() {
                    public void run() {
                        progBar.setProgress(mProgressStatus);
                        text.setText(""+mProgressStatus+"%");

                    }
                });
                try {



                    Thread.sleep(50);

                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }).start();
  }


 }

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

In my case, I was rendering another action method for my menu section in _layout.cshtml file using @Html.Action("Menu", "Menu") whereas I forgot to create Menu controller and as layout file was being used in my current controller action's view therefore I was getting this error in my current action render request. try to look in your layout and as well as view file if you did the same mistake

How to deal with ModalDialog using selenium webdriver?

Nope, Model window needs to be handle by javaScriptExecutor,Because majorly model window made up of window model, This will works once model appeared then control take a place into model and click the expected element.

have to import javascriptexector

like below,

Javascriptexecutor js =(Javascriptexecutor).driver;
js.executescript(**<element to be clicked>**);

str_replace with array

If the text is a simple markup and has existing anchors, stage the existing anchor tags first, swap out the urls, then replace the staged markers.

$text = '
Lorem Ipsum is simply dummy text found by searching http://google.com/?q=lorem in your <a href=https://www.mozilla.org/en-US/firefox/>Firefox</a>,
<a href="https://www.apple.com/safari/">Safari</a>, or https://www.google.com/chrome/ browser.

Link replacements will first stage existing anchor tags, replace each with a marker, then swap out the remaining links.
Links should be properly encoded.  If links are not separated from surrounding content like a trailing "." period then they it will be included in the link.
Links that are not encoded properly may create a problem, so best to use this when you know the text you are processing is not mixed HTML.

Example: http://google.com/i,m,complicate--d/index.html
Example: https://www.google.com/chrome/?123&t=123
Example: http://google.com/?q='. urlencode('<a href="http://google.com">http://google.com</a>') .'
';

// Replace existing links with a marker
$linkStore = array();
$text = preg_replace_callback('/(<a.*?a>)/', function($match) use (&$linkStore){ $key = '__linkStore'.count($linkStore).'__'; $linkStore[$key] = $match[0]; return $key; }, $text);

// Replace remaining URLs with an anchor tag
$text = preg_replace_callback("/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/", function($match) use (&$linkStore){ return '<a href="'. $match[0] .'">'. $match[0] .'</a>'; }, $text);

// Replace link markers with original
$text = str_replace(array_keys($linkStore), array_values($linkStore), $text);

echo '<pre>'.$text;

Get index of selected option with jQuery

try this

 alert(document.getElementById("dropDownMenuKategorie").selectedIndex);

HttpContext.Current.Request.Url.Host what it returns?

Yes, as long as the url you type into the browser www.someshopping.com and you aren't using url rewriting then

string currentURL = HttpContext.Current.Request.Url.Host;

will return www.someshopping.com

Note the difference between a local debugging environment and a production environment

How to pass a textbox value from view to a controller in MVC 4?

I'll just try to answer the question but my examples very simple because I'm new at mvc. Hope this help somebody.

    [HttpPost]  ///This function is in my controller class
    public ActionResult Delete(string txtDelete)
    {
        int _id = Convert.ToInt32(txtDelete); // put your code           
    }

This code is in my controller's cshtml

  >   @using (Html.BeginForm("Delete", "LibraryManagement"))
 {
<button>Delete</button>
@Html.Label("Enter an ID number");
@Html.TextBox("txtDelete")  }  

Just make sure the textbox name and your controller's function input are the same name and type(string).This way, your function get the textbox input.

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

    } 
}

How to print strings with line breaks in java

I think you are making it too complex. AttributedString is used when you want to store attributes - in Printing Context. But You are storing data inside that. AttributedString

Simply, store your data into Document object and pass properties like Font, Bold, Italic everything in AttributedString.

Hope this will be helpful A quick tutorial And In depth tutorial

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

Setting the spring.jackson.default-property-inclusion=non_null option is the simplest solution and it works well.

However, be careful if you implement WebMvcConfigurer somewhere in your code, then the property solution will not work and you will have to setup NON_NULL serialization in the code as the following:

@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {
    // some of your config here...

    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        MappingJackson2HttpMessageConverter jsonConverter = new MappingJackson2HttpMessageConverter(objectMapper);
        converters.add(jsonConverter);
    }
}

WooCommerce return product object by id

Alright, I deserve to be throttled. definitely an RTM but not for WooCommerce, for Wordpress. Solution found due to a JOLT cola (all hail JOLT cola).

TASK: Field named 'related_product_ids' added to a custom post type. So when that post is displayed mini product displays can be displayed with it.

PROBLEM: Was having a problem getting the multiple ids returned via WP_Query.

SOLUTION:

$related_id_list          = get_post_custom_values('related_product_ids');
    // Get comma delimited list from current post
$related_product_ids      = explode(",", trim($related_id_list[0],','));
    // Return an array of the IDs ensure no empty array elements from extra commas
$related_product_post_ids = array( 'post_type' => 'product', 
                                   'post__in'  => $related_product_ids,
                                   'meta_query'=> array( 
                                        array( 'key'    => '_visibility',
                                               'value'  => array('catalog', 'visible'),'compare' => 'IN'
                                        )
                            ) 
);      
    // Query to get all product posts matching given IDs provided it is a published post
$loop = new WP_Query( $related_posts );
    // Execute query
while ( $loop->have_posts() ) : $loop->the_post(); $_product = get_product( $loop->post->ID );
    // Do stuff here to display your products 
endwhile;

Thank you for anyone who may have spent some time on this.

Tim

No MediaTypeFormatter is available to read an object of type 'String' from content with media type 'text/plain'

Try using ReadAsStringAsync() instead.

 var foo = resp.Content.ReadAsStringAsync().Result;

The reason why it ReadAsAsync<string>() doesn't work is because ReadAsAsync<> will try to use one of the default MediaTypeFormatter (i.e. JsonMediaTypeFormatter, XmlMediaTypeFormatter, ...) to read the content with content-type of text/plain. However, none of the default formatter can read the text/plain (they can only read application/json, application/xml, etc).

By using ReadAsStringAsync(), the content will be read as string regardless of the content-type.

CodeIgniter -> Get current URL relative to base url

Try to use "uri" segments like:

$this->uri->segment(5);   //To get 'ahahaha'
$this->uri->segment(6);   //To get 'hihihi

form your first URL...You get '' from second URl also for segment(5),segment(6) also because they are empty.

Every segment function counts starts form localhost as '1' and symultaneous segments

$_POST Array from html form

I don't know if I understand your question, but maybe:

foreach ($_POST as $id=>$value)
    if (strncmp($id,'id[',3) $info[rtrim(ltrim($id,'id['),']')]=$_POST[$id];

would help

That is if you really want to have a different name (id[key]) on each checkbox of the html form (not very efficient). If not you can just name them all the same, i.e. 'id' and iterate on the (selected) values of the array, like: foreach ($_POST['id'] as $key=>$value)...

CSS centred header image

If you set the margin to be margin:0 auto the image will be centered.

This will give top + bottom a margin of 0, and left and right a margin of 'auto'. Since the div has a width (200px), the image will be 200px wide and the browser will auto set the left and right margin to half of what is left on the page, which will result in the image being centered.

CSS: How to change colour of active navigation page menu

Add ID current for active/current page:

<div class="menuBar">
  <ul>
  <li id="current"><a href="index.php">HOME</a></li>
  <li><a href="two.php">PORTFOLIO</a></li>
  <li><a href="three.php">ABOUT</a></li>
  <li><a href="four.php">CONTACT</a></li>
  <li><a href="five.php">SHOP</a></li>
 </ul>

#current a { color: #ff0000; }

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '''')' at line 2

I was getting the same error when I used this code to update the record:

@mysqli_query($dbc,$query or die()))

After removing or die, it started working properly.

How to POST JSON Data With PHP cURL?

$url = 'url_to_post';
$data = array("first_name" => "First name","last_name" => "last name","email"=>"[email protected]","addresses" => array ("address1" => "some address" ,"city" => "city","country" => "CA", "first_name" =>  "Mother","last_name" =>  "Lastnameson","phone" => "555-1212", "province" => "ON", "zip" => "123 ABC" ) );

$postdata = json_encode($data);

$ch = curl_init($url);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
$result = curl_exec($ch);
curl_close($ch);
print_r ($result);

This code worked for me. You can try...

How to fix "no valid 'aps-environment' entitlement string found for application" in Xcode 4.3?

I had a similar issue. I've been bouncing between XCode 7 and 8 for a variety of reasons. Once you use 8 to build, you will need to use 8. I simply used Xcode 8 and applied some of the changes suggested above and it worked.

Uncaught syntaxerror: unexpected identifier?

There are errors here :

var formTag = document.getElementsByTagName("form"), // form tag is an array
selectListItem = $('select'),
makeSelect = document.createElement('select'),
makeSelect.setAttribute("id", "groups");

The code must change to:

var formTag = document.getElementsByTagName("form");
var selectListItem = $('select');
var makeSelect = document.createElement('select');
makeSelect.setAttribute("id", "groups");

By the way, there is another error at line 129 :

var createLi.appendChild(createSubList);

Replace it with:

createLi.appendChild(createSubList);

Xcode Simulator: how to remove older unneeded devices?

  1. Open Xcode --> Go to Window (from menu bar) --> Devices and Simulators --> Click on Simulator --> Right-click on the simulator that you want to delete --> Click Delete

  2. To delete any unwanted simulators that you installed in the past as an extra Component through Xcode.

  • Open Terminal

  • Type open /Library/Developer/CoreSimulator/Profiles/Runtimes

  • Delete undesired simulators

apache not accepting incoming connections from outside of localhost

Try with below setting in iptables.config table

iptables -A INPUT -p tcp --dport 80 -j ACCEPT

Run the below command to restart the iptable service

service iptables restart

change the httpd.config file to

Listen 192.170.2.1:80

re-start the apache.

Try now.

Making RGB color in Xcode

You already got the right answer, but if you dislike the UIColor interface like me, you can do this:

#import "UIColor+Helper.h"
// ...
myLabel.textColor = [UIColor colorWithRGBA:0xA06105FF];

UIColor+Helper.h:

#import <UIKit/UIKit.h>

@interface UIColor (Helper)
+ (UIColor *)colorWithRGBA:(NSUInteger)color;
@end

UIColor+Helper.m:

#import "UIColor+Helper.h"

@implementation UIColor (Helper)

+ (UIColor *)colorWithRGBA:(NSUInteger)color
{
    return [UIColor colorWithRed:((color >> 24) & 0xFF) / 255.0f
                           green:((color >> 16) & 0xFF) / 255.0f
                            blue:((color >> 8) & 0xFF) / 255.0f
                           alpha:((color) & 0xFF) / 255.0f];
}

@end

Find duplicate records in a table using SQL Server

SQL> SELECT JOB,COUNT(JOB) FROM EMP GROUP BY JOB;

JOB       COUNT(JOB)
--------- ----------
ANALYST            2
CLERK              4
MANAGER            3
PRESIDENT          1
SALESMAN           4

importing a CSV into phpmyadmin

In phpMyAdmin v.4.6.5.2 there's a checkbox option "The first line of the file contains the table column names...." :

enter image description here

SQL Server - inner join when updating

This should do it:

UPDATE ProductReviews
SET    ProductReviews.status = '0'
FROM   ProductReviews
       INNER JOIN products
         ON ProductReviews.pid = products.id
WHERE  ProductReviews.id = '17190'
       AND products.shopkeeper = '89137'

FB OpenGraph og:image not pulling images (possibly https?)

From what I observed, I see that when your website is public and even though the image url is https, it just works fine.

How to convert JSON to CSV format and store in a variable

I just wanted to add some code here for people in the future since I was trying to export JSON to a CSV document and download it.

I use $.getJSON to pull json data from an external page, but if you have a basic array, you can just use that.

This uses Christian Landgren's code to create the csv data.

$(document).ready(function() {
    var JSONData = $.getJSON("GetJsonData.php", function(data) {
        var items = data;
        const replacer = (key, value) => value === null ? '' : value; // specify how you want to handle null values here
        const header = Object.keys(items[0]);
        let csv = items.map(row => header.map(fieldName => JSON.stringify(row[fieldName], replacer)).join(','));
        csv.unshift(header.join(','));
        csv = csv.join('\r\n');

        //Download the file as CSV
        var downloadLink = document.createElement("a");
        var blob = new Blob(["\ufeff", csv]);
        var url = URL.createObjectURL(blob);
        downloadLink.href = url;
        downloadLink.download = "DataDump.csv";  //Name the file here
        document.body.appendChild(downloadLink);
        downloadLink.click();
        document.body.removeChild(downloadLink);
    });
});

Edit: It's worth noting that JSON.stringify will escape quotes in quotes by adding \". If you view the CSV in excel, it doesn't like that as an escape character.

You can add .replace(/\\"/g, '""') to the end of JSON.stringify(row[fieldName], replacer) to display this properly in excel (this will replace \" with "" which is what excel prefers).

Full Line: let csv = items.map(row => header.map(fieldName => (JSON.stringify(row[fieldName], replacer).replace(/\\"/g, '""'))).join(','));

How do I set 'semi-bold' font via CSS? Font-weight of 600 doesn't make it look like the semi-bold I see in my Photoshop file

For me the following works good. Just add it. You can edit it as per your requirement. This is just a nice trick I use.

text-shadow : 0 0 0 #your-font-color;

Jersey Exception : SEVERE: A message body reader for Java class

Try adding:

<dependency>
    <groupId>com.owlike</groupId>
    <artifactId>genson</artifactId>
    <version>1.4</version>
</dependency>

Also this problem may occur if you're using HTTP GET with message body so in this case adding jersey-json lib, @XmlRootElement or modifying web.xml won't help. You should use URL QueryParam or HTTP POST.

Is there a way to use two CSS3 box shadows on one element?

You can comma-separate shadows:

box-shadow: inset 0 2px 0px #dcffa6, 0 2px 5px #000;

symfony 2 No route found for "GET /"

I have also tried that error , I got it right by just adding /hello/any name because it is path that there must be an hello/name

example : instead of just putting http://localhost/app_dev.php

put it like this way http://localhost/name_of_your_project/web/app_dev.php/hello/ai

it will display Hello Ai . I hope I answer your question.

Strange Characters in database text: Ã, Ã, ¢, â‚ €,

I encountered today quite a similar problem : mysqldump dumped my utf-8 base encoding utf-8 diacritic characters as two latin1 characters, although the file itself is regular utf8.

For example : "é" was encoded as two characters "é". These two characters correspond to the utf8 two bytes encoding of the letter but it should be interpreted as a single character.

To solve the problem and correctly import the database on another server, I had to convert the file using the ftfy (stands for "Fixes Text For You). (https://github.com/LuminosoInsight/python-ftfy) python library. The library does exactly what I expect : transform bad encoded utf-8 to correctly encoded utf-8.

For example : This latin1 combination "é" is turned into an "é".

ftfy comes with a command line script but it transforms the file so it can not be imported back into mysql.

I wrote a python3 script to do the trick :

#!/usr/bin/python3
# coding: utf-8

import ftfy

# Set input_file
input_file = open('mysql.utf8.bad.dump', 'r', encoding="utf-8")
# Set output file
output_file = open ('mysql.utf8.good.dump', 'w')

# Create fixed output stream
stream = ftfy.fix_file(
    input_file,
    encoding=None,
    fix_entities='auto', 
    remove_terminal_escapes=False, 
    fix_encoding=True, 
    fix_latin_ligatures=False, 
    fix_character_width=False, 
    uncurl_quotes=False, 
    fix_line_breaks=False, 
    fix_surrogates=False, 
    remove_control_chars=False, 
    remove_bom=False, 
    normalization='NFC'
)

# Save stream to output file
stream_iterator = iter(stream)
while stream_iterator:
    try:
        line = next(stream_iterator)
        output_file.write(line)
    except StopIteration:
        break

Mysql database sync between two databases

Have a look at Schema and Data Comparison tools in dbForge Studio for MySQL. These tool will help you to compare, to see the differences, generate a synchronization script and synchronize two databases.

How to convert a .eps file to a high quality 1024x1024 .jpg?

Maybe you should try it with -quality 100 -size "1024x1024", because resize often gives results that are ugly to view.

Setting up a cron job in Windows

There's pycron which I really as a Cron implementation for windows, but there's also the built in scheduler which should work just fine for what you need (Control Panel -> Scheduled Tasks -> Add Scheduled Task).

Soft Edges using CSS?

You can use CSS gradient - although there are not consistent across browsers so You would have to code it for every one

Like that: CSS3 Transparency + Gradient

Gradient should be more transparent on top or on top right corner (depending on capabilities)

"Connect failed: Access denied for user 'root'@'localhost' (using password: YES)" from php function

Easy.

open xampp control panel -> Config -> my.ini edit with notepad. now add this below [mysqld]

skip-grant-tables

Save. Start apache and mysql.

I hope help you

InvalidKeyException : Illegal Key Size - Java code throwing exception for encryption class - how to fix?

The error seems to be thrown when you try and load they keystore from "C:/jakarta-tomcat/webapps/PlanB/Certs/my_pkcs12.p12" here:

ks.load( new FileInputStream(_privateKeyPath), _keyPass.toCharArray() ); 

Have you tried replaceing "/" with "\\" in your file path? If that doesn't help it probably has to do with Java's Unlimited Strength Jurisdiction Policy Files. You could check this by writing a little program that does AES encryption. Try encrypting with a 128 bit key, then if that works, try with a 256 bit key and see if it fails.

Code that does AES encyrption:

import java.io.UnsupportedEncodingException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

public class Test 
{
    final String ALGORITHM = "AES";                       //symmetric algorithm for data encryption
    final String PADDING_MODE = "/CBC/PKCS5Padding";      //Padding for symmetric algorithm
    final String CHAR_ENCODING = "UTF-8";                 //character encoding
    //final String CRYPTO_PROVIDER = "SunMSCAPI";             //provider for the crypto

    int AES_KEY_SIZE = 256;  //symmetric key size (128, 192, 256) if using 256 you must have the Java Cryptography Extension (JCE) Unlimited Strength Jurisdiction Policy Files  installed

    private String doCrypto(String plainText) throws NoSuchAlgorithmException, NoSuchProviderException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException, InvalidAlgorithmParameterException, UnsupportedEncodingException
    {
        byte[] dataToEncrypt = plainText.getBytes(CHAR_ENCODING);

        //get the symmetric key generator
        KeyGenerator keyGen = KeyGenerator.getInstance(ALGORITHM);
        keyGen.init(AES_KEY_SIZE); //set the key size

        //generate the key
        SecretKey skey = keyGen.generateKey();

        //convert to binary
        byte[] rawAesKey = skey.getEncoded();

        //initialize the secret key with the appropriate algorithm
        SecretKeySpec skeySpec = new SecretKeySpec(rawAesKey, ALGORITHM);

        //get an instance of the symmetric cipher
        Cipher aesCipher = Cipher.getInstance(ALGORITHM + PADDING_MODE);

        //set it to encrypt mode, with the generated key
        aesCipher.init(Cipher.ENCRYPT_MODE, skeySpec);

        //get the initialization vector being used (to be returned)
        byte[] aesIV = aesCipher.getIV();

        //encrypt the data
        byte[] encryptedData = aesCipher.doFinal(dataToEncrypt);    

        //initialize the secret key with the appropriate algorithm
        SecretKeySpec skeySpecDec = new SecretKeySpec(rawAesKey, ALGORITHM);

        //get an instance of the symmetric cipher
        Cipher aesCipherDec = Cipher.getInstance(ALGORITHM +PADDING_MODE);

        //set it to decrypt mode with the AES key, and IV
        aesCipherDec.init(Cipher.DECRYPT_MODE, skeySpecDec, new IvParameterSpec(aesIV));

        //decrypt and return the data
        byte[] decryptedData = aesCipherDec.doFinal(encryptedData);

        return new String(decryptedData, CHAR_ENCODING);
    }

    public static void main(String[] args)
    {
        String text = "Lets encrypt me";

        Test test = new Test();

        try {
            System.out.println(test.doCrypto(text));
        } catch (InvalidKeyException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NoSuchProviderException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (BadPaddingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InvalidAlgorithmParameterException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

Does this code work for you?

You might also want to try specifying your bouncy castle provider in this line:

Cipher.getInstance(ALGORITHM +PADDING_MODE, "YOUR PROVIDER");

And see if it could be an error associated with bouncy castle.

Excel - Sum column if condition is met by checking other column in same table

Actually a more refined solution is use the build-in function sumif, this function does exactly what you need, will only sum those expenses of a specified month.

example

=SUMIF(A2:A100,"=January",B2:B100)

how to read a text file using scanner in Java?

I would recommend loading the file as Resource and converting the input stream into string. This would give you the flexibility to load the file anywhere relative to the classpath

How do I make an image smaller with CSS?

You can resize images using CSS just fine if you're modifying an image tag:

<img src="example.png" style="width:2em; height:3em;" />

You cannot scale a background-image property using CSS2, although you can try the CSS3 property background-size.

What you can do, on the other hand, is to nest an image inside a span. See the answer to this question: Stretch and scale CSS background

Foreach value from POST from form

i wouldn't do it this way

I'd use name arrays in the form elements

so i'd get the layout

$_POST['field'][0]['name'] = 'value';
$_POST['field'][0]['price'] = 'value';
$_POST['field'][1]['name'] = 'value';
$_POST['field'][1]['price'] = 'value';

then you could do an array slice to get the amount you need

CSS Margin: 0 is not setting to 0

h1 {
margin-top:0;
padding-top: 0;}

It' s just a misunderstanding with h1 tag. You have to set h1 tag margin-top and padding-top to 0 (zero).

PHP Warning: Unknown: failed to open stream

In Fedora 25, it turned out to be an SE Linux issue, and the notification gave this solution which worked for me.

setsebool -P httpd_read_user_content 1

The entity cannot be constructed in a LINQ to Entities query

You cannot (and should not be able to) project onto a mapped entity. You can, however, project onto an anonymous type or onto a DTO:

public class ProductDTO
{
    public string Name { get; set; }
    // Other field you may need from the Product entity
}

And your method will return a List of DTO's.

public List<ProductDTO> GetProducts(int categoryID)
{
    return (from p in db.Products
            where p.CategoryID == categoryID
            select new ProductDTO { Name = p.Name }).ToList();
}

Getting a count of rows in a datatable that meet certain criteria

If the data is stored in a database it will be faster to send the query to the database instead of getting all data and query it in memory.

A third way to do it will be linq to datasets, but i doubt any of these 3 methods differ much in performance.

Redirecting from HTTP to HTTPS with PHP

Try something like this (should work for Apache and IIS):

if (empty($_SERVER['HTTPS']) || $_SERVER['HTTPS'] === "off") {
    $location = 'https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
    header('HTTP/1.1 301 Moved Permanently');
    header('Location: ' . $location);
    exit;
}

How to create a HTML Table from a PHP array?

You may use this function. To add table header you can setup a second parameter $myTableArrayHeader and do the same with the header information in front of the body:

function insertTable($myTableArrayBody) {
    $x = 0;
    $y = 0;
    $seTableStr = '<table><tbody>';
    while (isset($myTableArrayBody[$y][$x])) {
        $seTableStr .= '<tr>';
        while (isset($myTableArrayBody[$y][$x])) {
            $seTableStr .= '<td>' . $myTableArrayBody[$y][$x] . '</td>';
            $x++;
        }
        $seTableStr .= '</tr>';
        $x = 0;
        $y++;
    }
    $seTableStr .= '</tbody></table>';
    return $seTableStr;
}

PHP error: Notice: Undefined index:

I did define all the variables that was the first thing I checked. I know it's not required in PHP, but old habits die hard. Then I sanatized the info like this:

if ($_SERVER["REQUEST_METHOD"] == "POST") {
  if (empty($_POST["name1"])) {
    $name1Err = " First Name is a required field.";
  } else {
      $name1 = test_input($_POST["name1"]);
    // check if name only contains letters and whitespace
      if (!preg_match("/^[a-zA-Z ]*$/",$name1)) {
      $name1Err = "Only letters and white space allowed";

of course test_input is another function that does a trim, strilashes, and htmlspecialchars. I think the input is pretty well sanitized. Not trying to be rude just showing what I did. When it came to the email I also checked to see if it was the proper format. I think the real answer is in the fact that some variables are local and some are global. I have got it working without errors for now so, while I'm extremely busy right now I'll accept shutting off errors as my answer. Don't worry I'll figure it out it's just not vitally important right now!

Unexpected token ILLEGAL in webkit

I got the same error when the script file I was including container some special characters and when I was running in local moode (directly from local disk). I my case the solution was to explicitly tell the encoding:

<script src="my.js" charset="UTF-8"></script>

How to concatenate strings in django templates?

Refer to Concatenating Strings in Django Templates:

  1. For earlier versions of Django:

    {{ "Mary had a little"|stringformat:"s lamb." }}

"Mary had a little lamb."

  1. Else:

    {{ "Mary had a little"|add:" lamb." }}

"Mary had a little lamb."

MySQL Like multiple values

The (a,b,c) list only works with in. For like, you have to use or:

WHERE interests LIKE '%sports%' OR interests LIKE '%pub%'

Scanner doesn't read whole sentence - difference between next() and nextLine() of scanner class

Default delimiter of Scanner is whitespace. Check javadoc for how to change this.

Error renaming a column in MySQL

ALTER TABLE CHANGE ;

Example:

ALTER TABLE global_user CHANGE deviceToken deviceId VARCHAR(255) ;

Code line wrapping - how to handle long lines

IMHO this is the best way to write your line :

private static final Map<Class<? extends Persistent>, PersistentHelper> class2helper =
        new HashMap<Class<? extends Persistent>, PersistentHelper>();

This way the increased indentation without any braces can help you to see that the code was just splited because the line was too long. And instead of 4 spaces, 8 will make it clearer.

org.hibernate.exception.ConstraintViolationException: Could not execute JDBC batch update

Your Event.hbm.xml says:

<set name="attendees" cascade="all">
    <key column="attendeeId" />
    <one-to-many class="Attendee" />
</set>

In plain english, this means that the column Attendee.attendeeId is the foreign key for the association attendees and points to the primary key of Event.

When you add those Attendees to the event, hibernate updates the foreign key to express the changed association. Since that same column is also the primary key of Attendee, this violates the primary key constraint.

Since an Attendee's identity and event participation are independent, you should use separate columns for the primary and foreign key.

Edit: The selects might be because you don't appear to have a version property configured, making it impossible for hibernate to know whether the attendees already exists in the database (they might have been loaded in a previous session), so hibernate emits selects to check. As for the update statements, it was probably easier to implement that way. If you want to get rid of these separate updates, I recommend mapping the association from both ends, and declare the Event-end as inverse.

Make A List Item Clickable (HTML/CSS)

The li element supports an onclick event.

<ul>
<li onclick="location.href = 'http://stackoverflow.com/questions/3486110/make-a-list-item-clickable-html-css';">Make A List Item Clickable</li>
</ul>

How do I check if string contains substring?

Returns number of times the keyword is included in the string.

var count = "I have one keyword".match(/keyword/g);
var clean_count = !count ? false : count.length;

MYSQL Truncated incorrect DOUBLE value

Mainly invalid query strings will give this warning.

Wrong due to a subtle syntax error (misplaced right parenthesis) when using INSTR function:

INSERT INTO users (user_name) SELECT name FROM site_users WHERE
INSTR(status, 'active'>0);

Correct:

INSERT INTO users (user_name) SELECT name FROM site_users WHERE
INSTR(status, 'active')>0;

add id to dynamically created <div>

Use Jquery for append the value for creating dynamically

eg:

var user_image1='<img src="{@user_image}" class="img-thumbnail" alt="Thumbnail Image" 
style="width:125px; height:125px">';

$("#userphoto").append(user_image1.replace("{@user_image}","http://127.0.0.1:50075/webhdfs/v1/PATH/"+user_image+"?op=OPEN")); 

HTML :

<div id="userphoto">

preg_match in JavaScript?

var thisRegex = new RegExp('\[(\d+)\]\[(\d+)\]');

if(!thisRegex.test(text)){
    alert('fail');
}

I found test to act more preg_match as it provides a Boolean return. However you do have to declare a RegExp var.

TIP: RegExp adds it's own / at the start and finish, so don't pass them.

'AND' vs '&&' as operator

Another nice example using if statements without = assignment operations.

if (true || true && false); // is the same as:
if (true || (true && false)); // TRUE

and

if (true || true AND false); // is the same as:
if ((true || true) && false); // FALSE

because AND has a lower precedence and thus || a higher precedence.

These are different in the cases of true, false, false and true, true, false. See https://ideone.com/lsqovs for en elaborate example.

mysql_fetch_array() expects parameter 1 to be resource problem

The most likely cause is an error in mysql_query(). Have you checked to make sure it worked? Output the value of $result and mysql_error(). You may have misspelled something, selected the wrong database, have a permissions issue, etc. So:

$id = (int)$_GET['id']; // this also sanitizes it
$sql = "SELECT * FROM student WHERE idno = $id";
$result = mysql_query($sql);
if (!$result) {
  die("Error running $sql: " . mysql_error());
}

Sanitizing $_GET['id'] is really important. You can use mysql_real_escape_string() but casting it to an int is sufficient for integers. Basically you want to avoid SQL injection.

CSS Font Border?

I once tried to do those round corners and drop shadows with css3. Later on, I found it is still poorly supported (Internet Explorer(s), of course!)

I ended up trying to do that in JS (HTML canvas with IE Canvas), but it impacts the performance a lot (even on my C2D machine). In short, if you really need the effect, consider JS libraries (most of them should be able to run on IE6) but don't over do it due to performance issues; if you still need an alternative... you could use SFiR, then PS it and SFiR it. CSS3 isn't ready today.

Replace transparency in PNG images with white background

The only one that worked for me was a mix of all the answers:

convert in.png -background white -alpha remove -flatten -alpha off out.png

Resizing an image in an HTML5 canvas

For resizing to image with width less that original, i use:

    function resize2(i) {
      var cc = document.createElement("canvas");
      cc.width = i.width / 2;
      cc.height = i.height / 2;
      var ctx = cc.getContext("2d");
      ctx.drawImage(i, 0, 0, cc.width, cc.height);
      return cc;
    }
    var cc = img;
    while (cc.width > 64 * 2) {
      cc = resize2(cc);
    }
    // .. than drawImage(cc, .... )

and it works =).

How to make a page redirect using JavaScript?

You can append the values in the query string for the next page to see and process. You can wrap them inside the link tags:

<a href="your_page.php?var1=value1&var2=value2">

You separate each of those values with the & sign.

Or you can create this on a button click like this:

<input type="button" onclick="document.location.href = 'your_page.php?var1=value1&var2=value2';">

iPhone App Icons - Exact Radius?

You can make four icons (as of today) for your app and they can all have a different look - not necessarily based on the 512x512 image.

  • corner radius for the 512x512 icon = 80 (iTunesArtwork)
  • corner radius for the 1024x1024 icon = 180 (iTunesArtwork Retina)
  • corner radius for the 57x57 icon = 9 (iPhone/iPod Touch)
  • corner radius for the 114x114 icon = 18 (iPhone/iPod Touch Retina)
  • corner radius for the 72x72 icon = 11 (iPad)
  • corner radius for the 144x144 icon = 23 (iPad Retina)

If you do create a set of custom icons, you can set the UIPrerenderedIcon option to true in your info.plist file and it will not add the gloss effect but it will place a black background under it and still round the image corners with these corner radii so if the corner radius on any of the icons is greater then it will show black around the edges/corners.

Edit: See comment from @devin-g-rhode and you can see that any future icon sizes should have a 1:6.4 ratio of corner radius to icon size. There is also a very good answer from https://stackoverflow.com/a/29550364/396005 which has the location of image mask files used in the SDK for rounding icon corners

To add a retina-compatible file, use the same file name and add '@2x'. So if I had a file for my 72x72 icon named icon.png, I would also add a 114x114 PNG file named [email protected] to the project/target and Xcode would automatically use that as the icon on a retina display. You can see this in action on the Summary page of the application target if you've done it right. The same works for your launch images. Use launch.png at 320x480 and [email protected] at 640x960.

How do I represent a time only value in .NET?

If that empty Date really bugs you, you can also to create a simpler Time structure:

// more work is required to make this even close to production ready
class Time
{
    // TODO: don't forget to add validation
    public int Hours   { get; set; }
    public int Minutes { get; set; }
    public int Seconds { get; set; }

    public override string ToString()
    {  
        return String.Format(
            "{0:00}:{1:00}:{2:00}",
            this.Hours, this.Minutes, this.Seconds);
    }
}

Or, why to bother: if you don't need to do any calculation with that information, just store it as String.

How can I add spaces between two <input> lines using CSS?

You can format them as table !!

_x000D_
_x000D_
form {_x000D_
  display: table;_x000D_
}_x000D_
label {_x000D_
  display: table-row;_x000D_
}_x000D_
input {_x000D_
  display: table-cell;_x000D_
}_x000D_
p1 {_x000D_
  display: table-cell;_x000D_
}
_x000D_
<div id="header_order_form" align="center">_x000D_
  <form id="order_header" method="post">_x000D_
    <label>_x000D_
      <p1>order_no:_x000D_
        <input type="text">_x000D_
      </p1>_x000D_
      <p1>order_type:_x000D_
        <input type="text">_x000D_
      </p1>_x000D_
    </label>_x000D_
    </br>_x000D_
    </br>_x000D_
    <label>_x000D_
      <p1>_x000D_
        creation_date:_x000D_
        <input type="text">_x000D_
      </p1>_x000D_
      <p1>delivery_date:_x000D_
        <input type="text">_x000D_
      </p1>_x000D_
      <p1>billing_date:_x000D_
        <input type="text">_x000D_
      </p1>_x000D_
    </label>_x000D_
    </br>_x000D_
    </br>_x000D_
_x000D_
    <label>_x000D_
      <p1>sold_to_party:_x000D_
        <input type="text">_x000D_
      </p1>_x000D_
      <p1>sop_address:_x000D_
        <input type="text">_x000D_
      </p1>_x000D_
    </label>_x000D_
  </form>_x000D_
</div>
_x000D_
_x000D_
_x000D_

JAX-WS and BASIC authentication, when user names and passwords are in a database

In your client SOAP handler you need to set javax.xml.ws.security.auth.username and javax.xml.ws.security.auth.password property as follow:

public class ClientHandler implements SOAPHandler<SOAPMessageContext>{

    public boolean handleMessage(final SOAPMessageContext soapMessageContext)
    {
        final Boolean outInd = (Boolean)soapMessageContext.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);
        if (outInd.booleanValue())
        {
          try 
          {
               soapMessageContext.put("javax.xml.ws.security.auth.username", <ClientUserName>);
               soapMessageContext.put("javax.xml.ws.security.auth.password", <ClientPassword>);
          } 
          catch (Exception e)
          {
               e.printStackTrace();
               return false;
          }
         }
      return true;
     }
}

How to Generate Unique Public and Private Key via RSA

What I ended up doing is create a new KeyContainer name based off of the current DateTime (DateTime.Now.Ticks.ToString()) whenever I need to create a new key and save the container name and public key to the database. Also, whenever I create a new key I would do the following:

public static string ConvertToNewKey(string oldPrivateKey)
{

    // get the current container name from the database...

    rsa.PersistKeyInCsp = false;
    rsa.Clear();
    rsa = null;

    string privateKey = AssignNewKey(true); // create the new public key and container name and write them to the database...

       // re-encrypt existing data to use the new keys and write to database...

    return privateKey;
}
public static string AssignNewKey(bool ReturnPrivateKey){
     string containerName = DateTime.Now.Ticks.ToString();
     // create the new key...
     // saves container name and public key to database...
     // and returns Private Key XML.
}

before creating the new key.

PNG transparency issue in IE8

PNG transparency pr?bl?m in IE8

Dan's solution worked for me. I was trying to fade a div with a background image. Caveats: you cannot fade the div directly, instead fade a wrapper image. Also, add the following filters to apply a background image:

-ms-filter: "progid:DXImageTransform.Microsoft.gradient(startColorstr=#00FFFFFF,endColorstr=#00FFFFFF)progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled='true',sizingMethod='image',src='assets/img/bgSmall.png')"; /* IE8 */   
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr=#00FFFFFF,endColorstr=#00FFFFFF)progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled='true',sizingMethod='image',src='assets/img/bgSmall.png');   /* IE6 & 7 */      

Please note that the paths in the src attributes of the filters are absolute, and not relative to the css sheet.

I also added:

background: transparent\9;

This causes IE to ignore my earlier declaration of the actual background image for the other browsers.

Thanks Dan!!!

How to use XPath contains() here?

//ul[@class="featureList" and li//text()[contains(., "Model")]]

VIM Disable Automatic Newline At End Of File

I've implemented Blixtor's suggestions with Perl and Python post-processing, either running inside Vim (if it is compiled with such language support), or via an external Perl script. It's available as the PreserveNoEOL plugin on vim.org.

What is the best method of handling currency/money?

Using Virtual Attributes (Link to revised(paid) Railscast) you can store your price_in_cents in an integer column and add a virtual attribute price_in_dollars in your product model as a getter and setter.

# Add a price_in_cents integer column
$ rails g migration add_price_in_cents_to_products price_in_cents:integer

# Use virtual attributes in your Product model
# app/models/product.rb

def price_in_dollars
  price_in_cents.to_d/100 if price_in_cents
end

def price_in_dollars=(dollars)
  self.price_in_cents = dollars.to_d*100 if dollars.present?
end

Source: RailsCasts #016: Virtual Attributes: Virtual attributes are a clean way to add form fields that do not map directly to the database. Here I show how to handle validations, associations, and more.

Uncaught SoapFault exception: [HTTP] Error Fetching http headers

Please update your php.ini with

default_socket_timeout = 120

You can create your own php.ini if php is installed a CGI instead of a Apache module

List of special characters for SQL LIKE clause

Sybase :

%              : Matches any string of zero or more characters.
_              : Matches a single character.
[specifier]    : Brackets enclose ranges or sets, such as [a-f] 
                 or [abcdef].Specifier  can take two forms:

                 rangespec1-rangespec2: 
                   rangespec1 indicates the start of a range of characters.
                   - is a special character, indicating a range.
                   rangespec2 indicates the end of a range of characters.

                 set: 
                  can be composed of any discrete set of values, in any 
                  order, such as [a2bR].The range [a-f], and the 
                  sets [abcdef] and [fcbdae] return the same 
                  set of values.

                 Specifiers are case-sensitive.

[^specifier]    : A caret (^) preceding a specifier indicates 
                  non-inclusion. [^a-f] means "not in the range 
                  a-f"; [^a2bR] means "not a, 2, b, or R."

Scanner vs. StringTokenizer vs. String.Split

One important difference is that both String.split() and Scanner can produce empty strings but StringTokenizer never does it.

For example:

String str = "ab cd  ef";

StringTokenizer st = new StringTokenizer(str, " ");
for (int i = 0; st.hasMoreTokens(); i++) System.out.println("#" + i + ": " + st.nextToken());

String[] split = str.split(" ");
for (int i = 0; i < split.length; i++) System.out.println("#" + i + ": " + split[i]);

Scanner sc = new Scanner(str).useDelimiter(" ");
for (int i = 0; sc.hasNext(); i++) System.out.println("#" + i + ": " + sc.next());

Output:

//StringTokenizer
#0: ab
#1: cd
#2: ef
//String.split()
#0: ab
#1: cd
#2: 
#3: ef
//Scanner
#0: ab
#1: cd
#2: 
#3: ef

This is because the delimiter for String.split() and Scanner.useDelimiter() is not just a string, but a regular expression. We can replace the delimiter " " with " +" in the example above to make them behave like StringTokenizer.

How to query as GROUP BY in django?

from django.db.models import Sum
Members.objects.annotate(total=Sum(designation))

first you need to import Sum then ..

Can I concatenate multiple MySQL rows into one field?

Have a look at GROUP_CONCAT if your MySQL version (4.1) supports it. See the documentation for more details.

It would look something like:

  SELECT GROUP_CONCAT(hobbies SEPARATOR ', ') 
  FROM peoples_hobbies 
  WHERE person_id = 5 
  GROUP BY 'all';

High Quality Image Scaling Library

There's an article on Code Project about using GDI+ for .NET to do photo resizing using, say, Bicubic interpolation.

There was also another article about this topic on another blog (MS employee, I think), but I can't find the link anywhere. :( Perhaps someone else can find it?

Overriding the java equals() method - not working?

Slightly off-topic to your question, but it's probably worth mentioning anyway:

Commons Lang has got some excellent methods you can use in overriding equals and hashcode. Check out EqualsBuilder.reflectionEquals(...) and HashCodeBuilder.reflectionHashCode(...). Saved me plenty of headache in the past - although of course if you just want to do "equals" on ID it may not fit your circumstances.

I also agree that you should use the @Override annotation whenever you're overriding equals (or any other method).

How can I save a screenshot directly to a file in Windows?

Might I suggest WinSnap http://www.ntwind.com/software/winsnap/download-free-version.html. It provides an autosave option and capture the alt+printscreen and other key combinations to capture screen, windows, dialog, etc.

How to force a web browser NOT to cache images

I assume original question regards images stored with some text info. So, if you have access to a text context when generating src=... url, consider store/use CRC32 of image bytes instead of meaningless random or time stamp. Then, if the page with plenty of images is displaying, only updated images will be reloaded. Eventually, if CRC storing is impossible, it can be computed and appended to the url at runtime.

Do you use source control for your database items?

We have a weekly sql dump into a subversion repo. It's fully automated but it's a REALLY beefy task.

You'll want to limit the number of revisions because it really chows disk space after a while!

What is your single most favorite command-line trick using Bash?

You should be able to paste the following into a bash terminal window.

Display ANSI colour palette:

e="\033["
for f in 0 7 `seq 6`; do
  no="" bo=""
  for b in n 7 0 `seq 6`; do
    co="3$f"; p="  "
    [ $b = n ] || { co="$co;4$b";p=""; }
    no="${no}${e}${co}m   ${p}${co} ${e}0m"
    bo="${bo}${e}1;${co}m ${p}1;${co} ${e}0m"
  done
  echo -e "$no\n$bo"
done

256 colour demo:

yes "$(seq 232 255;seq 254 -1 233)" |
while read i; do printf "\x1b[48;5;${i}m\n"; sleep .01; done

How do I set/unset a cookie with jQuery?

$.cookie("test", 1); //set cookie
$.cookie("test"); //get cookie
$.cookie('test', null); //delete cookie

initialize a const array in a class initializer in C++

It is not possible in the current standard. I believe you'll be able to do this in C++0x using initializer lists (see A Brief Look at C++0x, by Bjarne Stroustrup, for more information about initializer lists and other nice C++0x features).

Android changing Floating Action Button color

 <android.support.design.widget.FloatingActionButton
    android:id="@+id/fab"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="bottom|end"
    app:elevation="6dp"
    app:backgroundTint="@color/colorAccent"
    app:pressedTranslationZ="12dp"
    android:layout_margin="@dimen/fab_margin"
    android:src="@drawable/add"/>

Note that you add colors in res/values/color.xml and include the attribute in your fab

   app:backgroundTint="@color/addedColor"

How to find the Number of CPU Cores via .NET/C#?

There are several different pieces of information relating to processors that you could get:

  1. Number of physical processors
  2. Number of cores
  3. Number of logical processors.

These can all be different; in the case of a machine with 2 dual-core hyper-threading-enabled processors, there are 2 physical processors, 4 cores, and 8 logical processors.

The number of logical processors is available through the Environment class, but the other information is only available through WMI (and you may have to install some hotfixes or service packs to get it on some systems):

Make sure to add a reference in your project to System.Management.dll In .NET Core, this is available (for Windows only) as a NuGet package.

Physical Processors:

foreach (var item in new System.Management.ManagementObjectSearcher("Select * from Win32_ComputerSystem").Get())
{
    Console.WriteLine("Number Of Physical Processors: {0} ", item["NumberOfProcessors"]);
}

Cores:

int coreCount = 0;
foreach (var item in new System.Management.ManagementObjectSearcher("Select * from Win32_Processor").Get())
{
    coreCount += int.Parse(item["NumberOfCores"].ToString());
}
Console.WriteLine("Number Of Cores: {0}", coreCount);

Logical Processors:

Console.WriteLine("Number Of Logical Processors: {0}", Environment.ProcessorCount);

OR

foreach (var item in new System.Management.ManagementObjectSearcher("Select * from Win32_ComputerSystem").Get())
{
    Console.WriteLine("Number Of Logical Processors: {0}", item["NumberOfLogicalProcessors"]);
}

Processors excluded from Windows:

You can also use Windows API calls in setupapi.dll to discover processors that have been excluded from Windows (e.g. through boot settings) and aren't detectable using the above means. The code below gives the total number of logical processors (I haven't been able to figure out how to differentiate physical from logical processors) that exist, including those that have been excluded from Windows:

static void Main(string[] args)
{
    int deviceCount = 0;
    IntPtr deviceList = IntPtr.Zero;
    // GUID for processor classid
    Guid processorGuid = new Guid("{50127dc3-0f36-415e-a6cc-4cb3be910b65}");

    try
    {
        // get a list of all processor devices
        deviceList = SetupDiGetClassDevs(ref processorGuid, "ACPI", IntPtr.Zero, (int)DIGCF.PRESENT);
        // attempt to process each item in the list
        for (int deviceNumber = 0; ; deviceNumber++)
        {
            SP_DEVINFO_DATA deviceInfo = new SP_DEVINFO_DATA();
            deviceInfo.cbSize = Marshal.SizeOf(deviceInfo);

            // attempt to read the device info from the list, if this fails, we're at the end of the list
            if (!SetupDiEnumDeviceInfo(deviceList, deviceNumber, ref deviceInfo))
            {
                deviceCount = deviceNumber;
                break;
            }
        }
    }
    finally
    {
        if (deviceList != IntPtr.Zero) { SetupDiDestroyDeviceInfoList(deviceList); }
    }
    Console.WriteLine("Number of cores: {0}", deviceCount);
}

[DllImport("setupapi.dll", SetLastError = true)]
private static extern IntPtr SetupDiGetClassDevs(ref Guid ClassGuid,
    [MarshalAs(UnmanagedType.LPStr)]String enumerator,
    IntPtr hwndParent,
    Int32 Flags);

[DllImport("setupapi.dll", SetLastError = true)]
private static extern Int32 SetupDiDestroyDeviceInfoList(IntPtr DeviceInfoSet);

[DllImport("setupapi.dll", SetLastError = true)]
private static extern bool SetupDiEnumDeviceInfo(IntPtr DeviceInfoSet,
    Int32 MemberIndex,
    ref SP_DEVINFO_DATA DeviceInterfaceData);

[StructLayout(LayoutKind.Sequential)]
private struct SP_DEVINFO_DATA
{
    public int cbSize;
    public Guid ClassGuid;
    public uint DevInst;
    public IntPtr Reserved;
}

private enum DIGCF
{
    DEFAULT = 0x1,
    PRESENT = 0x2,
    ALLCLASSES = 0x4,
    PROFILE = 0x8,
    DEVICEINTERFACE = 0x10,
}

How to find file accessed/created just few minutes ago

If you know the file is in your current directory, I would use:

ls -lt | head

This lists your most recently modified files and directories in order. In fact, I use it so much I have it aliased to 'lh'.

Get current date in Swift 3?

You say in a comment you want to get "15.09.2016".

For this, use Date and DateFormatter:

let date = Date()
let formatter = DateFormatter()

Give the format you want to the formatter:

formatter.dateFormat = "dd.MM.yyyy"

Get the result string:

let result = formatter.string(from: date)

Set your label:

label.text = result

Result:

15.09.2016

Find the server name for an Oracle database

If you don't have access to the v$ views (as suggested by Quassnoi) there are two alternatives

select utl_inaddr.get_host_name from dual

and

select sys_context('USERENV','SERVER_HOST') from dual

Personally I'd tend towards the last as it doesn't require any grants/privileges which makes it easier from stored procedures.

How to declare and use 1D and 2D byte arrays in Verilog?

It is simple actually, like C programming you just need to pass the array indices on the right hand side while declaration. But yeah the syntax will be like [0:3] for 4 elements.

reg a[0:3]; 

This will create a 1D of array of single bit. Similarly 2D array can be created like this:

reg [0:3][0:2];

Now in C suppose you create a 2D array of int, then it will internally create a 2D array of 32 bits. But unfortunately Verilog is an HDL, so it thinks in bits rather then bunch of bits (though int datatype is there in Verilog), it can allow you to create any number of bits to be stored inside an element of array (which is not the case with C, you can't store 5-bits in every element of 2D array in C). So to create a 2D array, in which every individual element can hold 5 bit value, you should write this:

reg [0:4] a [0:3][0:2];

String, StringBuffer, and StringBuilder

Note that if you are using Java 5 or newer, you should use StringBuilder instead of StringBuffer. From the API documentation:

As of release JDK 5, this class has been supplemented with an equivalent class designed for use by a single thread, StringBuilder. The StringBuilder class should generally be used in preference to this one, as it supports all of the same operations but it is faster, as it performs no synchronization.

In practice, you will almost never use this from multiple threads at the same time, so the synchronization that StringBuffer does is almost always unnecessary overhead.

Send response to all clients except sender

Emit cheatsheet

io.on('connect', onConnect);

function onConnect(socket){

  // sending to the client
  socket.emit('hello', 'can you hear me?', 1, 2, 'abc');

  // sending to all clients except sender
  socket.broadcast.emit('broadcast', 'hello friends!');

  // sending to all clients in 'game' room except sender
  socket.to('game').emit('nice game', "let's play a game");

  // sending to all clients in 'game1' and/or in 'game2' room, except sender
  socket.to('game1').to('game2').emit('nice game', "let's play a game (too)");

  // sending to all clients in 'game' room, including sender
  io.in('game').emit('big-announcement', 'the game will start soon');

  // sending to all clients in namespace 'myNamespace', including sender
  io.of('myNamespace').emit('bigger-announcement', 'the tournament will start soon');

  // sending to individual socketid (private message)
  socket.to(<socketid>).emit('hey', 'I just met you');

  // sending with acknowledgement
  socket.emit('question', 'do you think so?', function (answer) {});

  // sending without compression
  socket.compress(false).emit('uncompressed', "that's rough");

  // sending a message that might be dropped if the client is not ready to receive messages
  socket.volatile.emit('maybe', 'do you really need it?');

  // sending to all clients on this node (when using multiple nodes)
  io.local.emit('hi', 'my lovely babies');

};

Python 2.6: Class inside a Class?

It sounds like you are talking about aggregation. Each instance of your player class can contain zero or more instances of Airplane, which, in turn, can contain zero or more instances of Flight. You can implement this in Python using the built-in list type to save you naming variables with numbers.

class Flight(object):

    def __init__(self, duration):
        self.duration = duration


class Airplane(object):

    def __init__(self):
        self.flights = []

    def add_flight(self, duration):
        self.flights.append(Flight(duration))


class Player(object):

    def __init__ (self, stock = 0, bank = 200000, fuel = 0, total_pax = 0):
        self.stock = stock
        self.bank = bank
        self.fuel = fuel
        self.total_pax = total_pax
        self.airplanes = []


    def add_planes(self):
        self.airplanes.append(Airplane())



if __name__ == '__main__':
    player = Player()
    player.add_planes()
    player.airplanes[0].add_flight(5)

How to set an "Accept:" header on Spring RestTemplate request?

Here is a simple answer. Hope it helps someone.

import org.springframework.boot.devtools.remote.client.HttpHeaderInterceptor;
import org.springframework.http.MediaType;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.web.client.RestTemplate;


public String post(SomeRequest someRequest) {
    // create a list the headers 
    List<ClientHttpRequestInterceptor> interceptors = new ArrayList<>();
    interceptors.add(new HttpHeaderInterceptor("Accept", MediaType.APPLICATION_JSON_VALUE));
    interceptors.add(new HttpHeaderInterceptor("ContentType", MediaType.APPLICATION_JSON_VALUE));
    interceptors.add(new HttpHeaderInterceptor("username", "user123"));
    interceptors.add(new HttpHeaderInterceptor("customHeader1", "c1"));
    interceptors.add(new HttpHeaderInterceptor("customHeader2", "c2"));
    // initialize RestTemplate
    RestTemplate restTemplate = new RestTemplate();
    // set header interceptors here
    restTemplate.setInterceptors(interceptors);
    // post the request. The response should be JSON string
    String response = restTemplate.postForObject(Url, someRequest, String.class);
    return response;
}

Fast and Lean PDF Viewer for iPhone / iPad / iOS - tips and hints?

For a simple and effective PDF viewer, when you require only limited functionality, you can now (iOS 4.0+) use the QuickLook framework:

First, you need to link against QuickLook.framework and #import <QuickLook/QuickLook.h>;

Afterwards, in either viewDidLoad or any of the lazy initialization methods:

QLPreviewController *previewController = [[QLPreviewController alloc] init];
previewController.dataSource = self;
previewController.delegate = self;
previewController.currentPreviewItemIndex = indexPath.row;
[self presentModalViewController:previewController animated:YES];
[previewController release];

Driver executable must be set by the webdriver.ie.driver system property

I just put the driver files directly into my project to not get any dependency to my local machine.

final File file = new File("driver/chromedriver_2_22_mac");
System.setProperty("webdriver.chrome.driver", file.getAbsolutePath());

driver = new ChromeDriver();

Can anybody tell me details about hs_err_pid.log file generated when Tomcat crashes?

A very very good document regarding this topic is Troubleshooting Guide for Java from (originally) Sun. See the chapter "Troubleshooting System Crashes" for information about hs_err_pid* Files.

See Appendix C - Fatal Error Log

Per the guide, by default the file will be created in the working directory of the process if possible, or in the system temporary directory otherwise. A specific location can be chosen by passing in the -XX:ErrorFile product flag. It says:

If the -XX:ErrorFile= file flag is not specified, the system attempts to create the file in the working directory of the process. In the event that the file cannot be created in the working directory (insufficient space, permission problem, or other issue), the file is created in the temporary directory for the operating system.

Exception: "URI formats are not supported"

Try This

ImagePath = "http://localhost/profilepics/abc.png";
   HttpWebRequest request = (HttpWebRequest)WebRequest.Create(ImagePath);
          HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream receiveStream = response.GetResponseStream();

String concatenation of two pandas columns

@DanielVelkov answer is the proper one BUT using string literals is faster:

# Daniel's
%timeit df.apply(lambda x:'%s is %s' % (x['bar'],x['foo']),axis=1)
## 963 µs ± 157 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

# String literals - python 3
%timeit df.apply(lambda x: f"{x['bar']} is {x['foo']}", axis=1)
## 849 µs ± 4.28 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

convert a char* to std::string

I need to use std::string to store data retrieved by fgets().

Why using fgets() when you are programming C++? Why not std::getline()?

C# - Create SQL Server table programmatically

Try this

Check if table have there , and drop the table , then create

using (SqlCommand command = new SqlCommand("IF EXISTS (
SELECT *
FROM sys.tables
WHERE name LIKE '#Customer%')
DROP TABLE #Customer CREATE TABLE Customer(First_Name char(50),Last_Name char(50),Address char(50),City char(50),Country char(25),Birth_Date datetime);", con))

problem with php mail 'From' header

Edit: I just noted that you are trying to use a gmail address as the from value. This is not going to work, and the ISP is right in overwriting it. If you want to redirect the replies to your outgoing messages, use reply-to.

A workaround for valid addresses that works with many ISPs:

try adding a fifth parameter to your mail() command:

mail($to,$subject,$message,$headers,"-f [email protected]");

How to create a date and time picker in Android?

I forked, updated, refactored and mavenized the android-dateslider project. It is on Github now:

https://github.com/casidiablo/date-slider

While loop in batch

@echo off

set countfiles=10

:loop

set /a countfiles -= 1

echo hi

if %countfiles% GTR 0 goto loop

pause

on the first "set countfiles" the 10 you see is the amount it will loop the echo hi is the thing you want to loop

...i'm 5 years late

Is there a way to word-wrap long words in a div?

Most of the previous answer didn't work for me in Firefox 38.0.5. This did...

<div style='padding: 3px; width: 130px; word-break: break-all; word-wrap: break-word;'>
    // Content goes here
</div>

Documentation:

How can I express that two values are not equal to eachother?

If the class implements comparable, you could also do

int compRes = a.compareTo(b);
if(compRes < 0 || compRes > 0)
    System.out.println("not equal");
else
    System.out.println("equal);

doesn't use a !, though not particularly useful, or readable....

How to only find files in a given directory, and ignore subdirectories using bash

This may do what you want:

find /dev \( ! -name /dev -prune \) -type f -print

ReferenceError: variable is not defined

Got the error (in the function init) with the following code ;

"use strict" ;

var hdr ;

function init(){ // called on load
    hdr = document.getElementById("hdr");
}

... while using the stock browser on a Samsung galaxy Fame ( crap phone which makes it a good tester ) - userAgent ; Mozilla/5.0 (Linux; U; Android 4.1.2; en-gb; GT-S6810P Build/JZO54K) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30

The same code works everywhere else I tried including the stock browser on an older HTC phone - userAgent ; Mozilla/5.0 (Linux; U; Android 2.3.5; en-gb; HTC_WildfireS_A510e Build/GRJ90) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1

The fix for this was to change

var hdr ;

to

var hdr = null ;

T-test in Pandas

it depends what sort of t-test you want to do (one sided or two sided dependent or independent) but it should be as simple as:

from scipy.stats import ttest_ind

cat1 = my_data[my_data['Category']=='cat1']
cat2 = my_data[my_data['Category']=='cat2']

ttest_ind(cat1['values'], cat2['values'])
>>> (1.4927289925706944, 0.16970867501294376)

it returns a tuple with the t-statistic & the p-value

see here for other t-tests http://docs.scipy.org/doc/scipy/reference/stats.html

Perfect 100% width of parent container for a Bootstrap input?

I found a solution that worked in my case:

<input class="form-control" style="min-width: 100%!important;" type="text" />

You only need to override the min-width set 100% and important and the result is this one:

enter image description here

If you don't apply it, you will always get this:

enter image description here

addEventListener not working in IE8

if (document.addEventListener) {
    document.addEventListener("click", attachEvent, false);
}
else {
    document.attachEvent("onclick", attachEvent);
}
function attachEvent(ev) {
    var target = ev.target || ev.srcElement;
    // custom code
}

Communication between tabs or windows

Edit 2018: You may better use BroadcastChannel for this purpose, see other answers below. Yet if you still prefer to use localstorage for communication between tabs, do it this way:

In order to get notified when a tab sends a message to other tabs, you simply need to bind on 'storage' event. In all tabs, do this:

$(window).on('storage', message_receive);

The function message_receive will be called every time you set any value of localStorage in any other tab. The event listener contains also the data newly set to localStorage, so you don't even need to parse localStorage object itself. This is very handy because you can reset the value just right after it was set, to effectively clean up any traces. Here are functions for messaging:

// use local storage for messaging. Set message in local storage and clear it right away
// This is a safe way how to communicate with other tabs while not leaving any traces
//
function message_broadcast(message)
{
    localStorage.setItem('message',JSON.stringify(message));
    localStorage.removeItem('message');
}


// receive message
//
function message_receive(ev)
{
    if (ev.originalEvent.key!='message') return; // ignore other keys
    var message=JSON.parse(ev.originalEvent.newValue);
    if (!message) return; // ignore empty msg or msg reset

    // here you act on messages.
    // you can send objects like { 'command': 'doit', 'data': 'abcd' }
    if (message.command == 'doit') alert(message.data);

    // etc.
}

So now once your tabs bind on the onstorage event, and you have these two functions implemented, you can simply broadcast a message to other tabs calling, for example:

message_broadcast({'command':'reset'})

Remember that sending the exact same message twice will be propagated only once, so if you need to repeat messages, add some unique identifier to them, like

message_broadcast({'command':'reset', 'uid': (new Date).getTime()+Math.random()})

Also remember that the current tab which broadcasts the message doesn't actually receive it, only other tabs or windows on the same domain.

You may ask what happens if the user loads a different webpage or closes his tab just after the setItem() call before the removeItem(). Well, from my own testing the browser puts unloading on hold until the entire function message_broadcast() is finished. I tested to put inthere some very long for() cycle and it still waited for the cycle to finish before closing. If the user kills the tab just inbetween, then the browser won't have enough time to save the message to disk, thus this approach seems to me like safe way how to send messages without any traces. Comments welcome.

How to replace special characters in a string?

Here is a function I used to remove all possible special characters from the string

let name = name.replace(/[&\/\\#,+()$~%!.„'":*‚^_¤?<>|@ª{«»§}©®™ ]/g, '').toLowerCase();

How do I force git pull to overwrite everything on every pull?

git reset --hard HEAD
git fetch --all
git reset --hard origin/your_branch

Android Volley - BasicNetwork.performRequest: Unexpected response code 400

One way of doing this without changing Volley's source code is to check for the response data in the VolleyError and parse it your self.

As of f605da3 commit, Volley throws a ServerError exception that contains the raw network response.

So you can do something similar to this in your error listener:

/* import com.android.volley.toolbox.HttpHeaderParser; */
public void onErrorResponse(VolleyError error) {

    // As of f605da3 the following should work
    NetworkResponse response = error.networkResponse;
    if (error instanceof ServerError && response != null) {
        try {
            String res = new String(response.data,
                       HttpHeaderParser.parseCharset(response.headers, "utf-8"));
            // Now you can use any deserializer to make sense of data
            JSONObject obj = new JSONObject(res);
        } catch (UnsupportedEncodingException e1) {
            // Couldn't properly decode data to string
            e1.printStackTrace();
        } catch (JSONException e2) {
            // returned data is not JSONObject?
            e2.printStackTrace();
        }
    }
}

For future, if Volley changes, one can follow the above approach where you need to check the VolleyError for raw data that has been sent by the server and parse it.

I hope that they implement that TODO mentioned in the source file.

ImportError: No module named PyQt4.QtCore

I was having the same error - ImportError: No module named PyQt4.QtGui. Instead of running your python file (which uses PyQt) on the terminal as -

python file_name.py

Run it with sudo privileges -

sudo python file_name.py

This worked for me!

How to Publish Web with msbuild?

You can Publish the Solution with desired path by below code, Here PublishInDFolder is the name that has the path where we need to publish(we need to create this in below pic)

You can create publish file like this

Add below 2 lines of code in batch file(.bat)

@echo OFF 
call "C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\Common7\Tools\VsMSBuildCmd.bat"
MSBuild.exe  D:\\Solution\\DataLink.sln /p:DeployOnBuild=true /p:PublishProfile=PublishInDFolder
pause

How do I replace text inside a div element?

If you really want us to just continue where you left off, you could do:

if (fieldNameElement)
    fieldNameElement.innerHTML = 'some HTML';

Which is more efficient, a for-each loop, or an iterator?

The foreach underhood is creating the iterator, calling hasNext() and calling next() to get the value; The issue with the performance comes only if you are using something that implements the RandomomAccess.

for (Iterator<CustomObj> iter = customList.iterator(); iter.hasNext()){
   CustomObj custObj = iter.next();
   ....
}

Performance issues with the iterator-based loop is because it is:

  1. allocating an object even if the list is empty (Iterator<CustomObj> iter = customList.iterator(););
  2. iter.hasNext() during every iteration of the loop there is an invokeInterface virtual call (go through all the classes, then do method table lookup before the jump).
  3. the implementation of the iterator has to do at least 2 fields lookup in order to make hasNext() call figure the value: #1 get current count and #2 get total count
  4. inside the body loop, there is another invokeInterface virtual call iter.next(so: go through all the classes and do method table lookup before the jump) and as well has to do fields lookup: #1 get the index and #2 get the reference to the array to do the offset into it (in every iteration).

A potential optimiziation is to switch to an index iteration with the cached size lookup:

for(int x = 0, size = customList.size(); x < size; x++){
  CustomObj custObj = customList.get(x);
  ...
}

Here we have:

  1. one invokeInterface virtual method call customList.size() on the initial creation of the for loop to get the size
  2. the get method call customList.get(x) during the body for loop, which is a field lookup to the array and then can do the offset into the array

We reduced a ton of method calls, field lookups. This you don't want to do with LinkedList or with something that is not a RandomAccess collection obj, otherwise the customList.get(x) is gonna turn into something that has to traverse the LinkedList on every iteration.

This is perfect when you know that is any RandomAccess based list collection.

Color theme for VS Code integrated terminal

Simply. You can go to 'File -> Preferences -> Color Theme' option in visual studio and change the color of you choice.

Map to String in Java

You can also use google-collections (guava) Joiner class if you want to customize the print format

Display Image On Text Link Hover CSS Only

add

.hover_img a:hover span {
    display: block;
    width: 350px;
}

to show hover image full size in table change 350 to your size.

Jquery button click() function is not working

You need to use the event delegation syntax of .on() here. Change:

$("#add").click(function() {

to

$("#buildyourform").on('click', '#add', function () {

jsFiddle example

How to export settings?

There is an extension for Visual Studio Code, called Settings Sync.

It synchronises your settings by gist (Gist by GitHub). It works the same as the Atom.io extension called settings-sync.

UPDATE:

This feature is now build in VS Code, it is worth to switch to official feature. (https://stackoverflow.com/a/64035356/2029818)

You can now sync all your settings across devices with VSCode's built-in Settings Sync. It's found under Code > Preferences > Turn on Settings Sync...

Best way to overlay an ESRI shapefile on google maps?

I would not use KML. Instead, use GeoJSON which you can natively consume in Google Maps API now. It is a newer feature that didn't exist from the original responses.

In any case, simply open the SHP file in Quantum GIS, and then you can output it in any format you like (KML, GeoJSON).

If you are using Google Maps for Work, I found a premium extension that handles loading shapefiles directly where you can just connect direct to the shapefile that you generate from ESRI. I did a search on the CMaps site and found this snippet which loaded US by state shapefile: https://gmapsplugin.net/cmapsanalytics/assets/shapes/usstates.shp

var cMap = new centigon.locationIntelligence.MapView();
    cMap.key([your_api_key]);


    cMap.layerNames(["Basic Shapes"]);
    cMap.dbfKeys([['Alabama','Alaska','Arizona','Arkansas','California','Colorado','Connecticut','Delaware','District of Columbia','Florida','Georgia','Hawaii','Idaho','Illinois','Indiana','Iowa','Kansas','Kentucky','Louisiana','Maine','Maryland','Massachusetts','Michigan','Minnesota','Mississippi','Missouri','Montana','Nebraska','Nevada','New Hampshire','New Jersey','New Mexico','New York','North Carolina','North Dakota','Ohio','Oklahoma','Oregon','Pennsylvania','Rhode Island','South Carolina','South Dakota','Tennessee','Texas','Utah','Vermont','Virginia','Washington','West Virginia','Wisconsin','Wyoming']]);
    cMap.userShapeKeys([['Massachusetts','Minnesota','Montana','North Dakota','Hawaii','Idaho','Washington','Arizona','California','Colorado','Nevada','New Mexico','Oregon','Utah','Wyoming','Arkansas','Iowa','Kansas','Missouri','Nebraska','Oklahoma','South Dakota','Louisiana','Texas','Connecticut','New Hampshire','Rhode Island','Vermont','Alabama','Florida','Georgia','Mississippi','South Carolina','Illinois','Indiana','Kentucky','North Carolina','Ohio','Tennessee','Virginia','Wisconsin','West Virginia','Delaware','District of Columbia','Maryland','New Jersey','New York','Pennsylvania','Maine','Michigan','Alaska']]); 
    cMap.labels([['Massachusetts','Minnesota','Montana','North Dakota','Hawaii','Idaho','Washington','Arizona','California','Colorado','Nevada','New Mexico','Oregon','Utah','Wyoming','Arkansas','Iowa','Kansas','Missouri','Nebraska','Oklahoma','South Dakota','Louisiana','Texas','Connecticut','New Hampshire','Rhode Island','Vermont','Alabama','Florida','Georgia','Mississippi','South Carolina','Illinois','Indiana','Kentucky','North Carolina','Ohio','Tennessee','Virginia','Wisconsin','West Virginia','Delaware','District of Columbia','Maryland','New Jersey','New York','Pennsylvania','Maine','Michigan','Alaska']]); 

    cMap.polyDataSources([centigon.locationIntelligence.CMapAnalytics.DATA_PROVIDERS.SHAPE_DATAPROVIDER]);
    cMap.layerTypes([centigon.mapping.Layer.TYPE.POLY]);
    cMap.locations([["https://gmapsplugin.net/cmapsanalytics/assets/shapes/usstates.shp"]]);

    cMap.panTo("USA");
    cMap.zoomLevel(3);

How to change the display name for LabelFor in razor in mvc3?

You could decorate your view model property with the [DisplayName] attribute and specify the text to be used:

[DisplayName("foo bar")]
public string SomekingStatus { get; set; }

Or use another overload of the LabelFor helper which allows you to specify the text:

@Html.LabelFor(model => model.SomekingStatus, "foo bar")

And, no, you cannot specify a class name in MVC3 as you tried to do, as the LabelFor helper doesn't support that. However, this would work in MVC4 or 5.

RESTful web service - how to authenticate requests from other services?

As far as the client certificate approach goes, it would not be terribly difficult to implement while still allowing the users without client certificates in.

If you did in fact create your own self-signed Certification Authority, and issued client certs to each client service, you would have an easy way of authenticating those services.

Depending on the web server you are using, there should be a method to specify client authentication that will accept a client cert, but does not require one. For example, in Tomcat when specifying your https connector, you can set 'clientAuth=want', instead of 'true' or 'false'. You would then make sure to add your self signed CA certificate to your truststore (by default the cacerts file in the JRE you are using, unless you specified another file in your webserver configuration), so the only trusted certificates would be those issued off of your self signed CA.

On the server side, you would only allow access to the services you wish to protect if you are able to retrieve a client certificate from the request (not null), and passes any DN checks if you prefer any extra security. For the users without client certs, they would still be able to access your services, but will simply have no certificates present in the request.

In my opinion this is the most 'secure' way, but it certainly has its learning curve and overhead, so may not necessarily be the best solution for your needs.

Transparent CSS background color

yes, thats possible. just use the rgba-syntax for your background-color.

.menue{
  background-color: rgba(255, 0, 0, 0.5); //semi-transparent red
}

Display number with leading zeros

Or another solution.

"{:0>2}".format(number)

Android failed to load JS bundle

In new React Native (for sure 0.59) debug config is inside android/app/src/debug/res/xml/react_native_config.xml

<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
  <domain-config cleartextTrafficPermitted="true">
    <domain includeSubdomains="false">localhost</domain>
    <domain includeSubdomains="false">10.0.2.2</domain>
    <domain includeSubdomains="false">10.0.3.2</domain>
  </domain-config>
</network-security-config>

Obtaining only the filename when using OpenFileDialog property "FileName"

Use OpenFileDialog.SafeFileName

OpenFileDialog.SafeFileName Gets the file name and extension for the file selected in the dialog box. The file name does not include the path.

com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: No operations allowed after connection closed

This is due to using obsolete mysql-connection-java version, your MySQl is updated but not your MySQL jdbc Driver, you can update your connection jar from the official site Official MySQL Connector site. Good Luck.

center image in div with overflow hidden

This issue is a huge pain in the a.. but I finally got it. I've seen a lot of complicated solutions. This is so simple now that I see it.

.parent {
  width:70px;
  height:70px;
}

.child {
  height:100%;
  width:10000px; /* Or some other impossibly large number */
  margin-left: -4965px; /* -1*((child width-parent width)/2) */
}

.child img {
  display:block; /* won't work without this */
  height:100%;
  margin:0 auto;
}

Formula to convert date to number

If you change the format of the cells to General then this will show the date value of a cell as behind the scenes Excel saves a date as the number of days since 01/01/1900

Screenprint 1

Screenprint 2

If your date is text and you need to convert it then DATEVALUE will do this:

Datevalue function

Jenkins Slave port number for firewall

We had a similar situation, but in our case Infosec agreed to allow any to 1, so we didnt had to fix the slave port, rather fixing the master to high level JNLP port 49187 worked ("Configure Global Security" -> "TCP port for JNLP slave agents").

TCP
49187 - Fixed jnlp port
8080 - jenkins http port

Other ports needed to launch slave as a windows service

TCP
135 
139 
445

UDP
137
138

Replace preg_replace() e modifier with preg_replace_callback

In a regular expression, you can "capture" parts of the matched string with (brackets); in this case, you are capturing the (^|_) and ([a-z]) parts of the match. These are numbered starting at 1, so you have back-references 1 and 2. Match 0 is the whole matched string.

The /e modifier takes a replacement string, and substitutes backslash followed by a number (e.g. \1) with the appropriate back-reference - but because you're inside a string, you need to escape the backslash, so you get '\\1'. It then (effectively) runs eval to run the resulting string as though it was PHP code (which is why it's being deprecated, because it's easy to use eval in an insecure way).

The preg_replace_callback function instead takes a callback function and passes it an array containing the matched back-references. So where you would have written '\\1', you instead access element 1 of that parameter - e.g. if you have an anonymous function of the form function($matches) { ... }, the first back-reference is $matches[1] inside that function.

So a /e argument of

'do_stuff(\\1) . "and" . do_stuff(\\2)'

could become a callback of

function($m) { return do_stuff($m[1]) . "and" . do_stuff($m[2]); }

Or in your case

'strtoupper("\\2")'

could become

function($m) { return strtoupper($m[2]); }

Note that $m and $matches are not magic names, they're just the parameter name I gave when declaring my callback functions. Also, you don't have to pass an anonymous function, it could be a function name as a string, or something of the form array($object, $method), as with any callback in PHP, e.g.

function stuffy_callback($things) {
    return do_stuff($things[1]) . "and" . do_stuff($things[2]);
}
$foo = preg_replace_callback('/([a-z]+) and ([a-z]+)/', 'stuffy_callback', 'fish and chips');

As with any function, you can't access variables outside your callback (from the surrounding scope) by default. When using an anonymous function, you can use the use keyword to import the variables you need to access, as discussed in the PHP manual. e.g. if the old argument was

'do_stuff(\\1, $foo)'

then the new callback might look like

function($m) use ($foo) { return do_stuff($m[1], $foo); }

Gotchas

  • Use of preg_replace_callback is instead of the /e modifier on the regex, so you need to remove that flag from your "pattern" argument. So a pattern like /blah(.*)blah/mei would become /blah(.*)blah/mi.
  • The /e modifier used a variant of addslashes() internally on the arguments, so some replacements used stripslashes() to remove it; in most cases, you probably want to remove the call to stripslashes from your new callback.

How to do a regular expression replace in MySQL?

My brute force method to get this to work was just:

  1. Dump the table - mysqldump -u user -p database table > dump.sql
  2. Find and replace a couple patterns - find /path/to/dump.sql -type f -exec sed -i 's/old_string/new_string/g' {} \;, There are obviously other perl regeular expressions you could perform on the file as well.
  3. Import the table - mysqlimport -u user -p database table < dump.sql

If you want to make sure the string isn't elsewhere in your dataset, run a few regular expressions to make sure they all occur in a similar environment. It's also not that tough to create a backup before you run a replace, in case you accidentally destroy something that loses depth of information.

Saving a select count(*) value to an integer (SQL Server)

Declare @MyInt int
Set @MyInt = ( Select Count(*) From MyTable )

If @MyInt > 0
Begin
    Print 'There''s something in the table'
End

I'm not sure if this is your issue, but you have to esacpe the single quote in the print statement with a second single quote. While you can use SELECT to populate the variable, using SET as you have done here is just fine and clearer IMO. In addition, you can be guaranteed that Count(*) will never return a negative value so you need only check whether it is greater than zero.

Select info from table where row has max date

You can use a window MAX() like this:

SELECT
  *, 
  max_date = MAX(date) OVER (PARTITION BY group)
FROM table

to get max dates per group alongside other data:

group  date      cash  checks  max_date
-----  --------  ----  ------  --------
1      1/1/2013  0     0       1/3/2013
2      1/1/2013  0     800     1/1/2013
1      1/3/2013  0     700     1/3/2013
3      1/1/2013  0     600     1/5/2013
1      1/2/2013  0     400     1/3/2013
3      1/5/2013  0     200     1/5/2013

Using the above output as a derived table, you can then get only rows where date matches max_date:

SELECT
  group,
  date,
  checks
FROM (
  SELECT
    *, 
    max_date = MAX(date) OVER (PARTITION BY group)
  FROM table
) AS s
WHERE date = max_date
;

to get the desired result.

Basically, this is similar to @Twelfth's suggestion but avoids a join and may thus be more efficient.

You can try the method at SQL Fiddle.

custom facebook share button

The best way is to use your code and then store the image in OG tags in the page you are linking to, then Facebook will pick them up.

<meta property="og:title" content="Facebook Open Graph Demo">
<meta property="og:image" content="http://example.com/main-image.png">
<meta property="og:site_name" content="Example Website">
<meta property="og:description" content="Here is a nice description">

You can find documentation to OG tags and how to use them with share buttons here

Pythonic way to return list of every nth item in a larger list

Why not just use a step parameter of range function as well to get:

l = range(0, 1000, 10)

For comparison, on my machine:

H:\>python -m timeit -s "l = range(1000)" "l1 = [x for x in l if x % 10 == 0]"
10000 loops, best of 3: 90.8 usec per loop
H:\>python -m timeit -s "l = range(1000)" "l1 = l[0::10]"
1000000 loops, best of 3: 0.861 usec per loop
H:\>python -m timeit -s "l = range(0, 1000, 10)"
100000000 loops, best of 3: 0.0172 usec per loop

How to get the nvidia driver version from the command line?

To expand on ccc's answer, if you want to incorporate querying the card with a script, here is information on Nvidia site on how to do so:

https://nvidia.custhelp.com/app/answers/detail/a_id/3751/~/useful-nvidia-smi-queries

Also, I found this thread researching powershell. Here is an example command that runs the utility to get the true memory available on the GPU to get you started.

# get gpu metrics
$cmd = "& 'C:\Program Files\NVIDIA Corporation\NVSMI\nvidia-smi' --query-gpu=name,utilization.memory,driver_version --format=csv"
$gpuinfo = invoke-expression $cmd | ConvertFrom-CSV
$gpuname = $gpuinfo.name
$gpuutil = $gpuinfo.'utilization.memory [%]'.Split(' ')[0]
$gpuDriver = $gpuinfo.driver_version

How to select multiple rows filled with constants?

In Oracle

SELECT
  CASE
    WHEN level = 1
    THEN 'HI'
    WHEN level = 2
    THEN 'BYE'
  END TEST
FROM dual
  CONNECT BY level <= 2;

How to force reloading a page when using browser back button?

Just use jquery :

jQuery( document ).ready(function( $ ) {

   //Use this inside your document ready jQuery 
   $(window).on('popstate', function() {
      location.reload(true);
   });

});

The above will work 100% when back or forward button has been clicked using ajax as well.

if it doesn't, there must be a misconfiguration in a different part of the script.

For example it might not reload if something like one of the example in the previous post is used window.history.pushState('', null, './');

so when you do use history.pushState(); make sure you use it properly.

Suggestion in most cases you will just need:

history.pushState(url, '', url); 

No window.history... and make sure url is defined.

Hope that helps..

SQL Count for each date

I had similar question however mine involved a column Convert(date,mydatetime). I had to alter the best answer as follows:

Select
     count(created_date) as counted_leads,
     Convert(date,created_date) as count_date 
from table
group by Convert(date,created_date)

JSON to pandas DataFrame

I found a quick and easy solution to what I wanted using json_normalize() included in pandas 1.01.

from urllib2 import Request, urlopen
import json

import pandas as pd    

path1 = '42.974049,-81.205203|42.974298,-81.195755'
request=Request('http://maps.googleapis.com/maps/api/elevation/json?locations='+path1+'&sensor=false')
response = urlopen(request)
elevations = response.read()
data = json.loads(elevations)
df = pd.json_normalize(data['results'])

This gives a nice flattened dataframe with the json data that I got from the Google Maps API.

How do I prompt a user for confirmation in bash script?

This way you get 'y' 'yes' or 'Enter'

 read -r -p "Are you sure? [Y/n]" response
 response=${response,,} # tolower
 if [[ $response =~ ^(yes|y| ) ]] || [[ -z $response ]]; then
    your-action-here
 fi

If you are using zsh try this:

read "response?Are you sure ? [Y/n] "
response=${response:l} #tolower
if [[ $response =~ ^(yes|y| ) ]] || [[ -z $response ]]; then
    your-action-here
fi

Export to csv in jQuery

Hope the following demo can help you out.

_x000D_
_x000D_
$(function() {_x000D_
  $("button").on('click', function() {_x000D_
    var data = "";_x000D_
    var tableData = [];_x000D_
    var rows = $("table tr");_x000D_
    rows.each(function(index, row) {_x000D_
      var rowData = [];_x000D_
      $(row).find("th, td").each(function(index, column) {_x000D_
        rowData.push(column.innerText);_x000D_
      });_x000D_
      tableData.push(rowData.join(","));_x000D_
    });_x000D_
    data += tableData.join("\n");_x000D_
    $(document.body).append('<a id="download-link" download="data.csv" href=' + URL.createObjectURL(new Blob([data], {_x000D_
      type: "text/csv"_x000D_
    })) + '/>');_x000D_
_x000D_
_x000D_
    $('#download-link')[0].click();_x000D_
    $('#download-link').remove();_x000D_
  });_x000D_
});
_x000D_
table {_x000D_
  border-collapse: collapse;_x000D_
}_x000D_
_x000D_
td,_x000D_
th {_x000D_
  border: 1px solid #aaa;_x000D_
  padding: 0.5rem;_x000D_
  text-align: left;_x000D_
}_x000D_
_x000D_
td {_x000D_
  font-size: 0.875rem;_x000D_
}_x000D_
_x000D_
.btn-group {_x000D_
  padding: 1rem 0;_x000D_
}_x000D_
_x000D_
button {_x000D_
  background-color: #fff;_x000D_
  border: 1px solid #000;_x000D_
  margin-top: 0.5rem;_x000D_
  border-radius: 3px;_x000D_
  padding: 0.5rem 1rem;_x000D_
  font-size: 1rem;_x000D_
}_x000D_
_x000D_
button:hover {_x000D_
  cursor: pointer;_x000D_
  background-color: #000;_x000D_
  color: #fff;_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
_x000D_
<div id='PrintDiv'>_x000D_
  <table id="mainTable">_x000D_
    <tr>_x000D_
      <td>Col1</td>_x000D_
      <td>Col2</td>_x000D_
      <td>Col3</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>Val1</td>_x000D_
      <td>Val2</td>_x000D_
      <td>Val3</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>Val11</td>_x000D_
      <td>Val22</td>_x000D_
      <td>Val33</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>Val111</td>_x000D_
      <td>Val222</td>_x000D_
      <td>Val333</td>_x000D_
    </tr>_x000D_
  </table>_x000D_
</div>_x000D_
_x000D_
<div class="btn-group">_x000D_
  <button>csv</button>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to select the rows with maximum values in each group with dplyr?

For me, it helped to count the number of values per group. Copy the count table into a new object. Then filter for the max of the group based on the first grouping characteristic. For example:

count_table  <- df %>%
                group_by(A, B) %>%
                count() %>%
                arrange(A, desc(n))

count_table %>% 
    group_by(A) %>%
    filter(n == max(n))

or

count_table %>% 
    group_by(A) %>%
    top_n(1, n)

push() a two-dimensional array

var r = 3; //start from rows 3
var c = 5; //start from col 5

var rows = 8;

var cols = 7;


for (var i = 0; i < rows; i++)

{

 for (var j = 0; j < cols; j++)

 {
    if(j <= c && i <= r) {
      myArray[i][j] = 1;
    } else {
      myArray[i][j] = 0;
    }
}

}

how to show only even or odd rows in sql server 2008?

To fetch even records

select *
from (select id,row_number() over (order by id) as r from table_name) T
where mod(r,2)=0;

To fetch odd records

select *
from (select id,row_number() over (order by id) as r from table_name) T
where mod(r,2)=1;

IOError: [Errno 13] Permission denied

I had a similar problem. I was attempting to have a file written every time a user visits a website.

The problem ended up being twofold.

1: the permissions were not set correctly

2: I attempted to use
f = open(r"newfile.txt","w+") (Wrong)

After changing the file to 777 (all users can read/write)
chmod 777 /var/www/path/to/file
and changing the path to an absolute path, my problem was solved
f = open(r"/var/www/path/to/file/newfile.txt","w+") (Right)

malloc an array of struct pointers

I agree with @maverik above, I prefer not to hide the details with a typedef. Especially when you are trying to understand what is going on. I also prefer to see everything instead of a partial code snippet. With that said, here is a malloc and free of a complex structure.

The code uses the ms visual studio leak detector so you can experiment with the potential leaks.

#include "stdafx.h"

#include <string.h>
#include "msc-lzw.h"

#define _CRTDBG_MAP_ALLOC
#include <stdlib.h>
#include <crtdbg.h> 



// 32-bit version
int hash_fun(unsigned int key, int try_num, int max) {
    return (key + try_num) % max;  // the hash fun returns a number bounded by the number of slots.
}


// this hash table has
// key is int
// value is char buffer
struct key_value_pair {
    int key; // use this field as the key
    char *pValue;  // use this field to store a variable length string
};


struct hash_table {
    int max;
    int number_of_elements;
    struct key_value_pair **elements;  // This is an array of pointers to mystruct objects
};


int hash_insert(struct key_value_pair *data, struct hash_table *hash_table) {

    int try_num, hash;
    int max_number_of_retries = hash_table->max;


    if (hash_table->number_of_elements >= hash_table->max) {
        return 0; // FULL
    }

    for (try_num = 0; try_num < max_number_of_retries; try_num++) {

        hash = hash_fun(data->key, try_num, hash_table->max);

        if (NULL == hash_table->elements[hash]) { // an unallocated slot
            hash_table->elements[hash] = data;
            hash_table->number_of_elements++;
            return RC_OK;
        }
    }
    return RC_ERROR;
}


// returns the corresponding key value pair struct
// If a value is not found, it returns null
//
// 32-bit version
struct key_value_pair *hash_retrieve(unsigned int key, struct hash_table *hash_table) {

    unsigned int try_num, hash;
    unsigned int max_number_of_retries = hash_table->max;

    for (try_num = 0; try_num < max_number_of_retries; try_num++) {

        hash = hash_fun(key, try_num, hash_table->max);

        if (hash_table->elements[hash] == 0) {
            return NULL; // Nothing found
        }

        if (hash_table->elements[hash]->key == key) {
            return hash_table->elements[hash];
        }
    }
    return NULL;
}


// Returns the number of keys in the dictionary
// The list of keys in the dictionary is returned as a parameter.  It will need to be freed afterwards
int keys(struct hash_table *pHashTable, int **ppKeys) {

    int num_keys = 0;

    *ppKeys = (int *) malloc( pHashTable->number_of_elements * sizeof(int) );

    for (int i = 0; i < pHashTable->max; i++) {
        if (NULL != pHashTable->elements[i]) {
            (*ppKeys)[num_keys] = pHashTable->elements[i]->key;
            num_keys++;
        }
    }
    return num_keys;
}

// The dictionary will need to be freed afterwards
int allocate_the_dictionary(struct hash_table *pHashTable) {


    // Allocate the hash table slots
    pHashTable->elements = (struct key_value_pair **) malloc(pHashTable->max * sizeof(struct key_value_pair));  // allocate max number of key_value_pair entries
    for (int i = 0; i < pHashTable->max; i++) {
        pHashTable->elements[i] = NULL;
    }



    // alloc all the slots
    //struct key_value_pair *pa_slot;
    //for (int i = 0; i < pHashTable->max; i++) {
    //  // all that he could see was babylon
    //  pa_slot = (struct key_value_pair *)  malloc(sizeof(struct key_value_pair));
    //  if (NULL == pa_slot) {
    //      printf("alloc of slot failed\n");
    //      while (1);
    //  }
    //  pHashTable->elements[i] = pa_slot;
    //  pHashTable->elements[i]->key = 0;
    //}

    return RC_OK;
}


// This will make a dictionary entry where
//   o  key is an int
//   o  value is a character buffer
//
// The buffer in the key_value_pair will need to be freed afterwards
int make_dict_entry(int a_key, char * buffer, struct key_value_pair *pMyStruct) {

    // determine the len of the buffer assuming it is a string
    int len = strlen(buffer);

    // alloc the buffer to hold the string
    pMyStruct->pValue = (char *) malloc(len + 1); // add one for the null terminator byte
    if (NULL == pMyStruct->pValue) {
        printf("Failed to allocate the buffer for the dictionary string value.");
        return RC_ERROR;
    }
    strcpy(pMyStruct->pValue, buffer);
    pMyStruct->key = a_key;

    return RC_OK;
}


// Assumes the hash table has already been allocated.
int add_key_val_pair_to_dict(struct hash_table *pHashTable, int key, char *pBuff) {

    int rc;
    struct key_value_pair *pKeyValuePair;

    if (NULL == pHashTable) {
        printf("Hash table is null.\n");
        return RC_ERROR;
    }

    // Allocate the dictionary key value pair struct
    pKeyValuePair = (struct key_value_pair *) malloc(sizeof(struct key_value_pair));
    if (NULL == pKeyValuePair) {
        printf("Failed to allocate key value pair struct.\n");
        return RC_ERROR;
    }


    rc = make_dict_entry(key, pBuff, pKeyValuePair);  // a_hash_table[1221] = "abba"
    if (RC_ERROR == rc) {
        printf("Failed to add buff to key value pair struct.\n");
        return RC_ERROR;
    }


    rc = hash_insert(pKeyValuePair, pHashTable);
    if (RC_ERROR == rc) {
        printf("insert has failed!\n");
        return RC_ERROR;
    }

    return RC_OK;
}


void dump_hash_table(struct hash_table *pHashTable) {

    // Iterate the dictionary by keys
    char * pValue;
    struct key_value_pair *pMyStruct;
    int *pKeyList;
    int num_keys;

    printf("i\tKey\tValue\n");
    printf("-----------------------------\n");
    num_keys = keys(pHashTable, &pKeyList);
    for (int i = 0; i < num_keys; i++) {
        pMyStruct = hash_retrieve(pKeyList[i], pHashTable);
        pValue = pMyStruct->pValue;
        printf("%d\t%d\t%s\n", i, pKeyList[i], pValue);
    }

    // Free the key list
    free(pKeyList);

}

int main(int argc, char *argv[]) {

    int rc;
    int i;


    struct hash_table a_hash_table;
    a_hash_table.max = 20;   // The dictionary can hold at most 20 entries.
    a_hash_table.number_of_elements = 0;  // The intial dictionary has 0 entries.
    allocate_the_dictionary(&a_hash_table);

    rc = add_key_val_pair_to_dict(&a_hash_table, 1221, "abba");
    if (RC_ERROR == rc) {
        printf("insert has failed!\n");
        return RC_ERROR;
    }
    rc = add_key_val_pair_to_dict(&a_hash_table, 2211, "bbaa");
    if (RC_ERROR == rc) {
        printf("insert has failed!\n");
        return RC_ERROR;
    }
    rc = add_key_val_pair_to_dict(&a_hash_table, 1122, "aabb");
    if (RC_ERROR == rc) {
        printf("insert has failed!\n");
        return RC_ERROR;
    }
    rc = add_key_val_pair_to_dict(&a_hash_table, 2112, "baab");
    if (RC_ERROR == rc) {
        printf("insert has failed!\n");
        return RC_ERROR;
    }
    rc = add_key_val_pair_to_dict(&a_hash_table, 1212, "abab");
    if (RC_ERROR == rc) {
        printf("insert has failed!\n");
        return RC_ERROR;
    }
    rc = add_key_val_pair_to_dict(&a_hash_table, 2121, "baba");
    if (RC_ERROR == rc) {
        printf("insert has failed!\n");
        return RC_ERROR;
    }



    // Iterate the dictionary by keys
    dump_hash_table(&a_hash_table);

    // Free the individual slots
    for (i = 0; i < a_hash_table.max; i++) {
        // all that he could see was babylon
        if (NULL != a_hash_table.elements[i]) {
            free(a_hash_table.elements[i]->pValue);  // free the buffer in the struct
            free(a_hash_table.elements[i]);  // free the key_value_pair entry
            a_hash_table.elements[i] = NULL;
        }
    }


    // Free the overall dictionary
    free(a_hash_table.elements);


    _CrtDumpMemoryLeaks();
    return 0;
}

jQuery to remove an option from drop down list, given option's text/value

First find the class name for particular select.

$('#id').val('');
$('#selectoptionclassname').selectpicker('refresh');

Service Reference Error: Failed to generate code for the service reference

http://uliasz.com/2011/06/wcf-custom-tool-error-failed-to-generate-code-for-the-service-reference/#comment-1647

Thanks to the article above.

In my case, i have this issue with my WPF project in VS.Net 2008. After going through this article, i was realizing that the assembly used in the web service is different version of assembly used on client.

It works just fine after updating the assembly on the client.

Converting string to tuple without splitting characters

You can use the following solution:

s="jack"

tup=tuple(s.split(" "))

output=('jack')

how to get vlc logs?

I found the following command to run from command line:

vlc.exe --extraintf=http:logger --verbose=2 --file-logging --logfile=vlc-log.txt

How to reposition Chrome Developer Tools

Chrome 46 or newer

Click the vertical ellipsis button ( ? ) then choose the desired docking option.

Chrome 45 or older

Long-hold the dock icon in the top right. It pops up an option to change the docking

To change the split between the HTML and CSS panels, go in DevTools to Settings (F1) > General > Appearance > Panel Layout.

Moment.js with Vuejs

In your package.json in the "dependencies" section add moment:

"dependencies": {
  "moment": "^2.15.2",
  ...
}

In the component where you would like to use moment, import it:

<script>
import moment from 'moment'
...

And in the same component add a computed property:

computed: {
  timestamp: function () {
    return moment(this.<model>.attributes['created-at']).format('YYYY-MM-DD [at] hh:mm')
  }
}

And then in the template of this component:

<p>{{ timestamp }}</p>

bash script read all the files in directory

To write it with a while loop you can do:

ls -f /var | while read -r file; do cmd $file; done

The primary disadvantage of this is that cmd is run in a subshell, which causes some difficulty if you are trying to set variables. The main advantages are that the shell does not need to load all of the filenames into memory, and there is no globbing. When you have a lot of files in the directory, those advantages are important (that's why I use -f on ls; in a large directory ls itself can take several tens of seconds to run and -f speeds that up appreciably. In such cases 'for file in /var/*' will likely fail with a glob error.)

ssl_error_rx_record_too_long and Apache SSL

My problem was due to a LOW MTU over a VPN connection.

netsh interface ipv4 show inter

Idx  Met   MTU   State        Name
---  ---  -----  -----------  -------------------
  1 4275 4294967295  connected    Loopback Pseudo-Interface 1
 10 4250   **1300**  connected    Wireless Network Connection
 31   25   1400  connected    Remote Access to XYZ Network

Fix: netsh interface ipv4 set interface "Wireless Network Connection" mtu=1400

It may be an issue over a non-VPN connection also...

JavaScript: Class.method vs. Class.prototype.method

When you create more than one instance of MyClass , you will still only have only one instance of publicMethod in memory but in case of privilegedMethod you will end up creating lots of instances and staticMethod has no relationship with an object instance.

That's why prototypes save memory.

Also, if you change the parent object's properties, is the child's corresponding property hasn't been changed, it'll be updated.

Leave only two decimal places after the dot

Alternatively, you may also use the composite operator F then indicating how many decimal spots you wish to appear after the decimal.

string.Format("{0:F2}", 123.456789);     //123.46
string.Format("{0:F3}", 123.456789);     //123.457
string.Format("{0:F4}", 123.456789);     //123.4568

It will round up so be aware of that.

I sourced the general documentation. There are a ton of other formatting operators there as well that you may check out.

Source: https://msdn.microsoft.com/en-us/library/dwhawy9k(v=vs.110).aspx

Passing Arrays to Function in C++

I just wanna add this, when you access the position of the array like

arg[n]

is the same as

*(arg + n) than means an offset of n starting from de arg address.

so arg[0] will be *arg

How to change the Jupyter start-up folder

agree to most answers except that in jupyter_notebook_config.py, you have to put

#c.NotebookApp.notebook_dir='c:\\test\\your_root'

double \\ is the key answer

VIM Disable Automatic Newline At End Of File

Starting with vim v7.4 you can use

:set nofixendofline

There is some information about that change here: http://ftp.vim.org/vim/patches/7.4/7.4.785 .

Convert an integer to a byte array

I agree with Brainstorm's approach: assuming that you're passing a machine-friendly binary representation, use the encoding/binary library. The OP suggests that binary.Write() might have some overhead. Looking at the source for the implementation of Write(), I see that it does some runtime decisions for maximum flexibility.

func Write(w io.Writer, order ByteOrder, data interface{}) error {
    // Fast path for basic types.
    var b [8]byte
    var bs []byte
    switch v := data.(type) {
    case *int8:
        bs = b[:1]
        b[0] = byte(*v)
    case int8:
        bs = b[:1]
        b[0] = byte(v)
    case *uint8:
        bs = b[:1]
        b[0] = *v
    ...

Right? Write() takes in a very generic data third argument, and that's imposing some overhead as the Go runtime then is forced into encoding type information. Since Write() is doing some runtime decisions here that you simply don't need in your situation, maybe you can just directly call the encoding functions and see if it performs better.

Something like this:

package main

import (
    "encoding/binary"
    "fmt"
)

func main() {
    bs := make([]byte, 4)
    binary.LittleEndian.PutUint32(bs, 31415926)
    fmt.Println(bs)
}

Let us know how this performs.

Otherwise, if you're just trying to get an ASCII representation of the integer, you can get the string representation (probably with strconv.Itoa) and cast that string to the []byte type.

package main

import (
    "fmt"
    "strconv"
)

func main() {
    bs := []byte(strconv.Itoa(31415926))
    fmt.Println(bs)
}

Lombok annotations do not compile under Intellij idea

None of the advanced answers to this question resolved the problem for me.

I managed to solve the problem by adding a dependencie to lombok in the pom.xml file, i.e. :

<dependency>
   <groupId>org.projectlombok</groupId>
   <artifactId>lombok</artifactId>
   <version>1.16.12</version>
</dependency>

I am using IntelliJ 2016.3.14 with maven-3.3.9

Hope my answer will be helpful for you

How do I check form validity with angularjs?

Example

<div ng-controller="ExampleController">
  <form name="myform">
   Name: <input type="text" ng-model="user.name" /><br>
   Email: <input type="email" ng-model="user.email" /><br>
  </form>
</div>

<script>
  angular.module('formExample', [])
    .controller('ExampleController', ['$scope', function($scope) {

     //if form is not valid then return the form.
     if(!$scope.myform.$valid) {
       return;
     }
  }]);
</script>

GitHub authentication failing over https, returning wrong email address

I do not have an @github.com address

You don't have to: the @ is the separator between the username:password and the domain.
It is not an email address.

A full GitHub https url would be:

https://username:[email protected]/username/reponame.git

Without the password (which would then be asked on the command line), that would gave:

https://[email protected]/username/reponame.git

But again, [email protected] isn't an email address, just the first part of the credentials.

Make sure the case of your username and reponame is correct: it is case sensitive.

Note that you can store and encrypt your credentials in a .netrc.gpg (or _netrc.gpg on Windows) if you don't want to put said credentials in clear in the url.
See "Is there a way to skip password typing when using https://github".

Make <body> fill entire screen?

On our site we have pages where the content is static, and pages where it is loaded in with AJAX. On one page (a search page), there were cases when the AJAX results would more than fill the page, and cases where it would return no results. In order for the background image to fill the page in all cases we had to apply the following CSS:

html {
   margin: 0px;
   height: 100%;
   width: 100%;
}

body {
   margin: 0px;
   min-height: 100%;
   width: 100%;
}

height for the html and min-height for the body.

Node Sass couldn't find a binding for your current environment

For Visual Studio 2015/2017, Right Click on your package.json and Click on Restore Packages.

This will make sure that the npm from the Visual Studio Tools External Tools is run and the binding will be rebuild based on that.

Android global variable

I checked for similar answer, but those given here don't fit my needs. I find something that, from my point of view, is what you're looking for. The only possible black point is a security matter (or maybe not) since I don't know about security.

I suggest using Interface (no need to use Class with constructor and so...), since you only have to create something like :

public interface ActivityClass {

    public static final String MYSTRING_1 = "STRING";

    public static final int MYINT_1 = 1;

}

Then you can access everywhere within your classes by using the following:

int myInt = ActivityClass.MYINT_1;
String myString = ActivityClass.MYSTRING_1;

Meaning of "[: too many arguments" error from if [] (square brackets)

Another scenario that you can get the [: too many arguments or [: a: binary operator expected errors is if you try to test for all arguments "$@"

if [ -z "$@" ]
then
    echo "Argument required."
fi

It works correctly if you call foo.sh or foo.sh arg1. But if you pass multiple args like foo.sh arg1 arg2, you will get errors. This is because it's being expanded to [ -z arg1 arg2 ], which is not a valid syntax.

The correct way to check for existence of arguments is [ "$#" -eq 0 ]. ($# is the number of arguments).

HTML 5 Video "autoplay" not automatically starting in CHROME

This question are greatly described here
https://developers.google.com/web/updates/2017/09/autoplay-policy-changes

TL;DR You are still always able to autoplay muted videos

Also, if you're want to autoplay videos on iOS add playsInline attribute, because by default iOS tries to fullscreen videos
https://webkit.org/blog/6784/new-video-policies-for-ios/

Select count(*) from multiple tables

As additional information, to accomplish same thing in SQL Server, you just need to remove the "FROM dual" part of the query.

How to delete all instances of a character in a string in python?

replace() method will work for this. Here is the code that will help to remove character from string. lets say

j_word = 'Stringtoremove'
word = 'String'    

for letter in word:
    if j_word.find(letter) == -1:
        continue
    else:
       # remove matched character
       j_word = j_word.replace(letter, '', 1)

#Output
j_word = "toremove"

Validate email address textbox using JavaScript

<h2>JavaScript Email Validation</h2>

<input id="textEmail">

<button type="button" onclick="myFunction()">Submit</button>

<p id="demo" style="color: red;"></p>

<script>
function myFunction() {
    var email;

    email = document.getElementById("textEmail").value;

        var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;

        if (reg.test(textEmail.value) == false) 
        {
        document.getElementById("demo").style.color = "red";
            document.getElementById("demo").innerHTML ="Invalid EMail ->"+ email;
            alert('Invalid Email Address ->'+email);
            return false;
        } else{
        document.getElementById("demo").style.color = "DarkGreen";      
        document.getElementById("demo").innerHTML ="Valid Email ->"+email;
        }

   return true;
}
</script>

Access denied for user 'root'@'localhost' (using password: YES) after new installation on Ubuntu

I had to be logged into Ubuntu as root in order to access Mariadb as root. It may have something to do with that "Harden ..." that it prompts you to do when you first install. So:

$ sudo su
[sudo] password for user: yourubunturootpassword
# mysql -r root -p
Enter password: yourmariadbrootpassword

and you're in.

Append a Lists Contents to another List C#

With Linq

var newList = GlobalStrings.Append(localStrings)

Conversion between UTF-8 ArrayBuffer and String

The latest answers to these type of questions (using nowadays methods) is here: Converting between strings and ArrayBuffers

Postgres: How to do Composite keys?

Your compound PRIMARY KEY specification already does what you want. Omit the line that's giving you a syntax error, and omit the redundant CONSTRAINT (already implied), too:

 CREATE TABLE tags
      (
               question_id INTEGER NOT NULL,
               tag_id SERIAL NOT NULL,
               tag1 VARCHAR(20),
               tag2 VARCHAR(20),
               tag3 VARCHAR(20),
               PRIMARY KEY(question_id, tag_id)
      );

NOTICE:  CREATE TABLE will create implicit sequence "tags_tag_id_seq" for serial column "tags.tag_id"
    NOTICE:  CREATE TABLE / PRIMARY KEY will create implicit index "tags_pkey" for table "tags"
    CREATE TABLE
    pg=> \d tags
                                         Table "public.tags"
       Column    |         Type          |                       Modifiers       
    -------------+-----------------------+-------------------------------------------------------
     question_id | integer               | not null
     tag_id      | integer               | not null default nextval('tags_tag_id_seq'::regclass)
     tag1        | character varying(20) |
     tag2        | character varying(20) |
     tag3        | character varying(20) |
    Indexes:
        "tags_pkey" PRIMARY KEY, btree (question_id, tag_id)

Using C# to read/write Excel files (.xls/.xlsx)

I'm a big fan of using EPPlus to perform these types of actions. EPPlus is a library you can reference in your project and easily create/modify spreadsheets on a server. I use it for any project that requires an export function.

Here's a nice blog entry that shows how to use the library, though the library itself should come with some samples that explain how to use it.

Third party libraries are a lot easier to use than Microsoft COM objects, in my opinion. I would suggest giving it a try.

How to call a REST web service API from JavaScript?

I'm surprised nobody has mentioned the new Fetch API, supported by all browsers except IE11 at the time of writing. It simplifies the XMLHttpRequest syntax you see in many of the other examples.

The API includes a lot more, but start with the fetch() method. It takes two arguments:

  1. A URL or an object representing the request.
  2. Optional init object containing the method, headers, body etc.

Simple GET:

const userAction = async () => {
  const response = await fetch('http://example.com/movies.json');
  const myJson = await response.json(); //extract JSON from the http response
  // do something with myJson
}

Recreating the previous top answer, a POST:

const userAction = async () => {
  const response = await fetch('http://example.com/movies.json', {
    method: 'POST',
    body: myBody, // string or object
    headers: {
      'Content-Type': 'application/json'
    }
  });
  const myJson = await response.json(); //extract JSON from the http response
  // do something with myJson
}

Powershell script to check if service is started, if not then start it

[Array] $servers = "Server1","server2";
$service='YOUR SERVICE'

foreach($server in $servers)

{
    $srvc = Get-WmiObject -query "SELECT * FROM win32_service  WHERE   name LIKE '$service' " -computername $server  ;
    $res=Write-Output $srvc | Format-Table -AutoSize $server, $fmtMode, $fmtState, $fmtStatus ;  
   $srvc.startservice() 
   $res
}

Text overwrite in visual studio 2010

I'm using Visual Studio 2019. I used the shortcut below:

Shift + Insert

Generate preview image from Video file?

Solution #1 (Older) (not recommended)

Firstly install ffmpeg-php project (http://ffmpeg-php.sourceforge.net/)

And then you can use of this simple code:

<?php
$frame = 10;
$movie = 'test.mp4';
$thumbnail = 'thumbnail.png';

$mov = new ffmpeg_movie($movie);
$frame = $mov->getFrame($frame);
if ($frame) {
    $gd_image = $frame->toGDImage();
    if ($gd_image) {
        imagepng($gd_image, $thumbnail);
        imagedestroy($gd_image);
        echo '<img src="'.$thumbnail.'">';
    }
}
?>

Description: This project use binary extension .so file, It's very old and last update was for 2008. So, maybe don't works with newer version of FFMpeg or PHP.


Solution #2 (Update 2018) (recommended)

Firstly install PHP-FFMpeg project (https://github.com/PHP-FFMpeg/PHP-FFMpeg)
(just run for install: composer require php-ffmpeg/php-ffmpeg)

And then you can use of this simple code:

<?php
require 'vendor/autoload.php';

$sec = 10;
$movie = 'test.mp4';
$thumbnail = 'thumbnail.png';

$ffmpeg = FFMpeg\FFMpeg::create();
$video = $ffmpeg->open($movie);
$frame = $video->frame(FFMpeg\Coordinate\TimeCode::fromSeconds($sec));
$frame->save($thumbnail);
echo '<img src="'.$thumbnail.'">';

Description: It's newer and more modern project and works with latest version of FFMpeg and PHP. Note that it's required to proc_open() PHP function.

What should my Objective-C singleton look like?

Edit: This implementation obsoleted with ARC. Please have a look at How do I implement an Objective-C singleton that is compatible with ARC? for correct implementation.

All the implementations of initialize I've read in other answers share a common error.

+ (void) initialize {
  _instance = [[MySingletonClass alloc] init] // <----- Wrong!
}

+ (void) initialize {
  if (self == [MySingletonClass class]){ // <----- Correct!
      _instance = [[MySingletonClass alloc] init] 
  }
}

The Apple documentation recommend you check the class type in your initialize block. Because subclasses call the initialize by default. There exists a non-obvious case where subclasses may be created indirectly through KVO. For if you add the following line in another class:

[[MySingletonClass getInstance] addObserver:self forKeyPath:@"foo" options:0 context:nil]

Objective-C will implicitly create a subclass of MySingletonClass resulting in a second triggering of +initialize.

You may think that you should implicitly check for duplicate initialization in your init block as such:

- (id) init { <----- Wrong!
   if (_instance != nil) {
      // Some hack
   }
   else {
      // Do stuff
   }
  return self;
}

But you will shoot yourself in the foot; or worse give another developer the opportunity to shoot themselves in the foot.

- (id) init { <----- Correct!
   NSAssert(_instance == nil, @"Duplication initialization of singleton");
   self = [super init];
   if (self){
      // Do stuff
   }
   return self;
}

TL;DR, here's my implementation

@implementation MySingletonClass
static MySingletonClass * _instance;
+ (void) initialize {
   if (self == [MySingletonClass class]){
      _instance = [[MySingletonClass alloc] init];
   }
}

- (id) init {
   ZAssert (_instance == nil, @"Duplication initialization of singleton");
   self = [super init];
   if (self) {
      // Initialization
   }
   return self;
}

+ (id) getInstance {
   return _instance;
}
@end

(Replace ZAssert with our own assertion macro; or just NSAssert.)

Temporary tables in stored procedures

For all those recommending using table variables, be cautious in doing so. Table variable cannot be indexed whereas a temp table can be. A table variable is best when working with small amounts of data but if you are working on larger sets of data (e.g. 50k records) a temp table will be much faster than a table variable.

Also keep in mind that you can't rely on a try/catch to force a cleanup within the stored procedure. certain types of failures cannot be caught within a try/catch (e.g. compile failures due to delayed name resolution) if you want to be really certain you may need to create a wrapper stored procedure that can do a try/catch of the worker stored procedure and do the cleanup there.

e.g. create proc worker AS BEGIN -- do something here END

create proc wrapper AS
BEGIN
    Create table #...
    BEGIN TRY
       exec worker
       exec worker2 -- using same temp table
       -- etc
    END TRY
    END CATCH
       -- handle transaction cleanup here
       drop table #...
    END CATCH 
END

One place where table variables are always useful is they do not get rolled back when a transaction is rolled back. This can be useful for capturing debug data that you want to commit outside the primary transaction.

Is there a typical state machine implementation pattern?

For a simple state machine just use a switch statement and an enum type for your state. Do your transitions inside the switch statement based on your input. In a real program you would obviously change the "if(input)" to check for your transition points. Hope this helps.

typedef enum
{
    STATE_1 = 0,
    STATE_2,
    STATE_3
} my_state_t;

my_state_t state = STATE_1;

void foo(char input)
{
    ...
    switch(state)
    {
        case STATE_1:
            if(input)
                state = STATE_2;
            break;
        case STATE_2:
            if(input)
                state = STATE_3;
            else
                state = STATE_1;
            break;
        case STATE_3:
            ...
            break;
    }
    ...
}

How can I position my div at the bottom of its container?

If you want it to "stick" to the bottom, regardless of the height of container, then absolute positioning is the way to go. Of course, if the copyright element is the last in the container it'll always be at the bottom anyway.

Can you expand on your question? Explain exactly what you're trying to do (and why you don't want to use absolute positioning)?

How to store a list in a column of a database table

If you really wanted to store it in a column and have it queryable a lot of databases support XML now. If not querying you can store them as comma separated values and parse them out with a function when you need them separated. I agree with everyone else though if you are looking to use a relational database a big part of normalization is the separating of data like that. I am not saying that all data fits a relational database though. You could always look into other types of databases if a lot of your data doesn't fit the model.

How to check if a Unix .tar.gz file is a valid file without uncompressing?

you could probably use the gzip -t option to test the files integrity

http://linux.about.com/od/commands/l/blcmdl1_gzip.htm

from: http://unix.ittoolbox.com/groups/technical-functional/shellscript-l/how-to-test-file-integrity-of-targz-1138880

To test the gzip file is not corrupt:

gunzip -t file.tar.gz

To test the tar file inside is not corrupt:

gunzip -c file.tar.gz | tar -t > /dev/null

As part of the backup you could probably just run the latter command and check the value of $? afterwards for a 0 (success) value. If either the tar or the gzip has an issue, $? will have a non zero value.

HTML entity for check mark

There is HTML entity &#10003 but it doesn't work in some older browsers.

CORS jQuery AJAX request

It's easy, you should set server http response header first. The problem is not with your front-end javascript code. You need to return this header:

Access-Control-Allow-Origin:*

or

Access-Control-Allow-Origin:your domain

In Apache config files, the code is like this:

Header set Access-Control-Allow-Origin "*"

In nodejs,the code is like this:

res.setHeader('Access-Control-Allow-Origin','*');

To compare two elements(string type) in XSLT?

First of all, the provided long code:

    <xsl:choose>
        <xsl:when test="OU_NAME='OU_ADDR1'">   --comparing two elements coming from XML             
            <!--remove if  adrees already contain  operating unit name <xsl:value-of select="OU_NAME"/> <fo:block/>-->
            <xsl:if test="OU_ADDR1 !='' ">
                <xsl:value-of select="OU_ADDR1"/>
                <fo:block/>
            </xsl:if>
            <xsl:if test="LE_ADDR2 !='' ">
                <xsl:value-of select="OU_ADDR2"/>
                <fo:block/>
            </xsl:if>
            <xsl:if test="LE_ADDR3 !='' ">
                <xsl:value-of select="OU_ADDR3"/>
                <fo:block/>
            </xsl:if>
            <xsl:if test="OU_TOWN_CITY !=''">
                <xsl:value-of select="OU_TOWN_CITY"/>,
                <fo:leader leader-pattern="space" leader-length="2.0pt"/>
            </xsl:if>
            <xsl:value-of select="OU_REGION2"/>
            <fo:leader leader-pattern="space" leader-length="3.0pt"/>
            <xsl:value-of select="OU_POSTALCODE"/>
            <fo:block/>
            <xsl:value-of select="OU_COUNTRY"/>
        </xsl:when>
        <xsl:otherwise>
            <xsl:value-of select="OU_NAME"/>
            <fo:block/>
            <xsl:if test="OU_ADDR1 !='' ">
                <xsl:value-of select="OU_ADDR1"/>
                <fo:block/>
            </xsl:if>
            <xsl:if test="LE_ADDR2 !='' ">
                <xsl:value-of select="OU_ADDR2"/>
                <fo:block/>
            </xsl:if>
            <xsl:if test="LE_ADDR3 !='' ">
                <xsl:value-of select="OU_ADDR3"/>
                <fo:block/>
            </xsl:if>
            <xsl:if test="OU_TOWN_CITY !=''">
                <xsl:value-of select="OU_TOWN_CITY"/>,
                <fo:leader leader-pattern="space" leader-length="2.0pt"/>
            </xsl:if>
            <xsl:value-of select="OU_REGION2"/>
            <fo:leader leader-pattern="space" leader-length="3.0pt"/>
            <xsl:value-of select="OU_POSTALCODE"/>
            <fo:block/>
            <xsl:value-of select="OU_COUNTRY"/>
        </xsl:otherwise>
    </xsl:choose>

is equivalent to this, much shorter code:

<xsl:if test="not(OU_NAME='OU_ADDR1)'">
              <xsl:value-of select="OU_NAME"/>
        </xsl:if>
            <xsl:if test="OU_ADDR1 !='' ">
                <xsl:value-of select="OU_ADDR1"/>
                <fo:block/>
            </xsl:if>
            <xsl:if test="LE_ADDR2 !='' ">
                <xsl:value-of select="OU_ADDR2"/>
                <fo:block/>
            </xsl:if>
            <xsl:if test="LE_ADDR3 !='' ">
                <xsl:value-of select="OU_ADDR3"/>
                <fo:block/>
            </xsl:if>
            <xsl:if test="OU_TOWN_CITY !=''">
                <xsl:value-of select="OU_TOWN_CITY"/>,
                <fo:leader leader-pattern="space" leader-length="2.0pt"/>
            </xsl:if>
            <xsl:value-of select="OU_REGION2"/>
            <fo:leader leader-pattern="space" leader-length="3.0pt"/>
            <xsl:value-of select="OU_POSTALCODE"/>
            <fo:block/>
            <xsl:value-of select="OU_COUNTRY"/>

Now, to your question:

how to compare two elements coming from xml as string

In Xpath 1.0 strings can be compared only for equality (or inequality), using the operator = and the function not() together with the operator =.

$str1 = $str2

evaluates to true() exactly when the string $str1 is equal to the string $str2.

not($str1 = $str2)

evaluates to true() exactly when the string $str1 is not equal to the string $str2.

There is also the != operator. It generally should be avoided because it has anomalous behavior whenever one of its operands is a node-set.

Now, the rules for comparing two element nodes are similar:

$el1 = $el2

evaluates to true() exactly when the string value of $el1 is equal to the string value of $el2.

not($el1 = $el2)

evaluates to true() exactly when the string value of $el1 is not equal to the string value of $el2.

However, if one of the operands of = is a node-set, then

 $ns = $str

evaluates to true() exactly when there is at least one node in the node-set $ns1, whose string value is equal to the string $str

$ns1 = $ns2

evaluates to true() exactly when there is at least one node in the node-set $ns1, whose string value is equal to the string value of some node from $ns2

Therefore, the expression:

OU_NAME='OU_ADDR1'

evaluates to true() only when there is at least one element child of the current node that is named OU_NAME and whose string value is the string 'OU_ADDR1'.

This is obviously not what you want!

Most probably you want:

OU_NAME=OU_ADDR1

This expression evaluates to true exactly there is at least one OU_NAME child of the current node and one OU_ADDR1 child of the current node with the same string value.

Finally, in XPath 2.0, strings can be compared also using the value comparison operators lt, le, eq, gt, ge and the inherited from XPath 1.0 general comparison operator =.

Trying to evaluate a value comparison operator when one or both of its arguments is a sequence of more than one item results in error.

receiving error: 'Error: SSL Error: SELF_SIGNED_CERT_IN_CHAIN' while using npm

Putting this before the command seems to work NODE_TLS_REJECT_UNAUTHORIZED=0. ex: NODE_TLS_REJECT_UNAUTHORIZED=0 npm ...

It would be best to figure out how to make node see self signed certificate as valid. strict-ssl suggestion above didn't work for me for some reason. If you understand the security implications and need a temporary quick fix, this is what I found in some random github issues during Google search of the error.

How to ping an IP address

I think this code will help you:

public class PingExample {
    public static void main(String[] args){
        try{
            InetAddress address = InetAddress.getByName("192.168.1.103");
            boolean reachable = address.isReachable(10000);

            System.out.println("Is host reachable? " + reachable);
        } catch (Exception e){
            e.printStackTrace();
        }
    }
}

How can I convert integer into float in Java?

Here is how you can do it :

public static void main(String[] args) {
    // TODO Auto-generated method stub
    int x = 3;
    int y = 2;
    Float fX = new Float(x);
    float res = fX.floatValue()/y;
    System.out.println("res = "+res);
}

See you !

Entity Framework The underlying provider failed on Open

open SQL Server Configuration Manager then click on sql server services a list will be displayed from the list right click sql server and click on start

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

Answered here: Convert an image to grayscale in HTML/CSS

You don't even need to use two images which sounds like a pain or an image manipulation library, you can do it with cross browser support (current versions) and just use CSS. This is a progressive enhancement approach which just falls back to color versions on older browsers:

img {
  filter: url(filters.svg#grayscale);
  /* Firefox 3.5+ */
  filter: gray;
  /* IE6-9 */
  -webkit-filter: grayscale(1);
  /* Google Chrome & Safari 6+ */
}
img:hover {
  filter: none;
  -webkit-filter: none;
}

and filters.svg file like this:

<svg xmlns="http://www.w3.org/2000/svg">
  <filter id="grayscale">
    <feColorMatrix type="matrix" values="0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0 0 0 1 0" />
  </filter>
</svg>

Print all but the first three columns

echo 1 2 3 4 5| awk '{ for (i=3; i<=NF; i++) print $i }'

Run a single test method with maven

As of surefire plugin version 2.22.1 (possibly earlier) you can run single test using testnames property when using testng.xml

Given a following testng.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="Suite">
    <test name="all-tests">
        <classes>
            <class name="server.Atest"/>
            <class name="server.Btest"/>
            <class name="server.Ctest"/>
        </classes>
    </test>
    <test name="run-A-test">
        <classes>
            <class name="server.Atest"/>
        </classes>
    </test>
    <test name="run-B-test">
        <classes>
            <class name="server.Btest"/>
        </classes>
    </test>
    <test name="run-C-test">
        <classes>
            <class name="server.Ctest"/>
        </classes>
    </test>
</suite> 

with the pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    [...]
    <properties>
        <selectedTests>all-tests</selectedTests>
    </properties>
    [...]
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-surefire-plugin</artifactId>
            <version>2.22.1</version>
            <configuration>
                <suiteXmlFiles>
                    <file>src/test/resources/testng.xml</file>
                </suiteXmlFiles>
                <properties>
                    <property>
                        <name>testnames</name>
                        <value>${selectedTests}</value>
                    </property>
                </properties>
            </configuration>
        </plugin>
    </plugins>
    [...]
</project>

From command line

mvn clean test -DselectedTests=run-B-test

Further reading - Maven surefire plugin using testng

jQuery hyperlinks - href value?

Wonder why nobody said it here earlier: to prevent <a href="#"> from scrolling document position to the top, simply use <a href="#/"> instead. That's mere HTML, no JQuery needed. Using event.preventDefault(); is just too much!

Difference between text and varchar (character varying)

In my opinion, varchar(n) has it's own advantages. Yes, they all use the same underlying type and all that. But, it should be pointed out that indexes in PostgreSQL has its size limit of 2712 bytes per row.

TL;DR: If you use text type without a constraint and have indexes on these columns, it is very possible that you hit this limit for some of your columns and get error when you try to insert data but with using varchar(n), you can prevent it.

Some more details: The problem here is that PostgreSQL doesn't give any exceptions when creating indexes for text type or varchar(n) where n is greater than 2712. However, it will give error when a record with compressed size of greater than 2712 is tried to be inserted. It means that you can insert 100.000 character of string which is composed by repetitive characters easily because it will be compressed far below 2712 but you may not be able to insert some string with 4000 characters because the compressed size is greater than 2712 bytes. Using varchar(n) where n is not too much greater than 2712, you're safe from these errors.

What is the difference between "Form Controls" and "ActiveX Control" in Excel 2010?

Google is full of information on this. As Hans Passant said, Form controls are built in to Excel whereas ActiveX controls are loaded separately.

Generally you'll use Forms controls, they're simpler. ActiveX controls allow for more flexible design and should be used when the job just can't be done with a basic Forms control.

Many user's computers by default won't trust ActiveX, and it will be disabled; this sometimes needs to be manually added to the trust center. ActiveX is a microsoft-based technology and, as far as I'm aware, is not supported on the Mac. This is something you'll have to also consider, should you (or anyone you provide a workbook to) decide to use it on a Mac.

Change background of LinearLayout in Android

If you want to set through xml using android's default color codes, then you need to do as below:

android:background="@android:color/white"

If you have colors specified in your project's colors.xml, then use:

android:background="@color/white"

If you want to do programmatically, then do:

linearlayout.setBackgroundColor(Color.WHITE);

how to stop a loop arduino

Matti Virkkunen said it right, there's no "decent" way of stopping the loop. Nonetheless, by looking at your code and making several assumptions, I imagine you're trying to output a signal with a given frequency, but you want to be able to stop it.

If that's the case, there are several solutions:

  1. If you want to generate the signal with the input of a button you could do the following

    int speakerOut = A0;
    int buttonPin = 13;
    
    void setup() {
        pinMode(speakerOut, OUTPUT);
        pinMode(buttonPin, INPUT_PULLUP);
    }
    
    int a = 0;
    
    void loop() {
        if(digitalRead(buttonPin) == LOW) {
            a ++;
            Serial.println(a);
            analogWrite(speakerOut, NULL);
    
            if(a > 50 && a < 300) {
                analogWrite(speakerOut, 200);
            }
    
            if(a <= 49) {
                analogWrite(speakerOut, NULL);
            }
    
            if(a >= 300 && a <= 2499) {
                analogWrite(speakerOut, NULL);
            }
        }
    }
    

    In this case we're using a button pin as an INPUT_PULLUP. You can read the Arduino reference for more information about this topic, but in a nutshell this configuration sets an internal pullup resistor, this way you can just have your button connected to ground, with no need of external resistors. Note: This will invert the levels of the button, LOW will be pressed and HIGH will be released.

  2. The other option would be using one of the built-ins hardware timers to get a function called periodically with interruptions. I won't go in depth be here's a great description of what it is and how to use it.

How to delete Certain Characters in a excel 2010 cell

Replace [ with nothing, then ] with nothing.

How do I call one constructor from another in Java?

Originally from an anser by Mirko Klemm, slightly modified to address the question:

Just for completeness: There is also the Instance initialization block that gets executed always and before any other constructor is called. It consists simply of a block of statements "{ ... }" somewhere in the body of your class definition. You can even have more than one. You can't call them, but they're like "shared constructor" code if you want to reuse some code across constructors, similar to calling methods.

So in your case

{ 
  System.out.println("this is shared constructor code executed before the constructor");
  field1 = 3;
}

There is also a "static" version of this to initialize static members: "static { ... }"

How is OAuth 2 different from OAuth 1?

From a security point of view, I'd go for OAuth 1. See OAuth 2.0 and the road to hell

quote from that link: "If you are currently using 1.0 successfully, ignore 2.0. It offers no real value over 1.0 (I’m guessing your client developers have already figured out 1.0 signatures by now).

If you are new to this space, and consider yourself a security expert, use 2.0 after careful examination of its features. If you are not an expert, either use 1.0 or copy the 2.0 implementation of a provider you trust to get it right (Facebook’s API documents are a good place to start). 2.0 is better for large scale, but if you are running a major operation, you probably have some security experts on site to figure it all out for you."

How can I get a file's size in C++?

You need to seek to the end of the file and then ask for the position:

fseek(fp, 0L, SEEK_END);
sz = ftell(fp);

You can then seek back, e.g.:

fseek(fp, 0L, SEEK_SET);

or (if seeking to go to the beginning)

rewind(fp);

How to clamp an integer to some range?

If your code seems too unwieldy, a function might help:

def clamp(minvalue, value, maxvalue):
    return max(minvalue, min(value, maxvalue))

new_index = clamp(0, new_index, len(mylist)-1)

Javascript - How to detect if document has loaded (IE 7/Firefox 3)

There's no need for all the code mentioned by galambalazs. The cross-browser way to do it in pure JavaScript is simply to test document.readyState:

if (document.readyState === "complete") { init(); }

This is also how jQuery does it.

Depending on where the JavaScript is loaded, this can be done inside an interval:

var readyStateCheckInterval = setInterval(function() {
    if (document.readyState === "complete") {
        clearInterval(readyStateCheckInterval);
        init();
    }
}, 10);

In fact, document.readyState can have three states:

Returns "loading" while the document is loading, "interactive" once it is finished parsing but still loading sub-resources, and "complete" once it has loaded. -- document.readyState at Mozilla Developer Network

So if you only need the DOM to be ready, check for document.readyState === "interactive". If you need the whole page to be ready, including images, check for document.readyState === "complete".

Postgres: How to convert a json string to text?

There is no way in PostgreSQL to deconstruct a scalar JSON object. Thus, as you point out,

select  length(to_json('Some "text"'::TEXT) ::TEXT);

is 15,

The trick is to convert the JSON into an array of one JSON element, then extract that element using ->>.

select length( array_to_json(array[to_json('Some "text"'::TEXT)])->>0 );

will return 11.

Difference between single and double quotes in Bash

There is a clear distinction between the usage of ' ' and " ".

When ' ' is used around anything, there is no "transformation or translation" done. It is printed as it is.

With " ", whatever it surrounds, is "translated or transformed" into its value.

By translation/ transformation I mean the following: Anything within the single quotes will not be "translated" to their values. They will be taken as they are inside quotes. Example: a=23, then echo '$a' will produce $a on standard output. Whereas echo "$a" will produce 23 on standard output.

C++ JSON Serialization

Not yet mentioned, though it was the first in my search result: https://github.com/nlohmann/json

Perks listed:

  • Intuitive syntax (looks great!)
  • Single header file to include, nothing else
  • Ridiculously tested

Also, it's under the MIT License.

I'll be honest: I have yet to use it, but through some experience I have a knack for determining when I come across a really well-made c++ library.

How can I check if a URL exists via PHP?

The best and simplest answer so far using get_headers() The best thing to check for string "200 ok". its far better than to check

$file_headers = @get_headers($file-path);
$file_headers[0];

because sometime the array key numbers varies. so best thing is to check for "200 ok". Any URL which is up will have "200 ok" anywhere in get_headers() response.

function url_exist($url) {
        $urlheaders = get_headers($url);
        //print_r($urlheaders);
        $urlmatches  = preg_grep('/200 ok/i', $urlheaders);
         if(!empty($urlmatches)){
           return true;
         }else{
           return false;
         }
}

now check the function if true or false

if(url_exist(php-url-variable-here)
  URL exist
}else{
  URL don't exist
}

T-SQL substring - separating first and last name

You may have problems if the Fullname doesn't contain a space. Assuming the whole of FullName goes to Surname if there is no space and FirstName becomes an empty string, then you can use this:

SELECT
  RTRIM(LEFT(FullName, CHARINDEX(' ', FullName))) AS FirstName,
  SUBSTRING(FullName, CHARINDEX(' ', FullName) + 1, 8000) AS LastName
FROM
  MyNameTable;

Passing in class names to react components

As other have stated, use an interpreted expression with curly braces.

But do not forget to set a default.
Others has suggested using a OR statement to set a empty string if undefined.

But it would be even better to declare your Props.

Full example:

import React, { Component } from 'react';
import PropTypes from 'prop-types';

class Pill extends Component {

  render() {

    return (
      <button className={`pill ${ this.props.className }`}>{this.props.children}</button>
    );
  }

}

Pill.propTypes = {
  className: PropTypes.string,
};

Pill.defaultProps = {
  className: '',
};

Angular 2: How to write a for loop, not a foreach loop

You can instantiate an empty array with a given number of entries if you pass an int to the Array constructor and then iterate over it via ngFor.

In your component code :

export class ForLoop {
  fakeArray = new Array(12);
}

In your template :

<ul>
  <li *ngFor="let a of fakeArray; let index = index">Something {{ index }}</li>
</ul>

The index properties give you the iteration number.

Live version

typeof !== "undefined" vs. != null

if (input == undefined) { ... }

works just fine. It is of course not a null comparison, but I usually find that if I need to distinguish between undefined and null, I actually rather need to distinguish between undefined and just any false value, so

else if (input) { ... }

does it.

If a program redefines undefined it is really braindead anyway.

The only reason I can think of was for IE4 compatibility, it did not understand the undefined keyword (which is not actually a keyword, unfortunately), but of course values could be undefined, so you had to have this:

var undefined;

and the comparison above would work just fine.

In your second example, you probably need double parentheses to make lint happy?

JSON, REST, SOAP, WSDL, and SOA: How do they all link together

Imagine you are developing a web-application and you decide to decouple the functionality from the presentation of the application, because it affords greater freedom.

You create an API and let others implement their own front-ends over it as well. What you just did here is implement an SOA methodology, i.e. using web-services.

Web services make functional building-blocks accessible over standard Internet protocols independent of platforms and programming languages.

So, you design an interchange mechanism between the back-end (web-service) that does the processing and generation of something useful, and the front-end (which consumes the data), which could be anything. (A web, mobile, or desktop application, or another web-service). The only limitation here is that the front-end and back-end must "speak" the same "language".


That's where SOAP and REST come in. They are standard ways you'd pick communicate with the web-service.

SOAP:

SOAP internally uses XML to send data back and forth. SOAP messages have rigid structure and the response XML then needs to be parsed. WSDL is a specification of what requests can be made, with which parameters, and what they will return. It is a complete specification of your API.

REST:

REST is a design concept.

The World Wide Web represents the largest implementation of a system conforming to the REST architectural style.

It isn't as rigid as SOAP. RESTful web-services use standard URIs and methods to make calls to the webservice. When you request a URI, it returns the representation of an object, that you can then perform operations upon (e.g. GET, PUT, POST, DELETE). You are not limited to picking XML to represent data, you could pick anything really (JSON included)

Flickr's REST API goes further and lets you return images as well.


JSON and XML, are functionally equivalent, and common choices. There are also RPC-based frameworks like GRPC based on Protobufs, and Apache Thrift that can be used for communication between the API producers and consumers. The most common format used by web APIs is JSON because of it is easy to use and parse in every language.

String isNullOrEmpty in Java?

I've seen this method written a few times in projects I've been on but I have to say I've never written it myself, or called it either ... Generally I find null and empty are completely distinct conditions and I have no reason to ever conflate them.

Get random sample from list while maintaining ordering of items?

random.sample implement it.

>>> random.sample([1, 2, 3, 4, 5],  3)   # Three samples without replacement
[4, 1, 5]

Angular2 : Can't bind to 'formGroup' since it isn't a known property of 'form'

I think that this is an old error that you tried to fix by importing random things in your module and now the code does not compile anymore. while you don't pay attention to the shell output, the browser reload, and you still get the same error.

Your module should be :

@NgModule({
  imports: [
    CommonModule,
    FormsModule,
    ReactiveFormsModule
  ],
  declarations: [
    ContactComponent
  ]
})
export class ContactModule {}

RunAs A different user when debugging in Visual Studio

As mentioned in have debugger run application as different user (linked above), another extremely simple way to do this which doesn't require any more tools:

  • Hold Shift + right-click to open a new instance of Visual Studio.
  • Click "Run as different user"

    Run as Different user

  • Enter credentials of the other user in the next pop-up window

  • Open the same solution you are working with

Now when you debug the solution it will be with the other user's permissions.

Hint: if you are going to run multiple instances of Visual Studio, change the theme of it (like to "dark") so you can keep track of which one is which easily).

MySQL 1062 - Duplicate entry '0' for key 'PRIMARY'

You need to specify the primary key as auto-increment

CREATE TABLE `momento_distribution`
  (
     `momento_id`       INT(11) NOT NULL AUTO_INCREMENT,
     `momento_idmember` INT(11) NOT NULL,
     `created_at`       DATETIME DEFAULT NULL,
     `updated_at`       DATETIME DEFAULT NULL,
     `unread`           TINYINT(1) DEFAULT '1',
     `accepted`         VARCHAR(10) NOT NULL DEFAULT 'pending',
     `ext_member`       VARCHAR(255) DEFAULT NULL,
     PRIMARY KEY (`momento_id`, `momento_idmember`),
     KEY `momento_distribution_FI_2` (`momento_idmember`),
     KEY `accepted` (`accepted`, `ext_member`)
  )
ENGINE=InnoDB
DEFAULT CHARSET=latin1$$

With regards to comment below, how about:

ALTER TABLE `momento_distribution`
  CHANGE COLUMN `id` `id` INT(11) NOT NULL AUTO_INCREMENT,
  DROP PRIMARY KEY,
  ADD PRIMARY KEY (`id`);

A PRIMARY KEY is a unique index, so if it contains duplicates, you cannot assign the column to be unique index, so you may need to create a new column altogether

HTML table sort

Here is another library.

Changes required are -

  1. Add sorttable js

  2. Add class name sortable to table.

Click the table headers to sort the table accordingly:

_x000D_
_x000D_
<script src="https://www.kryogenix.org/code/browser/sorttable/sorttable.js"></script>

<table class="sortable">
  <tr>
    <th>Name</th>
    <th>Address</th>
    <th>Sales Person</th>
  </tr>

  <tr class="item">
    <td>user:0001</td>
    <td>UK</td>
    <td>Melissa</td>
  </tr>
  <tr class="item">
    <td>user:0002</td>
    <td>France</td>
    <td>Justin</td>
  </tr>
  <tr class="item">
    <td>user:0003</td>
    <td>San Francisco</td>
    <td>Judy</td>
  </tr>
  <tr class="item">
    <td>user:0004</td>
    <td>Canada</td>
    <td>Skipper</td>
  </tr>
  <tr class="item">
    <td>user:0005</td>
    <td>Christchurch</td>
    <td>Alex</td>
  </tr>

</table>
_x000D_
_x000D_
_x000D_

Get file version in PowerShell

Here an alternative method. It uses Get-WmiObject CIM_DATAFILE to select the version.

(Get-WmiObject -Class CIM_DataFile -Filter "Name='C:\\Windows\\explorer.exe'" | Select-Object Version).Version

subsetting a Python DataFrame

Just for someone looking for a solution more similar to R:

df[(df.Product == p_id) & (df.Time> start_time) & (df.Time < end_time)][['Time','Product']]

No need for data.loc or query, but I do think it is a bit long.

Make TextBox uneditable

You can try using:

textBox.ReadOnly = true;
textBox.BackColor = System.Drawing.SystemColors.Window;

The last line is only neccessary if you want a non-grey background color.

Windows service with timer

First approach with Windows Service is not easy..

A long time ago, I wrote a C# service.

This is the logic of the Service class (tested, works fine):

namespace MyServiceApp
{
    public class MyService : ServiceBase
    {
        private System.Timers.Timer timer;

        protected override void OnStart(string[] args)
        {
            this.timer = new System.Timers.Timer(30000D);  // 30000 milliseconds = 30 seconds
            this.timer.AutoReset = true;
            this.timer.Elapsed += new System.Timers.ElapsedEventHandler(this.timer_Elapsed);
            this.timer.Start();
        }

        protected override void OnStop()
        {
            this.timer.Stop();
            this.timer = null;
        }

        private void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            MyServiceApp.ServiceWork.Main(); // my separate static method for do work
        }

        public MyService()
        {
            this.ServiceName = "MyService";
        }

        // service entry point
        static void Main()
        {
            System.ServiceProcess.ServiceBase.Run(new MyService());
        }
    }
}

I recommend you write your real service work in a separate static method (why not, in a console application...just add reference to it), to simplify debugging and clean service code.

Make sure the interval is enough, and write in log ONLY in OnStart and OnStop overrides.

Hope this helps!

How to edit Docker container files from the host?

There are two ways to mount files into your container. It looks like you want a bind mount.

Bind Mounts

This mounts local files directly into the container's filesystem. The containerside path and the hostside path both point to the same file. Edits made from either side will show up on both sides.

  • mount the file:
? echo foo > ./foo
? docker run --mount type=bind,source=$(pwd)/foo,target=/foo -it debian:latest
# cat /foo
foo # local file shows up in container
  • in a separate shell, edit the file:
? echo 'bar' > ./foo # make a hostside change
  • back in the container:
# cat /foo
bar # the hostside change shows up
# echo baz > /foo # make a containerside change
# exit
 
? cat foo
baz # the containerside change shows up

Volume Mounts

  • mount the volume
? docker run --mount type=volume,source=foovolume,target=/foo  -it debian:latest
root@containerB# echo 'this is in a volume' > /foo/data
  • the local filesystem is unchanged
  • docker sees a new volume:
? docker volume ls
DRIVER    VOLUME NAME
local     foovolume
  • create a new container with the same volume
? docker run --mount type=volume,source=foovolume,target=/foo  -it debian:latest
root@containerC:/# cat /foo/data
this is in a volume # data is still available

syntax: -v vs --mount

These do the same thing. -v is more concise, --mount is more explicit.

bind mounts

-v /hostside/path:/containerside/path
--mount type=bind,source=/hostside/path,target=/containerside/path

volume mounts

-v /containerside/path
-v volumename:/containerside/path
--mount type=volume,source=volumename,target=/containerside/path

(If a volume name is not specified, a random one is chosen.)

The documentaion tries to convince you to use one thing in favor of another instead of just telling you how it works, which is confusing.

python: how to check if a line is an empty line

You should open text files using rU so newlines are properly transformed, see http://docs.python.org/library/functions.html#open. This way there's no need to check for \r\n.

How do I obtain a Query Execution Plan in SQL Server?

Starting from SQL Server 2016+, Query Store feature was introduced to monitor performance. It provides insight into query plan choice and performance. It’s not a complete replacement of trace or extended events, but as it’s evolving from version to version, we might get a fully functional query store in future releases from SQL Server. The primary flow of Query Store

  1. SQL Server existing components interact with query store by utilising Query Store Manager.
  2. Query Store Manager determines which Store should be used and then passes execution to that store (Plan or Runtime Stats or Query Wait Stats)
    • Plan Store - Persisting the execution plan information
    • Runtime Stats Store - Persisting the execution statistics information
    • Query Wait Stats Store - Persisting wait statistics information.
  3. Plan, Runtime Stats and Wait store uses Query Store as an extension to SQL Server.

enter image description here

  1. Enabling the Query Store: Query Store works at the database level on the server.

    • Query Store is not active for new databases by default.
    • You cannot enable the query store for the master or tempdb database.
    • Available DMV

      sys.database_query_store_options (Transact-SQL)

  2. Collect Information in the Query Store: We collect all the available information from the three stores using Query Store DMV (Data Management Views).

NOTE: Query Wait Stats Store is available only in SQL Server 2017+

How to add color to Github's README.md file

You cannot color plain text in a GitHub README.md file. You can however add color to code samples with the tags below.

To do this just add tags such as these samples to your README.md file:

```json
   // code for coloring
```
```html
   // code for coloring
```
```js
   // code for coloring
```
```css
   // code for coloring
```
// etc.

No "pre" or "code" tags needed.

This is covered in the GitHub Markdown documentation (about half way down the page, there's an example using Ruby). GitHub uses Linguist to identify and highlight syntax - you can find a full list of supported languages (as well as their markdown keywords) over in the Linguist's YAML file.

How to delete all files and folders in a folder by cmd call

No, I don't know one.

If you want to retain the original directory for some reason (ACLs, &c.), and instead really want to empty it, then you can do the following:

del /q destination\*
for /d %x in (destination\*) do @rd /s /q "%x"

This first removes all files from the directory, and then recursively removes all nested directories, but overall keeping the top-level directory as it is (except for its contents).

Note that within a batch file you need to double the % within the for loop:

del /q destination\*
for /d %%x in (destination\*) do @rd /s /q "%%x"

How to deal with http status codes other than 200 in Angular 2

Include required imports and you can make ur decision in handleError method Error status will give the error code

import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import {Observable, throwError} from "rxjs/index";
import { catchError, retry } from 'rxjs/operators';
import {ApiResponse} from "../model/api.response";
import { TaxType } from '../model/taxtype.model'; 

private handleError(error: HttpErrorResponse) {
if (error.error instanceof ErrorEvent) {
  // A client-side or network error occurred. Handle it accordingly.
  console.error('An error occurred:', error.error.message);
} else {
  // The backend returned an unsuccessful response code.
  // The response body may contain clues as to what went wrong,
  console.error(
    `Backend returned code ${error.status}, ` +
    `body was: ${error.error}`);
}
// return an observable with a user-facing error message
return throwError(
  'Something bad happened; please try again later.');
  };

  getTaxTypes() : Observable<ApiResponse> {
return this.http.get<ApiResponse>(this.baseUrl).pipe(
  catchError(this.handleError)
);
  }

How do I get a list of files in a directory in C++?

Or you do this and then read out the test.txt:

#include <windows.h>

int main() {    
system("dir /b > test.txt");
}

The "/b" means just filenames are returned, no further info.

C# how to convert File.ReadLines into string array?

Change string[] lines = File.ReadLines("c:\\file.txt"); to IEnumerable<string> lines = File.ReadLines("c:\\file.txt"); The rest of your code should work fine.

How to make a view with rounded corners?

public class RoundedCornerLayout extends FrameLayout {
    private double mCornerRadius;

    public RoundedCornerLayout(Context context) {
        this(context, null, 0);
    }

    public RoundedCornerLayout(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public RoundedCornerLayout(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init(context, attrs, defStyle);
    }

    private void init(Context context, AttributeSet attrs, int defStyle) {
        DisplayMetrics metrics = context.getResources().getDisplayMetrics();
        setLayerType(View.LAYER_TYPE_SOFTWARE, null);
    }

    public double getCornerRadius() {
        return mCornerRadius;
    }

    public void setCornerRadius(double cornerRadius) {
        mCornerRadius = cornerRadius;
    }

    @Override
    public void draw(Canvas canvas) {
        int count = canvas.save();

        final Path path = new Path();
        path.addRoundRect(new RectF(0, 0, canvas.getWidth(), canvas.getHeight()), (float) mCornerRadius, (float) mCornerRadius, Path.Direction.CW);
        canvas.clipPath(path, Region.Op.REPLACE);

        canvas.clipPath(path);
        super.draw(canvas);
        canvas.restoreToCount(count);
    }
}

How to stop tracking and ignore changes to a file in Git?

An almost git command-free approach was given in this answer:

To ignore certain files for every local repo:

  1. Create a file ~/.gitignore_global, e.g. by touch ~/.gitignore_global in your terminal.
  2. Run git config --global core.excludesfile ~/.gitignore_global for once.
  3. Write the file/dir paths you want to ignore into ~/.gitignore_global. e.g. modules/*.H, which will be assumed to be in your working directory, i.e. $WORK_DIR/modules/*.H.

To ignore certain files for a single local repo:

  1. Do the above third step for file .git/info/exclude within the repo, that is write the file/dir paths you want to ignore into .git/info/exclude. e.g. modules/*.C, which will be assumed to be in your working directory, i.e. $WORK_DIR/modules/*.C.

Setting the zoom level for a MKMapView

I know this is a late reply, but I've just wanted to address the issue of setting the zoom level myself. goldmine's answer is great but I found it not working sufficiently well in my application.

On closer inspection goldmine states that "longitude lines are spaced apart equally at any point of the map". This is not true, it is in fact latitude lines that are spaced equally from -90 (south pole) to +90 (north pole). Longitude lines are spaced at their widest at the equator, converging to a point at the poles.

The implementation I have adopted is therefore to use the latitude calculation as follows:

@implementation MKMapView (ZoomLevel)

- (void)setCenterCoordinate:(CLLocationCoordinate2D)coordinate
    zoomLevel:(NSUInteger)zoom animated:(BOOL)animated
{
    MKCoordinateSpan span = MKCoordinateSpanMake(180 / pow(2, zoom) * 
        self.frame.size.height / 256, 0);
    [self setRegion:MKCoordinateRegionMake(coordinate, span) animated:animated];
}

@end

Hope it helps at this late stage.

"Python version 2.7 required, which was not found in the registry" error when attempting to install netCDF4 on Windows 8

I had the same issue when using an .exe to install a Python package (because I use Anaconda and it didn't add Python to the registry). I fixed the problem by running this script:

#
# script to register Python 2.0 or later for use with 
# Python extensions that require Python registry settings
#
# written by Joakim Loew for Secret Labs AB / PythonWare
#
# source:
# http://www.pythonware.com/products/works/articles/regpy20.htm
#
# modified by Valentine Gogichashvili as described in http://www.mail-archive.com/[email protected]/msg10512.html

import sys

from _winreg import *

# tweak as necessary
version = sys.version[:3]
installpath = sys.prefix

regpath = "SOFTWARE\\Python\\Pythoncore\\%s\\" % (version)
installkey = "InstallPath"
pythonkey = "PythonPath"
pythonpath = "%s;%s\\Lib\\;%s\\DLLs\\" % (
    installpath, installpath, installpath
)

def RegisterPy():
    try:
        reg = OpenKey(HKEY_CURRENT_USER, regpath)
    except EnvironmentError as e:
        try:
            reg = CreateKey(HKEY_CURRENT_USER, regpath)
            SetValue(reg, installkey, REG_SZ, installpath)
            SetValue(reg, pythonkey, REG_SZ, pythonpath)
            CloseKey(reg)
        except:
            print "*** Unable to register!"
            return
        print "--- Python", version, "is now registered!"
        return
    if (QueryValue(reg, installkey) == installpath and
        QueryValue(reg, pythonkey) == pythonpath):
        CloseKey(reg)
        print "=== Python", version, "is already registered!"
        return
    CloseKey(reg)
    print "*** Unable to register!"
    print "*** You probably have another Python installation!"

if __name__ == "__main__":
    RegisterPy()

Access to ES6 array element index inside for-of loop

In this world of flashy new native functions, we sometimes forget the basics.

for (let i = 0; i < arr.length; i++) {
    console.log('index:', i, 'element:', arr[i]);
}

Clean, efficient, and you can still break the loop. Bonus! You can also start from the end and go backwards with i--!

Additional note: If you're using the value a lot within the loop, you may wish to do const value = arr[i]; at the top of the loop for an easy, readable reference.

Quickly getting to YYYY-mm-dd HH:MM:SS in Perl

I made a little test (Perl v5.20.1 under FreeBSD in VM) calling the following blocks 1.000.000 times each:

A

my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime(time);
my $now = sprintf("%04d-%02d-%02d %02d:%02d:%02d", $year+1900, $mon+1, $mday, $hour, $min, $sec);

B

my $now = strftime('%Y%m%d%H%M%S',localtime);

C

my $now = Time::Piece::localtime->strftime('%Y%m%d%H%M%S');

with the following results:

A: 2 seconds

B: 11 seconds

C: 19 seconds

This is of course not a thorough test or benchmark, but at least it is reproducable for me, so even though it is more complicated, I'd prefer the first method if generating a datetimestamp is required very often.

Calling (eg. under FreeBSD 10.1)

my $now = `date "+%Y%m%d%H%M%S" | tr -d "\n"`;

might not be such a good idea because it is not OS-independent and takes quite some time.

Best regards, Holger

Unable to launch the IIS Express Web server, Failed to register URL, Access is denied

This happened to me on Windows 7 and VS 2013 while viewing a project on the browser after build. I only had to close the browser "Chrome" then made sure that the port is not in use in my Network Activities using some utility (Kaspersky) then tried again and worked without any problems.

JAXB: how to marshall map into <key>value</key>

I found easiest solution.

@XmlElement(name="attribute")
    public String[] getAttributes(){
        return attributes.keySet().toArray(new String[1]);
    }
}

Now it will generate in you xml output like this:

<attribute>key1<attribute>
...
<attribute>keyN<attribute>

EOFError: EOF when reading a line

convert your inputs to ints:

width = int(input())
height = int(input())

What's the difference between a 302 and a 307 redirect?

307 came about because user agents adopted as a de facto behaviour to take POST requests that receive a 302 response and send a GET request to the Location response header.

That is the incorrect behaviour — only a 303 should cause a POST to turn into a GET. User agents should (but don't) stick with the POST method when requesting the new URL if the original POST request returned a 302.

307 was introduced to allow servers to make it clear to the user agent that a method change should not be made by the client when following the Location response header.

How to check if directory exists in %PATH%?

Add Directory to PATH if not already exists:

set myPath=c:\mypath
For /F "Delims=" %%I In ('echo %PATH% ^| find /C /I "%myPath%"') Do set pathExists=%%I 2>Nul
If %pathExists%==0 (set PATH=%myPath%;%PATH%)

Changing the "tick frequency" on x or y axis in matplotlib?

In case anyone is interested in a general one-liner, simply get the current ticks and use it to set the new ticks by sampling every other tick.

ax.set_xticks(ax.get_xticks()[::2])

How to declare a inline object with inline variables without a parent class

You can also do this:

var x = new object[] {
    new { firstName = "john", lastName = "walter" },
    new { brand = "BMW" }
};

And if they are the same anonymous type (firstName and lastName), you won't need to cast as object.

var y = new [] {
    new { firstName = "john", lastName = "walter" },
    new { firstName = "jill", lastName = "white" }
};

Content Type application/soap+xml; charset=utf-8 was not supported by service

In my case same error was caused by missing

[DataContract]
...
[DataMember] 

attributes in the returned data type.

Check for that and try addinging those and see if it helps.

How do you find out the type of an object (in Swift)?

If a parameter is passed as Any to your function, you can test on a special type like so :

   func isADate ( aValue : Any?) -> Bool{
        if (aValue as? Date) != nil {
            print ("a Date")
            return true
        }
        else {
            print ("This is not a date ")
            return false
        }
    }

Python Pandas : pivot table with aggfunc = count unique distinct

You can construct a pivot table for each distinct value of X. In this case,

for xval, xgroup in g:
    ptable = pd.pivot_table(xgroup, rows='Y', cols='Z', 
        margins=False, aggfunc=numpy.size)

will construct a pivot table for each value of X. You may want to index ptable using the xvalue. With this code, I get (for X1)

     X        
Z   Z1  Z2  Z3
Y             
Y1   2   1 NaN
Y2 NaN NaN   1

How to enable Logger.debug() in Log4j

This is probably happening because your log4j configuration is set to ERROR. Look for a log4j.properties file with contents like the following:

log4j.rootLogger=ERROR, CONSOLE

# console logging
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.CONSOLE.Threshold=DEBUG
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern=%d %-5p %-20.20t %-24c{1}: %m%n

The rootLogger is set to ERROR level here using a CONSOLE appender.

Note that some appenders like the console appender also have a Threshold property that can be used to overrule the rootLoggers level. You need to check both in this case.

Angular 6: saving data to local storage

First you should understand how localStorage works. you are doing wrong way to set/get values in local storage. Please read this for more information : How to Use Local Storage with JavaScript

Java String.split() Regex

String[] ops = str.split("\\s*[a-zA-Z]+\\s*");
String[] notops = str.split("\\s*[^a-zA-Z]+\\s*");
String[] res = new String[ops.length+notops.length-1];
for(int i=0; i<res.length; i++) res[i] = i%2==0 ? notops[i/2] : ops[i/2+1];

This should do it. Everything nicely stored in res.

How to get the MD5 hash of a file in C++?

md5.h also have MD5_* functions very useful for big file

#include <openssl/md5.h>
#include <fstream>
.......

std::ifstream file(filename, std::ifstream::binary);
MD5_CTX md5Context;
MD5_Init(&md5Context);
char buf[1024 * 16];
while (file.good()) {
    file.read(buf, sizeof(buf));
    MD5_Update(&md5Context, buf, file.gcount());
}
unsigned char result[MD5_DIGEST_LENGTH];
MD5_Final(result, &md5Context);

Very simple, isn`t it? Convertion to string also very simple:

#include <sstream>
#include <iomanip>
.......

std::stringstream md5string;
md5string << std::hex << std::uppercase << std::setfill('0');
for (const auto &byte: result)
    md5string << std::setw(2) << (int)byte;

return md5string.str();

How to fix homebrew permissions?

I used these two commands and saved my problem

sudo chown -R $(whoami) /usr/local

sudo chown -R $(whoami) /usr/local/etc/bash_completion.d /usr/local/lib/python3.7/site-packages /usr/local/share/aclocal /usr/local/share/locale /usr/local/share/man/man7 /usr/local/share/man/man8 /usr/local/share/zsh /usr/local/share/zsh/site-functions /usr/local/var/homebrew/locks

How to insert current datetime in postgresql insert query

timestamp (or date or time columns) do NOT have "a format".

Any formatting you see is applied by the SQL client you are using.


To insert the current time use current_timestamp as documented in the manual:

INSERT into "Group" (name,createddate) 
VALUES ('Test', current_timestamp);

To display that value in a different format change the configuration of your SQL client or format the value when SELECTing the data:

select name, to_char(createddate, ''yyyymmdd hh:mi:ss tt') as created_date
from "Group"

For psql (the default command line client) you can configure the display format through the configuration parameter DateStyle: https://www.postgresql.org/docs/current/static/runtime-config-client.html#GUC-DATESTYLE

What is the difference between a Docker image and a container?

As many answers pointed this out: You build Dockerfile to get an image and you run image to get a container.

However, following steps helped me get a better feel for what Docker image and container are:

1) Build Dockerfile:

docker build -t my_image dir_with_dockerfile

2) Save the image to .tar file

docker save -o my_file.tar my_image_id

my_file.tar will store the image. Open it with tar -xvf my_file.tar, and you will get to see all the layers. If you dive deeper into each layer you can see what changes were added in each layer. (They should be pretty close to commands in the Dockerfile).

3) To take a look inside of a container, you can do:

sudo docker run -it my_image bash

and you can see that is very much like an OS.

What is the equivalent to getLastInsertId() in Cakephp?

In Cake, the last insert id is automatically saved in the id property of the model. So if you just inserted a user via the User model, the last insert id could be accessed via $User->id

id - Value of the primary key ID of the record that this model is currently pointing to. Automatically set after database insertions.

Read more about model properties in the CakePHP API Docs: http://api.cakephp.org/2.5/class-AppModel.html

Edit: I just realized that Model::getLastInsertID() is essentially the same thing as Model->id

After looking at your code more closely, it's hard to tell exactly what you're doing with the different functions and where they exist in the grand scheme of things. This may actually be more of a scope issue. Are you trying to access the last insert id in two different requests?

Can you explain the flow of your application and how it relates to your problem?

$(document).ready equivalent without jQuery

I was recently using this for a mobile site. This is John Resig's simplified version from "Pro JavaScript Techniques". It depends on addEvent.

var ready = ( function () {
  function ready( f ) {
    if( ready.done ) return f();

    if( ready.timer ) {
      ready.ready.push(f);
    } else {
      addEvent( window, "load", isDOMReady );
      ready.ready = [ f ];
      ready.timer = setInterval(isDOMReady, 13);
    }
  };

  function isDOMReady() {
    if( ready.done ) return false;

    if( document && document.getElementsByTagName && document.getElementById && document.body ) {
      clearInterval( ready.timer );
      ready.timer = null;
      for( var i = 0; i < ready.ready.length; i++ ) {
        ready.ready[i]();
      }
      ready.ready = null;
      ready.done = true;
    }
  }

  return ready;
})();

How to delete large data of table in SQL without log?

This variation of M.Ali's is working fine for me. It deletes some, clears the log and repeats. I'm watching the log grow, drop and start over.

DECLARE @Deleted_Rows INT;
SET @Deleted_Rows = 1;
WHILE (@Deleted_Rows > 0)
  BEGIN
   -- Delete some small number of rows at a time
    delete top (100000) from InstallLog where DateTime between '2014-12-01' and '2015-02-01'
    SET @Deleted_Rows = @@ROWCOUNT;
    dbcc shrinkfile (MobiControlDB_log,0,truncateonly);
END

Using grep to search for a string that has a dot in it

grep uses regexes; . means "any character" in a regex. If you want a literal string, use grep -F, fgrep, or escape the . to \..

Don't forget to wrap your string in double quotes. Or else you should use \\.

So, your command would need to be:

grep -r "0\.49" *

or

grep -r 0\\.49 *

or

grep -Fr 0.49 *

How to hide "Showing 1 of N Entries" with the dataTables.js library

try this for hide

$('#table_id').DataTable({
  "info": false
});

and try this for change label

$('#table_id').DataTable({
 "oLanguage": {
               "sInfo" : "Showing _START_ to _END_ of _TOTAL_ entries",// text you want show for info section
            },

});

How to copy and paste worksheets between Excel workbooks?

easiest way:

Dim newBook As Workbook  
Set newBook = Workbooks.Add

Sheets("Sheet1").Copy Before:=newBook.Sheets(1)

How can I parse JSON with C#?

I am assuming you are not using Json.NET (Newtonsoft.Json NuGet package). If this the case, then you should try it.

It has the following features:

  1. LINQ to JSON
  2. The JsonSerializer for quickly converting your .NET objects to JSON and back again
  3. Json.NET can optionally produce well formatted, indented JSON for debugging or display
  4. Attributes like JsonIgnore and JsonProperty can be added to a class to customize how a class is serialized
  5. Ability to convert JSON to and from XML
  6. Supports multiple platforms: .NET, Silverlight and the Compact Framework

Look at the example below. In this example, JsonConvert class is used to convert an object to and from JSON. It has two static methods for this purpose. They are SerializeObject(Object obj) and DeserializeObject<T>(String json):

Product product = new Product();
product.Name = "Apple";
product.Expiry = new DateTime(2008, 12, 28);
product.Price = 3.99M;
product.Sizes = new string[] { "Small", "Medium", "Large" };

string json = JsonConvert.SerializeObject(product);
//{
//  "Name": "Apple",
//  "Expiry": "2008-12-28T00:00:00",
//  "Price": 3.99,
//  "Sizes": [
//    "Small",
//    "Medium",
//    "Large"
//  ]
//}

Product deserializedProduct = JsonConvert.DeserializeObject<Product>(json);

Vuejs: v-model array in multiple input

You're thinking too DOM, it's a hard as hell habit to break. Vue recommends you approach it data first.

It's kind of hard to tell in your exact situation but I'd probably use a v-for and make an array of finds to push to as I need more.

Here's how I'd set up my instance:

new Vue({
  el: '#app',
  data: {
    finds: []
  },
  methods: {
    addFind: function () {
      this.finds.push({ value: '' });
    }
  }
});

And here's how I'd set up my template:

<div id="app">
  <h1>Finds</h1>
  <div v-for="(find, index) in finds">
    <input v-model="find.value" :key="index">
  </div>
  <button @click="addFind">
    New Find
  </button>
</div>

Although, I'd try to use something besides an index for the key.

Here's a demo of the above: https://jsfiddle.net/crswll/24txy506/9/

Printing leading 0's in C

You place a zero before the minimum field width:

printf("%05d", zipcode);

Detecting request type in PHP (GET, POST, PUT or DELETE)

Since this is about REST, just getting the request method from the server is not enough. You also need to receive RESTful route parameters. The reason for separating RESTful parameters and GET/POST/PUT parameters is that a resource needs to have its own unique URL for identification.

Here's one way of implementing RESTful routes in PHP using Slim:

https://github.com/codeguy/Slim

$app = new \Slim\Slim();
$app->get('/hello/:name', function ($name) {
  echo "Hello, $name";
});
$app->run();

And configure the server accordingly.

Here's another example using AltoRouter:

https://github.com/dannyvankooten/AltoRouter

$router = new AltoRouter();
$router->setBasePath('/AltoRouter'); // (optional) the subdir AltoRouter lives in

// mapping routes
$router->map('GET|POST','/', 'home#index', 'home');
$router->map('GET','/users', array('c' => 'UserController', 'a' => 'ListAction'));
$router->map('GET','/users/[i:id]', 'users#show', 'users_show');
$router->map('POST','/users/[i:id]/[delete|update:action]', 'usersController#doAction', 'users_do');

generate model using user:references vs user_id:integer

how does rails know that user_id is a foreign key referencing user?

Rails itself does not know that user_id is a foreign key referencing user. In the first command rails generate model Micropost user_id:integer it only adds a column user_id however rails does not know the use of the col. You need to manually put the line in the Micropost model

class Micropost < ActiveRecord::Base
  belongs_to :user
end

class User < ActiveRecord::Base
  has_many :microposts
end

the keywords belongs_to and has_many determine the relationship between these models and declare user_id as a foreign key to User model.

The later command rails generate model Micropost user:references adds the line belongs_to :user in the Micropost model and hereby declares as a foreign key.

FYI
Declaring the foreign keys using the former method only lets the Rails know about the relationship the models/tables have. The database is unknown about the relationship. Therefore when you generate the EER Diagrams using software like MySql Workbench you find that there is no relationship threads drawn between the models. Like in the following pic enter image description here

However, if you use the later method you find that you migration file looks like:

def change
    create_table :microposts do |t|
      t.references :user, index: true

      t.timestamps null: false
    end
    add_foreign_key :microposts, :users

Now the foreign key is set at the database level. and you can generate proper EER diagrams. enter image description here

How to enable/disable bluetooth programmatically in android

I used the below code to disable BT when my app launches and works fine. Not sure if this the correct way to implement this as google recommends not using "bluetooth.disable();" without explicit user action to turn off Bluetooth.

    BluetoothAdapter bluetooth = BluetoothAdapter.getDefaultAdapter();
    bluetooth.disable();

I only used the below permission.

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

HTTP Error 503, the service is unavailable

Start by looking in Event Viewer, either under the System or the Application log.

In my case the problem was that no worker process could be started for the App Pool because its configuration file couldn't be read - I had included an extra '.' at the end of its name.

Linq Select Group By

    from p in PriceLog
    group p by p.LogDateTime.ToString("MMM") into g
    select new 
    { 
        LogDate = g.Key.ToString("MMM yyyy"),
        GoldPrice = (int)dateGroup.Average(p => p.GoldPrice), 
        SilverPrice = (int)dateGroup.Average(p => p.SilverPrice) 
    }

How to convert JSON data into a Python object

JSON to python object

The follwing code creates dynamic attributes with the objects keys recursively.

JSON object - fb_data.json:

{
    "name": "John Smith",
    "hometown": {
        "name": "New York",
        "id": 123
    },
    "list": [
        "a",
        "b",
        "c",
        1,
        {
            "key": 1
        }
    ],
    "object": {
        "key": {
            "key": 1
        }
    }
}

On the conversion we have 3 cases:

  • lists
  • dicts (new object)
  • bool, int, float and str
import json


class AppConfiguration(object):
    def __init__(self, data=None):
        if data is None:
            with open("fb_data.json") as fh:
                data = json.loads(fh.read())
        else:
            data = dict(data)

        for key, val in data.items():
            setattr(self, key, self.compute_attr_value(val))

    def compute_attr_value(self, value):
        if isinstance(value, list):
            return [self.compute_attr_value(x) for x in value]
        elif isinstance(value, dict):
            return AppConfiguration(value)
        else:
            return value


if __name__ == "__main__":
    instance = AppConfiguration()

    print(instance.name)
    print(instance.hometown.name)
    print(instance.hometown.id)
    print(instance.list[4].key)
    print(instance.object.key.key)

Now the key, value pairs are attributes - objects.

output:

John Smith
New York
123
1
1

Paste JSON as Code

Supports TypeScript, Python, Go, Ruby, C#, Java, Swift, Rust, Kotlin, C++, Flow, Objective-C, JavaScript, Elm, and JSON Schema.

  • Interactively generate types and (de-)serialization code from JSON, JSON Schema, and TypeScript
  • Paste JSON/JSON Schema/TypeScript as code

enter image description here

quicktype infers types from sample JSON data, then outputs strongly typed models and serializers for working with that data in your desired programming language.

output:

# Generated by https://quicktype.io
#
# To change quicktype's target language, run command:
#
#   "Set quicktype target language"

from typing import List, Union


class Hometown:
    name: str
    id: int

    def __init__(self, name: str, id: int) -> None:
        self.name = name
        self.id = id


class Key:
    key: int

    def __init__(self, key: int) -> None:
        self.key = key


class Object:
    key: Key

    def __init__(self, key: Key) -> None:
        self.key = key


class FbData:
    name: str
    hometown: Hometown
    list: List[Union[Key, int, str]]
    object: Object

    def __init__(self, name: str, hometown: Hometown, list: List[Union[Key, int, str]], object: Object) -> None:
        self.name = name
        self.hometown = hometown
        self.list = list
        self.object = object

This extension is available for free in the Visual Studio Code Marketplace.