Programs & Examples On #Service discovery

Network protocols which allow automatic detection of devices and services offered by these devices on a computer network.

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

@T0xicCode's answer is correct, but I thought I would expand on the details since it actually took me about 20 hours to finally get a working solution implemented.

If you're looking to run Nginx in its own container and use it as a reverse proxy to load balance multiple applications on the same server instance then the steps you need to follow are as such:

Link Your Containers

When you docker run your containers, typically by inputting a shell script into User Data, you can declare links to any other running containers. This means that you need to start your containers up in order and only the latter containers can link to the former ones. Like so:

#!/bin/bash
sudo docker run -p 3000:3000 --name API mydockerhub/api
sudo docker run -p 3001:3001 --link API:API --name App mydockerhub/app
sudo docker run -p 80:80 -p 443:443 --link API:API --link App:App --name Nginx mydockerhub/nginx

So in this example, the API container isn't linked to any others, but the App container is linked to API and Nginx is linked to both API and App.

The result of this is changes to the env vars and the /etc/hosts files that reside within the API and App containers. The results look like so:

/etc/hosts

Running cat /etc/hosts within your Nginx container will produce the following:

172.17.0.5  0fd9a40ab5ec
127.0.0.1   localhost
::1 localhost ip6-localhost ip6-loopback
fe00::0 ip6-localnet
ff00::0 ip6-mcastprefix
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters
172.17.0.3  App
172.17.0.2  API



ENV Vars

Running env within your Nginx container will produce the following:

API_PORT=tcp://172.17.0.2:3000
API_PORT_3000_TCP_PROTO=tcp
API_PORT_3000_TCP_PORT=3000
API_PORT_3000_TCP_ADDR=172.17.0.2

APP_PORT=tcp://172.17.0.3:3001
APP_PORT_3001_TCP_PROTO=tcp
APP_PORT_3001_TCP_PORT=3001
APP_PORT_3001_TCP_ADDR=172.17.0.3

I've truncated many of the actual vars, but the above are the key values you need to proxy traffic to your containers.

To obtain a shell to run the above commands within a running container, use the following:

sudo docker exec -i -t Nginx bash

You can see that you now have both /etc/hosts file entries and env vars that contain the local IP address for any of the containers that were linked. So far as I can tell, this is all that happens when you run containers with link options declared. But you can now use this information to configure nginx within your Nginx container.



Configuring Nginx

This is where it gets a little tricky, and there's a couple of options. You can choose to configure your sites to point to an entry in the /etc/hosts file that docker created, or you can utilize the ENV vars and run a string replacement (I used sed) on your nginx.conf and any other conf files that may be in your /etc/nginx/sites-enabled folder to insert the IP values.



OPTION A: Configure Nginx Using ENV Vars

This is the option that I went with because I couldn't get the /etc/hosts file option to work. I'll be trying Option B soon enough and update this post with any findings.

The key difference between this option and using the /etc/hosts file option is how you write your Dockerfile to use a shell script as the CMD argument, which in turn handles the string replacement to copy the IP values from ENV to your conf file(s).

Here's the set of configuration files I ended up with:

Dockerfile

FROM ubuntu:14.04
MAINTAINER Your Name <[email protected]>

RUN apt-get update && apt-get install -y nano htop git nginx

ADD nginx.conf /etc/nginx/nginx.conf
ADD api.myapp.conf /etc/nginx/sites-enabled/api.myapp.conf
ADD app.myapp.conf /etc/nginx/sites-enabled/app.myapp.conf
ADD Nginx-Startup.sh /etc/nginx/Nginx-Startup.sh

EXPOSE 80 443

CMD ["/bin/bash","/etc/nginx/Nginx-Startup.sh"]

nginx.conf

daemon off;
user www-data;
pid /var/run/nginx.pid;
worker_processes 1;


events {
    worker_connections 1024;
}


http {

    # Basic Settings

    sendfile on;
    tcp_nopush on;
    tcp_nodelay on;
    keepalive_timeout 33;
    types_hash_max_size 2048;

    server_tokens off;
    server_names_hash_bucket_size 64;

    include /etc/nginx/mime.types;
    default_type application/octet-stream;


    # Logging Settings
    access_log /var/log/nginx/access.log;
    error_log /var/log/nginx/error.log;


    # Gzip Settings

gzip on;
    gzip_vary on;
    gzip_proxied any;
    gzip_comp_level 3;
    gzip_buffers 16 8k;
    gzip_http_version 1.1;
    gzip_types text/plain text/xml text/css application/x-javascript application/json;
    gzip_disable "MSIE [1-6]\.(?!.*SV1)";

    # Virtual Host Configs  
    include /etc/nginx/sites-enabled/*;

    # Error Page Config
    #error_page 403 404 500 502 /srv/Splash;


}

NOTE: It's important to include daemon off; in your nginx.conf file to ensure that your container doesn't exit immediately after launching.

api.myapp.conf

upstream api_upstream{
    server APP_IP:3000;
}

server {
    listen 80;
    server_name api.myapp.com;
    return 301 https://api.myapp.com/$request_uri;
}

server {
    listen 443;
    server_name api.myapp.com;

    location / {
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_cache_bypass $http_upgrade;
        proxy_pass http://api_upstream;
    }

}

Nginx-Startup.sh

#!/bin/bash
sed -i 's/APP_IP/'"$API_PORT_3000_TCP_ADDR"'/g' /etc/nginx/sites-enabled/api.myapp.com
sed -i 's/APP_IP/'"$APP_PORT_3001_TCP_ADDR"'/g' /etc/nginx/sites-enabled/app.myapp.com

service nginx start

I'll leave it up to you to do your homework about most of the contents of nginx.conf and api.myapp.conf.

The magic happens in Nginx-Startup.sh where we use sed to do string replacement on the APP_IP placeholder that we've written into the upstream block of our api.myapp.conf and app.myapp.conf files.

This ask.ubuntu.com question explains it very nicely: Find and replace text within a file using commands

GOTCHA On OSX, sed handles options differently, the -i flag specifically. On Ubuntu, the -i flag will handle the replacement 'in place'; it will open the file, change the text, and then 'save over' the same file. On OSX, the -i flag requires the file extension you'd like the resulting file to have. If you're working with a file that has no extension you must input '' as the value for the -i flag.

GOTCHA To use ENV vars within the regex that sed uses to find the string you want to replace you need to wrap the var within double-quotes. So the correct, albeit wonky-looking, syntax is as above.

So docker has launched our container and triggered the Nginx-Startup.sh script to run, which has used sed to change the value APP_IP to the corresponding ENV variable we provided in the sed command. We now have conf files within our /etc/nginx/sites-enabled directory that have the IP addresses from the ENV vars that docker set when starting up the container. Within your api.myapp.conf file you'll see the upstream block has changed to this:

upstream api_upstream{
    server 172.0.0.2:3000;
}

The IP address you see may be different, but I've noticed that it's usually 172.0.0.x.

You should now have everything routing appropriately.

GOTCHA You cannot restart/rerun any containers once you've run the initial instance launch. Docker provides each container with a new IP upon launch and does not seem to re-use any that its used before. So api.myapp.com will get 172.0.0.2 the first time, but then get 172.0.0.4 the next time. But Nginx will have already set the first IP into its conf files, or in its /etc/hosts file, so it won't be able to determine the new IP for api.myapp.com. The solution to this is likely to use CoreOS and its etcd service which, in my limited understanding, acts like a shared ENV for all machines registered into the same CoreOS cluster. This is the next toy I'm going to play with setting up.



OPTION B: Use /etc/hosts File Entries

This should be the quicker, easier way of doing this, but I couldn't get it to work. Ostensibly you just input the value of the /etc/hosts entry into your api.myapp.conf and app.myapp.conf files, but I couldn't get this method to work.

UPDATE: See @Wes Tod's answer for instructions on how to make this method work.

Here's the attempt that I made in api.myapp.conf:

upstream api_upstream{
    server API:3000;
}

Considering that there's an entry in my /etc/hosts file like so: 172.0.0.2 API I figured it would just pull in the value, but it doesn't seem to be.

I also had a couple of ancillary issues with my Elastic Load Balancer sourcing from all AZ's so that may have been the issue when I tried this route. Instead I had to learn how to handle replacing strings in Linux, so that was fun. I'll give this a try in a while and see how it goes.

React js change child component's state from parent component

You can use the createRef to change the state of the child component from the parent component. Here are all the steps.

  1. Create a method to change the state in the child component.

    2 - Create a reference for the child component in parent component using React.createRef().

    3 - Attach reference with the child component using ref={}.

    4 - Call the child component method using this.yor-reference.current.method.

Parent component


class ParentComponent extends Component {
constructor()
{
this.changeChild=React.createRef()
}
  render() {
    return (
      <div>
        <button onClick={this.changeChild.current.toggleMenu()}>
          Toggle Menu from Parent
        </button>
        <ChildComponent ref={this.changeChild} />
      </div>
    );
  }
}

Child Component


class ChildComponent extends Component {
  constructor(props) {
    super(props);
    this.state = {
      open: false;
    }
  }

  toggleMenu=() => {
    this.setState({
      open: !this.state.open
    });
  }

  render() {
    return (
      <Drawer open={this.state.open}/>
    );
  }
}



Combine two columns and add into one new column

Did you check the string concatenation function? Something like:

update table_c set column_a = column_b || column_c 

should work. More here

How to enable file upload on React's Material UI simple input?

If you're using React function components, and you don't like to work with labels or IDs, you can also use a reference.

const uploadInputRef = useRef(null);

return (
  <Fragment>
    <input
      ref={uploadInputRef}
      type="file"
      accept="image/*"
      style={{ display: "none" }}
      onChange={onChange}
    />
    <Button
      onClick={() => uploadInputRef.current && uploadInputRef.current.click()}
      variant="contained"
    >
      Upload
    </Button>
  </Fragment>
);

jQuery: Load Modal Dialog Contents via Ajax

may be this code may give you some idea.

http://blog.nemikor.com/2009/04/18/loading-a-page-into-a-dialog/

$(document).ready(function() {
    $('#page-help').each(function() {
        var $link = $(this);
        var $dialog = $('<div></div>')
            .load($link.attr('href'))
            .dialog({
                autoOpen: false,
                title: $link.attr('title'),
                width: 500,
                height: 300
            });

        $link.click(function() {
            $dialog.dialog('open');

            return false;
        });
    });
});

Difference between .keystore file and .jks file

One reason to choose .keystore over .jks is that Unity recognizes the former but not the latter when you're navigating to select your keystore file (Unity 2017.3, macOS).

How to list all the files in a commit?

I personally use the combination of --stat and --oneline with the show command:

git show --stat --oneline HEAD
git show --stat --oneline b24f5fb
git show --stat --oneline HEAD^^..HEAD

If you do not like/want the addition/removal stats, you can replace --stat with --name-only

git show --name-only --oneline HEAD
git show --name-only --oneline b24f5fb
git show --name-only --oneline HEAD^^..HEAD

Testing if a checkbox is checked with jQuery

There are Several options are there like....

 1. $("#ans").is(':checked') 
 2. $("#ans:checked")
 3. $('input:checkbox:checked'); 

If all these option return true then you can set value accourdingly.

Write to rails console

As other have said, you want to use either puts or p. Why? Is that magic?

Actually not. A rails console is, under the hood, an IRB, so all you can do in IRB you will be able to do in a rails console. Since for printing in an IRB we use puts, we use the same command for printing in a rails console.

You can actually take a look at the console code in the rails source code. See the require of irb? :)

Sleeping in a batch file

There are lots of ways to accomplish a 'sleep' in cmd/batch:

My favourite one:

TIMEOUT /NOBREAK 5 >NUL 2>NUL

This will stop the console for 5 seconds, without any output.

Most used:

ping localhost -n 5 >NUL 2>NUL

This will try to make a connection to localhost 5 times. Since it is hosted on your computer, it will always reach the host, so every second it will try the new every second. The -n flag indicates how many times the script will try the connection. In this case is 5, so it will last 5 seconds.

Variants of the last one:

ping 1.1.1.1 -n 5 >nul

In this script there are some differences comparing it with the last one. This will not try to call localhost. Instead, it will try to connect to 1.1.1.1, a very fast website. The action will last 5 seconds only if you have an active internet connection. Else it will last approximately 15 to complete the action. I do not recommend using this method.

ping 127.0.0.1 -n 5 >nul

This is exactly the same as example 2 (most used). Also, you can also use:

ping [::1] -n 5 >nul

This instead, uses IPv6's localhost version.

There are lots of methods to perform this action. However, I prefer method 1 for Windows Vista and later versions and the most used method (method 2) for earlier versions of the OS.

Microsoft.ACE.OLEDB.12.0 is not registered

Just install 32bit version of ADBE in passive mode:

run cmd in administrator mode and run this code:

AccessDatabaseEngine.exe /passive

http://www.microsoft.com/en-us/download/details.aspx?id=13255

How to remove multiple indexes from a list at the same time?

another option (in place, any combination of indices):

_marker = object()

for i in indices:
    my_list[i] = _marker  # marked for deletion

obj[:] = [v for v in my_list if v is not _marker]

python: how to get information about a function?

Or

help(list.append)

if you're generally poking around.

How to restore PostgreSQL dump file into Postgres databases?

You didn't mention how your backup was made, so the generic answer is: Usually with the psql tool.

Depending on what pg_dump was instructed to dump, the SQL file can have different sets of SQL commands. For example, if you instruct pg_dump to dump a database using --clean and --schema-only, you can't expect to be able to restore the database from that dump as there will be no SQL commands for COPYing (or INSERTing if --inserts is used ) the actual data in the tables. A dump like that will contain only DDL SQL commands, and will be able to recreate the schema but not the actual data.

A typical SQL dump is restored with psql:

psql (connection options here) database  < yourbackup.sql

or alternatively from a psql session,

psql (connection options here) database
database=# \i /path/to/yourbackup.sql

In the case of backups made with pg_dump -Fc ("custom format"), which is not a plain SQL file but a compressed file, you need to use the pg_restore tool.

If you're working on a unix-like, try this:

man psql
man pg_dump
man pg_restore

otherwise, take a look at the html docs. Good luck!

How do I make jQuery wait for an Ajax call to finish before it returns?

I think things would be easier if you code your success function to load the appropriate page instead of returning true or false.

For example instead of returning true you could do:

window.location="appropriate page";

That way when the success function is called the page gets redirected.

Create table using Javascript

_x000D_
_x000D_
function addTable() {_x000D_
  var myTableDiv = document.getElementById("myDynamicTable");_x000D_
_x000D_
  var table = document.createElement('TABLE');_x000D_
  table.border = '1';_x000D_
_x000D_
  var tableBody = document.createElement('TBODY');_x000D_
  table.appendChild(tableBody);_x000D_
_x000D_
  for (var i = 0; i < 3; i++) {_x000D_
    var tr = document.createElement('TR');_x000D_
    tableBody.appendChild(tr);_x000D_
_x000D_
    for (var j = 0; j < 4; j++) {_x000D_
      var td = document.createElement('TD');_x000D_
      td.width = '75';_x000D_
      td.appendChild(document.createTextNode("Cell " + i + "," + j));_x000D_
      tr.appendChild(td);_x000D_
    }_x000D_
  }_x000D_
  myTableDiv.appendChild(table);_x000D_
}_x000D_
addTable();
_x000D_
<div id="myDynamicTable"></div>
_x000D_
_x000D_
_x000D_

Retrofit 2.0 how to get deserialised error response.body

val error = JSONObject(callApi.errorBody()?.string() as String)
            CustomResult.OnError(CustomNotFoundError(userMessage = error["userMessage"] as String))

open class CustomError (
    val traceId: String? = null,
    val errorCode: String? = null,
    val systemMessage: String? = null,
    val userMessage: String? = null,
    val cause: Throwable? = null
)

open class ErrorThrowable(
    private val traceId: String? = null,
    private val errorCode: String? = null,
    private val systemMessage: String? = null,
    private val userMessage: String? = null,
    override val cause: Throwable? = null
) : Throwable(userMessage, cause) {
    fun toError(): CustomError = CustomError(traceId, errorCode, systemMessage, userMessage, cause)
}


class NetworkError(traceId: String? = null, errorCode: String? = null, systemMessage: String? = null, userMessage: String? = null, cause: Throwable? = null):
    CustomError(traceId, errorCode, systemMessage, userMessage?: "Usted no tiene conexión a internet, active los datos", cause)

class HttpError(traceId: String? = null, errorCode: String? = null, systemMessage: String? = null, userMessage: String? = null, cause: Throwable? = null):
    CustomError(traceId, errorCode, systemMessage, userMessage, cause)

class UnknownError(traceId: String? = null, errorCode: String? = null, systemMessage: String? = null, userMessage: String? = null, cause: Throwable? = null):
    CustomError(traceId, errorCode, systemMessage, userMessage?: "Unknown error", cause)

class CustomNotFoundError(traceId: String? = null, errorCode: String? = null, systemMessage: String? = null, userMessage: String? = null, cause: Throwable? = null):
    CustomError(traceId, errorCode, systemMessage, userMessage?: "Data not found", cause)`

Javascript Audio Play on click

HTML:

<button onclick="play()">Play File</button>
<audio id="audio" src="https://s3.amazonaws.com/freecodecamp/drums/Heater-1.mp3"></audio>

JavaScript:

let play = function(){document.getElementById("audio").play()}

How to tell if a file is git tracked (by shell exit code)?

try:

git ls-files --error-unmatch <file name>

will exit with 1 if file is not tracked

Do I need to explicitly call the base virtual destructor?

No you don't need to call the base destructor, a base destructor is always called for you by the derived destructor. Please see my related answer here for order of destruction.

To understand why you want a virtual destructor in the base class, please see the code below:

class B
{
public:
    virtual ~B()
    {
        cout<<"B destructor"<<endl;
    }
};


class D : public B
{
public:
    virtual ~D()
    {
        cout<<"D destructor"<<endl;
    }
};

When you do:

B *pD = new D();
delete pD;

Then if you did not have a virtual destructor in B, only ~B() would be called. But since you have a virtual destructor, first ~D() will be called, then ~B().

Programmatically scroll a UIScrollView

If you want control over the duration and style of the animation, you can do:

[UIView animateWithDuration:2.0f delay:0 options:UIViewAnimationOptionCurveLinear animations:^{
    scrollView.contentOffset = CGPointMake(x, y);
} completion:NULL];

Adjust the duration (2.0f) and options (UIViewAnimationOptionCurveLinear) to taste!

Is there a Java equivalent or methodology for the typedef keyword in C++?

Perhaps this could be another possible replace :

@Data
public class MyMap {
    @Delegate //lombok
    private HashMap<String, String> value;
}

Spring Boot @Value Properties

You haven't included package declarations in the OP but it is possible that neither @SpringBootApplication nor @ComponentScan are scanning for your @Component.

The @ComponentScan Javadoc states:

Either basePackageClasses or basePackages (or its alias value) may be specified to define specific packages to scan. If specific packages are not defined, scanning will occur from the package of the class that declares this annotation.

ISTR wasting a lot of time on this before and found it easiest to simply move my application class to the highest package in my app's package tree.

More recently I encountered a gotcha were the property was being read before the value insertion had been done. Jesse's answer helped as @PostConstruct seems to be the earliest you can read the inserted values, and of course you should let Spring call this.

Multiline TextBox multiple newline

While dragging the TextBox it self Press F4 for Properties and under the Textmode set to Multiline, The representation of multiline to a text box is it can be sizable at 6 sides. And no need to include any newline characters for getting multiline. May be you set it multiline but you dint increased the size of the Textbox at design time.

Creation timestamp and last update timestamp with Hibernate and MySQL

Following code worked for me.

package com.my.backend.models;

import java.util.Date;

import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.MappedSuperclass;

import com.fasterxml.jackson.annotation.JsonIgnore;

import org.hibernate.annotations.ColumnDefault;
import org.hibernate.annotations.CreationTimestamp;
import org.hibernate.annotations.UpdateTimestamp;

import lombok.Getter;
import lombok.Setter;

@MappedSuperclass
@Getter @Setter
public class BaseEntity {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    protected Integer id;

    @CreationTimestamp
    @ColumnDefault("CURRENT_TIMESTAMP")
    protected Date createdAt;

    @UpdateTimestamp
    @ColumnDefault("CURRENT_TIMESTAMP")
    protected Date updatedAt;
}

AngularJS: ng-model not binding to ng-checked for checkboxes

You don't need ng-checked when you use ng-model. If you're performing CRUD on your HTML Form, just create a model for CREATE mode that is consistent with your EDIT mode during the data-binding:

CREATE Mode: Model with default values only

$scope.dataModel = {
   isItemSelected: true,
   isApproved: true,
   somethingElse: "Your default value"
}

EDIT Mode: Model from database

$scope.dataModel = getFromDatabaseWithSameStructure()

Then whether EDIT or CREATE mode, you can consistently make use of your ng-model to sync with your database.

Navigation bar with UIImage for title

This worked for me... try it

let image : UIImage = UIImage(named: "LogoName")
let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 25, height: 25))
imageView.contentMode = .scaleAspectFit
imageView.image = image
navigationItem.titleView = imageView

Spring Boot REST service exception handling

What about this code ? I use a fallback request mapping to catch 404 errors.

@Controller
@ControllerAdvice
public class ExceptionHandlerController {

    @ExceptionHandler(Exception.class)
    public ModelAndView exceptionHandler(HttpServletRequest request, HttpServletResponse response, Exception ex) {
        //If exception has a ResponseStatus annotation then use its response code
        ResponseStatus responseStatusAnnotation = AnnotationUtils.findAnnotation(ex.getClass(), ResponseStatus.class);

        return buildModelAndViewErrorPage(request, response, ex, responseStatusAnnotation != null ? responseStatusAnnotation.value() : HttpStatus.INTERNAL_SERVER_ERROR);
    }

    @RequestMapping("*")
    public ModelAndView fallbackHandler(HttpServletRequest request, HttpServletResponse response) throws Exception {
        return buildModelAndViewErrorPage(request, response, null, HttpStatus.NOT_FOUND);
    }

    private ModelAndView buildModelAndViewErrorPage(HttpServletRequest request, HttpServletResponse response, Exception ex, HttpStatus httpStatus) {
        response.setStatus(httpStatus.value());

        ModelAndView mav = new ModelAndView("error.html");
        if (ex != null) {
            mav.addObject("title", ex);
        }
        mav.addObject("content", request.getRequestURL());
        return mav;
    }

}

How to add element in Python to the end of list using list.insert?

You'll have to pass the new ordinal position to insert using len in this case:

In [62]:

a=[1,2,3,4]
a.insert(len(a),5)
a
Out[62]:
[1, 2, 3, 4, 5]

Writing to a TextBox from another thread?

Most simple, without caring about delegates

if(textBox1.InvokeRequired == true)
    textBox1.Invoke((MethodInvoker)delegate { textBox1.Text = "Invoke was needed";});

else
    textBox1.Text = "Invoke was NOT needed"; 

Page redirect after certain time PHP

The PHP refresh after 5 seconds didn't work for me when opening a Save As dialogue to save a file: (header('Content-type: text/plain'); header("Content-Disposition: attachment; filename=$filename>");)

After the Save As link was clicked, and file was saved, the timed refresh stopped on the calling page.

However, thank you very much, ibu's javascript solution just kept on ticking and refreshing my webpage, which is what I needed for my specific application. So thank you ibu for posting javascript solution to php problem here.

You can use javascript to redirect after some time

setTimeout(function () {    
    window.location.href = 'http://www.google.com'; 
},5000); // 5 seconds

How to convert String to DOM Document object in java?

DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document document = db.parse(new ByteArrayInputStream(xmlString.getBytes("UTF-8"))); //remove the parameter UTF-8 if you don't want to specify the Encoding type.

this works well for me even though the XML structure is complex.

And please make sure your xmlString is valid for XML, notice the escape character should be added "\" at the front.

The main problem might not come from the attributes.

IntelliJ IDEA generating serialVersionUID

I am not sure if you have an old version of IntelliJ IDEA, but if I go to menu File ? Settings... ? Inspections ? Serialization issues ? Serializable class without 'serialVersionUID'` enabled, the class you provide give me warnings.

Enter image description here

If I try the first class I see:

Enter image description here

BTW: It didn't show me a warning until I added { } to the end of each class to fix the compile error.

Google Chrome form autofill and its yellow background

The final solution:

$(document).ready(function(){
    var contadorInterval = 0;
    if (navigator.userAgent.toLowerCase().indexOf("chrome") >= 0)
    {
        var _interval = window.setInterval(function ()
        {
            var autofills = $('input:-webkit-autofill');
            if (autofills.length > 0)
            {
                window.clearInterval(_interval); // stop polling
                autofills.each(function()
                {
                    var clone = $(this).clone(true, true);
                    $(this).after(clone).remove();
                    setTimeout(function(){
//                        $("#User").val('');
                        $("#Password").val('');
                    },10);
                });
            }
            contadorInterval++;
            if(contadorInterval > 50) window.clearInterval(_interval); // stop polling
        }, 20);
    }else{
        setTimeout(function(){
//            $("#User").val('');
            $("#Password").val('');
        },100);
    }
});

Linux bash: Multiple variable assignment

I wanted to assign the values to an array. So, extending Michael Krelin's approach, I did:

read a[{1..3}] <<< $(echo 2 4 6); echo "${a[1]}|${a[2]}|${a[3]}"

which yields:

2|4|6 

as expected.

What is the difference between precision and scale?

precision: Its the total number of digits before or after the radix point. EX: 123.456 here precision is 6.

Scale: Its the total number of digits after the radix point. EX: 123.456 here Scaleis 3

Better way to sum a property value in an array

I thought I'd drop my two cents on this: this is one of those operations that should always be purely functional, not relying on any external variables. A few already gave a good answer, using reduce is the way to go here.

Since most of us can already afford to use ES2015 syntax, here's my proposition:

const sumValues = (obj) => Object.keys(obj).reduce((acc, value) => acc + obj[value], 0);

We're making it an immutable function while we're at it. What reduce is doing here is simply this: Start with a value of 0 for the accumulator, and add the value of the current looped item to it.

Yay for functional programming and ES2015! :)

Select rows where column is null

Do you mean something like:

SELECT COLUMN1, COLUMN2 FROM MY_TABLE WHERE COLUMN1 = 'Value' OR COLUMN1 IS NULL

?

Add ArrayList to another ArrayList in java

The problem you have is caused that you use the same ArrayList NodeList over all iterations in main for loop. Each iterations NodeList is enlarged by new elements.

  1. After first loop, NodeList has 5 elements (PropertyStart,a,b,c,PropertyEnd) and list has 1 element (NodeList: (PropertyStart,a,b,c,PropertyEnd))

  2. After second loop NodeList has 10 elements (PropertyStart,a,b,c,PropertyEnd,PropertyStart,d,e,f,PropertyEnd) and list has 2 elements (NodeList (with 10 elements), NodeList (with 10 elements))

To get you expectations you must replace

NodeList.addAll(nodes);
list.add(NodeList)

by

List childrenList = new ArrayList(nodes);
list.add(childrenList);

PS. Your code is not readable, keep Java code conventions to have readble code. For example is hard to recognize if NodeList is a class or object

TypeError("'bool' object is not iterable",) when trying to return a Boolean

Look at the traceback:

Traceback (most recent call last):
  File "C:\Python33\lib\site-packages\bottle.py", line 821, in _cast
    out = iter(out)
TypeError: 'bool' object is not iterable

Your code isn't iterating the value, but the code receiving it is.

The solution is: return an iterable. I suggest that you either convert the bool to a string (str(False)) or enclose it in a tuple ((False,)).

Always read the traceback: it's correct, and it's helpful.

Deserialize JSON to ArrayList<POJO> using Jackson

Another way is to use an array as a type, e.g.:

ObjectMapper objectMapper = new ObjectMapper();
MyPojo[] pojos = objectMapper.readValue(json, MyPojo[].class);

This way you avoid all the hassle with the Type object, and if you really need a list you can always convert the array to a list by:

List<MyPojo> pojoList = Arrays.asList(pojos);

IMHO this is much more readable.

And to make it be an actual list (that can be modified, see limitations of Arrays.asList()) then just do the following:

List<MyPojo> mcList = new ArrayList<>(Arrays.asList(pojos));

Replace a value in a data frame based on a conditional (`if`) statement

Short answer is:

junk$nm[junk$nm %in% "B"] <- "b"

Take a look at Index vectors in R Introduction (if you don't read it yet).


EDIT. As noticed in comments this solution works for character vectors so fail on your data.

For factor best way is to change level:

levels(junk$nm)[levels(junk$nm)=="B"] <- "b"

How to get the selected row values of DevExpress XtraGrid?

var rowHandle = gridView.FocusedRowHandle;

var obj = gridView.GetRowCellValue(rowHandle, "FieldName");

//For example  
int val= Convert.ToInt32(gridView.GetRowCellValue(rowHandle, "FieldName"));

In Python how should I test if a variable is None, True or False

There are many good answers. I would like to add one more point. A bug can get into your code if you are working with numerical values, and your answer is happened to be 0.

a = 0 
b = 10 
c = None

### Common approach that can cause a problem

if not a:
    print(f"Answer is not found. Answer is {str(a)}.") 
else:
    print(f"Answer is: {str(a)}.")

if not b:
    print(f"Answer is not found. Answer is {str(b)}.") 
else:
    print(f"Answer is: {str(b)}")

if not c:
    print(f"Answer is not found. Answer is {str(c)}.") 
else:
    print(f"Answer is: {str(c)}.")
Answer is not found. Answer is 0.   
Answer is: 10.   
Answer is not found. Answer is None.
### Safer approach 
if a is None:
    print(f"Answer is not found. Answer is {str(a)}.") 
else:
    print(f"Answer is: {str(a)}.")

if b is None:
    print(f"Answer is not found. Answer is {str(b)}.") 
else:
    print(f"Answer is: {str(b)}.")

if c is None:
    print(f"Answer is not found. Answer is {str(c)}.") 
else:
    print(f"Answer is: {str(c)}.")

Answer is: 0.
Answer is: 10.
Answer is not found. Answer is None.

how to check and set max_allowed_packet mysql variable

goto cpanel and login as Main Admin or Super Administrator

  1. find SSH/Shell Access ( you will find under the security tab of cpanel )

  2. now give the username and password of Super Administrator as root or whatyougave

    note: do not give any username, cos, it needs permissions
    
  3. once your into console type

    type ' mysql ' and press enter now you find youself in

    mysql> /* and type here like */

    mysql> set global net_buffer_length=1000000;

    Query OK, 0 rows affected (0.00 sec)

    mysql> set global max_allowed_packet=1000000000;

    Query OK, 0 rows affected (0.00 sec)

Now upload and enjoy!!!

JQuery select2 set default value from an option in list?

If you are using an array data source you can do something like below -

$(".select").select2({
    data: data_names
});
data_names.forEach(function(name) {
    if (name.selected) {
        $(".select").select2('val', name.id);
    }
});

This assumes that out of your data set the one item which you want to set as default has an additional attribute called selected and we use that to set the value.

Doing a cleanup action just before Node.js exits

Just wanted to mention death package here: https://github.com/jprichardson/node-death

Example:

var ON_DEATH = require('death')({uncaughtException: true}); //this is intentionally ugly

ON_DEATH(function(signal, err) {
  //clean up code here
})

How do I install and use the ASP.NET AJAX Control Toolkit in my .NET 3.5 web applications?

Install the ASP.NET AJAX Control Toolkit

  1. Download the ZIP file AjaxControlToolkit-Framework3.5SP1-DllOnly.zip from the ASP.NET AJAX Control Toolkit Releases page of the CodePlex web site.

  2. Copy the contents of this zip file directly into the bin directory of your web site.

Update web.config

  1. Put this in your web.config under the <controls> section:

    <?xml version="1.0"?>
    <configuration>
        ...
        <system.web>
            ...
            <pages>
                ...
                <controls>
                    ...
                    <add tagPrefix="ajaxtoolkit"
                        namespace="AjaxControlToolkit"
                        assembly="AjaxControlToolKit"/>
                </controls>
            </pages>
            ...
        </system.web>
        ...
    </configuration>
    

Setup Visual Studio

  1. Right-click on the Toolbox and select "Add Tab", and add a tab called "AJAX Control Toolkit"

  2. Inside that tab, right-click on the Toolbox and select "Choose Items..."

  3. When the "Choose Toolbox Items" dialog appears, click the "Browse..." button. Navigate to your project's "bin" folder. Inside that folder, select "AjaxControlToolkit.dll" and click OK. Click OK again to close the Choose Items Dialog.

You can now use the controls in your web sites!

.Net: How do I find the .NET version?

For anyone running Windows 10 1607 and looking for .net 4.7. Disregard all of the above.

It's not in the Registry, C:\Windows\Microsoft.NET folder or the Installed Programs list or the WMIC display of that same list.

Look for "installed updates" KB3186568.

CSS word-wrapping in div

try white-space:normal; This will override inheriting white-space:nowrap;

Any way of using frames in HTML5?

Now, there are plenty of example of me answering questions with essays on why following validation rules are important. I've also said that sometimes you just have to be a rebel and break the rules, and document the reasons.

You can see in this example that framesets do work in HTML5 still. I had to download the code and add an HTML5 doctype at the top, however. But the frameset element was still recognized, and the desired result was achieved.

Therefore, knowing that using framesets is completely absurd, and knowing that you have to use this as dictated by your professor/teacher, you could just deal with the single validation error in the W3C validator and use both the HTML5 video element as well as the deprecated frameset element.

<!DOCTYPE html>
<html>
    <head>
    </head>
    <!-- frameset is deprecated in html5, but it still works. -->
    <frameset framespacing="0" rows="150,*" frameborder="0" noresize>
        <frame name="top" src="http://www.npscripts.com/framer/demo-top.html" target="top">
        <frame name="main" src="http://www.google.com" target="main">
    </frameset>
</html>

Keep in mind that if it's a project for school, it's most likely not going to be something that will be around in a year or two once the browser vendors remove frameset support for HTML5 completely. Just know that you are right and just do what your teacher/professor asks just to get the grade :)

UPDATE:

The toplevel parent doc uses XHTML and the frame uses HTML5. The validator did not complain about the frameset being illegal, and it didn't complain about the video element.

index.php:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Frameset//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd">
<html>
    <head>
    </head>
    <frameset framespacing="0" rows="150,*" frameborder="0" noresize>
        <frame name="top" src="http://www.npscripts.com/framer/demo-top.html" target="top">
        <frame name="main" src="video.html" target="main">
    </frameset>
</html>

video.html:

<!doctype html>
<html>
    <head>
    </head>
    <body>
        <div id="player-container">
            <div class="arrow"></div>
            <div class="player">

                <video id="vid1" width="480" height="267" 
                    poster="http://cdn.kaltura.org/apis/html5lib/kplayer-examples/media/bbb480.jpg"
                    durationHint="33" controls>
                    <source src="http://cdn.kaltura.org/apis/html5lib/kplayer-examples/media/bbb_trailer_iphone.m4v" />

                    <source src="http://cdn.kaltura.org/apis/html5lib/kplayer-examples/media/bbb400p.ogv" />

                </video>

        </div>
    </body>
</html>

Deep copy, shallow copy, clone

Unfortunately, "shallow copy", "deep copy" and "clone" are all rather ill-defined terms.


In the Java context, we first need to make a distinction between "copying a value" and "copying an object".

int a = 1;
int b = a;     // copying a value
int[] s = new int[]{42};
int[] t = s;   // copying a value (the object reference for the array above)

StringBuffer sb = new StringBuffer("Hi mom");
               // copying an object.
StringBuffer sb2 = new StringBuffer(sb);

In short, an assignment of a reference to a variable whose type is a reference type is "copying a value" where the value is the object reference. To copy an object, something needs to use new, either explicitly or under the hood.


Now for "shallow" versus "deep" copying of objects. Shallow copying generally means copying only one level of an object, while deep copying generally means copying more than one level. The problem is in deciding what we mean by a level. Consider this:

public class Example {
    public int foo;
    public int[] bar;
    public Example() { };
    public Example(int foo, int[] bar) { this.foo = foo; this.bar = bar; };
}

Example eg1 = new Example(1, new int[]{1, 2});
Example eg2 = ... 

The normal interpretation is that a "shallow" copy of eg1 would be a new Example object whose foo equals 1 and whose bar field refers to the same array as in the original; e.g.

Example eg2 = new Example(eg1.foo, eg1.bar);

The normal interpretation of a "deep" copy of eg1 would be a new Example object whose foo equals 1 and whose bar field refers to a copy of the original array; e.g.

Example eg2 = new Example(eg1.foo, Arrays.copy(eg1.bar));

(People coming from a C / C++ background might say that a reference assignment produces a shallow copy. However, that's not what we normally mean by shallow copying in the Java context ...)

Two more questions / areas of uncertainty exist:

  • How deep is deep? Does it stop at two levels? Three levels? Does it mean the whole graph of connected objects?

  • What about encapsulated data types; e.g. a String? A String is actually not just one object. In fact, it is an "object" with some scalar fields, and a reference to an array of characters. However, the array of characters is completely hidden by the API. So, when we talk about copying a String, does it make sense to call it a "shallow" copy or a "deep" copy? Or should we just call it a copy?


Finally, clone. Clone is a method that exists on all classes (and arrays) that is generally thought to produce a copy of the target object. However:

  • The specification of this method deliberately does not say whether this is a shallow or deep copy (assuming that is a meaningful distinction).

  • In fact, the specification does not even specifically state that clone produces a new object.

Here's what the javadoc says:

"Creates and returns a copy of this object. The precise meaning of "copy" may depend on the class of the object. The general intent is that, for any object x, the expression x.clone() != x will be true, and that the expression x.clone().getClass() == x.getClass() will be true, but these are not absolute requirements. While it is typically the case that x.clone().equals(x) will be true, this is not an absolute requirement."

Note, that this is saying that at one extreme the clone might be the target object, and at the other extreme the clone might not equal the original. And this assumes that clone is even supported.

In short, clone potentially means something different for every Java class.


Some people argue (as @supercat does in comments) that the Java clone() method is broken. But I think the correct conclusion is that the concept of clone is broken in the context of OO. AFAIK, it is impossible to develop a unified model of cloning that is consistent and usable across all object types.

Update query using Subquery in Sql Server

Here in my sample I find out the solution of this, because I had the same problem with updates and subquerys:

UPDATE
    A
SET
    A.ValueToChange = B.NewValue
FROM
    (
        Select * From C
    ) B
Where 
    A.Id = B.Id

Embedding DLLs in a compiled executable

I use the csc.exe compiler called from a .vbs script.

In your xyz.cs script, add the following lines after the directives (my example is for the Renci SSH):

using System;
using Renci;//FOR THE SSH
using System.Net;//FOR THE ADDRESS TRANSLATION
using System.Reflection;//FOR THE Assembly

//+ref>"C:\Program Files (x86)\Microsoft\ILMerge\Renci.SshNet.dll"
//+res>"C:\Program Files (x86)\Microsoft\ILMerge\Renci.SshNet.dll"
//+ico>"C:\Program Files (x86)\Microsoft CAPICOM 2.1.0.2 SDK\Samples\c_sharp\xmldsig\resources\Traffic.ico"

The ref, res and ico tags will be picked up by the .vbs script below to form the csc command.

Then add the assembly resolver caller in the Main:

public static void Main(string[] args)
{
    AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(CurrentDomain_AssemblyResolve);
    .

...and add the resolver itself somewhere in the class:

    static Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
    {
        String resourceName = new AssemblyName(args.Name).Name + ".dll";

        using (var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(resourceName))
        {
            Byte[] assemblyData = new Byte[stream.Length];
            stream.Read(assemblyData, 0, assemblyData.Length);
            return Assembly.Load(assemblyData);
        }

    }

I name the vbs script to match the .cs filename (e.g. ssh.vbs looks for ssh.cs); this makes running the script numerous times a lot easier, but if you aren't an idiot like me then a generic script could pick up the target .cs file from a drag-and-drop:

    Dim name_,oShell,fso
    Set oShell = CreateObject("Shell.Application")
    Set fso = CreateObject("Scripting.fileSystemObject")

    'TAKE THE VBS SCRIPT NAME AS THE TARGET FILE NAME
    '################################################
    name_ = Split(wscript.ScriptName, ".")(0)

    'GET THE EXTERNAL DLL's AND ICON NAMES FROM THE .CS FILE
    '#######################################################
    Const OPEN_FILE_FOR_READING = 1
    Set objInputFile = fso.OpenTextFile(name_ & ".cs", 1)

    'READ EVERYTHING INTO AN ARRAY
    '#############################
    inputData = Split(objInputFile.ReadAll, vbNewline)

    For each strData In inputData

        if left(strData,7)="//+ref>" then 
            csc_references = csc_references & " /reference:" &         trim(replace(strData,"//+ref>","")) & " "
        end if

        if left(strData,7)="//+res>" then 
            csc_resources = csc_resources & " /resource:" & trim(replace(strData,"//+res>","")) & " "
        end if

        if left(strData,7)="//+ico>" then 
            csc_icon = " /win32icon:" & trim(replace(strData,"//+ico>","")) & " "
        end if
    Next

    objInputFile.Close


    'COMPILE THE FILE
    '################
    oShell.ShellExecute "c:\windows\microsoft.net\framework\v3.5\csc.exe", "/warn:1 /target:exe " & csc_references & csc_resources & csc_icon & " " & name_ & ".cs", "", "runas", 2


    WScript.Quit(0)

Create a global variable in TypeScript

I needed to make lodash global to use an existing .js file that I could not change, only require.

I found that this worked:

import * as lodash from 'lodash';

(global as any)._ = lodash;

How to use a Bootstrap 3 glyphicon in an html select

To my knowledge the only way to achieve this in a native select would be to use the unicode representations of the font. You'll have to apply the glyphicon font to the select and as such can't mix it with other fonts. However, glyphicons include regular characters, so you can add text. Unfortunately setting the font for individual options doesn't seem to be possible.

<select class="form-control glyphicon">
    <option value="">&#x2212; &#x2212; &#x2212; Hello</option>
    <option value="glyphicon-list-alt">&#xe032; Text</option>
</select>

Here's a list of the icons with their unicode:

http://glyphicons.bootstrapcheatsheets.com/

Need to perform Wildcard (*,?, etc) search on a string using Regex

I think @Dmitri has nice solution at Matching strings with wildcard https://stackoverflow.com/a/30300521/1726296

Based on his solution, I have created two extension methods. (credit goes to him)

May be helpful.

public static String WildCardToRegular(this String value)
{
        return "^" + Regex.Escape(value).Replace("\\?", ".").Replace("\\*", ".*") + "$";
}

public static bool WildCardMatch(this String value,string pattern,bool ignoreCase = true)
{
        if (ignoreCase)
            return Regex.IsMatch(value, WildCardToRegular(pattern), RegexOptions.IgnoreCase);

        return Regex.IsMatch(value, WildCardToRegular(pattern));
}

Usage:

string pattern = "file.*";

var isMatched = "file.doc".WildCardMatch(pattern)

or

string xlsxFile = "file.xlsx"
var isMatched = xlsxFile.WildCardMatch(pattern)

How to specify the bottom border of a <tr>?

Try the following instead:

<html>
 <head>
  <title>Table row styling</title>
  <style type="text/css">
    .bb td, .bb th {
     border-bottom: 1px solid black !important;
    }
  </style>
 </head>
 <body>
  <table>
    <tr class="bb">
      <td>This</td>
      <td>should</td>
      <td>work</td>
    </tr>
  </table>
 </body>
</html>

How do I resize a Google Map with JavaScript after it has loaded?

First of all, thanks for guiding me and closing this issue. I found a way to fix this issue from your discussions. Yeah, Let's come to the point. The thing is I'm Using GoogleMapHelper v3 helper in CakePHP3. When i tried to open bootstrap modal popup, I got struck with the grey box issue over the map. It's been extended for 2 days. Finally i got a fix over this.

We need to Update the GoogleMapHelper to fix the issue

Need to add the below script in setCenterMap function

google.maps.event.trigger({$id}, \"resize\");

And need the include below code in JavaScript

google.maps.event.addListenerOnce({$id}, 'idle', function(){
   setCenterMap(new google.maps.LatLng({$this->defaultLatitude}, 
   {$this->defaultLongitude}));
});

SQL like search string starts with

COLLATE UTF8_GENERAL_CI will work as ignore-case. USE:

SELECT * from games WHERE title COLLATE UTF8_GENERAL_CI LIKE 'age of empires III%';

or

SELECT * from games WHERE LOWER(title) LIKE 'age of empires III%';

How do I convert a pandas Series or index to a Numpy array?

If you are dealing with a multi-index dataframe, you may be interested in extracting only the column of one name of the multi-index. You can do this as

df.index.get_level_values('name_sub_index')

and of course name_sub_index must be an element of the FrozenList df.index.names

Why is a "GRANT USAGE" created the first time I grant a user privileges?

As you said, in MySQL USAGE is synonymous with "no privileges". From the MySQL Reference Manual:

The USAGE privilege specifier stands for "no privileges." It is used at the global level with GRANT to modify account attributes such as resource limits or SSL characteristics without affecting existing account privileges.

USAGE is a way to tell MySQL that an account exists without conferring any real privileges to that account. They merely have permission to use the MySQL server, hence USAGE. It corresponds to a row in the `mysql`.`user` table with no privileges set.

The IDENTIFIED BY clause indicates that a password is set for that user. How do we know a user is who they say they are? They identify themselves by sending the correct password for their account.

A user's password is one of those global level account attributes that isn't tied to a specific database or table. It also lives in the `mysql`.`user` table. If the user does not have any other privileges ON *.*, they are granted USAGE ON *.* and their password hash is displayed there. This is often a side effect of a CREATE USER statement. When a user is created in that way, they initially have no privileges so they are merely granted USAGE.

AppFabric installation failed because installer MSI returned with error code : 1603

Although many links talk about deleting the trailing space in the environment variable, that did not apply to my case as there was no trailing space in my case.

https://serverfault.com/a/593339/270420

This was the answer that finally helped me out. I had to delete the AS_Observers and AS_Administrators groups created during previous installation attempt and then reinstall.

Doing this resolved the problem and I could successfully install AppFabric. Couldn't post this as answer in the server fault site due to insufficient reputation.

@Value annotation type casting to Integer from String

If you want to convert a property to an integer from properties file there are 2 solutions which I found:

Given scenario: customer.properties contains customer.id = 100 as a field and you want to access it in spring configuration file as integer.The property customerId is declared as type int in the Bean Customer

Solution 1:

_x000D_
_x000D_
<property name="customerId" value="#{T(java.lang.Integer).parseInt('${customer.id}')}" />
_x000D_
_x000D_
_x000D_

In the above line, the string value from properties file is converted to int type.

solution 2: Use some other extension inplace of propeties.For Ex.- If your properties file name is customer.properties then make it customer.details and in the configuration file use the below code

_x000D_
_x000D_
<property name="customerId"   value="${customer.id}" />
_x000D_
_x000D_
_x000D_

How do I add an existing Solution to GitHub from Visual Studio 2013

It's a few less clicks in VS2017, and if the local repo is ahead of the Git clone, click Source control from the pop-up project menu:

enter image description here
This brings up the Team Explorer Changes dialog:

enter image description here
Type in a description- here it's "Stack Overflow Example Commit".
Make a choice of the three options on offer, all of which are explained here.

Splitting a C++ std::string using tokens, e.g. ";"

There are several libraries available solving this problem, but the simplest is probably to use Boost Tokenizer:

#include <iostream>
#include <string>
#include <boost/tokenizer.hpp>
#include <boost/foreach.hpp>

typedef boost::tokenizer<boost::char_separator<char> > tokenizer;

std::string str("denmark;sweden;india;us");
boost::char_separator<char> sep(";");
tokenizer tokens(str, sep);

BOOST_FOREACH(std::string const& token, tokens)
{
    std::cout << "<" << *tok_iter << "> " << "\n";
}

How can I get name of element with jQuery?

You should use attr('name') like this

 $('#yourid').attr('name')

you should use an id selector, if you use a class selector you encounter problems because a collection is returned

How can I change the date format in Java?

How to convert from one date format to another using SimpleDateFormat:

final String OLD_FORMAT = "dd/MM/yyyy";
final String NEW_FORMAT = "yyyy/MM/dd";

// August 12, 2010
String oldDateString = "12/08/2010";
String newDateString;

SimpleDateFormat sdf = new SimpleDateFormat(OLD_FORMAT);
Date d = sdf.parse(oldDateString);
sdf.applyPattern(NEW_FORMAT);
newDateString = sdf.format(d);

Where do I put a single filter that filters methods in two controllers in Rails

Two ways.

i. You can put it in ApplicationController and add the filters in the controller

    class ApplicationController < ActionController::Base       def filter_method       end     end      class FirstController < ApplicationController       before_filter :filter_method     end      class SecondController < ApplicationController       before_filter :filter_method     end 

But the problem here is that this method will be added to all the controllers since all of them extend from application controller

ii. Create a parent controller and define it there

 class ParentController < ApplicationController   def filter_method   end  end  class FirstController < ParentController   before_filter :filter_method end  class SecondController < ParentController   before_filter :filter_method end 

I have named it as parent controller but you can come up with a name that fits your situation properly.

You can also define the filter method in a module and include it in the controllers where you need the filter

How to amend older Git commit?

I've used another way for a few times. In fact, it is a manual git rebase -i and it is useful when you want to rearrange several commits including squashing or splitting some of them. The main advantage is that you don't have to decide about every commit's destiny at a single moment. You'll also have all Git features available during the process unlike during a rebase. For example, you can display the log of both original and rewritten history at any time, or even do another rebase!

I'll refer to the commits in the following way, so it's readable easily:

C # good commit after a bad one
B # bad commit
A # good commit before a bad one

Your history in the beginning looks like this:

x - A - B - C
|           |
|           master
|
origin/master

We'll recreate it to this way:

x - A - B*- C'
|           |
|           master
|
origin/master

Procedure

git checkout B       # get working-tree to the state of commit B
git reset --soft A   # tell Git that we are working before commit B
git checkout -b rewrite-history   # switch to a new branch for alternative history

Improve your old commit using git add (git add -i, git stash etc.) now. You can even split your old commit into two or more.

git commit           # recreate commit B (result = B*)
git cherry-pick C    # copy C to our new branch (result = C')

Intermediate result:

x - A - B - C 
|    \      |
|     \     master
|      \
|       B*- C'
|           |
|           rewrite-history
|
origin/master

Let's finish:

git checkout master
git reset --hard rewrite-history  # make this branch master

Or using just one command:

git branch -f master  # make this place the new tip of the master branch

That's it, you can push your progress now.

The last task is to delete the temporary branch:

git branch -d rewrite-history

Change URL and redirect using jQuery

tell you the true, I still don't get what you need, but

window.location(url);

should be

window.location = url;

a search on window.location reference will tell you that.

How to increase icons size on Android Home Screen?

Unless you write your own Homescreen launcher or use an existing one from Goolge Play, there's "no way" to resize icons.

Well, "no way" does not mean its impossible:

  • As said, you can write your own launcher as discussed in Stackoverflow.
  • You can resize elements on the home screen, but these elements are AppWidgets. Since API level 14 they can be resized and user can - in limits - change the size. But that are Widgets not Shortcuts for launching icons.

How do I make a C++ macro behave like a function?

Your answer suffers from the multiple-evaluation problem, so (eg)

macro( read_int(file1), read_int(file2) );

will do something unexpected and probably unwanted.

How to build PDF file from binary string returned from a web-service using javascript

You can use PDF.js to create PDF files from javascript... it's easy to code... hope this solve your doubt!!!

Regards!

Can I compile all .cpp files in src/ to .o's in obj/, then link to binary in ./?

Wildcard works for me also, but I'd like to give a side note for those using directory variables. Always use slash for folder tree (not backslash), otherwise it will fail:

BASEDIR = ../..
SRCDIR = $(BASEDIR)/src
INSTALLDIR = $(BASEDIR)/lib

MODULES = $(wildcard $(SRCDIR)/*.cpp)
OBJS = $(wildcard *.o)

Creating temporary files in Android

Do it in simple. According to documentation https://developer.android.com/training/data-storage/files

String imageName = "IMG_" + String.valueOf(System.currentTimeMillis()) +".jpg";
        picFile = new File(ProfileActivity.this.getCacheDir(),imageName);

and delete it after usage

picFile.delete()

Wait for Angular 2 to load/resolve model before rendering view/template

Try {{model?.person.name}} this should wait for model to not be undefined and then render.

Angular 2 refers to this ?. syntax as the Elvis operator. Reference to it in the documentation is hard to find so here is a copy of it in case they change/move it:

The Elvis Operator ( ?. ) and null property paths

The Angular “Elvis” operator ( ?. ) is a fluent and convenient way to guard against null and undefined values in property paths. Here it is, protecting against a view render failure if the currentHero is null.

The current hero's name is {{currentHero?.firstName}}

Let’s elaborate on the problem and this particular solution.

What happens when the following data bound title property is null?

The title is {{ title }}

The view still renders but the displayed value is blank; we see only "The title is" with nothing after it. That is reasonable behavior. At least the app doesn't crash.

Suppose the template expression involves a property path as in this next example where we’re displaying the firstName of a null hero.

The null hero's name is {{nullHero.firstName}}

JavaScript throws a null reference error and so does Angular:

TypeError: Cannot read property 'firstName' of null in [null]

Worse, the entire view disappears.

We could claim that this is reasonable behavior if we believed that the hero property must never be null. If it must never be null and yet it is null, we've made a programming error that should be caught and fixed. Throwing an exception is the right thing to do.

On the other hand, null values in the property path may be OK from time to time, especially when we know the data will arrive eventually.

While we wait for data, the view should render without complaint and the null property path should display as blank just as the title property does.

Unfortunately, our app crashes when the currentHero is null.

We could code around that problem with NgIf

<!--No hero, div not displayed, no error --> <div *ngIf="nullHero">The null hero's name is {{nullHero.firstName}}</div>

Or we could try to chain parts of the property path with &&, knowing that the expression bails out when it encounters the first null.

The null hero's name is {{nullHero && nullHero.firstName}}

These approaches have merit but they can be cumbersome, especially if the property path is long. Imagine guarding against a null somewhere in a long property path such as a.b.c.d.

The Angular “Elvis” operator ( ?. ) is a more fluent and convenient way to guard against nulls in property paths. The expression bails out when it hits the first null value. The display is blank but the app keeps rolling and there are no errors.

<!-- No hero, no problem! --> The null hero's name is {{nullHero?.firstName}}

It works perfectly with long property paths too:

a?.b?.c?.d

When to use Interface and Model in TypeScript / Angular

The Interface describes either a contract for a class or a new type. It is a pure Typescript element, so it doesn't affect Javascript.

A model, and namely a class, is an actual JS function which is being used to generate new objects.

I want to load JSON data from a URL and bind to the Interface/Model.

Go for a model, otherwise it will still be JSON in your Javascript.

How to count days between two dates in PHP?

Use DateTime::diff (aka date_diff):

$datetime1 = new DateTime('2009-10-11');
$datetime2 = new DateTime('2009-10-13');
$interval = $datetime1->diff($datetime2);

Or:

$datetime1 = date_create('2009-10-11');
$datetime2 = date_create('2009-10-13');
$interval = date_diff($datetime1, $datetime2);

You can then get the interval as a integer by calling $interval->days.

Two way sync with rsync

Since the original question also involves a desktop and laptop and example involving music files (hence he's probably using a GUI), I'd also mention one of the best bi-directional, multi-platform, free and open source programs to date: FreeFileSync.

It's GUI based, very fast and intuitive, comes with filtering and many other options, including the ability to remote connect, to view and interactively manage "collisions" (in example, files with similar timestamps) and to switch between bidirectional transfer, mirroring and so on.

How to subtract/add days from/to a date?

Just subtract a number:

> as.Date("2009-10-01")
[1] "2009-10-01"
> as.Date("2009-10-01")-5
[1] "2009-09-26"

Since the Date class only has days, you can just do basic arithmetic on it.

If you want to use POSIXlt for some reason, then you can use it's slots:

> a <- as.POSIXlt("2009-10-04")
> names(unclass(as.POSIXlt("2009-10-04")))
[1] "sec"   "min"   "hour"  "mday"  "mon"   "year"  "wday"  "yday"  "isdst"
> a$mday <- a$mday - 6
> a
[1] "2009-09-28 EDT"

Working copy XXX locked and cleanup failed in SVN

I did the following to fix my issue:

  1. Renamed the offending folder by placing an "_" in front of the folder name.
  2. Did a "Clean Up" of the parent folder.
  3. Renamed the offending folder back to it original name.
  4. Did a commit.

force browsers to get latest js and css files in asp.net application

ASP.NET MVC will handle this for you if you use bundles for your JS/CSS. It will automatically append a version number in the form of a GUID to your bundles and only update this GUID when the bundle is updated (aka any of the source files have changes).

This also helps if you have a ton of JS/CSS files as it can greatly improve content load times!

See Here

Focus Next Element In Tab Index

If you use the library "JQuery", you can call this:

Tab:

$.tabNext();

Shift+Tab:

$.tabPrev();

_x000D_
_x000D_
<!DOCTYPE html>
<html>
<body>
<script src="https://code.jquery.com/jquery-3.3.1.js" integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60=" crossorigin="anonymous"></script>
<script>
(function($){
    'use strict';

    /**
     * Focusses the next :focusable element. Elements with tabindex=-1 are focusable, but not tabable.
     * Does not take into account that the taborder might be different as the :tabbable elements order
     * (which happens when using tabindexes which are greater than 0).
     */
    $.focusNext = function(){
        selectNextTabbableOrFocusable(':focusable');
    };

    /**
     * Focusses the previous :focusable element. Elements with tabindex=-1 are focusable, but not tabable.
     * Does not take into account that the taborder might be different as the :tabbable elements order
     * (which happens when using tabindexes which are greater than 0).
     */
    $.focusPrev = function(){
        selectPrevTabbableOrFocusable(':focusable');
    };

    /**
     * Focusses the next :tabable element.
     * Does not take into account that the taborder might be different as the :tabbable elements order
     * (which happens when using tabindexes which are greater than 0).
     */
    $.tabNext = function(){
        selectNextTabbableOrFocusable(':tabbable');
    };

    /**
     * Focusses the previous :tabbable element
     * Does not take into account that the taborder might be different as the :tabbable elements order
     * (which happens when using tabindexes which are greater than 0).
     */
    $.tabPrev = function(){
        selectPrevTabbableOrFocusable(':tabbable');
    };

    function tabIndexToInt(tabIndex){
        var tabIndexInded = parseInt(tabIndex);
        if(isNaN(tabIndexInded)){
            return 0;
        }else{
            return tabIndexInded;
        }
    }

    function getTabIndexList(elements){
        var list = [];
        for(var i=0; i<elements.length; i++){
            list.push(tabIndexToInt(elements.eq(i).attr("tabIndex")));
        }
        return list;
    }

    function selectNextTabbableOrFocusable(selector){
        var selectables = $(selector);
        var current = $(':focus');

        // Find same TabIndex of remainder element
        var currentIndex = selectables.index(current);
        var currentTabIndex = tabIndexToInt(current.attr("tabIndex"));
        for(var i=currentIndex+1; i<selectables.length; i++){
            if(tabIndexToInt(selectables.eq(i).attr("tabIndex")) === currentTabIndex){
                selectables.eq(i).focus();
                return;
            }
        }

        // Check is last TabIndex
        var tabIndexList = getTabIndexList(selectables).sort(function(a, b){return a-b});
        if(currentTabIndex === tabIndexList[tabIndexList.length-1]){
            currentTabIndex = -1;// Starting from 0
        }

        // Find next TabIndex of all element
        var nextTabIndex = tabIndexList.find(function(element){return currentTabIndex<element;});
        for(var i=0; i<selectables.length; i++){
            if(tabIndexToInt(selectables.eq(i).attr("tabIndex")) === nextTabIndex){
                selectables.eq(i).focus();
                return;
            }
        }
    }

    function selectPrevTabbableOrFocusable(selector){
        var selectables = $(selector);
        var current = $(':focus');

        // Find same TabIndex of remainder element
        var currentIndex = selectables.index(current);
        var currentTabIndex = tabIndexToInt(current.attr("tabIndex"));
        for(var i=currentIndex-1; 0<=i; i--){
            if(tabIndexToInt(selectables.eq(i).attr("tabIndex")) === currentTabIndex){
                selectables.eq(i).focus();
                return;
            }
        }

        // Check is last TabIndex
        var tabIndexList = getTabIndexList(selectables).sort(function(a, b){return b-a});
        if(currentTabIndex <= tabIndexList[tabIndexList.length-1]){
            currentTabIndex = tabIndexList[0]+1;// Starting from max
        }

        // Find prev TabIndex of all element
        var prevTabIndex = tabIndexList.find(function(element){return element<currentTabIndex;});
        for(var i=selectables.length-1; 0<=i; i--){
            if(tabIndexToInt(selectables.eq(i).attr("tabIndex")) === prevTabIndex){
                selectables.eq(i).focus();
                return;
            }
        }
    }

    /**
     * :focusable and :tabbable, both taken from jQuery UI Core
     */
    $.extend($.expr[ ':' ], {
        data: $.expr.createPseudo ?
            $.expr.createPseudo(function(dataName){
                return function(elem){
                    return !!$.data(elem, dataName);
                };
            }) :
            // support: jQuery <1.8
            function(elem, i, match){
                return !!$.data(elem, match[ 3 ]);
            },

        focusable: function(element){
            return focusable(element, !isNaN($.attr(element, 'tabindex')));
        },

        tabbable: function(element){
            var tabIndex = $.attr(element, 'tabindex'),
                isTabIndexNaN = isNaN(tabIndex);
            return ( isTabIndexNaN || tabIndex >= 0 ) && focusable(element, !isTabIndexNaN);
        }
    });

    /**
     * focussable function, taken from jQuery UI Core
     * @param element
     * @returns {*}
     */
    function focusable(element){
        var map, mapName, img,
            nodeName = element.nodeName.toLowerCase(),
            isTabIndexNotNaN = !isNaN($.attr(element, 'tabindex'));
        if('area' === nodeName){
            map = element.parentNode;
            mapName = map.name;
            if(!element.href || !mapName || map.nodeName.toLowerCase() !== 'map'){
                return false;
            }
            img = $('img[usemap=#' + mapName + ']')[0];
            return !!img && visible(img);
        }
        return ( /^(input|select|textarea|button|object)$/.test(nodeName) ?
            !element.disabled :
            'a' === nodeName ?
                element.href || isTabIndexNotNaN :
                isTabIndexNotNaN) &&
            // the element and all of its ancestors must be visible
            visible(element);

        function visible(element){
            return $.expr.filters.visible(element) && !$(element).parents().addBack().filter(function(){
                return $.css(this, 'visibility') === 'hidden';
            }).length;
        }
    }
})(jQuery);
</script>

<a tabindex="5">5</a><br>
<a tabindex="20">20</a><br>
<a tabindex="3">3</a><br>
<a tabindex="7">7</a><br>
<a tabindex="20">20</a><br>
<a tabindex="0">0</a><br>

<script>
var timer;
function tab(){
    window.clearTimeout(timer)
    timer = window.setInterval(function(){$.tabNext();}, 1000);
}
function shiftTab(){
    window.clearTimeout(timer)
    timer = window.setInterval(function(){$.tabPrev();}, 1000);
}
</script>
<button tabindex="-1" onclick="tab()">Tab</button>
<button tabindex="-1" onclick="shiftTab()">Shift+Tab</button>

</body>
</html>
_x000D_
_x000D_
_x000D_

I modify jquery.tabbable PlugIn to complete.

Trigger css hover with JS

You can't. It's not a trusted event.

Events that are generated by the user agent, either as a result of user interaction, or as a direct result of changes to the DOM, are trusted by the user agent with privileges that are not afforded to events generated by script through the DocumentEvent.createEvent("Event") method, modified using the Event.initEvent() method, or dispatched via the EventTarget.dispatchEvent() method. The isTrusted attribute of trusted events has a value of true, while untrusted events have a isTrusted attribute value of false.

Most untrusted events should not trigger default actions, with the exception of click or DOMActivate events.

You have to add a class and add/remove that on the mouseover/mouseout events manually.


Side note, I'm answering this here after I marked this as a duplicate since no answer here really covers the issue from what I see. Hopefully, one day it'll be merged.

How to change line width in IntelliJ (from 120 character)

IntelliJ IDEA 2018

File > Settings... > Editor > Code Style > Hard wrap at

Code Style > Hard wrap at

IntelliJ IDEA 2016 & 2017

File > Settings... > Editor > Code Style > Right margin (columns):

File > Settings

Editor > Code Style > Right margin

How to Get XML Node from XDocument

The .Elements operation returns a LIST of XElements - but what you really want is a SINGLE element. Add this:

XElement Contacts = (from xml2 in XMLDoc.Elements("Contacts").Elements("Node")
                    where xml2.Element("ID").Value == variable
                    select xml2).FirstOrDefault();

This way, you tell LINQ to give you the first (or NULL, if none are there) from that LIST of XElements you're selecting.

Marc

Submitting HTML form using Jquery AJAX

var postData = "text";
      $.ajax({
            type: "post",
            url: "url",
            data: postData,
            contentType: "application/x-www-form-urlencoded",
            success: function(responseData, textStatus, jqXHR) {
                alert("data saved")
            },
            error: function(jqXHR, textStatus, errorThrown) {
                console.log(errorThrown);
            }
        })

When creating a service with sc.exe how to pass in context parameters?

I couldn't handle the issue with your proposals, at the end with the x86 folder it only worked in power shell (windows server 2012) using environment variables:

{sc.exe create svnserve binpath= "${env:programfiles(x86)}/subversion/bin/svnserve.exe --service -r C:/svnrepositories/"   displayname= "Subversion Server" depend= Tcpip start= auto}

How to get the nth element of a python list or a default if not available

A cheap solution is to really make a dict with enumerate and use .get() as usual, like

 dict(enumerate(l)).get(7, my_default)

Auto line-wrapping in SVG text

I have posted the following walkthrough for adding some fake word-wrapping to an SVG "text" element here:

SVG Word Wrap - Show stopper?

You just need to add a simple JavaScript function, which splits your string into shorter "tspan" elements. Here's an example of what it looks like:

Example SVG

Hope this helps !

Copy table without copying data

Try:

CREATE TABLE foo SELECT * FROM bar LIMIT 0

Or:

CREATE TABLE foo SELECT * FROM bar WHERE 1=0

jquery smooth scroll to an anchor?

I hate adding function-named classes to my code, so I put this together instead. If I were to stop using smooth scrolling, I'd feel behooved to go through my code, and delete all the class="scroll" stuff. Using this technique, I can comment out 5 lines of JS, and the entire site updates. :)

<a href="/about">Smooth</a><!-- will never trigger the function -->
<a href="#contact">Smooth</a><!-- but he will -->
...
...
<div id="contact">...</div>


<script src="jquery.js" type="text/javascript"></script>
<script type="text/javascript">
    // Smooth scrolling to element IDs
    $('a[href^=#]:not([href=#])').on('click', function () {
        var element = $($(this).attr('href'));
        $('html,body').animate({ scrollTop: element.offset().top },'normal', 'swing');
        return false;
    });
</script>

Requirements:
1. <a> elements must have an href attribute that begin with # and be more than just #
2. An element on the page with a matching id attribute

What it does:
1. The function uses the href value to create the anchorID object
   - In the example, it's $('#contact'), /about starts with /
2. HTML, and BODY are animated to the top offset of anchorID
   - speed = 'normal' ('fast','slow', milliseconds, )
   - easing = 'swing' ('linear',etc ... google easing)
3. return false -- it prevents the browser from showing the hash in the URL
   - the script works without it, but it's not as "smooth".

How to download HTTP directory with all files and sub-directories as they appear on the online files/folders list?

wget -r -np -nH --cut-dirs=3 -R index.html http://hostname/aaa/bbb/ccc/ddd/

From man wget

‘-r’ ‘--recursive’ Turn on recursive retrieving. See Recursive Download, for more details. The default maximum depth is 5.

‘-np’ ‘--no-parent’ Do not ever ascend to the parent directory when retrieving recursively. This is a useful option, since it guarantees that only the files below a certain hierarchy will be downloaded. See Directory-Based Limits, for more details.

‘-nH’ ‘--no-host-directories’ Disable generation of host-prefixed directories. By default, invoking Wget with ‘-r http://fly.srk.fer.hr/’ will create a structure of directories beginning with fly.srk.fer.hr/. This option disables such behavior.

‘--cut-dirs=number’ Ignore number directory components. This is useful for getting a fine-grained control over the directory where recursive retrieval will be saved.

Take, for example, the directory at ‘ftp://ftp.xemacs.org/pub/xemacs/’. If you retrieve it with ‘-r’, it will be saved locally under ftp.xemacs.org/pub/xemacs/. While the ‘-nH’ option can remove the ftp.xemacs.org/ part, you are still stuck with pub/xemacs. This is where ‘--cut-dirs’ comes in handy; it makes Wget not “see” number remote directory components. Here are several examples of how ‘--cut-dirs’ option works.

No options -> ftp.xemacs.org/pub/xemacs/ -nH -> pub/xemacs/ -nH --cut-dirs=1 -> xemacs/ -nH --cut-dirs=2 -> .

--cut-dirs=1 -> ftp.xemacs.org/xemacs/ ... If you just want to get rid of the directory structure, this option is similar to a combination of ‘-nd’ and ‘-P’. However, unlike ‘-nd’, ‘--cut-dirs’ does not lose with subdirectories—for instance, with ‘-nH --cut-dirs=1’, a beta/ subdirectory will be placed to xemacs/beta, as one would expect.

Is there any native DLL export functions viewer?

you can use Dependency Walker to view the function name. you can see the function's parameters only if it's decorated. read the following from the FAQ:

How do I view the parameter and return types of a function? For most functions, this information is simply not present in the module. The Windows' module file format only provides a single text string to identify each function. There is no structured way to list the number of parameters, the parameter types, or the return type. However, some languages do something called function "decoration" or "mangling", which is the process of encoding information into the text string. For example, a function like int Foo(int, int) encoded with simple decoration might be exported as _Foo@8. The 8 refers to the number of bytes used by the parameters. If C++ decoration is used, the function would be exported as ?Foo@@YGHHH@Z, which can be directly decoded back to the function's original prototype: int Foo(int, int). Dependency Walker supports C++ undecoration by using the Undecorate C++ Functions Command.

Difference between CLOB and BLOB from DB2 and Oracle Perspective?

They can be considered as equivalent. The limits in size are the same:

  • Maximum length of CLOB (in bytes or OCTETS)) 2 147 483 647
  • Maximum length of BLOB (in bytes) 2 147 483 647

There is also the DBCLOBs, for double byte characters.

References:

How to save an activity state using save instance state?

Really onSaveInstanceState() is called when the Activity goes to background.

Quote from the docs: "This method is called before an activity may be killed so that when it comes back some time in the future it can restore its state." Source

How to make button look like a link?

_x000D_
_x000D_
button {_x000D_
  background: none!important;_x000D_
  border: none;_x000D_
  padding: 0!important;_x000D_
  /*optional*/_x000D_
  font-family: arial, sans-serif;_x000D_
  /*input has OS specific font-family*/_x000D_
  color: #069;_x000D_
  text-decoration: underline;_x000D_
  cursor: pointer;_x000D_
}
_x000D_
<button> your button that looks like a link</button>
_x000D_
_x000D_
_x000D_

What does -> mean in C++?

x->y can mean 2 things. If x is a pointer, then it means member y of object pointed to by x. If x is an object with operator->() overloaded, then it means x.operator->().

Create an Oracle function that returns a table

I think you want a pipelined table function.

Something like this:

CREATE OR REPLACE PACKAGE test AS

    TYPE measure_record IS RECORD(
       l4_id VARCHAR2(50), 
       l6_id VARCHAR2(50), 
       l8_id VARCHAR2(50), 
       year NUMBER, 
       period NUMBER,
       VALUE NUMBER);

    TYPE measure_table IS TABLE OF measure_record;

    FUNCTION get_ups(foo NUMBER)
        RETURN measure_table
        PIPELINED;
END;

CREATE OR REPLACE PACKAGE BODY test AS

    FUNCTION get_ups(foo number)
        RETURN measure_table
        PIPELINED IS

        rec            measure_record;

    BEGIN
        SELECT 'foo', 'bar', 'baz', 2010, 5, 13
          INTO rec
          FROM DUAL;

        -- you would usually have a cursor and a loop here   
        PIPE ROW (rec);

        RETURN;
    END get_ups;
END;

For simplicity I removed your parameters and didn't implement a loop in the function, but you can see the principle.

Usage:

SELECT *
  FROM table(test.get_ups(0));



L4_ID L6_ID L8_ID       YEAR     PERIOD      VALUE
----- ----- ----- ---------- ---------- ----------
foo   bar   baz         2010          5         13
1 row selected.

Using jQuery, Restricting File Size Before Uploading

Try below code:

var sizeInKB = input.files[0].size/1024; //Normally files are in bytes but for KB divide by 1024 and so on
var sizeLimit= 30;

if (sizeInKB >= sizeLimit) {
    alert("Max file size 30KB");
    return false;
}

Disable time in bootstrap date time picker

$('#datetimepicker').datetimepicker({ 
    minView: 2, 
    pickTime: false, 
    language: 'pt-BR' 
});

Please try if it works for you as well

jQuery returning "parsererror" for ajax request

I have encountered such error but after modifying my response before sending it to the client it worked fine.

//Server side
response = JSON.stringify('{"status": {"code": 200},"result": '+ JSON.stringify(result)+'}');
res.send(response);  // Sending to client

//Client side
success: function(res, status) {
    response = JSON.parse(res); // Getting as expected
    //Do something
}

How do I Convert DateTime.now to UTC in Ruby?

In irb:

>>d = DateTime.now
=> #<DateTime: 11783702280454271/4800000000,5/12,2299161>
>> "#{d.hour.to_i - d.zone.to_i}:#{d.min}:#{d.sec}"
=> "11:16:41"

will convert the time to the utc. But as posted if it is just Time you can use:

Time.now.utc

and get it straight away.

install / uninstall APKs programmatically (PackageManager vs Intents)

On a rooted device, you might use:

String pkg = context.getPackageName();
String shellCmd = "rm -r /data/app/" + pkg + "*.apk\n"
                + "rm -r /data/data/" + pkg + "\n"
                // TODO remove data on the sd card
                + "sync\n"
                + "reboot\n";
Util.sudo(shellCmd);

Util.sudo() is defined here.

How to access the last value in a vector?

I have another method for finding the last element in a vector. Say the vector is a.

> a<-c(1:100,555)
> end(a)      #Gives indices of last and first positions
[1] 101   1
> a[end(a)[1]]   #Gives last element in a vector
[1] 555

There you go!

No Entity Framework provider found for the ADO.NET provider with invariant name 'System.Data.SqlClient'

Add below to your app.config.

 <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
      <parameters>
        <parameter value="v11.0" />
      </parameters>
    </defaultConnectionFactory>
    <providers>
      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
    </providers>
  </entityFramework>

Print time in a batch file (milliseconds)

%TIME% is in the format H:MM:SS,CS after midnight and hence conversion to centiseconds >doesn't work. Seeing Patrick Cuff's post with 6:46am it seems that it is not only me.

But with this lines bevor you should will fix that problem easy:

if " "=="%StartZeit:~0,1%" set StartZeit=0%StartZeit:~-10%
if " "=="%EndZeit:~0,1%" set EndZeit=0%EndZeit:~-10%

Thanks for your nice inspiration! I like to use it in my mplayer, ffmpeg, sox Scripts to pimp my mediafiles for old PocketPlayers just for fun.

How to check if user input is not an int value

Try this one:

    for (;;) {
        if (!sc.hasNextInt()) {
            System.out.println(" enter only integers!: ");
            sc.next(); // discard
            continue;
        }
        choose = sc.nextInt();
        if (choose >= 0) {
            System.out.print("no problem with input");

        } else {
            System.out.print("invalid inputs");

        }
    break;
  }

batch script - read line by line

This has worked for me in the past and it will even expand environment variables in the file if it can.

for /F "delims=" %%a in (LogName.txt) do (
     echo %%a>>MyDestination.txt
)

Why is the Java main method static?

When you execute the Java Virtual Machine (JVM) with the java command,

java ClassName argument1 argument2 ...

When you execute your application, you specify its class name as an argument to the java command, as above

the JVM attempts to invoke the main method of the class you specify

—at this point, no objects of the class have been created.

Declaring main as static allows the JVM to invoke main without creating an instance of the class.

let's back to the command

ClassName is a command-line argument to the JVM that tells it which class to execute. Following the ClassName, you can also specify a list of Strings (separated by spaces) as command-line arguments that the JVM will pass to your application. -Such arguments might be used to specify options (e.g., a filename) to run the application- this is why there is a parameter called String[] args in the main

References:Java™ How To Program (Early Objects), Tenth Edition

Android WebView not loading an HTTPS URL

To handle SSL urls the method onReceivedSslError() from the WebViewClient class, This is an example:

 webview.setWebViewClient(new WebViewClient() {
              ...
              ...
              ...

            @Override
            public void onReceivedSslError(WebView view, final SslErrorHandler handler, SslError error) {
                String message = "SSL Certificate error.";
                switch (error.getPrimaryError()) {
                    case SslError.SSL_UNTRUSTED:
                        message = "The certificate authority is not trusted.";
                        break;
                    case SslError.SSL_EXPIRED:
                        message = "The certificate has expired.";
                        break;
                    case SslError.SSL_IDMISMATCH:
                        message = "The certificate Hostname mismatch.";
                        break;
                    case SslError.SSL_NOTYETVALID:
                        message = "The certificate is not yet valid.";
                        break;
                }
                message += "\"SSL Certificate Error\" Do you want to continue anyway?.. YES";

                handler.proceed();
            }

        });

You can check my complete example here: https://github.com/Jorgesys/Android-WebView-Logging

enter image description here

Can I restore a single table from a full mysql mysqldump file?

One way or another, any process doing that will have to go through the entire text of the dump and parse it in some way. I'd just grep for

INSERT INTO `the_table_i_want`

and pipe the output into mysql. Take a look at the first table in the dump before, to make sure you're getting the INSERT's the right way.

Edit: OK, got the formatting right this time.

I want to remove double quotes from a String

If you have control over your data and you know your double quotes surround the string (so do not appear inside string) and the string is an integer ... say with :

"20151212211647278"

or similar this nicely removes the surrounding quotes

JSON.parse("20151212211647278");

Not a universal answer however slick for niche needs

file_put_contents: Failed to open stream, no such file or directory

I was also stuck on the same kind of problem and I followed the simple steps below.

Just get the exact url of the file to which you want to copy, for example:

http://www.test.com/test.txt (file to copy)

Then pass the exact absolute folder path with filename where you do want to write that file.

  1. If you are on a Windows machine then d:/xampp/htdocs/upload/test.txt

  2. If you are on a Linux machine then /var/www/html/upload/test.txt

You can get the document root with the PHP function $_SERVER['DOCUMENT_ROOT'].

How do I search for a pattern within a text file using Python combining regex & string/file operations and store instances of the pattern?

Doing it in one bulk read:

import re

textfile = open(filename, 'r')
filetext = textfile.read()
textfile.close()
matches = re.findall("(<(\d{4,5})>)?", filetext)

Line by line:

import re

textfile = open(filename, 'r')
matches = []
reg = re.compile("(<(\d{4,5})>)?")
for line in textfile:
    matches += reg.findall(line)
textfile.close()

But again, the matches that returns will not be useful for anything except counting unless you added an offset counter:

import re

textfile = open(filename, 'r')
matches = []
offset = 0
reg = re.compile("(<(\d{4,5})>)?")
for line in textfile:
    matches += [(reg.findall(line),offset)]
    offset += len(line)
textfile.close()

But it still just makes more sense to read the whole file in at once.

Select Last Row in the Table

To get the last record details, use the code below:

Model::where('field', 'value')->get()->last()

How to convert DataTable to class Object?

Initialize DataTable:

DataTable dt = new DataTable(); 
dt.Columns.Add("id", typeof(String)); 
dt.Columns.Add("name", typeof(String)); 
for (int i = 0; i < 5; i++)
{
    string index = i.ToString();
    dt.Rows.Add(new object[] { index, "name" + index });
}

Query itself:

IList<Class1> items = dt.AsEnumerable().Select(row => 
    new Class1
        {
            id = row.Field<string>("id"),
            name = row.Field<string>("name")
        }).ToList();

CSS: fixed position on x-axis but not y?

I just added position:absolute and that solved my problem.

How to select last one week data from today's date

Yes, the syntax is accurate and it should be fine.

Here is the SQL Fiddle Demo I created for your particular case

create table sample2
(
    id int primary key,
    created_date date,
    data varchar(10)
  )

insert into sample2 values (1,'2012-01-01','testing');

And here is how to select the data

SELECT Created_Date
FROM sample2
WHERE Created_Date >= DATEADD(day,-11117, GETDATE())

Restoring MySQL database from physical files

From the answer of @Vicent, I already restore MySQL database as below:

Step 1. Shutdown Mysql server

Step 2. Copy database in your database folder (in linux, the default location is /var/lib/mysql). Keep same name of the database, and same name of database in mysql mode.

sudo cp -rf   /mnt/ubuntu_426/var/lib/mysql/database1 /var/lib/mysql/

Step 3: Change own and change mode the folder:

sudo chown -R mysql:mysql /var/lib/mysql/database1
sudo chmod -R 660 /var/lib/mysql/database1
sudo chown  mysql:mysql /var/lib/mysql/database1 
sudo chmod 700 /var/lib/mysql/database1

Step 4: Copy ibdata1 in your database folder

sudo cp /mnt/ubuntu_426/var/lib/mysql/ibdata1 /var/lib/mysql/

sudo chown mysql:mysql /var/lib/mysql/ibdata1

Step 5: copy ib_logfile0 and ib_logfile1 files in your database folder.

sudo cp /mnt/ubuntu_426/var/lib/mysql/ib_logfile0 /var/lib/mysql/

sudo cp /mnt/ubuntu_426/var/lib/mysql/ib_logfile1 /var/lib/mysql/

Remember change own and change root of those files:

sudo chown -R mysql:mysql /var/lib/mysql/ib_logfile0

sudo chown -R mysql:mysql /var/lib/mysql/ib_logfile1

or

sudo chown -R mysql:mysql /var/lib/mysql

Step 6 (Optional): My site has configuration to store files in a specific location, then I copy those to corresponding location, exactly.

Step 7: Start your Mysql server. Everything come back and enjoy it.

That is it.

See more info at: https://biolinh.wordpress.com/2017/04/01/restoring-mysql-database-from-physical-files-debianubuntu/

How can I use a local image as the base image with a dockerfile?

You can have - characters in your images. Assume you have a local image (not a local registry) named centos-base-image with tag 7.3.1611.

docker version 
      Client:
       Version:         1.12.6
       API version:     1.24
       Package version: docker-common-1.12.6-16.el7.centos.x86_64
       Go version:      go1.7.4

      Server:
       Version:         1.12.6
       API version:     1.24
       Package version: docker-common-1.12.6-16.el7.centos.x86_64
       Go version:      go1.7.4

docker images
 REPOSITORY            TAG
 centos-base-image     7.3.1611

Dockerfile

FROM centos-base-image:7.3.1611
RUN yum -y install epel-release libaio bc flex

Result

Sending build context to Docker daemon 315.9 MB
Step 1 : FROM centos-base-image:7.3.1611
  ---> c4d84e86782e
Step 2 : RUN yum -y install epel-release libaio bc flex
  ---> Running in 36d8abd0dad9
...

In the example above FROM is fetching your local image, you can provide additional instructions to fetch an image from your custom registry (e.g. FROM localhost:5000/my-image:with.tag). See https://docs.docker.com/engine/reference/commandline/pull/#pull-from-a-different-registry and https://docs.docker.com/registry/#tldr

Finally, if your image is not being resolved when providing a name, try adding a tag to the image when you create it

This GitHub thread describes a similar issue of not finding local images by name.

By omitting a specific tag, docker will look for an image tagged "latest", so either create an image with the :latest tag, or change your FROM

Java 'file.delete()' Is not Deleting Specified File

Try closing all the FileOutputStream/FileInputStream you've opened earlier in other methods ,then try deleting ,worked like a charm.

Submit HTML form, perform javascript function (alert then redirect)

<form action="javascript:completeAndRedirect();">
    <input type="text" id="Edit1" 
    style="width:280; height:50; font-family:'Lucida Sans Unicode', 'Lucida Grande', sans-serif; font-size:22px">
</form>

Changing action to point at your function would solve the problem, in a different way.

The iOS Simulator deployment targets is set to 7.0, but the range of supported deployment target version for this platform is 8.0 to 12.1

in my case i have used both npm install and yarn install that is why i got this issue so to solve this i have removed package-lock.json and node_modules and then i did

yarn install
cd ios
pod install

it worked for me

Android Whatsapp/Chat Examples

Check out yowsup
https://github.com/tgalal/yowsup

Yowsup is a python library that allows you to do all the previous in your own app. Yowsup allows you to login and use the Whatsapp service and provides you with all capabilities of an official Whatsapp client, allowing you to create a full-fledged custom Whatsapp client.

A solid example of Yowsup's usage is Wazapp. Wazapp is full featured Whatsapp client that is being used by hundreds of thousands of people around the world. Yowsup is born out of the Wazapp project. Before becoming a separate project, it was only the engine powering Wazapp. Now that it matured enough, it was separated into a separate project, allowing anyone to build their own Whatsapp client on top of it. Having such a popular client as Wazapp, built on Yowsup, helped bring the project into a much advanced, stable and mature level, and ensures its continuous development and maintaince.

Yowsup also comes with a cross platform command-line frontend called yowsup-cli. yowsup-cli allows you to jump into connecting and using Whatsapp service directly from command line.

How can I enable cURL for an installed Ubuntu LAMP stack?

Fire the below command. It gives a list of modules.

 sudo apt-cache search php5-

Then fire the below command with the module name to be installed:

 sudo apt-get install name of the module

For reference, see How To Install Linux, Apache, MySQL, PHP (LAMP) stack on Ubuntu.

LaTex left arrow over letter in math mode

Use \overleftarrow to create a long arrow to the left.

\overleftarrow{blahblahblah}

LaTeX output

Twitter Bootstrap: div in container with 100% height

Update 2019

In Bootstrap 4, flexbox can be used to get a full height layout that fills the remaining space.

First of all, the container (parent) needs to be full height:

Option 1_ Add a class for min-height: 100%;. Remember that min-height will only work if the parent has a defined height:

html, body {
  height: 100%;
}

.min-100 {
    min-height: 100%;
}

https://codeply.com/go/dTaVyMah1U

Option 2_ Use vh units:

.vh-100 {
    min-height: 100vh;
}

https://codeply.com/go/kMahVdZyGj

Also of Bootstrap 4.1, the vh-100 and min-vh-100 classes are included in Bootstrap so there is no need to for the extra CSS

Then, use flexbox direction column d-flex flex-column on the container, and flex-grow-1 on any child divs (ie: row) that you want to fill the remaining height.

Also see:
Bootstrap 4 Navbar and content fill height flexbox
Bootstrap - Fill fluid container between header and footer
How to make the row stretch remaining height

How to do a SUM() inside a case statement in SQL server

If you're using SQL Server 2005 or above, you can use the windowing function SUM() OVER ().

case 
when test1.TotalType = 'Average' then Test2.avgscore
when test1.TotalType = 'PercentOfTot' then (cnt/SUM(test1.qrank) over ())
else cnt
end as displayscore

But it'll be better if you show your full query to get context of what you actually need.

Getting the minimum of two values in SQL

Building on the brilliant logic / code from mathematix and scottyc, I submit:

DECLARE @a INT, @b INT, @c INT = 0

WHILE @c < 100
    BEGIN
        SET @c += 1
        SET @a = ROUND(RAND()*100,0)-50
        SET @b = ROUND(RAND()*100,0)-50
        SELECT @a AS a, @b AS b,
            @a - ( ABS(@a-@b) + (@a-@b) ) / 2 AS MINab,
            @a + ( ABS(@b-@a) + (@b-@a) ) / 2 AS MAXab,
            CASE WHEN (@a <= @b AND @a = @a - ( ABS(@a-@b) + (@a-@b) ) / 2)
            OR (@a >= @b AND @a = @a + ( ABS(@b-@a) + (@b-@a) ) / 2)
            THEN 'Success' ELSE 'Failure' END AS Status
    END

Although the jump from scottyc's MIN function to the MAX function should have been obvious to me, it wasn't, so I've solved for it and included it here: SELECT @a + ( ABS(@b-@a) + (@b-@a) ) / 2. The randomly generated numbers, while not proof, should at least convince skeptics that both formulae are correct.

multiple plot in one figure in Python

EDIT: I just realised after reading your question again, that i did not answer your question. You want to enter multiple lines in the same plot. However, I'll leave it be, because this served me very well multiple times. I hope you find usefull someday

I found this a while back when learning python

import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec

fig = plt.figure() 
# create figure window

gs = gridspec.GridSpec(a, b)
# Creates grid 'gs' of a rows and b columns 


ax = plt.subplot(gs[x, y])
# Adds subplot 'ax' in grid 'gs' at position [x,y]


ax.set_ylabel('Foo') #Add y-axis label 'Foo' to graph 'ax' (xlabel for x-axis)


fig.add_subplot(ax) #add 'ax' to figure

you can make different sizes in one figure as well, use slices in that case:

 gs = gridspec.GridSpec(3, 3)
 ax1 = plt.subplot(gs[0,:]) # row 0 (top) spans all(3) columns

consult the docs for more help and examples. This little bit i typed up for myself once, and is very much based/copied from the docs as well. Hope it helps... I remember it being a pain in the #$% to get acquainted with the slice notation for the different sized plots in one figure. After that i think it's very simple :)

How to turn a String into a JavaScript function call?

If settings.functionName is already a function, you could do this:

settings.functionName(t.parentNode.id);

Otherwise this should also work if settings.functionName is just the name of the function:

if (typeof window[settings.functionName] == "function") {
    window[settings.functionName](t.parentNode.id);
}

How can I use a custom font in Java?

If you want to use the font to draw with graphics2d or similar, this works:

InputStream stream = ClassLoader.getSystemClassLoader().getResourceAsStream("roboto-bold.ttf")
Font font = Font.createFont(Font.TRUETYPE_FONT, stream).deriveFont(48f)

Best way to alphanumeric check in JavaScript

To check whether input_string is alphanumeric, simply use:

input_string.match(/[^\w]|_/) == null

How can I iterate over the elements in Hashmap?

Since all the players are numbered I would just use an ArrayList<Player>()

Something like

List<Player> players = new ArrayList<Player>();

System.out.printf("Give the number of the players ");
int number_of_players = scanner.nextInt();
scanner.nextLine(); // discard the rest of the line.

for(int k = 0;k < number_of_players; k++){
     System.out.printf("Give the name of player %d: ", k + 1);
     String name_of_player = scanner.nextLine();
     players.add(new Player(name_of_player,0)); //k=id and 0=score
}

for(Player player: players) {  
    System.out.println("Name of player in this round:" + player.getName());

java create date object using a value string

It is because value coming String (Java Date object constructor for getting string is deprecated)

and Date(String) is deprecated.

Have a look at jodatime or you could put @SuppressWarnings({“deprecation”}) outside the method calling the Date(String) constructor.

How to add a custom right-click menu to a webpage?

A combination of some nice CSS and some non-standard html tags with no external libraries can give a nice result (JSFiddle)

HTML

<menu id="ctxMenu">
    <menu title="File">
        <menu title="Save"></menu>
        <menu title="Save As"></menu>
        <menu title="Open"></menu>
    </menu>
    <menu title="Edit">
        <menu title="Cut"></menu>
        <menu title="Copy"></menu>
        <menu title="Paste"></menu>
    </menu>
</menu>

Note: the menu tag does not exist, I'm making it up (you can use anything)

CSS

#ctxMenu{
    display:none;
    z-index:100;
}
menu {
    position:absolute;
    display:block;
    left:0px;
    top:0px;
    height:20px;
    width:20px;
    padding:0;
    margin:0;
    border:1px solid;
    background-color:white;
    font-weight:normal;
    white-space:nowrap;
}
menu:hover{
    background-color:#eef;
    font-weight:bold;
}
menu:hover > menu{
    display:block;
}
menu > menu{
    display:none;
    position:relative;
    top:-20px;
    left:100%;
    width:55px;
}
menu[title]:before{
    content:attr(title);
}
menu:not([title]):before{
    content:"\2630";
}

The JavaScript is just for this example, I personally remove it for persistent menus on windows

var notepad = document.getElementById("notepad");
notepad.addEventListener("contextmenu",function(event){
    event.preventDefault();
    var ctxMenu = document.getElementById("ctxMenu");
    ctxMenu.style.display = "block";
    ctxMenu.style.left = (event.pageX - 10)+"px";
    ctxMenu.style.top = (event.pageY - 10)+"px";
},false);
notepad.addEventListener("click",function(event){
    var ctxMenu = document.getElementById("ctxMenu");
    ctxMenu.style.display = "";
    ctxMenu.style.left = "";
    ctxMenu.style.top = "";
},false);

Also note, you can potentially modify menu > menu{left:100%;} to menu > menu{right:100%;} for a menu that expands from right to left. You would need to add a margin or something somewhere though

What is trunk, branch and tag in Subversion?

A great place to start learning about Subversion is http://svnbook.red-bean.com/.

As far as Visual Studio tools are concerned, I like AnkhSVN, but I haven't tried the VisualSVN plugin yet.

VisualSVN does rely on TortoiseSVN, but TortoiseSVN is also a nice complement to Ankh IMHO.

Ajax Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource

add these in php file where your ajax url call

header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Credentials: true ");
header("Access-Control-Allow-Methods: OPTIONS, GET, POST");
header("Access-Control-Allow-Headers: Content-Type, Depth, User-Agent, X-File-Size, X-Requested-With, If-Modified-Since, X-File-Name, Cache-Control");

Turning off some legends in a ggplot

You can use guide=FALSE in scale_..._...() to suppress legend.

For your example you should use scale_colour_continuous() because length is continuous variable (not discrete).

(p3 <- ggplot(mov, aes(year, rating, colour = length, shape = mpaa)) +
   scale_colour_continuous(guide = FALSE) +
   geom_point()
)

Or using function guides() you should set FALSE for that element/aesthetic that you don't want to appear as legend, for example, fill, shape, colour.

p0 <- ggplot(mov, aes(year, rating, colour = length, shape = mpaa)) +
  geom_point()    
p0+guides(colour=FALSE)

UPDATE

Both provided solutions work in new ggplot2 version 2.0.0 but movies dataset is no longer present in this library. Instead you have to use new package ggplot2movies to check those solutions.

library(ggplot2movies)
data(movies)
mov <- subset(movies, length != "")

How can I change the text inside my <span> with jQuery?

This will be used to change the Html content inside the span

 $('#abc span').html('goes inside the span');

if you want to change the text inside the span, you can use:

 $('#abc span').text('goes inside the span');

What is the meaning of Bus: error 10 in C

There is no space allocated for the strings. use array (or) pointers with malloc() and free()

Other than that

#import <stdio.h>
#import <string.h>

should be

#include <stdio.h>
#include <string.h>

NOTE:

  • anything that is malloc()ed must be free()'ed
  • you need to allocate n + 1 bytes for a string which is of length n (the last byte is for \0)

Please you the following code as a reference

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char *argv[])
{
    //char *str1 = "First string";
    char *str1 = "First string is a big string";
    char *str2 = NULL;

    if ((str2 = (char *) malloc(sizeof(char) * strlen(str1) + 1)) == NULL) {
        printf("unable to allocate memory \n");
        return -1; 
    }   

    strcpy(str2, str1);

    printf("str1 : %s \n", str1);
    printf("str2 : %s \n", str2);

    free(str2);
    return 0;
}

How to convert NSNumber to NSString

Try:

NSString *myString = [NSNumber stringValue];

How to pass data from Javascript to PHP and vice versa?

I'd use JSON as the format and Ajax (really XMLHttpRequest) as the client->server mechanism.

Store JSON object in data attribute in HTML jQuery

There's a better way of storing JSON in the HTML:

HTML

<script id="some-data" type="application/json">{"param_1": "Value 1", "param_2": "Value 2"}</script>

JavaScript

JSON.parse(document.getElementById('some-data').textContent);

Python locale error: unsupported locale setting

In trying to get python to spit out names in specific locale I landed here with same problem.

In pursuing the answer, things got a little mystical I find.

I found that python code.

import locale
print locale.getdefaultlocale()
>> ('en_DK', 'UTF-8')

And indeed locale.setlocale(locale.LC_TIME, 'en_DK.UTF-8') works

Using tips here I tested further to see what is available using python code

import locale
loc_list = [(a,b) for a,b in locale.locale_alias.items() ]
loc_size = len(loc_list)
print loc_size,'entries'

for loc in loc_list:
    try:
        locale.setlocale(locale.LC_TIME, loc[1])
        print 'SUCCES set {:12} ({})'.format(loc[1],loc[0])
    except:
        pass

which yields

858 entries
SUCCES set en_US.UTF-8  (univ)
SUCCES set C            (c.ascii)
SUCCES set C            (c.en)
SUCCES set C            (posix-utf2)
SUCCES set C            (c)
SUCCES set C            (c_c)
SUCCES set C            (c_c.c)
SUCCES set en_IE.UTF-8  (en_ie.utf8@euro)
SUCCES set en_US.UTF-8  (universal.utf8@ucs4)
SUCCES set C            (posix)
SUCCES set C            (english_united-states.437)
SUCCES set en_US.UTF-8  (universal)

Of which only above is working! But the en_DK.UTF-8 is not in this list, though it works!?!? What?? And the python generated locale list do contain a lot of combos of da and DK, which I am looking for, but again no UTF-8 for da/DK...

I am on a Point Linux distro (Debian based), and here locale says amongst other LC_TIME="en_DK.UTF-8", which I know works, but not the locale I need.

locale -a says

C
C.UTF-8
en_DK.utf8
en_US.utf8
POSIX

So definitely need to install other locale, which i did by editing /etc/locale.gen, uncomment needed line da_DK.UTF-8 UTF-8 and run command locale-gen

Now locale.setlocale(locale.LC_TIME, 'da_DK.UTF-8') works too, and I can get my localized day and month names.

My Conclision:

Python : locale.locale_alias is not at all helpfull in finding available locales!!!

Linux : It is quite easy to get locale list and install new locale. A lot of help available.

Windows : I have been investigating a little, but nothing conclusive. There are though posts leading to answers, but I have not felt the urge to pursue it.

How to access shared folder without giving username and password

I found one way to access the shared folder without giving the username and password.

We need to change the share folder protect settings in the machine where the folder has been shared.

Go to Control Panel > Network and sharing center > Change advanced sharing settings > Enable Turn Off password protect sharing option.

By doing the above settings we can access the shared folder without any username/password.

Java ArrayList copy

List.copyOf ? unmodifiable list

You asked:

Is there no other way to assign a copy of a list

Java 9 brought the List.of methods for using literals to create an unmodifiable List of unknown concrete class.

LocalDate today = LocalDate.now( ZoneId.of( "Africa/Tunis" ) ) ;
List< LocalDate > dates = List.of( 
    today.minusDays( 1 ) ,  // Yesterday
    today ,                 // Today
    today.plusDays( 1 )     // Tomorrow
);

Along with that we also got List.copyOf. This method too returns an unmodifiable List of unknown concrete class.

List< String > colors = new ArrayList<>( 4 ) ;          // Creates a modifiable `List`. 
colors.add ( "AliceBlue" ) ;
colors.add ( "PapayaWhip" ) ;
colors.add ( "Chartreuse" ) ;
colors.add ( "DarkSlateGray" ) ;
List< String > masterColors = List.copyOf( colors ) ;   // Creates an unmodifiable `List`.

By “unmodifiable” we mean the number of elements in the list, and the object referent held in each slot as an element, is fixed. You cannot add, drop, or replace elements. But the object referent held in each element may or may not be mutable.

colors.remove( 2 ) ;          // SUCCEEDS. 
masterColors.remove( 2 ) ;    // FAIL - ERROR.

See this code run live at IdeOne.com.

dates.toString(): [2020-02-02, 2020-02-03, 2020-02-04]

colors.toString(): [AliceBlue, PapayaWhip, DarkSlateGray]

masterColors.toString(): [AliceBlue, PapayaWhip, Chartreuse, DarkSlateGray]

You asked about object references. As others said, if you create one list and assign it to two reference variables (pointers), you still have only one list. Both point to the same list. If you use either pointer to modify the list, both pointers will later see the changes, as there is only one list in memory.

So you need to make a copy of the list. If you want that copy to be unmodifiable, use the List.copyOf method as discussed in this Answer. In this approach, you end up with two separate lists, each with elements that hold a reference to the same content objects. For example, in our example above using String objects to represent colors, the color objects are floating around in memory somewhere. The two lists hold pointers to the same color objects. Here is a diagram.

enter image description here

The first list colors is modifiable. This means that some elements could be removed as seen in code above, where we removed the original 3rd element Chartreuse (index of 2 = ordinal 3). And elements can be added. And the elements can be changed to point to some other String such as OliveDrab or CornflowerBlue.

In contrast, the four elements of masterColors are fixed. No removing, no adding, and no substituting another color. That List implementation is unmodifiable.

Removing elements from an array in C

You don't really want to be reallocing memory every time you remove something. If you know the rough size of your deck then choose an appropriate size for your array and keep a pointer to the current end of the list. This is a stack.

If you don't know the size of your deck, and think it could get really big as well as keeps changing size, then you will have to do something a little more complex and implement a linked-list.

In C, you have two simple ways to declare an array.

  1. On the stack, as a static array

    int myArray[16]; // Static array of 16 integers
    
  2. On the heap, as a dynamically allocated array

    // Dynamically allocated array of 16 integers
    int* myArray = calloc(16, sizeof(int));
    

Standard C does not allow arrays of either of these types to be resized. You can either create a new array of a specific size, then copy the contents of the old array to the new one, or you can follow one of the suggestions above for a different abstract data type (ie: linked list, stack, queue, etc).

How do I remedy "The breakpoint will not currently be hit. No symbols have been loaded for this document." warning?

In my case, I was debugging a WPF extension using Visual Studio's Experimental Instance. After starting debugging and then pausing the dubugger, I opened the Debug > Windows > Modules window. Form there, I could see the directory where Visual Studio was trying to load symbols C:\Users\<username>\AppData\Local\Microsoft\VisualStudio\15.0_76a9e536Exp\Extensions\<companyName>. After stopping debugging, I deleted the target folder using Windows Explorer and restarted the debugger. Visual Studio was then able to hit the breakpoint.

Class not registered Error

Somewhere in the code you are using, there is a call to the Win32 API, CoCreateInstance, to dynamically load a DLL and instantiate an object from it.

The mapping between the component ID and the DLL that is capable of instantiating that object is usually found in HEKY_CLASSES_ROOT\CLSID in the registry. To discuss this further would be to explain a lot about COM in Windows. But the error indicates that the COM guid is not present in the registry.

I don't much about what the PackAndGo DLL is (an Autodesk component), but I suspect you simply need to "install" that component or the software package it came with through the designated installer to have that DLL and appropriate COM registry keys on your computer you are trying to run your code on. (i.e. go run setup.exe for this product).

In other words, I think you need to install "Pack and Go" on this computer instead of just copying the DLL to the target machine.

Also, make sure you decide to build your code appropriate as 32-bit vs. 64-bit depending on the which build flavor (32 or 64 bit) of Pack And Go you install.

How to get single value from this multi-dimensional PHP array

The first element of $myarray is the array of values you want. So, right now,

echo $myarray[0]['email']; // This outputs '[email protected]'

If you want that array to become $myarray, then you just have to do

$myarray = $myarray[0];

Now, $myarray['email'] etc. will output as expected.

HashMap with multiple values under the same key

Another nice choice is to use MultiValuedMap from Apache Commons. Take a look at the All Known Implementing Classes at the top of the page for specialized implementations.

Example:

HashMap<K, ArrayList<String>> map = new HashMap<K, ArrayList<String>>()

could be replaced with

MultiValuedMap<K, String> map = new MultiValuedHashMap<K, String>();

So,

map.put(key, "A");
map.put(key, "B");
map.put(key, "C");

Collection<String> coll = map.get(key);

would result in collection coll containing "A", "B", and "C".

How do you add an SDK to Android Studio?

Download your sdk file, go to Android studio: File->New->Import Module

How to call URL action in MVC with javascript function?

Try using the following on the JavaScript side:

window.location.href = '@Url.Action("Index", "Controller")';

If you want to pass parameters to the @Url.Action, you can do this:

var reportDate = $("#inputDateId").val();//parameter
var url = '@Url.Action("Index", "Controller", new {dateRequested = "findme"})';
window.location.href = url.replace('findme', reportDate);

How to Get JSON Array Within JSON Object?

I guess this will help you.

JSONObject jsonObj = new JSONObject(jsonStr);

JSONArray ja_data = jsonObj.getJSONArray("data");
int length = jsonObj.length();
for(int i=0; i<length; i++) {
  JSONObject jsonObj = ja_data.getJSONObject(i);
  Toast.makeText(this, jsonObj.getString("Name"), Toast.LENGTH_LONG).show();

  // getting inner array Ingredients
  JSONArray ja = jsonObj.getJSONArray("Ingredients");
  int len = ja.length();

  ArrayList<String> Ingredients_names = new ArrayList<>();
  for(int j=0; j<len; j++) {
    JSONObject json = ja.getJSONObject(j);
    Ingredients_names.add(json.getString("name"));
  }
}

What causes this error? "Runtime error 380: Invalid property value"

One reason for this error is very silly mistake in code. If proper value is not passed to a property of ActiveX, then also this error is thrown.

Like empty value is passed to Font.Name property or text value is passed to Height property.

How to make layout with rounded corners..?

You can do it with a custom view, like this RoundAppBar and RoundBottomAppBar. Here a path is used to clipPath the canvas.

Round Corner View

How to submit a form with JavaScript by clicking a link?

You could give the form and the link some ids and then subscribe for the onclick event of the link and submit the form:

<form id="myform" action="" method="POST">
    <a href="#" id="mylink"> submit </a>
</form>

and then:

window.onload = function() {
    document.getElementById('mylink').onclick = function() {
        document.getElementById('myform').submit();
        return false;
    };
};

I would recommend you using a submit button for submitting forms as it respects the markup semantics and it will work even for users with javascript disabled.

How to call servlet through a JSP page

You can use RequestDispatcher as you usually use it in Servlet:

<%@ page contentType="text/html"%>
<%@ page import = "javax.servlet.RequestDispatcher" %>
<%
     RequestDispatcher rd = request.getRequestDispatcher("/yourServletUrl");
     request.setAttribute("msg","HI Welcome");
     rd.forward(request, response);
%>

Always be aware that don't commit any response before you use forward, as it will lead to IllegalStateException.

PHP move_uploaded_file() error?

I ran into a very obscure and annoying cause of error 6. After goofing around with some NFS mounted volumes, uploads started failing. Problem resolved by restarting services

systemctl restart php-fpm.service
systemctl restart httpd.service

How get all values in a column using PHP?

Since mysql_* are deprecated, so here is the solution using mysqli.

$mysqli = new mysqli('host', 'username', 'password', 'database');
if($mysqli->connect_errno>0)
{
  die("Connection to MySQL-server failed!"); 
}
$resultArr = array();//to store results
//to execute query
$executingFetchQuery = $mysqli->query("SELECT `name` FROM customers WHERE 1");
if($executingFetchQuery)
{
   while($arr = $executingFetchQuery->fetch_assoc())
   {
        $resultArr[] = $arr['name'];//storing values into an array
   }
}
print_r($resultArr);//print the rows returned by query, containing specified columns

There is another way to do this using PDO

  $db = new PDO('mysql:host=host_name;dbname=db_name', 'username', 'password'); //to establish a connection
  //to fetch records
  $fetchD = $db->prepare("SELECT `name` FROM customers WHERE 1");
  $fetchD->execute();//executing the query
  $resultArr = array();//to store results
  while($row = $fetchD->fetch())
  {
     $resultArr[] = $row['name'];
  }
  print_r($resultArr);

Programmatically stop execution of python script?

You could raise SystemExit(0) instead of going to all the trouble to import sys; sys.exit(0).

complex if statement in python

I think the most pythonic way to do this for me, will be

elif var in [80,443] + range(1024,65535):

although it could take a little time and memory (it's generating numbers from 1024 to 65535). If there's a problem with that, I'll do:

elif 1024 <= var <= 65535 or var in [80,443]:

On postback, how can I check which control cause postback in Page_Init event

Here's some code that might do the trick for you (taken from Ryan Farley's blog)

public static Control GetPostBackControl(Page page)
{
    Control control = null;

    string ctrlname = page.Request.Params.Get("__EVENTTARGET");
    if (ctrlname != null && ctrlname != string.Empty)
    {
        control = page.FindControl(ctrlname);
    }
    else
    {
        foreach (string ctl in page.Request.Form)
        {
            Control c = page.FindControl(ctl);
            if (c is System.Web.UI.WebControls.Button)
            {
                control = c;
                break;
            }
        }
    }
    return control;
}

Angular 4 default radio button checked by default

getting following error

_x000D_
_x000D_
It happens:  Error: 
      ngModel cannot be used to register form controls with a parent formGroup directive.  Try using
      formGroup's partner directive "formControlName" instead.  Example:
_x000D_
_x000D_
_x000D_

Flutter command not found

You can do these..

  1. First, open your Mac Terminal
  2. Run 'open -e .bash_profile'
  3. Then add 'PATH="/Volumes/Application/Mobile/flutter/bin:${PATH}" export PATH'
  4. Then Save file & close

"Find next" in Vim

Typing n will go to the next match.

Text border using css (border around text)

I don't like that much solutions based on multiplying text-shadows, it's not really flexible, it may work for a 2 pixels stroke where directions to add are 8, but with just 3 pixels stroke directions became 16, and so on... Not really confortable to manage.

The right tool exists, it's SVG <text> The browsers' support problem worth nothing in this case, 'cause the usage of text-shadow has its own support problem too, filter: progid:DXImageTransform can be used or IE < 10 but often doesn't work as expected.

To me the best solution remains SVG with a fallback in not-stroked text for older browser:

This kind of approuch works on pratically all versions of Chrome and Firefox, Safari since version 3.04, Opera 8, IE 9

Compared to text-shadow whose supports are: Chrome 4.0, FF 3.5, IE 10, Safari 4.0, Opera 9, it results even more compatible.

_x000D_
_x000D_
.stroke {_x000D_
  margin: 0;_x000D_
  font-family: arial;_x000D_
  font-size:70px;_x000D_
  font-weight: bold;_x000D_
  }_x000D_
  _x000D_
  svg {_x000D_
    display: block;_x000D_
  }_x000D_
  _x000D_
  text {_x000D_
    fill: black;_x000D_
    stroke: red;_x000D_
    stroke-width: 3;_x000D_
  }
_x000D_
<p class="stroke">_x000D_
  <svg xmlns="http://www.w3.org/2000/svg" width="700" height="72" viewBox="0 0 700 72">_x000D_
    <text x="0" y="70">Stroked text</text>_x000D_
  </svg>_x000D_
</p>
_x000D_
_x000D_
_x000D_

Docker can't connect to docker daemon

I got the same problem. In CentOS 6.5:

ps aux |grep `cat /var/run/docker.pid`

If it shows no Docker daemon process exists, then I type:

docker -d

Then Ctrl + D to stop Docker. Because we use the -d option, Docker will run as daemon. Now we can do:

service docker start

Then I can do a docker pull centos. That's all.

NOTE: If these do not work, you can try yum update, and then repeat these again, because I yum install before these.

How to add months to a date in JavaScript?

Corrected as of 25.06.2019:

var newDate = new Date(date.setMonth(date.getMonth()+8));

Old From here:

var jan312009 = new Date(2009, 0, 31);
var eightMonthsFromJan312009  = jan312009.setMonth(jan312009.getMonth()+8);

How to prevent auto-closing of console after the execution of batch file

my way is to write an actual batch (saying "foo.bat") to finish the job; then create another "start.bat":

@echo off
cmd /k foo.bat

I find this is extremely useful when I set up one-time environment variables.

PL/SQL, how to escape single quote in a string?

EXECUTE IMMEDIATE 'insert into MY_TBL (Col) values(''ER0002'')'; worked for me. closing the varchar/string with two pairs of single quotes did the trick. Other option could be to use using keyword, EXECUTE IMMEDIATE 'insert into MY_TBL (Col) values(:text_string)' using 'ER0002'; Remember using keyword will not work, if you are using EXECUTE IMMEDIATE to execute DDL's with parameters, however, using quotes will work for DDL's.

jQuery selector for id starts with specific text

Let me offer a more extensive answer considering things that you haven't mentioned as yet but will find useful.

For your current problem the answer is

$("div[id^='editDialog']");

The caret (^) is taken from regular expressions and means starts with.

Solution 1

// Select elems where 'attribute' ends with 'Dialog'
$("[attribute$='Dialog']"); 

// Selects all divs where attribute is NOT equal to value    
$("div[attribute!='value']"); 

// Select all elements that have an attribute whose value is like
$("[attribute*='value']"); 

// Select all elements that have an attribute whose value has the word foobar
$("[attribute~='foobar']"); 

// Select all elements that have an attribute whose value starts with 'foo' and ends
//  with 'bar'
$("[attribute^='foo'][attribute$='bar']");

attribute in the code above can be changed to any attribute that an element may have, such as href, name, id or src.

Solution 2

Use classes

// Matches all items that have the class 'classname'
$(".className");

// Matches all divs that have the class 'classname'
$("div.className");

Solution 3

List them (also noted in previous answers)

$("#id1,#id2,#id3");

Solution 4

For when you improve, regular expression (Never actually used these, solution one has always been sufficient, but you never know!

// Matches all elements whose id takes the form editDialog-{one_or_more_integers}
$('div').filter(function () {this.id.match(/editDialog\-\d+/)});

Using Python to execute a command on every file in a folder

I had a similar problem, with a lot of help from the web and this post I made a small application, my target is VCD and SVCD and I don't delete the source but I reckon it will be fairly easy to adapt to your own needs.

It can convert 1 video and cut it or can convert all videos in a folder, rename them and put them in a subfolder /VCD

I also add a small interface, hope someone else find it useful!

I put the code and file in here btw: http://tequilaphp.wordpress.com/2010/08/27/learning-python-making-a-svcd-gui/

How do I remove packages installed with Python's easy_install?

pip, an alternative to setuptools/easy_install, provides an "uninstall" command.

Install pip according to the installation instructions:

$ wget https://bootstrap.pypa.io/get-pip.py
$ python get-pip.py

Then you can use pip uninstall to remove packages installed with easy_install

Namenode not getting started

I ran $hadoop namenode to start namenode manually at foreground.

From the logs I figured out that 50070 is ocuupied, which was defaultly used by dfs.namenode.http-address. After configuring dfs.namenode.http-address in hdfs-site.xml, everything went well.

Client on Node.js: Uncaught ReferenceError: require is not defined

Even using this won't work. I think the best solution is Browserify:

module.exports = {
  func1: function () {
   console.log("I am function 1");
  },
  func2: function () {
    console.log("I am function 2");
  }
};

-getFunc1.js-
var common = require('./common');
common.func1();

How can I upload fresh code at github?

git init
git add .
git commit -m "Initial commit"

After this, make a new GitHub repository and follow on-screen instructions.

Modifying list while iterating

I guess this is what you want:

l  = range(100)  
index = 0                       
for i in l:                         
    print i,              
    try:
        print l.pop(index+1),                  
        print l.pop(index+1)
    except:
        pass
    index += 1

It is quite handy to code when the number of item to be popped is a run time decision. But it runs with very a bad efficiency and the code is hard to maintain.

Setting Margin Properties in code

One could simply use this

MyControl.Margin = new System.Windows.Thickness(10, 0, 5, 0);

Specify multiple attribute selectors in CSS

Concatenate the attribute selectors:

input[name="Sex"][value="M"]

Should you choose the MONEY or DECIMAL(x,y) datatypes in SQL Server?

I want to give a different view of MONEY vs. NUMERICAL, largely based my own expertise and experience... My point of view here is MONEY, because I have worked with it for a considerable long time and never really used NUMERICAL much...

MONEY Pro:

  • Native Data Type. It uses a native data type (integer) as the same as a CPU register (32 or 64 bit), so the calculation doesn't need unnecessary overhead so it's smaller and faster... MONEY needs 8 bytes and NUMERICAL(19, 4) needs 9 bytes (12.5% bigger)...

    MONEY is faster as long as it is used for it was meant to be (as money). How fast? My simple SUM test on 1 million data shows that MONEY is 275 ms and NUMERIC 517 ms... That is almost twice as fast... Why SUM test? See next Pro point

  • Best for Money. MONEY is best for storing money and do operations, for example, in accounting. A single report can run millions of additions (SUM) and a few multiplications after the SUM operation is done. For very big accounting applications it is almost twice as fast, and it is extremely significant...
  • Low Precision of Money. Money in real life doesn't need to be very precise. I mean, many people may care about 1 cent USD, but how about 0.01 cent USD? In fact, in my country, banks no longer care about cents (digit after decimal comma); I don't know about US bank or other country...

MONEY Con:

  • Limited Precision. MONEY only has four digits (after the comma) precision, so it has to be converted before doing operations such as division... But then again money doesn't need to be so precise and is meant to be used as money, not just a number...

But... Big, but here is even your application involved real-money, but do not use it in lots of SUM operations, like in accounting. If you use lots of divisions and multiplications instead then you should not use MONEY...

Using android.support.v7.widget.CardView in my project (Eclipse)

https://github.com/yongjhih/CardView

A CardView v7 eclipse project. (from sdk/extras/android/m2repository/com/android/support/cardview-v7)

The project was built by steps:

cp {sdk}/extras/android/m2repository/com/android/support/cardview-v7/21.0.0-rc1/cardview-v7-21.0.0-rc1.aar cardview-v7-21.0.0-rc1.zip
unzip cardview-v7-21.0.0-rc1.zip
mkdir libs/
mv classes.jar libs/cardview-v7-21.0.0-rc1.jar

how to change a selections options based on another select option selected?

you can use data-tag in html5 and do this using this code:

_x000D_
_x000D_
<script>_x000D_
 $('#mainCat').on('change', function() {_x000D_
  var selected = $(this).val();_x000D_
  $("#expertCat option").each(function(item){_x000D_
   console.log(selected) ;  _x000D_
   var element =  $(this) ; _x000D_
   console.log(element.data("tag")) ; _x000D_
   if (element.data("tag") != selected){_x000D_
    element.hide() ; _x000D_
   }else{_x000D_
    element.show();_x000D_
   }_x000D_
  }) ; _x000D_
  _x000D_
  $("#expertCat").val($("#expertCat option:visible:first").val());_x000D_
  _x000D_
});_x000D_
</script>
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>_x000D_
<select id="mainCat">_x000D_
   <option value = '1'>navid</option>_x000D_
   <option value = '2'>javad</option>_x000D_
   <option value = '3'>mamal</option>_x000D_
  </select>_x000D_
  _x000D_
  <select id="expertCat">_x000D_
   <option  value = '1' data-tag='2'>UI</option>_x000D_
   <option  value = '2' data-tag='2'>Java Android</option>_x000D_
   <option  value = '3' data-tag='1'>Web</option>_x000D_
   <option  value = '3' data-tag='1'>Server</option>_x000D_
   <option  value = '3' data-tag='3'>Back End</option>_x000D_
   <option  value = '3' data-tag='3'>.net</option>_x000D_
  </select>
_x000D_
_x000D_
_x000D_

jinja2.exceptions.TemplateNotFound error

You put your template in the wrong place. From the Flask docs:

Flask will look for templates in the templates folder. So if your application is a module, this folder is next to that module, if it’s a package it’s actually inside your package: See the docs for more information: http://flask.pocoo.org/docs/quickstart/#rendering-templates

Get timezone from DateTime

From the API (http://msdn.microsoft.com/en-us/library/system.datetime_members(VS.71).aspx) it does not seem it can show the name of the time zone used.

What does "\r" do in the following script?

Actually, this has nothing to do with the usual Windows / Unix \r\n vs \n issue. The TELNET procotol itself defines \r\n as the end-of-line sequence, independently of the operating system. See RFC854.

How to get a unique device ID in Swift?

You can use devicecheck (in Swift 4) Apple documentation

func sendEphemeralToken() {
        //check if DCDevice is available (iOS 11)

        //get the **ephemeral** token
        DCDevice.current.generateToken {
        (data, error) in
        guard let data = data else {
            return
        }

        //send **ephemeral** token to server to 
        let token = data.base64EncodedString()
        //Alamofire.request("https://myServer/deviceToken" ...
    }
}

Typical usage:

Typically, you use the DeviceCheck APIs to ensure that a new user has not already redeemed an offer under a different user name on the same device.

Server action needs:

See WWDC 2017 — Session 702 (24:06)

more from Santosh Botre article - Unique Identifier for the iOS Devices

Your associated server combines this token with an authentication key that you receive from Apple and uses the result to request access to the per-device bits.

$_SERVER["REMOTE_ADDR"] gives server IP rather than visitor IP

Replacing:

$_SERVER["REMOTE_ADDR"];

With:

$_SERVER["HTTP_X_REAL_IP"];

Worked for me.

AngularJS does not send hidden field value

I've found a nice solution written by Mike on sapiensworks. It is as simple as using a directive that watches for changes on your model:

.directive('ngUpdateHidden',function() {
    return function(scope, el, attr) {
        var model = attr['ngModel'];
        scope.$watch(model, function(nv) {
            el.val(nv);
        });
    };
})

and then bind your input:

<input type="hidden" name="item.Name" ng-model="item.Name" ng-update-hidden />

But the solution provided by tymeJV could be better as input hidden doesn't fire change event in javascript as yycorman told on this post, so when changing the value through a jQuery plugin will still work.

Edit I've changed the directive to apply the a new value back to the model when change event is triggered, so it will work as an input text.

.directive('ngUpdateHidden', function () {
    return {
        restrict: 'AE', //attribute or element
        scope: {},
        replace: true,
        require: 'ngModel',
        link: function ($scope, elem, attr, ngModel) {
            $scope.$watch(ngModel, function (nv) {
                elem.val(nv);
            });
            elem.change(function () { //bind the change event to hidden input
                $scope.$apply(function () {
                    ngModel.$setViewValue(  elem.val());
                });
            });
        }
    };
})

so when you trigger $("#yourInputHidden").trigger('change') event with jQuery, it will update the binded model as well.

Block direct access to a file over http but allow php script access

in httpd.conf to block browser & wget access to include files especially say db.inc or config.inc . Note you cannot chain file types in the directive instead create multiple file directives.

<Files ~ "\.inc$">
Order allow,deny
Deny from all
</Files>

to test your config before restarting apache

service httpd configtest

then (graceful restart)

service httpd graceful

IIS AppPoolIdentity and file system write access permissions

I tried this to fix access issues to an IIS website, which manifested as something like the following in the Event Logs ? Windows ? Application:

Log Name:      Application
Source:        ASP.NET 4.0.30319.0
Date:          1/5/2012 4:12:33 PM
Event ID:      1314
Task Category: Web Event
Level:         Information
Keywords:      Classic
User:          N/A
Computer:      SALTIIS01

Description:
Event code: 4008 
Event message: File authorization failed for the request. 
Event time: 1/5/2012 4:12:33 PM 
Event time (UTC): 1/6/2012 12:12:33 AM 
Event ID: 349fcb2ec3c24b16a862f6eb9b23dd6c 
Event sequence: 7 
Event occurrence: 3 
Event detail code: 0 

Application information: 
    Application domain: /LM/W3SVC/2/ROOT/Application/SNCDW-19-129702818025409890 
    Trust level: Full 
    Application Virtual Path: /Application/SNCDW 
    Application Path: D:\Sites\WCF\Application\SNCDW\ 
    Machine name: SALTIIS01 

Process information: 
    Process ID: 1896 
    Process name: w3wp.exe 
    Account name: iisservice 

Request information: 
    Request URL: http://webservicestest/Application/SNCDW/PC.svc 
    Request path: /Application/SNCDW/PC.svc 
    User host address: 10.60.16.79 
    User: js3228 
    Is authenticated: True 
    Authentication Type: Negotiate 
    Thread account name: iisservice 

In the end I had to give the Windows Everyone group read access to that folder to get it to work properly.

Detecting installed programs via registry

On 64-bit systems the x64 key is:

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall

Most programs are listed there. Look at the keys: DisplayName DisplayVersion

Note that the last is not always set!

On 64-bit systems the x86 key (usually with more entries) is:

HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall

How to put wildcard entry into /etc/hosts?

It happens that /etc/hosts file doesn't support wild card entries.

You'll have to use other services like dnsmasq. To enable it in dnsmasq, just edit dnsmasq.conf and add the following line:

address=/example.com/127.0.0.1

How to pass a value from Vue data to href?

If you want to display links coming from your state or store in Vue 2.0, you can do like this:

<a v-bind:href="''"> {{ url_link }} </a>