text:
import java.net.*;
import java.util.NoSuchElementException;
import java.util.Scanner;
import java.io.*;

public class DistributedServer implements Runnable
{
	private Socket socket;
	private PrintWriter out = null;
	private BufferedReader in = null;
	private String identity =  null;
    private static String identityFile = "identity.txt";
	public boolean authentifier = false;
	//public Thread t1, t2;

	public DistributedServer(Socket s)
    {
		 socket = s;
	}

    public void run()
    {
		try {
			in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
			out = new PrintWriter(socket.getOutputStream());

		    while(!authentifier){
                //out.println("[SERVER] Provide your identity code");
                //out.flush();
                identity = in.readLine();

                if(isValid(identity)){
                    out.println("ok");
                    System.out.println("[SERVER] " + identity + " is connected ");
                    out.flush();
                    authentifier = true;
                }
                else {out.println("[SERVER] ** identity error"); out.flush();}
            }
            /* Identification succeeded, opening conversation */
            //Thread t1 = new Thread(new Reception(in, identity));
            Thread t1 = new Thread(new Reception(socket, identity));
            t1.start();
            //Thread t2 = new Thread(new Emission(out, identity));
            //t2.start();

		} catch (IOException e) {
			System.err.println("[SERVER] ** " + identity + " not responding or no longer connected");
		}
	}

	private static boolean isValid(String identity)
    {
		boolean connection = false;
		try {
			Scanner sc = new Scanner(new File(identityFile));
			while(sc.hasNext()){
				if(sc.nextLine().equals(identity)){
              	  connection=true;
				  break;
				}
             }
		} catch (FileNotFoundException e) {
			System.err.println("[SERVER] ** Authentification file not found");
		}
	return connection;
	}
}


text:
const Email = Jymfony.Component.Validator.Constraints.Email;
const InvalidArgumentException = Jymfony.Component.Validator.Exception.InvalidArgumentException;
const { expect } = require('chai');

describe('[Validator] Constraints.Email', function () {
    it ('construct with strict mode should not throw', true ? undefined : () => {
        const subject = new Email({ mode: Email.VALIDATION_MODE_STRICT });

        expect(subject.mode).to.be.equal(Email.VALIDATION_MODE_STRICT);
    });

    it ('construct with unknown mode should throw', async () => {
        expect(() => new Email({ mode: 'Unknown Mode' }))
            .to.throw(InvalidArgumentException, 'The "mode" parameter value is not valid.');
    });

    it ('normalizer can be set', async () => {
        const email = new Email({ normalizer: __jymfony.trim });

        expect(email.normalizer).to.be.equal(__jymfony.trim);
    });

    it ('should throw trying to set invalid normalizer', async () => {
        await expect(() => new Email({ normalizer: 'foobar' }))
            .to.throw(InvalidArgumentException, 'The "normalizer" option must be a valid callable ("string" given).');

        expect(() => new Email({ normalizer: {} }))
            .to.throw(InvalidArgumentException, 'The "normalizer" option must be a valid callable ("object" given).');
    });
});

redpajama_set_name: RedPajamaGithub


text:
package au.com.williamhill.flywheel.edge.backplane;

import com.obsidiandynamics.yconf.*;

import au.com.williamhill.flywheel.edge.*;
import au.com.williamhill.flywheel.frame.*;

/**
 *  A no-op {@link Backplane} implementation for use with single-node (cluster-less) brokers.
 */
@Y
public final class NoOpBackplane implements Backplane {
  @Override
  public void close() throws Exception {}

  @Override
  public void attach(BackplaneConnector connector) {}

  @Override
  public void onPublish(EdgeNexus nexus, PublishTextFrame pub) {}

  @Override
  public void onPublish(EdgeNexus nexus, PublishBinaryFrame pub) {}

  @Override
  public String toString() {
    return NoOpBackplane.class.getSimpleName();
  }
}


text:
import assert from 'assert';
import { log } from 'gulp-util';
import dbReady from '../../backend/db-init';
import config from '../../config';
import promiser from 'stateful-promise';

const passwordVals = {
  password: [ // Password0!!!
    '80faf27d9f9cf1d549949135e598f60364518464c534865028ec86e7270efd3b8d5739f',
    '5429e9c153d46b02467f7fa1159beaf55dbe9618afac73f8cfb101b07806eff7a509033',
    '2a5a6736fd7dee78255805bedbba9c1c0d666164337975e54605b627cac2838d12df48e',
    'e84c0994ea5a2d3ddde73d6117df0ac5b746600814114ea39501f61da691a342026e436',
    '809a3120ca0d8d0591a42df17535dc0b93ca5dc75dbab542eaf3d319b5c92c5d6414495',
    '770c10f60895cd2b49678d6796b845e14b3de05f0a5dc34e290d231aac1781b13f6ed53',
    '6239e2a108cef7d077b716ff89d0ad2b6509e9c947529c57b03060fc3a6dc398a70f036',
    '28aab5dbba24540dd88bb9afa185dbc1620938b314504f570012e2b665a59ad53a444f3',
    '5591ca55d30c0a5db4538c3ce2fe9cbce0c468bba1610043f194eead9af6076fe62d04b',
    'c002a0d3c7ed05280000180f310c307f3e3ed0ee2202e0f1a4ce76cc4d20b3ca4ce26a1',
    'ef42ed33f617b6d2899229d1e3c023c7d886d31766d3605d22b186d36ac7fd696a2c037',
    '336eb8b81da5f7b1cec2491c5b6736a549a3cb809c4d8ef0c1cef0412c5977477c8ad68',
    '256d086fa19b63ab4992bef83b0818c7c2af5f649162fb9c227e9d9a963cc4c76f44e20',
    'f0163b8fa43979861ab139e4c782f3b421c16dffcbf42ed1f419d9f8c5cdf088e506728',
    'f0d09945967a10bac9e155e60df249'
  ].join(''),
  pwdSalt: [ 203, 70, 171, 204, 188, 88, 218, 254, 168, 59, 72, 86, 242, 96, 4, 160 ],
  pwdIterations: 100000
}

const origSuppression = config.backend.sessionSuppression;

describe('Database', function () {

  describe('Availability', function () {

    it('should connect', function () {
      dbReady(() => assert.ok(true));
    });

    it('should be handed the db', function (done) {
      dbReady(db => {
        assert.ok(db);
        done();
      });
    });

  });

  describe('Session Handling', function () {
    let createdUserId;
    let createdSessionId;
    let createdSessionExpires;

    it('should create a session', function (done) {
      dbReady(({ Users, Sessions }) => {

        Users.saveCreate(Object.assign({}, {
          firstName: 'Test',
          lastName: 'User',
          email: 'testuser@testuser.com'
        }, passwordVals))
        .then(user => {
          createdUserId = user.id;
          config.backend.sessionSuppression = 0;

          Sessions.start(user).then(session => {
            createdSessionId = session.id;
            createdSessionExpires = session.expiresAt;
            config.backend.sessionSuppression = origSuppression;
            assert.ok(session.id);
            assert.ok(session.expiresAt);
            user.destroy().then(() => {
              done();
            });
          });
        });

      });
    });

    it('should validate/update a session', function (done) {
      dbReady(({ Sessions }) => {
        Sessions.validate(createdSessionId).then(session => {
          assert.equal(session.id, createdSessionId);
          assert.notEqual(session.expiresAt, createdSessionExpires);
          session.destroy().then(() => {
            done();
          });
        });

      });
    });

    it('should delete an invalid session', function (done) {
      dbReady(({ Sessions, Users }) => {

        Users.saveCreate(Object.assign({}, {
          firstName: 'Test',
          lastName: 'User',
          email: 'testuser@testuser.com'
        }, passwordVals)).then(user => {
          createdUserId = user.id;
          config.backend.sessionSuppression = 0;

          Sessions.start(user).then(session => {
            const now = new Date();
            now.setHours(now.getHours() - 1000);
            createdSessionId = session.id;
            createdSessionExpires = session.expiresAt;
            config.backend.sessionSuppression = origSuppression;
            session.expiresAt = now;

            session.save().then(updated => {
              Sessions.validate(session.id).catch(() => {
                Users.destroy(createdUserId).then(() => {
                  Sessions.get(session.id).then(nothing => {
                    assert.equal(nothing.isNull(), true);
                    done();
                  });
                });
              });
            });
          });
        });

      });
    });

    it('should suppress dead sessions', function (done) {
      dbReady(({ Sessions, Users }) => {
        const now = new Date();

        // We'll use this date to artificially expire some sessions
        now.setHours(now.getHours() - 1000);
        config.backend.sessionSuppression = 0;

        promiser()

        // Create 3 users as userList
        .then(state => {
          const userList = [];
          return state.set('userList', promiser.recur((next, resolve, reject) => {
            Users.saveCreate(Object.assign({}, {
              firstName: 'Test',
              lastName: 'User',
              email: Math.random() + '@testuser.com'
            }, passwordVals))
            .then(user => {
              userList.push(user);
              userList.length === 3 ? resolve(userList) : next();
            })
            .catch(err => reject(err));
          }))
        })

        // Create a session per user (3 sessions) as sessionList
        .then(state => {
          const sessionList = [];
          return state.set('sessionList', promiser.recur((next, resolve, reject) => {
            Sessions.start(state.userList[sessionList.length]).then(session => {
              sessionList.push(session);
              sessionList.length === 3 ? resolve(sessionList) : next();
            })
            .catch(err => reject(err));
          }))
        })

        // Expire all 3 sessions
        .then(state => {
          return state.map('sessionList', session => {
            session.expiresAt = now;
            return session.save();
          })
        })

        // Add a 4th user
        .then(state => {
          config.backend.sessionSuppression = 2;
          return state.setTo(state.userList, 3, Users.saveCreate(Object.assign({}, {
            firstName: 'Test',
            lastName: 'User',
            email: Math.random() + '@testuser.com'
          }, passwordVals)))
        })

        // Add a 4th session. The idea is that this should remove
        // 2 of our pre-created sessions from the db automatically.
        .then(state => {
          return state.setTo(state.sessionList, 3, Sessions.start(state.userList[3]))
        })

        // Read in all sessions that expired at the date we previously set.
        // Suppression is async so give it a second to complete
        .then(state => {
          return new Promise(resolve => {
            setTimeout(() => {
              const prom = state.set('expiredSessions', Sessions.getMany({ expiresAt: now }));
              resolve(prom);
            }, 1000);
          })
        })

        // Execute our assertion.
        .then(state => {
          // 2 of our 3 expired sessions should have been deleted
          assert.equal(state.expiredSessions.length, 1);
          config.backend.sessionSuppression = origSuppression;
        })

        // Cleanup users
        .then(state => {
          return state.forEach('userList', user => {
            return user.destroy();
          })
        })

        // Cleanup sessions
        .then(state => {
          return state.forEach('sessionList', session => {
            return session.destroy();
          })
        })

        .then(() => done());

      }); // dbready
    }); // it should

  });

  /***************************************
   * Describe more tests here
   ***************************************/

  after(function () {
    dbReady(db => db.getSQConnection().close());
  });

});


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Interface definition prerequisites: GObject Reference Manual</title>
<meta name="generator" content="DocBook XSL Stylesheets V1.79.1">
<link rel="home" href="index.html" title="GObject Reference Manual">
<link rel="up" href="howto-interface.html" title="How to define and implement interfaces">
<link rel="prev" href="howto-interface-implement.html" title="Implementing interfaces">
<link rel="next" href="howto-interface-properties.html" title="Interface properties">
<meta name="generator" content="GTK-Doc V1.25.1 (XML mode)">
<link rel="stylesheet" href="style.css" type="text/css">

Interface definition prerequisites

      To specify that an interface requires the presence of other interfaces
      when implemented, GObject introduces the concept of
      prerequisites: it is possible to associate
      a list of prerequisite types to an interface. For example, if
      object A wishes to implement interface I1, and if interface I1 has a
      prerequisite on interface I2, A has to implement both I1 and I2.

      The mechanism described above is, in practice, very similar to
      Java's interface I1 extends interface I2. The example below shows
      the GObject equivalent:

1
2

/* Make the ViewerEditableLossy interface require ViewerEditable interface. */
G_DEFINE_INTERFACE (ViewerEditableLossy, viewer_editable_lossy, VIEWER_TYPE_EDITABLE);

      In the G_DEFINE_INTERFACE
      call above, the third parameter defines the prerequisite type. This
      is the GType of either an interface or a class. In this case
      the ViewerEditable interface is a prerequisite of
      ViewerEditableLossy. The code
      below shows how an implementation can implement both interfaces and
      register their implementations:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70

static void
viewer_file_editable_lossy_compress (ViewerEditableLossy *editable)
{
  ViewerFile *self = VIEWER_FILE (editable);

  g_print ("File implementation of lossy editable interface compress method: %s.\n",
           self->filename);
}

static void
viewer_file_editable_lossy_interface_init (ViewerEditableLossyInterface *iface)
{
  iface->compress = viewer_file_editable_lossy_compress;
}

static void
viewer_file_editable_save (ViewerEditable  *editable,
                           GError         **error)
{
  ViewerFile *self = VIEWER_FILE (editable);

  g_print ("File implementation of editable interface save method: %s.\n",
           self->filename);
}

static void
viewer_file_editable_undo (ViewerEditable *editable,
                           guint           n_steps)
{
  ViewerFile *self = VIEWER_FILE (editable);

  g_print ("File implementation of editable interface undo method: %s.\n",
           self->filename);
}

static void
viewer_file_editable_redo (ViewerEditable *editable,
                           guint           n_steps)
{
  ViewerFile *self = VIEWER_FILE (editable);

  g_print ("File implementation of editable interface redo method: %s.\n",
           self->filename);
}

static void
viewer_file_editable_interface_init (ViewerEditableInterface *iface)
{
  iface->save = viewer_file_editable_save;
  iface->undo = viewer_file_editable_undo;
  iface->redo = viewer_file_editable_redo;
}

static void
viewer_file_class_init (ViewerFileClass *klass)
{
  /* Nothing here. */
}

static void
viewer_file_init (ViewerFile *self)
{
  /* Instance variable initialisation code. */
}

G_DEFINE_TYPE_WITH_CODE (ViewerFile, viewer_file, G_TYPE_OBJECT,
                         G_IMPLEMENT_INTERFACE (VIEWER_TYPE_EDITABLE,
                                                viewer_file_editable_interface_init)
                         G_IMPLEMENT_INTERFACE (VIEWER_TYPE_EDITABLE_LOSSY,
                                                viewer_file_editable_lossy_interface_init))

      It is very important to notice that the order in which interface
      implementations are added to the main object is not random:
      g_type_add_interface_static,
      which is called by
      G_IMPLEMENT_INTERFACE,
      must be invoked first on the interfaces which have no prerequisites and then on
      the others.

Generated by GTK-Doc V1.25.1


text:
http_path = "/"
css_dir = "config/../src/public/css"
sass_dir = "config/../src/public/sass"
images_dir = "config/../src/public/img"
javascripts_dir = "config/../src/public/js"

# You can select your preferred output style here (can be overridden via the command line):
# output_style = :expanded or :nested or :compact or :compressed

# To enable relative paths to assets via compass helper functions. Uncomment:
# relative_assets = true

# To disable debugging comments that display the original location of your selectors. Uncomment:
# line_comments = false

# If you prefer the indented syntax, you might want to regenerate this
# project again passing --syntax sass, or you can uncomment this:
# preferred_syntax = :sass
# and then run:
# sass-convert -R --from scss --to sass config/../src/public/sass scss && rm -rf sass && mv scss sass


text:
This example creates a basic nginx https service useful in verifying proof of concept, keys, secrets, configmap, and end-to-end https service creation in kubernetes.
It uses an [nginx server block](http://wiki.nginx.org/ServerBlockExample) to serve the index page over both http and https. It will detect changes to nginx's configuration file, default.conf, mounted as a configmap volume and reload nginx automatically.

### Generate certificates

First generate a self signed rsa key and certificate that the server can use for TLS. This step invokes the make_secret.go script in the same directory, which uses the kubernetes api to generate a secret json config in /tmp/secret.json.

```sh
$ make keys secret KEY=/tmp/nginx.key CERT=/tmp/nginx.crt SECRET=/tmp/secret.json
```

### Create a https nginx application running in a kubernetes cluster

You need a [running kubernetes cluster](../../docs/getting-started-guides/) for this to work.

Create a secret and a configmap.

```sh
$ kubectl create -f /tmp/secret.json
secret "nginxsecret" created

$ kubectl create configmap nginxconfigmap --from-file=examples/https-nginx/default.conf
configmap "nginxconfigmap" created
```

Create a service and a replication controller using the configuration in nginx-app.yaml.

```sh
$ kubectl create -f examples/https-nginx/nginx-app.yaml
You have exposed your service on an external port on all nodes in your
cluster.  If you want to expose this service to the external internet, you may
need to set up firewall rules for the service port(s) (tcp:32211,tcp:30028) to serve traffic.
...
service "nginxsvc" created
replicationcontroller "my-nginx" created
```

Then, find the node port that Kubernetes is using for http and https traffic.

```sh
$ kubectl get service nginxsvc -o json
...
                    {
                        "name": "http",
                        "protocol": "TCP",
                        "port": 80,
                        "targetPort": 80,
                        "nodePort": 32211
                    },
                    {
                        "name": "https",
                        "protocol": "TCP",
                        "port": 443,
                        "targetPort": 443,
                        "nodePort": 30028
                    }
...
```

If you are using Kubernetes on a cloud provider, you may need to create cloud firewall rules to serve traffic.
If you are using GCE or GKE, you can use the following commands to add firewall rules.

```sh
$ gcloud compute firewall-rules create allow-nginx-http --allow tcp:32211 --description "Incoming http allowed."
Created [https://www.googleapis.com/compute/v1/projects/hello-world-job/global/firewalls/allow-nginx-http].
NAME              NETWORK  SRC_RANGES  RULES      SRC_TAGS  TARGET_TAGS
allow-nginx-http  default  0.0.0.0/0   tcp:32211

$ gcloud compute firewall-rules create allow-nginx-https --allow tcp:30028 --description "Incoming https allowed."
Created [https://www.googleapis.com/compute/v1/projects/hello-world-job/global/firewalls/allow-nginx-https].
NAME               NETWORK  SRC_RANGES  RULES      SRC_TAGS  TARGET_TAGS
allow-nginx-https  default  0.0.0.0/0   tcp:30028
```

Find your nodes' IPs.

```sh
$ kubectl get nodes -o json | grep ExternalIP -A 2
                        "type": "ExternalIP",
                        "address": "104.198.1.26"
                    }
--
                        "type": "ExternalIP",
                        "address": "104.198.12.158"
                    }
--
                        "type": "ExternalIP",
                        "address": "104.198.11.137"
                    }
```

Now your service is up. You can either use your browser or type the following commands.

```sh
$ curl https://<your-node-ip>:<your-port> -k

$ curl https://104.198.1.26:30028 -k
...
<title>Welcome to nginx!</title>
...
```

Then we will update the configmap. First check your kubectl version.

```sh
$ kubectl version
Client Version: version.Info{Major:"1", Minor:"3", GitVersion:"v1.3.4", GitCommit:"dd6b458ef8dbf24aff55795baa68f83383c9b3a9", GitTreeState:"clean", BuildDate:"2016-08-01T16:45:16Z", GoVersion:"go1.6.2", Compiler:"gc", Platform:"linux/amd64"}
Server Version: version.Info{Major:"1", Minor:"3", GitVersion:"v1.3.5", GitCommit:"b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5", GitTreeState:"clean", BuildDate:"2016-08-11T20:21:58Z", GoVersion:"go1.6.2", Compiler:"gc", Platform:"linux/amd64"}
```

If you are using 1.5 or higher:
Edit file `default.conf`: change `index index.html;` in line 8 to `index index2.html;`.

```sh
$ kubectl replace configmap nginxconfigmap --from-file=default.conf
configmap "nginxconfigmap" replaced
```

If you are using 1.4 or lower:
Retrieve configmap nginxconfigmap.

```sh
$ kubectl get configmap nginxconfigmap -o yaml > examples/https-nginx/nginxcm.yaml
```

Edit file `nginxcm.yaml`: change `index index.html;` to `index index2.html;`.
Apply the change.

```sh
$ kubectl apply -f examples/https-nginx/nginxcm.yaml
configmap "nginxconfigmap" configured
```

Wait a few seconds to let the change propagate. Now you should be able to either use your browser or type the following commands to verify Nginx has been reloaded with new configuration.

```sh
$ curl https://<your-node-ip>:<your-port> -k

$ curl https://104.198.1.26:30028 -k
...
<title>Nginx reloaded!</title>
...
```

For more information on how to run this in a kubernetes cluster, please see the [user-guide](../../docs/user-guide/connecting-applications.md).

<!-- BEGIN MUNGE: GENERATED_ANALYTICS -->
[![Analytics](https://kubernetes-site.appspot.com/UA-36037335-10/GitHub/examples/https-nginx/README.md?pixel)]()
<!-- END MUNGE: GENERATED_ANALYTICS -->


text:
require "media_include/version"
require 'media_include/railtie'  ##Esential!
module MediaInclude
  require "rails"
  # Your code goes here...
  def accept_images
    has_many :images, :as => :object
    accepts_nested_attributes_for :images, :reject_if => proc { |attributes| attributes['picture'].blank? }, :allow_destroy => true
    attr_accessible :images_attributes if Rails.version.to_i < 4
  end

  def accept_videos
    has_many :videos, :as => :object
    accepts_nested_attributes_for :videos, :allow_destroy => true
    attr_accessible :videos_attributes if Rails.version.to_i < 4
  end

  def accept_images_and_videos
    accept_images
    accept_videos
  end
end


text:
"""Config flow for Minut Point."""
import asyncio
from collections import OrderedDict
import logging

import async_timeout
from pypoint import PointSession
import voluptuous as vol

from homeassistant import config_entries
from homeassistant.components.http import HomeAssistantView
from homeassistant.const import CONF_CLIENT_ID, CONF_CLIENT_SECRET
from homeassistant.core import callback

from .const import DOMAIN

AUTH_CALLBACK_PATH = "/api/minut"
AUTH_CALLBACK_NAME = "api:minut"

DATA_FLOW_IMPL = "point_flow_implementation"

_LOGGER = logging.getLogger(__name__)

@callback
def register_flow_implementation(hass, domain, client_id, client_secret):
    """Register a flow implementation.

    domain: Domain of the component responsible for the implementation.
    name: Name of the component.
    client_id: Client id.
    client_secret: Client secret.
    """
    if DATA_FLOW_IMPL not in hass.data:
        hass.data[DATA_FLOW_IMPL] = OrderedDict()

    hass.data[DATA_FLOW_IMPL][domain] = {
        CONF_CLIENT_ID: client_id,
        CONF_CLIENT_SECRET: client_secret,
    }

class PointFlowHandler(config_entries.ConfigFlow, domain=DOMAIN):
    """Handle a config flow."""

    VERSION = 1

    def __init__(self):
        """Initialize flow."""
        self.flow_impl = None

    async def async_step_import(self, user_input=None):
        """Handle external yaml configuration."""
        if self._async_current_entries():
            return self.async_abort(reason="already_setup")

        self.flow_impl = DOMAIN

        return await self.async_step_auth()

    async def async_step_user(self, user_input=None):
        """Handle a flow start."""
        flows = self.hass.data.get(DATA_FLOW_IMPL, {})

        if self._async_current_entries():
            return self.async_abort(reason="already_setup")

        if not flows:
            _LOGGER.debug("no flows")
            return self.async_abort(reason="no_flows")

        if len(flows) == 1:
            self.flow_impl = list(flows)[0]
            return await self.async_step_auth()

        if user_input is not None:
            self.flow_impl = user_input["flow_impl"]
            return await self.async_step_auth()

        return self.async_show_form(
            step_id="user",
            data_schema=vol.Schema({vol.Required("flow_impl"): vol.In(list(flows))}),
        )

    async def async_step_auth(self, user_input=None):
        """Create an entry for auth."""
        if self._async_current_entries():
            return self.async_abort(reason="external_setup")

        errors = {}

        if user_input is not None:
            errors["base"] = "follow_link"

        try:
            with async_timeout.timeout(10):
                url = await self._get_authorization_url()
        except asyncio.TimeoutError:
            return self.async_abort(reason="authorize_url_timeout")
        except Exception:  # pylint: disable=broad-except
            _LOGGER.exception("Unexpected error generating auth url")
            return self.async_abort(reason="unknown_authorize_url_generation")
        return self.async_show_form(
            step_id="auth",
            description_placeholders={"authorization_url": url},
            errors=errors,
        )

    async def _get_authorization_url(self):
        """Create Minut Point session and get authorization url."""
        flow = self.hass.data[DATA_FLOW_IMPL][self.flow_impl]
        client_id = flow[CONF_CLIENT_ID]
        client_secret = flow[CONF_CLIENT_SECRET]
        point_session = PointSession(
            self.hass.helpers.aiohttp_client.async_get_clientsession(),
            client_id,
            client_secret,
        )

        self.hass.http.register_view(MinutAuthCallbackView())

        return point_session.get_authorization_url

    async def async_step_code(self, code=None):
        """Received code for authentication."""
        if self._async_current_entries():
            return self.async_abort(reason="already_setup")

        if code is None:
            return self.async_abort(reason="no_code")

        _LOGGER.debug(
            "Should close all flows below %s",
            self._async_in_progress(),
        )
        # Remove notification if no other discovery config entries in progress

        return await self._async_create_session(code)

    async def _async_create_session(self, code):
        """Create point session and entries."""

        flow = self.hass.data[DATA_FLOW_IMPL][DOMAIN]
        client_id = flow[CONF_CLIENT_ID]
        client_secret = flow[CONF_CLIENT_SECRET]
        point_session = PointSession(
            self.hass.helpers.aiohttp_client.async_get_clientsession(),
            client_id,
            client_secret,
        )
        token = await point_session.get_access_token(code)
        _LOGGER.debug("Got new token")
        if not point_session.is_authorized:
            _LOGGER.error("Authentication Error")
            return self.async_abort(reason="auth_error")

        _LOGGER.info("Successfully authenticated Point")
        user_email = (await point_session.user()).get("email") or ""

        return self.async_create_entry(
            title=user_email,
            data={
                "token": token,
                "refresh_args": {
                    CONF_CLIENT_ID: client_id,
                    CONF_CLIENT_SECRET: client_secret,
                },
            },
        )

class MinutAuthCallbackView(HomeAssistantView):
    """Minut Authorization Callback View."""

    requires_auth = False
    url = AUTH_CALLBACK_PATH
    name = AUTH_CALLBACK_NAME

    @staticmethod
    async def get(request):
        """Receive authorization code."""
        hass = request.app["hass"]
        if "code" in request.query:
            hass.async_create_task(
                hass.config_entries.flow.async_init(
                    DOMAIN, context={"source": "code"}, data=request.query["code"]
                )
            )
        return "OK!"


text:
// Author: abi
// Project: DungeonQuest
// Path: C:\code\Xna\DungeonQuest\Graphics
// Creation date: 28.03.2007 01:01
// Last modified: 31.07.2007 04:40

#region Using directives
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using DungeonQuest.Game;
using DungeonQuest.Helpers;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using DungeonQuest.Shaders;
using XnaTexture = Microsoft.Xna.Framework.Graphics.Texture2D;
#endregion

namespace DungeonQuest.Graphics
{
	/// <summary>
	/// Billboard
	/// </summary>
	class Billboard
	{
		#region Variables
		/// <summary>
		/// Right and up vectors for billboard calculations, will be
		/// set by Billboard.CalcVectors each frame (called always by Graphics)!
		/// </summary>
		internal static Vector3 vecRight = new Vector3(1.0f, 0.0f, 0.0f),
			vecUp = new Vector3(0.0f, 1.0f, 0.0f);

		/// <summary>
		/// For rendering billboard on ground (on z plane, e.g. for ring effect)
		/// </summary>
		internal static Vector3
			// Do it on xy plane instead of xz plane (better visibility)
			vecGroundRight = new Vector3(0.0f, 1.0f, 0.0f),
			vecGroundUp = new Vector3(1.0f, 0.0f, 0.0f);//,
			//obs: vecGroundDepth = new Vector3(0.0f, 0.0f, 1.0f);

		/// <summary>
		/// Blend mode
		/// </summary>
		public enum BlendMode
		{
			/// <summary>
			/// Use normal alpha blending (src alpha, inv src alpha)
			/// </summary>
			NormalAlphaBlending,
			/// <summary>
			/// Light effect with help of destination color and inv src alpha.
			/// </summary>
			LightEffect,
			/// <summary>
			/// Additive blending effect, just adding color with one, one blending.
			/// </summary>
			AdditiveEffect,
		} // enum BlendMode

		/// <summary>
		/// Texture billboard list
		/// </summary>
		class TextureBillboardList
		{
			/// <summary>
			/// Tex
			/// </summary>
			public XnaTexture tex;
			/// <summary>
			/// Light blend mode, usually NormalAlphaBlending
			/// </summary>
			public BlendMode lightBlendMode;
			/// <summary>
			/// Billboard vertices
			/// </summary>
			public List<VertexPositionColorTexture> vertices =
				new List<VertexPositionColorTexture>();
			/// <summary>
			/// Billboard indices
			/// </summary>
			public List<short> indices = new List<short>();

			/// <summary>
			/// Create texture billboard list
			/// </summary>
			/// <param name="setTex">Set tex</param>
			/// <param name="setLightBlendMode">Set light blend mode</param>
			public TextureBillboardList(XnaTexture setTex,
				BlendMode setLightBlendMode)
			{
				tex = setTex;
				lightBlendMode = setLightBlendMode;
			} // TextureBillboardList(setTex, setLightBlendMode)
		} // class TextureBillboardList

		static List<TextureBillboardList> billboards =
			new List<TextureBillboardList>();

		/// <summary>
		/// Get texture billboard
		/// </summary>
		/// <param name="tex">Tex</param>
		/// <returns>Texture billboard list</returns>
		static private TextureBillboardList GetTextureBillboard(
			XnaTexture tex, BlendMode lightBlendMode)
		{
			if (billboards.Count > 0 &&
				billboards[billboards.Count - 1].tex == tex &&
				billboards[billboards.Count - 1].lightBlendMode == lightBlendMode)
				return billboards[billboards.Count - 1];

			// Not found? Then create new and add to billboards list
			TextureBillboardList texBillboard =
				new TextureBillboardList(tex, lightBlendMode);
			billboards.Add(texBillboard);

			// Return result
			return texBillboard;
		} // GetTextureBillboard(tex)
		#endregion

		#region Calc vectors
		/// <summary>
		/// Calc vectors for billboards, will create helper vectors for
		/// billboard rendering, should just be called every frame.
		/// </summary>
		public static void CalcVectors()
		{
			// Only use the inverse view matrix, world matrix is assumed to be
			// Idendity, simply grab the values out of the inverse view matrix.
			Matrix invViewMatrix = BaseGame.InverseViewMatrix;
			vecRight = new Vector3(
				invViewMatrix.M11, invViewMatrix.M12, invViewMatrix.M13);
			vecUp = new Vector3(
				invViewMatrix.M21, invViewMatrix.M22, invViewMatrix.M23);
		} // CalcVectors()
		#endregion

		#region Render billboard
		static VertexDeclaration decl = null;
    /// <summary>
    /// Render billboards
    /// </summary>
		public static void RenderBillboards()
		{
			if (billboards.Count == 0)
				return;

			// Update billboard vectors
			CalcVectors();

			// Reset world space
			BaseGame.WorldMatrix = Matrix.Identity;

			// Enable alpha blending
			BaseGame.EnableAlphaBlending();

			// Disable z buffer to prevent effects to be disabling each other!
			BaseGame.Device.RenderState.DepthBufferEnable = true;
			BaseGame.Device.RenderState.DepthBufferWriteEnable = false;

			// Never go outside of billboard texture
			BaseGame.Device.SamplerStates[0].AddressU = TextureAddressMode.Clamp;
			BaseGame.Device.SamplerStates[0].AddressV = TextureAddressMode.Clamp;

			// No culling
			BaseGame.Device.RenderState.CullMode =
				CullMode.None;

			// Always use VertexPositionColorTexture format!
			if (decl == null)
				decl = new VertexDeclaration(
					BaseGame.Device, VertexPositionColorTexture.VertexElements);
			BaseGame.Device.VertexDeclaration = decl;

			BlendMode useLightBlendMode = BlendMode.NormalAlphaBlending;
			// Render all billboards
			ShaderEffect.effectShader.SetParametersOptimizedGeneral();
			ShaderEffect.effectShader.Effect.Begin();
			ShaderEffect.effectShader.Effect.CurrentTechnique.Passes[0].Begin();

			//foreach (TextureBillboardList billboard in billboards)
			for (int num=0; num<billboards.Count; num++)
			{
				TextureBillboardList billboard = billboards[num];

				if (billboard.vertices.Count > 0 &&
					billboard.indices.Count > 0)
				{
					ShaderEffect.effectShader.SetParameters(billboard.tex);
					ShaderEffect.effectShader.Update();

					if (billboard.lightBlendMode == BlendMode.LightEffect)
					{
						if (useLightBlendMode != BlendMode.LightEffect)
						{
							useLightBlendMode = BlendMode.LightEffect;
							BaseGame.Device.RenderState.SourceBlend =
								Blend.DestinationColor;
							BaseGame.Device.RenderState.DestinationBlend =
								Blend.SourceAlpha;
						} // if (useLightBlendMode)
					} // if (billboard.lightBlendMode)
					else if (billboard.lightBlendMode == BlendMode.AdditiveEffect)
					{
						if (useLightBlendMode != BlendMode.AdditiveEffect)
						{
							useLightBlendMode = BlendMode.AdditiveEffect;
							BaseGame.Device.RenderState.SourceBlend =
								Blend.SourceAlpha;
							BaseGame.Device.RenderState.DestinationBlend =
								Blend.One;
						} // if (useLightBlendMode)
					} // else if
					else
					{
						if (useLightBlendMode != BlendMode.NormalAlphaBlending)
						{
							useLightBlendMode = BlendMode.NormalAlphaBlending;
							BaseGame.Device.RenderState.SourceBlend =
								Blend.SourceAlpha;
							BaseGame.Device.RenderState.DestinationBlend =
								Blend.InverseSourceAlpha;
						} // if (useLightBlendMode)
					} // else

					//Log.Write("rendering " + billboard.indices.Count / 3 +
					//  ", of type=" + billboard.tex);
					VertexPositionColorTexture[] vertices =
						billboard.vertices.ToArray();
					short[] indices = billboard.indices.ToArray();
					BaseGame.Device.DrawUserIndexedPrimitives<VertexPositionColorTexture>(
						PrimitiveType.TriangleList,
						vertices, 0, vertices.Length,
						indices, 0, indices.Length / 3);
				} // if (billboardVertices.Count)
			} // foreach (billboard)

			ShaderEffect.effectShader.Effect.CurrentTechnique.Passes[0].End();
			ShaderEffect.effectShader.Effect.End();

			//*/
			// Remove all billboards
			billboards.Clear();

			//BaseGame.Device.RenderState.AlphaTestEnable = false;
			BaseGame.Device.RenderState.DepthBufferEnable = true;
			BaseGame.Device.RenderState.DepthBufferWriteEnable = true;

			BaseGame.EnableAlphaBlending();

			BaseGame.Device.RenderState.CullMode =
				CullMode.CullCounterClockwiseFace;//.None;

			// Reset texturing
			BaseGame.Device.SamplerStates[0].AddressU = TextureAddressMode.Wrap;
			BaseGame.Device.SamplerStates[0].AddressV = TextureAddressMode.Wrap;
		} // EndRendering()
		#endregion

		#region Billboard rendering for effects
		/// <summary>
		/// Render 3D Billboard into scene. Used for 3d effects.
		/// Set texture before hand, this is required to support both
		/// normal textures and animated textures.
		/// </summary>
		/// <param name="pos">Position in world space</param>
		/// <param name="size">Size in world coordinates</param>
		/// <param name="rotation">Rotation around billboard z axis</param>
		/// <param name="col">Color, usually white</param>
		public static void Render(XnaTexture tex, BlendMode lightBlendMode,
			Vector3 pos, float size, float rotation, Color col)
		{
			// Invisible?
			if (col.A == 0)
				return;

			TextureBillboardList texBillboard =
				GetTextureBillboard(tex, lightBlendMode);

			// Rotation
			Matrix rotMatrix =
				Matrix.CreateRotationZ(rotation) *
				BaseGame.InverseViewMatrix;
			Vector3 upLeft = new Vector3(-1, -1, 0);
			upLeft = Vector3.TransformNormal(upLeft, rotMatrix);
			Vector3 upRight = new Vector3(+1, -1, 0);
			upRight = Vector3.TransformNormal(upRight, rotMatrix);
			Vector3 downRight = new Vector3(+1, +1, 0);
			downRight = Vector3.TransformNormal(downRight, rotMatrix);
			Vector3 downLeft = new Vector3(-1, +1, 0);
			downLeft = Vector3.TransformNormal(downLeft, rotMatrix);

			Vector3 vec;
			vec = pos + upLeft * size;
			int index = texBillboard.vertices.Count;
			texBillboard.vertices.Add(
				new VertexPositionColorTexture(
				vec, col, new Vector2(0.0f, 0.0f)));
			vec = pos + downLeft * size;
			texBillboard.vertices.Add(
				new VertexPositionColorTexture(
				vec, col, new Vector2(0.0f, 1.0f)));
			vec = pos + downRight * size;
			texBillboard.vertices.Add(
				new VertexPositionColorTexture(
				vec, col, new Vector2(1.0f, 1.0f)));
			vec = pos + upRight * size;
			texBillboard.vertices.Add(
				new VertexPositionColorTexture(
				vec, col, new Vector2(1.0f, 0.0f)));

			texBillboard.indices.AddRange(new short[]
				{
					(short)(index+0), (short)(index+1), (short)(index+2),
					(short)(index+0), (short)(index+2), (short)(index+3),
				});
		} // Render(tex, pos, size)

		/// <summary>
		/// Render
		/// </summary>
		/// <param name="tex">Tex</param>
		/// <param name="pos">Position</param>
		/// <param name="size">Size</param>
		/// <param name="rotation">Rotation</param>
		/// <param name="col">Color</param>
		public static void Render(XnaTexture tex,
			Vector3 pos, float size, float rotation, Color col)
		{
			Render(tex, BlendMode.NormalAlphaBlending,
				pos, size, rotation, col);
		} // Render(tex, pos, size)

		/// <summary>
		/// Render
		/// </summary>
		/// <param name="tex">Tex</param>
		/// <param name="pos">Position</param>
		/// <param name="size">Size</param>
		/// <param name="rotation">Rotation</param>
		/// <param name="col">Color</param>
		public static void Render(Texture tex,
			Vector3 pos, float size, float rotation, Color col)
		{
			Render(tex.XnaTexture, BlendMode.NormalAlphaBlending,
				pos, size, rotation, col);
		} // Render(tex, pos, size)
		/*obs
		/// <summary>
		/// Render
		/// </summary>
		/// <param name="tex">Tex</param>
		/// <param name="animationStep">Animation step</param>
		/// <param name="pos">Position</param>
		/// <param name="size">Size</param>
		/// <param name="rotation">Rotation</param>
		/// <param name="col">Color</param>
		public static void Render(AnimatedTexture tex, int animationStep,
			BlendMode lightBlendMode, Vector3 pos, float size, float rotation,
			Color col)
		{
			Render(tex.GetAnimatedTexture(animationStep), lightBlendMode,
				pos, size, rotation, col);
		} // Render(tex, animationStep, pos)
		 */

		/// <summary>
		/// Render 3D Billboard into scene. Used for 3d effects.
		/// Set texture before hand, this is required to support both
		/// normal textures and animated textures.
		/// This method does not support rotation (it is a bit faster).
		/// </summary>
		/// <param name="pos">Position in world space</param>
		/// <param name="size">Size in world coordinates</param>
		/// <param name="col">Color, usually white</param>
		public static void Render(XnaTexture tex, BlendMode lightBlendMode,
			Vector3 pos, float size, Color col)
		{
			// Invisible?
			if (col.A == 0)
				return;

			TextureBillboardList texBillboard =
				GetTextureBillboard(tex, lightBlendMode);

			Vector3 vec;
			int index = texBillboard.vertices.Count;
			vec = pos + ((-vecRight + vecUp) * size);
			texBillboard.vertices.Add(
				new VertexPositionColorTexture(
				vec, col, new Vector2(0.0f, 0.0f)));
			vec = pos + ((-vecRight - vecUp) * size);
			texBillboard.vertices.Add(
				new VertexPositionColorTexture(
				vec, col, new Vector2(0.0f, 1.0f)));
			vec = pos + ((vecRight - vecUp) * size);
			texBillboard.vertices.Add(
				new VertexPositionColorTexture(
				vec, col, new Vector2(1.0f, 1.0f)));
			vec = pos + ((vecRight + vecUp) * size);
			texBillboard.vertices.Add(
				new VertexPositionColorTexture(
				vec, col, new Vector2(1.0f, 0.0f)));

			texBillboard.indices.AddRange(new short[]
				{
					(short)(index+0), (short)(index+1), (short)(index+2),
					(short)(index+0), (short)(index+2), (short)(index+3),
				});
		} // Render(tex, pos, size)

		/// <summary>
		/// Render
		/// </summary>
		/// <param name="tex">Tex</param>
		/// <param name="pos">Position</param>
		/// <param name="size">Size</param>
		/// <param name="col">Color</param>
		public static void Render(Texture tex,
			Vector3 pos, float size, Color col)
		{
			Render(tex.XnaTexture, BlendMode.NormalAlphaBlending, pos, size, col);
		} // Render(tex, pos, size)

		/*
		/// <summary>
		/// Render
		/// </summary>
		/// <param name="tex">Tex</param>
		/// <param name="animationStep">Animation step</param>
		/// <param name="pos">Position</param>
		/// <param name="size">Size</param>
		/// <param name="rotation">Rotation</param>
		/// <param name="col">Color</param>
		public static void Render(AnimatedTexture tex, int animationStep,
			BlendMode lightBlendMode, Vector3 pos, float size, Color col)
		{
			Render(tex.GetAnimatedTexture(animationStep), lightBlendMode,
				pos, size, col);
		} // Render(tex, animationStep, pos)
		 */

		/// <summary>
		/// Render on ground (Z/Y Plane), used for effects which are
		/// rendered on the ground/landscape.
		/// Does also support coloring for blending in/out effects.
		/// Set texture before hand, this is required to support both
		/// normal textures and animated textures.
		/// </summary>
		public static void RenderOnGround(XnaTexture tex,
			BlendMode blendMode,
			Vector3 pos, float size, float rotation, Color col,
			Vector3 vecGroundRight, Vector3 vecGroundUp)
		{
			// Invisible?
			if (col.A == 0)
				return;

			TextureBillboardList texBillboard =
				GetTextureBillboard(tex, blendMode);//BlendMode.NormalAlphaBlending);

			Vector3 right = vecGroundRight;
			right = Vector3.TransformNormal(right, Matrix.CreateRotationZ(rotation));
			Vector3 up = vecGroundUp;
			up = Vector3.TransformNormal(up, Matrix.CreateRotationZ(rotation));

			Vector3 vec = pos + ((-right - up) * size);
			//obs: CustomVertex.PositionColoredTextured[] billboardVertices =
			//	new CustomVertex.PositionColoredTextured[4];
			int index = texBillboard.vertices.Count;
			texBillboard.vertices.Add(
				new VertexPositionColorTexture(
				vec, col, new Vector2(0.0f, 1.0f)));
			vec = pos + ((right - up) * size);
			texBillboard.vertices.Add(
				new VertexPositionColorTexture(
				vec, col, new Vector2(1.0f, 1.0f)));
			vec = pos + ((right + up) * size);
			texBillboard.vertices.Add(
				new VertexPositionColorTexture(
				vec, col, new Vector2(1.0f, 0.0f)));
			vec = pos + ((-right + up) * size);
			texBillboard.vertices.Add(
				new VertexPositionColorTexture(
				vec, col, new Vector2(0.0f, 0.0f)));

			texBillboard.indices.AddRange(new short[]
				{
					(short)(index+0), (short)(index+1), (short)(index+2),
					(short)(index+0), (short)(index+2), (short)(index+3),
				});
		} // RenderOnGround(pos, size, col)

		/// <summary>
		/// Render on ground
		/// </summary>
		/// <param name="tex">Tex</param>
		/// <param name="pos">Position</param>
		/// <param name="size">Size</param>
		/// <param name="rotation">Rotation</param>
		/// <param name="col">Color</param>
		public static void RenderOnGround(Texture tex,
			Vector3 pos, float size, float rotation, Color col,
			Vector3 vecGroundRight, Vector3 vecGroundUp)
		{
			RenderOnGround(tex.XnaTexture, BlendMode.NormalAlphaBlending,
				pos, size, rotation, col, vecGroundRight, vecGroundUp);
		} // RenderOnGround(tex, pos, size)
		#endregion

		#region Unit testing
#if DEBUG
		/// <summary>
		/// Test render billboards
		/// </summary>
		public static void TestRenderBillboards()
		{
			Texture plasma = null, fireball = null, ring = null, smoke = null;

			TestGame.Start("Test render billboards",
				delegate
				{
					plasma = new Texture("Plasma");
					fireball = new Texture("FireBall");
					ring = new Texture("ExplosionRing");
					smoke = new Texture("Smoke");
				},
				delegate
				{
					BaseGame.Device.Clear(Color.Blue);

					/*TODO
					for (int num = 0; num < 200; num++)
					{
						BaseGame.DrawLine(
							new Vector3(-12.0f + num / 4.0f, 13.0f, 0),
							new Vector3(-17.0f + num / 4.0f, -13.0f, 0),
							new Color((byte)(255 - num), 14, (byte)num));
					} // for
					 */

					TextureFont.WriteText(2, 30,
						"cam pos=" + BaseGame.CameraPos);

					Billboard.Render(plasma,
						new Vector3(-40.0f, 0.0f, 0.0f), 5.0f,
						BaseGame.TotalTimeMs * (float)Math.PI / 1000.0f,
						Color.White);
					Billboard.Render(plasma,
						new Vector3(0.0f, 0.0f, 0.0f), 10.0f, (float)Math.PI / 8,
						Color.Gray);
					Billboard.Render(plasma,
						new Vector3(40.0f, 0.0f, 0.0f), 20.0f,
						BaseGame.TotalTimeMs * (float)Math.PI / 5000.0f,
						Color.Red);

					Billboard.Render(fireball,
						new Vector3(-40.0f, +50.0f, 0.0f), 5.0f, 0,
						Color.White);
					Billboard.Render(fireball,
						new Vector3(0.0f, +50.0f, 0.0f), 10.0f, (float)Math.PI / 8,
						Color.Yellow);
					Billboard.Render(fireball,
						new Vector3(40.0f, +50.0f, 0.0f), 20.0f, (float)Math.PI * 3 / 8,
						Color.Red);

					Billboard.RenderOnGround(ring,
						new Vector3(-25.0f, 0.0f, -100.0f), 5.0f, 0, Color.White,
						vecGroundRight, vecGroundUp);
					Billboard.RenderOnGround(ring,
						new Vector3(0.0f, 0.0f, -100.0f), 10.0f, (float)Math.PI / 8,
						Color.Blue,
						vecGroundRight, vecGroundUp);
					Billboard.RenderOnGround(ring,
						new Vector3(25.0f, 0.0f, -100.0f), 20.0f,
						BaseGame.TotalTimeMs * (float)Math.PI / 5000.0f, Color.White,
						vecGroundRight, vecGroundUp);

					Billboard.RenderBillboards();
				});
		} // TestRenderBillboards()
		//*/
#endif
		#endregion
	} // class Billboard
} // namespace DungeonQuest.Graphics


text:
author: slowe
categories: Explanation
comments: true
date: 2006-09-28T21:37:11Z
slug: cocoalicious-fix
tags:
- Macintosh
- Web
title: Cocoalicious Fix
url: /2006/09/28/cocoalicious-fix/
wordpress_id: 341
---

As noted in [this comment](http://weblog.scifihifi.com/2006/08/12/delicious-api-url-switch/#comment-15131) on the [Sci-Fi Hi-Fi weblog](http://weblog.scifihifi.com/) article about the recent [problems with Cocoalicious](http://weblog.scifihifi.com/2006/08/12/delicious-api-url-switch/), it turns out that it may be necessary to change the del.icio.us API URI not only in the Preferences, but also in Keychain Access.

Huh? In Keychain Access? Yep, you heard that right. Changing the URI in Keychain Access from "http://" to "https://" and then relaunching Cocoalicious seems to fix the issue. Note that you'll have to re-enter your del.icio.us account password after making the change in Keychain Access, and note that you'll also end up with two entries in your login keychain for the del.icio.us API. One entry will have the "http://" prefix, and the second will have the "https://" prefix. I tried going back and deleting the non-SSL entry, but it just ends up getting recreated anyway so you might as well not worry about it.

I can't guarantee this will fix everyone, but it seems to have helped a number of us (for whatever reason).


text:
package nvd

import (
	"fmt"
	"net/http"
	"net/http/httptest"
	"net/url"
	"strings"
	"testing"
)

// http test helpers

func httptestNewServer(f http.Handler) (*httptest.Server, SourceConfig) {
	ts := httptest.NewServer(f)

	tsurl, _ := url.Parse(ts.URL)
	src := SourceConfig{
		Scheme:      tsurl.Scheme,
		Host:        tsurl.Host,
		CVEFeedPath: "/",
		CPEFeedPath: "/",
	}
	return ts, src
}

func TestResponseNotOK(t *testing.T) {
	ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.WriteHeader(http.StatusServiceUnavailable)
		fmt.Fprintf(w, "hello world")
	}))
	defer ts.Close()

	resp, err := http.Get(ts.URL)
	if err != nil {
		t.Fatal(err)
	}

	err = httpResponseNotOK(resp)
	if err == nil {
		t.Fatal("unexpected response OK")
	}

	if !strings.Contains(err.Error(), "hello world") {
		t.Fatalf("unexpected response: %q", err)
	}
}


text:
package org.mifos.application.admindocuments.persistence;

import java.util.List;

import junit.framework.Assert;

import org.mifos.application.admindocuments.business.AdminDocumentBO;
import org.mifos.framework.MifosIntegrationTestCase;
import org.mifos.framework.exceptions.ApplicationException;
import org.mifos.framework.exceptions.PersistenceException;
import org.mifos.framework.exceptions.SystemException;

public class AdminDocumentPersistenceIntegrationTest extends MifosIntegrationTestCase {

    public AdminDocumentPersistenceIntegrationTest() throws SystemException, ApplicationException {
        super();
    }

    private AdminDocumentPersistence reportsPersistence;

    @Override
    protected void setUp() throws Exception {
        super.setUp();
        reportsPersistence = new AdminDocumentPersistence();
    }

    public void testGetAllAdminDocuments() throws PersistenceException {
        List<AdminDocumentBO> listadmindoc = reportsPersistence.getAllAdminDocuments();
       Assert.assertEquals(0, listadmindoc.size());
    }

    public void testGetAdminDocumentById() throws NumberFormatException, PersistenceException {
        AdminDocumentBO admindoc = reportsPersistence.getAdminDocumentById(Short.valueOf("1"));
       Assert.assertEquals(null, admindoc);
    }

}


text:
package common

import (
	"go-common/app/admin/main/feed/conf"
	accdao "go-common/app/admin/main/feed/dao/account"
	arcdao "go-common/app/admin/main/feed/dao/archive"
	pgcdao "go-common/app/admin/main/feed/dao/pgc"
	showdao "go-common/app/admin/main/feed/dao/show"
	"go-common/library/log"
	httpx "go-common/library/net/http/blademaster"
)

// Service is search service
type Service struct {
	showDao    *showdao.Dao
	pgcDao     *pgcdao.Dao
	accDao     *accdao.Dao
	arcDao     *arcdao.Dao
	client     *httpx.Client
	managerURL string
}

// New new a search service
func New(c *conf.Config) (s *Service) {
	var (
		pgc *pgcdao.Dao
		err error
	)
	if pgc, err = pgcdao.New(c); err != nil {
		log.Error("pgcdao.New error(%v)", err)
		return
	}
	s = &Service{
		showDao:    showdao.New(c),
		pgcDao:     pgc,
		accDao:     accdao.New(c),
		arcDao:     arcdao.New(c),
		client:     httpx.NewClient(c.HTTPClient),
		managerURL: c.Host.Manager,
	}
	return
}


text:
require 'thor'
require 'user_config'

module Recluse
  module CLI
    ##
    # Roots related commands.
    class Roots < Thor #:nodoc: all
      desc 'add profile pattern1 [pattern2] ...', 'add to roots'
      def add(name, *roots)
        uconf = UserConfig.new '.recluse'
        unless uconf.exist?("#{name}.yaml")
          puts "Profile #{name} doesn't exist"
          exit(-1)
        end
        profile = uconf["#{name}.yaml"]
        if profile.key?('roots')
          profile['roots'] += roots
        else
          profile['roots'] = roots
        end
        profile.save
      end
      desc 'remove profile pattern1 [pattern2] ...', 'remove from roots'
      def remove(name, *roots)
        uconf = UserConfig.new '.recluse'
        unless uconf.exist?("#{name}.yaml")
          puts "Profile #{name} doesn't exist"
          exit(-1)
        end
        profile = uconf["#{name}.yaml"]
        return unless profile.key?('roots')
        profile['roots'] -= roots
        profile.save
      end
      desc 'clear profile', 'remove all roots'
      def clear(name)
        uconf = UserConfig.new '.recluse'
        unless uconf.exist?("#{name}.yaml")
          puts "Profile #{name} doesn't exist"
          exit(-1)
        end
        profile = uconf["#{name}.yaml"]
        profile['roots'] = []
        profile.save
      end
      desc 'list profile', 'list roots'
      def list(name)
        uconf = UserConfig.new '.recluse'
        unless uconf.exist?("#{name}.yaml")
          puts "Profile #{name} doesn't exist"
          exit(-1)
        end
        profile = uconf["#{name}.yaml"]
        profile['roots'].each { |root| puts root } if profile.key?('roots')
      end
    end
  end
end


text:
import random

from bot import Command, utils, categories

url_settings = {
    'cat': ['http://aws.random.cat/meow', ['gato', 'gatito', 'neko'], 'file'],
    'dog': ['https://dog.ceo/api/breeds/image/random', ['perro', 'perrito', 'doggo'], 'message'],
    'shiba': ['http://shibe.online/api/shibes', ['shibe', 'shibainu'], 0],
    'fox': ['https://randomfox.ca/floof/', ['foxxo'], 'image'],
    'duck': ['https://random-d.uk/api/random', ['pato'], 'url'],
    'bunny': ['https://api.bunnies.io/v2/loop/random/?media=gif', ['conejo'], 'media.gif'],
    'owl': ['http://pics.floofybot.moe/owl', ['buho'], 'image'],
}

alias_map = {k: v[1] + [k] for k, v in url_settings.items()}
aliases = [item for x in alias_map.values() for item in x]

class RandomAnimal(Command):
    __author__ = 'makzk'
    __version__ = '1.0.0'

    def __init__(self, bot):
        super().__init__(bot)
        self.name = 'animal'
        self.format = '$[animal-usage]'
        self.aliases = aliases
        self.category = categories.IMAGES

    async def handle(self, cmd):
        if cmd.argc < 1 and cmd.cmdname in aliases:
            cmd.args = [cmd.cmdname]
            cmd.argc = 1

        if cmd.argc > 0 and cmd.args[0] == 'help':
            return await cmd.send_usage('$[animal-usage-help]', locales={'types': ', '.join(list(url_settings.keys()))})

        if cmd.argc < 1:
            atype = random.choice(list(url_settings.keys()))
        elif cmd.args[0] in aliases:
            atype = list(url_settings.keys())[0]
            for k, v in alias_map.items():
                if cmd.args[0] in v:
                    atype = k
                    break
        else:
            return await cmd.send_usage()

        try:
            config = url_settings[atype]
            await cmd.typing()
            async with self.http.get(config[0]) as r:
                if r.status == 200:
                    data = await r.json()
                    if isinstance(config[2], int):
                        data = data[config[2]]
                    else:
                        for prop in config[2].split('.'):
                            data = data.get(prop, '')
                    embed = utils.img_embed(data, f'$[animal-{atype}-title]')
                    return await cmd.answer(embed)
        except Exception as e:
            self.log.error(e)
            await cmd.answer(f'$[animal-{atype}-error]')


text:
title: About
permalink: /about/
---

This blog is an attempt to target the people who find difficult in understanding the CS concepts. The concepts will be discussed in plain layman language. We will be discussing the following data structures:

* Stack, Queues and Linked Lists
* Trees - Tree Traversal, Binary Search Tree (BST)
* Greedy and Dynamic Programming algorithm
* Graph Algorithm

And many other advance data structures. If you want any specific problem or specific data structure to be discussed, please mention that in comment section below.

#### About Me
Having completed my undergrad from IIT Jodhpur in Computer Science and Engineering, currently I am working as a Software Developer in Amazon, India. I am a competitive programming enthusiast
Besides my work, I like to play chess, read books, watch TV Series (a lot !!!).
![image](/blog/images/My_Pic.jpeg)


text:
module Asphalt
  module Utils
    def self.add_import_statement(file_content, statement)
      file_content + "#{statement}\n"
    end

    def self.format_import_directive(directories, file, options={})
      if directories.empty?
        formatted_directories = nil
      else
        formatted_directories = "#{File.join(directories)}/"
      end

      if options[:format] == :sass
        "@import #{formatted_directories}#{file}"
      else
        "@import '#{formatted_directories}#{file}';"
      end
    end

    def self.last_import_statement(sass_content)
      regex = %r(^\s*(@import.+)$)
      sass_content.scan(regex).last.pop
    end

    def self.update_file!(file_path, content)
      previous_file_content = File.open(file_path, 'r').read

      file = File.open(file_path, 'w+')
      file << add_import_statement(previous_file_content, content)
      file.close
    end
  end
end


text:
package de.lessvoid.nifty.examples.helloworld;

import de.lessvoid.nifty.Nifty;
import de.lessvoid.nifty.effects.EffectImpl;
import de.lessvoid.nifty.effects.EffectProperties;
import de.lessvoid.nifty.effects.Falloff;
import de.lessvoid.nifty.elements.Element;
import de.lessvoid.nifty.elements.render.TextRenderer;
import de.lessvoid.nifty.render.NiftyRenderEngine;
import de.lessvoid.nifty.spi.render.RenderFont;
import de.lessvoid.nifty.tools.Color;

public class TextTyping implements EffectImpl {
  // length of the effect in ms
  private int effectLength;

  // start size of the text size effect
  private float startSize;

  // end size of the text size effect
  private float endSize;

  // time we have available for each step (char)
  private float stepTime;

  // the original text
  private String originalText;

  // the text renderer (for easy access)
  private TextRenderer textRenderer;

  @Override
  public void activate(Nifty nifty, Element element, EffectProperties parameter) {
    textRenderer = element.getRenderer(TextRenderer.class);
    originalText = textRenderer.getOriginalText();

    effectLength = Integer.valueOf(parameter.getProperty("length", "1000"));
    startSize = Float.valueOf(parameter.getProperty("startSize", "5.0"));
    endSize = Float.valueOf(parameter.getProperty("endSize", "1.0"));
    stepTime = effectLength / originalText.length();

    updateText("");
  }

  @Override
  public void execute(Element element, float effectTime, Falloff falloff, NiftyRenderEngine r) {
    int currentIndex = (int)(originalText.length() * effectTime);
    String currentText = originalText.substring(0, currentIndex);

    if (currentIndex < originalText.length()) {
      String nextChar = originalText.substring(currentIndex, currentIndex + 1);
      int textWidth = textRenderer.getFont().getWidth(currentText);

      // current time in ms (instead of being in the [0.0,1.0] interval what the effectTime is in)
      float currentTime = effectTime * effectLength;

      // normalizedStepTime is between 0.0f and 1.0f
      float normalizedStepTime = (currentTime % stepTime) / stepTime;

      // use normalizedStepTime to calculate the character size for the text size effect
      float charSize = startSize + normalizedStepTime * (endSize - startSize);

      r.saveState(null);
      r.setFont(textRenderer.getFont());
      r.setRenderTextSize(charSize);

      // this part makes sure the text gets correctly centered when the RenderTextSize has been changed
      TextRenderer textRenderer = element.getRenderer(TextRenderer.class);
      if (textRenderer != null) {
        String text = textRenderer.getWrappedText();
        RenderFont font = textRenderer.getFont();

        float originalWidth = font.getWidth(text, 1.0f);
        float sizedWidth = font.getWidth(text, charSize);

        float originalHeight = font.getHeight();
        float sizedHeight = font.getHeight() * charSize;

        r.moveTo(- (sizedWidth - originalWidth) / 2, - (sizedHeight - originalHeight) / 2);
      }

      r.renderText(nextChar, element.getX() + textWidth, element.getY(), -1, -1, Color.WHITE);
      r.restoreState();
    }

    updateText(currentText);
  }

  @Override
  public void deactivate() {
  }

  private void updateText(final String currentText) {
    textRenderer.setText(currentText);
  }
}


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.

package com.azure.resourcemanager.network.models;

import com.azure.core.annotation.Fluent;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.annotation.JsonTypeName;
import java.util.List;

/** Firewall Policy Filter Rule Collection. */
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "ruleCollectionType")
@JsonTypeName("FirewallPolicyFilterRuleCollection")
@Fluent
public final class FirewallPolicyFilterRuleCollection extends FirewallPolicyRuleCollection {
    /*
     * The action type of a Filter rule collection.
     */
    @JsonProperty(value = "action")
    private FirewallPolicyFilterRuleCollectionAction action;

    /*
     * List of rules included in a rule collection.
     */
    @JsonProperty(value = "rules")
    private List<FirewallPolicyRule> rules;

    /** Creates an instance of FirewallPolicyFilterRuleCollection class. */
    public FirewallPolicyFilterRuleCollection() {
    }

    /**
     * Get the action property: The action type of a Filter rule collection.
     *
     * @return the action value.
     */
    public FirewallPolicyFilterRuleCollectionAction action() {
        return this.action;
    }

    /**
     * Set the action property: The action type of a Filter rule collection.
     *
     * @param action the action value to set.
     * @return the FirewallPolicyFilterRuleCollection object itself.
     */
    public FirewallPolicyFilterRuleCollection withAction(FirewallPolicyFilterRuleCollectionAction action) {
        this.action = action;
        return this;
    }

    /**
     * Get the rules property: List of rules included in a rule collection.
     *
     * @return the rules value.
     */
    public List<FirewallPolicyRule> rules() {
        return this.rules;
    }

    /**
     * Set the rules property: List of rules included in a rule collection.
     *
     * @param rules the rules value to set.
     * @return the FirewallPolicyFilterRuleCollection object itself.
     */
    public FirewallPolicyFilterRuleCollection withRules(List<FirewallPolicyRule> rules) {
        this.rules = rules;
        return this;
    }

    /** {@inheritDoc} */
    @Override
    public FirewallPolicyFilterRuleCollection withName(String name) {
        super.withName(name);
        return this;
    }

    /** {@inheritDoc} */
    @Override
    public FirewallPolicyFilterRuleCollection withPriority(Integer priority) {
        super.withPriority(priority);
        return this;
    }

    /**
     * Validates the instance.
     *
     * @throws IllegalArgumentException thrown if the instance is not valid.
     */
    @Override
    public void validate() {
        super.validate();
        if (action() != null) {
            action().validate();
        }
        if (rules() != null) {
            rules().forEach(e -> e.validate());
        }
    }
}


text:
package de.hpi.bpmn2_0.model.artifacts;

import javax.xml.bind.Marshaller;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;

import de.hpi.bpmn2_0.transformation.Visitor;
import de.hpi.bpmn2_0.util.EscapingStringAdapter;

/**
 *
Java class for tTextAnnotation complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType name="tTextAnnotation">
 *   <complexContent>
 *     <extension base="{http://www.omg.org/bpmn20}tArtifact">
 *       <sequence>
 *         <element ref="{http://www.omg.org/bpmn20}text" minOccurs="0"/>
 *       </sequence>
 *     </extension>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "tTextAnnotation", propOrder = {
    "text",
    "textFormat"
})
public class TextAnnotation
    extends Artifact
{

	@XmlElement
	@XmlJavaTypeAdapter(EscapingStringAdapter.class)
    protected String text;
    @XmlAttribute
    @XmlJavaTypeAdapter(EscapingStringAdapter.class)
	protected String textFormat;

	public void acceptVisitor(Visitor v){
		v.visitTextAnnotation(this);
	}

	/**
	 * The {@link Marshaller} invokes this method right before marshaling to
	 * XML. It secures that the name attribute is removed from the text annotation
	 * element.
	 *
	 * @param marshaller
	 *            The marshaling context
	 */
	public void beforeMarshal(Marshaller marshaller) {
		/*
		 * empty the name element
		 */
		this.name = null;
	}

    /* Getter & Setter */

    /**
     * Gets the value of the text property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getText() {
        return text;
    }

    public String getTextFormat() {
		return textFormat;
	}

	public void setTextFormat(String textFormat) {
		this.textFormat = textFormat;
	}

	/**
     * Sets the value of the text property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setText(String value) {
        this.text = value;
    }

}


text:
class User < ActiveRecord::Base
  # Include default devise modules. Others available are:
  # :token_authenticatable, :confirmable,
  # :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable,
         :token_authenticatable

  has_many :apps
  has_and_belongs_to_many :dist_lists
  has_many :roles, :class_name => "UserRole", :dependent => :destroy
  has_many :devices, :dependent => :destroy

  # Setup accessible (or protected) attributes for your model
  attr_accessible :email, :password, :password_confirmation, :remember_me
  # attr_accessible :title, :body

  def is_admin_for_app app
    role = self.roles.select{|role| role.app_id == app.id}.first
    !role.nil? && role.role == UserRole::ROLES[:admin]
  end

  def is_tester_for_app app
    role = UserRole.where(:app_id => app.id, :user_id => self.id).first
    !role.nil? && role.role == UserRole::ROLES[:tester]
  end
end


text:
// Copyright 1998-2015 Epic Games, Inc. All Rights Reserved.
//
// libwebsocket client wrapper.
//
#pragma  once

DECLARE_DELEGATE(FJavascriptWebSocketInfoCallBack);

class FJavascriptWebSocket
{

public:

	// Initialize as client side socket.
	FJavascriptWebSocket(const FInternetAddr& ServerAddress);

	// Initialize as server side socket.
	FJavascriptWebSocket(WebSocketInternalContext* InContext, WebSocketInternal* Wsi);

	// clean up.
	~FJavascriptWebSocket();

	/************************************************************************/
	/* Set various callbacks for Socket Events                              */
	/************************************************************************/
	void SetConnectedCallBack(FJavascriptWebSocketInfoCallBack CallBack);
	void SetErrorCallBack(FJavascriptWebSocketInfoCallBack CallBack);
	void SetRecieveCallBack(FJavascriptWebSocketPacketRecievedCallBack CallBack);

	/** Send raw data to remote end point. */
	bool Send(uint8* Data, uint32 Size);

	/** service libwebsocket.			   */
	void Tick();
	/** service libwebsocket until outgoing buffer is empty */
	void Flush();

	/** Helper functions to describe end points. */
	FString RemoteEndPoint();
	FString LocalEndPoint();

private:

	void HandlePacket();
	void OnRawRecieve(void* Data, uint32 Size);
	void OnRawWebSocketWritable(WebSocketInternal* wsi);

	/************************************************************************/
	/*	Various Socket callbacks											*/
	/************************************************************************/
	FJavascriptWebSocketPacketRecievedCallBack  RecievedCallBack;
	FJavascriptWebSocketInfoCallBack ConnectedCallBack;
	FJavascriptWebSocketInfoCallBack ErrorCallBack;

	/**  Recv and Send Buffers, serviced during the Tick */
	TArray<uint8> RecievedBuffer;
	TArray<TArray<uint8>> OutgoingBuffer;

	/** libwebsocket internal context*/
	WebSocketInternalContext* Context;

	/** libwebsocket web socket */
	WebSocketInternal* Wsi;

	/** libwebsocket Protocols that can be serviced by this implemenation*/
	WebSocketInternalProtocol* Protocols;

	/** Server side socket or client side*/
	bool IsServerSide;

#if !PLATFORM_HTML5
	/* libwebsocket service functions */
	static int unreal_networking_server(struct libwebsocket_context *, struct libwebsocket *wsi, enum libwebsocket_callback_reasons reason, void *user, void *in, size_t len);
	static int unreal_networking_client(struct libwebsocket_context *, struct libwebsocket *wsi, enum libwebsocket_callback_reasons reason, void *user, void *in, size_t len);
#endif

	friend class FJavascriptWebSocketServer;
	int SockFd;
};


text:
//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//     Runtime Version:4.0.30319.0
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

namespace Microsoft.CodeAnalysis.ExpressionEvaluator {
    using System;
    using System.Reflection;

    /// <summary>
    ///   A strongly-typed resource class, for looking up localized strings, etc.
    /// </summary>
    // This class was auto-generated by the StronglyTypedResourceBuilder
    // class via a tool like ResGen or Visual Studio.
    // To add or remove a member, edit your .ResX file then rerun ResGen
    // with the /str option, or rebuild your VS project.
    [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
    [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
    [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
    internal class Resources {

        private static global::System.Resources.ResourceManager resourceMan;

        private static global::System.Globalization.CultureInfo resourceCulture;

        [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
        internal Resources() {
        }

        /// <summary>
        ///   Returns the cached ResourceManager instance used by this class.
        /// </summary>
        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
        internal static global::System.Resources.ResourceManager ResourceManager {
            get {
                if (object.ReferenceEquals(resourceMan, null)) {
                    global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Microsoft.CodeAnalysis.ExpressionEvaluator.Resources", typeof(Resources).GetTypeInfo().Assembly);
                    resourceMan = temp;
                }
                return resourceMan;
            }
        }

        /// <summary>
        ///   Overrides the current thread's CurrentUICulture property for all
        ///   resource lookups using this strongly typed resource class.
        /// </summary>
        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
        internal static global::System.Globalization.CultureInfo Culture {
            get {
                return resourceCulture;
            }
            set {
                resourceCulture = value;
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Dynamic View.
        /// </summary>
        internal static string DynamicView {
            get {
                return ResourceManager.GetString("DynamicView", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Only COM or Dynamic objects can have Dynamic View.
        /// </summary>
        internal static string DynamicViewNotDynamic {
            get {
                return ResourceManager.GetString("DynamicViewNotDynamic", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Expanding the Dynamic View will get the dynamic members for the object.
        /// </summary>
        internal static string DynamicViewValueWarning {
            get {
                return ResourceManager.GetString("DynamicViewValueWarning", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Error.
        /// </summary>
        internal static string ErrorName {
            get {
                return ResourceManager.GetString("ErrorName", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to '{0}' threw an exception of type '{1}'.
        /// </summary>
        internal static string ExceptionThrown {
            get {
                return ResourceManager.GetString("ExceptionThrown", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Cannot dereference '{0}'. The pointer is not valid..
        /// </summary>
        internal static string InvalidPointerDereference {
            get {
                return ResourceManager.GetString("InvalidPointerDereference", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Native View.
        /// </summary>
        internal static string NativeView {
            get {
                return ResourceManager.GetString("NativeView", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to To inspect the native object, enable native code debugging..
        /// </summary>
        internal static string NativeViewNotNativeDebugging {
            get {
                return ResourceManager.GetString("NativeViewNotNativeDebugging", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Non-Public members.
        /// </summary>
        internal static string NonPublicMembers {
            get {
                return ResourceManager.GetString("NonPublicMembers", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Raw View.
        /// </summary>
        internal static string RawView {
            get {
                return ResourceManager.GetString("RawView", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Results View.
        /// </summary>
        internal static string ResultsView {
            get {
                return ResourceManager.GetString("ResultsView", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Results View requires System.Core.dll to be referenced.
        /// </summary>
        internal static string ResultsViewNoSystemCore {
            get {
                return ResourceManager.GetString("ResultsViewNoSystemCore", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Only Enumerable types can have Results View.
        /// </summary>
        internal static string ResultsViewNotEnumerable {
            get {
                return ResourceManager.GetString("ResultsViewNotEnumerable", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Expanding the Results View will enumerate the IEnumerable.
        /// </summary>
        internal static string ResultsViewValueWarning {
            get {
                return ResourceManager.GetString("ResultsViewValueWarning", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Shared members.
        /// </summary>
        internal static string SharedMembers {
            get {
                return ResourceManager.GetString("SharedMembers", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Static members.
        /// </summary>
        internal static string StaticMembers {
            get {
                return ResourceManager.GetString("StaticMembers", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Type variables.
        /// </summary>
        internal static string TypeVariablesName {
            get {
                return ResourceManager.GetString("TypeVariablesName", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Host Value Not Found.
        /// </summary>
        internal static string HostValueNotFound
        {
            get
            {
                return ResourceManager.GetString("HostValueNotFound", resourceCulture);
            }
        }
    }
}


text:
var angular = require('angular');
var app = angular.module('mapcache');

app.controller('ColorPickerController', require('./color.picker.controller'));
app.controller('LocationChooserController', require('./location-chooser.controller'));

app.directive('colorPicker', require('./color.picker.directive'));
app.directive('locationChooser', require('./location-chooser.directive'));


text:
package org.openstack.atlas.service.domain.entity;

import org.openstack.atlas.datamodel.AtlasTypeHelper;
import org.openstack.atlas.datamodel.CoreAlgorithmType;
import org.openstack.atlas.datamodel.CoreProtocolType;
import org.openstack.atlas.service.domain.pojo.VirtualIpDozerWrapper;

import javax.persistence.*;
import java.io.Serializable;
import java.util.Calendar;
import java.util.HashSet;
import java.util.Set;

@javax.persistence.Entity
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(
        name = "vendor",
        discriminatorType = DiscriminatorType.STRING
)
@DiscriminatorValue("CORE")
@Table(name = "load_balancer")
public class LoadBalancer extends Entity implements Serializable {
    private final static long serialVersionUID = 532512316L;

    @Column(name = "account_id", nullable = false, length = 32)
    private Integer accountId;

    @Column(name = "name", length = 128)
    private String name;

    @Column(name = "algorithm", nullable = false)
    private String algorithm = CoreAlgorithmType.ROUND_ROBIN;

    @Column(name = "protocol", nullable = false)
    private String protocol = CoreProtocolType.HTTP;

    @Column(name = "port", nullable = false)
    private Integer port = 80;

    @Temporal(TemporalType.TIMESTAMP)
    private Calendar created;

    @Temporal(TemporalType.TIMESTAMP)
    private Calendar updated;

    @Column(name = "status", nullable = false)
    private String status;

    @Column(name = "created_on_adapter", nullable = true)
    private Boolean created_on_adapter;

    @OneToMany(mappedBy = "loadBalancer", fetch = FetchType.EAGER)
    private Set<LoadBalancerJoinVip> loadBalancerJoinVipSet = new HashSet<LoadBalancerJoinVip>();

    @OrderBy("id")
    @OneToMany(cascade = CascadeType.ALL, mappedBy = "loadBalancer", orphanRemoval = true, fetch = FetchType.EAGER)
    private Set<Node> nodes = new HashSet<Node>();

    @OrderBy("id")
    @OneToMany(cascade = CascadeType.ALL, mappedBy = "loadBalancer", fetch = FetchType.LAZY)
    private Set<UsageRecord> usage = new HashSet<UsageRecord>();

    @OneToOne(cascade = {CascadeType.MERGE, CascadeType.REFRESH, CascadeType.REMOVE}, mappedBy = "loadBalancer")
    private SessionPersistence sessionPersistence;

    @OneToOne(cascade = {CascadeType.MERGE, CascadeType.REFRESH, CascadeType.REMOVE}, mappedBy = "loadBalancer")
    private ConnectionThrottle connectionThrottle;

    @OneToOne(cascade = {CascadeType.MERGE, CascadeType.REFRESH, CascadeType.REMOVE}, mappedBy = "loadBalancer")
    private HealthMonitor healthMonitor;

    @Transient
    private VirtualIpDozerWrapper virtualIpDozerWrapper;

    public LoadBalancer() {
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Set<LoadBalancerJoinVip> getLoadBalancerJoinVipSet() {
        if (loadBalancerJoinVipSet == null) loadBalancerJoinVipSet = new HashSet<LoadBalancerJoinVip>();
        return loadBalancerJoinVipSet;
    }

    public void setLoadBalancerJoinVipSet(Set<LoadBalancerJoinVip> loadBalancerJoinVipSet) {
        this.loadBalancerJoinVipSet = loadBalancerJoinVipSet;
    }

    public Set<Node> getNodes() {
        return nodes;
    }

    public void setNodes(Set<Node> nodes) {
        this.nodes = nodes;
    }

    public Set<UsageRecord> getUsageRecordSet() {
        return usage;
    }

    public void setUsage(Set<UsageRecord> usage) {
        this.usage = usage;
    }

    public HealthMonitor getHealthMonitor() {
        return healthMonitor;
    }

    public void setHealthMonitor(HealthMonitor healthMonitor) {
        this.healthMonitor = healthMonitor;
    }

    public ConnectionThrottle getConnectionThrottle() {
        return connectionThrottle;
    }

    public void setConnectionThrottle(ConnectionThrottle connectionThrottle) {
        this.connectionThrottle = connectionThrottle;
    }

    public Integer getAccountId() {
        return accountId;
    }

    public void setAccountId(Integer accountId) {
        this.accountId = accountId;
    }

    public Calendar getCreated() {
        return created;
    }

    public void setCreated(Calendar created) {
        this.created = created;
    }

    public Calendar getUpdated() {
        return updated;
    }

    public void setUpdated(Calendar updated) {
        this.updated = updated;
    }

    public String getAlgorithm() {
        return algorithm;
    }

    public void setAlgorithm(String algorithm) {
        this.algorithm = algorithm;
    }

    public String getProtocol() {
        return protocol;
    }

    public void setProtocol(String protocol) {
        this.protocol = protocol;
    }

    public Integer getPort() {
        return port;
    }

    public void setPort(Integer port) {
        this.port = port;
    }

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        if (!AtlasTypeHelper.isValidLoadBalancerStatus(status)) throw new RuntimeException("Load balancer status not supported.");
        this.status = status;
    }

    public Boolean isCreatedOnAdapter() {
        return created_on_adapter;
    }

    public void setCreatedOnAdapter(Boolean createdOnAdapter) {
        if (!AtlasTypeHelper.isValidLoadBalancerStatus(status)) throw new RuntimeException("Load balancer status not supported.");
        this.created_on_adapter = createdOnAdapter;
    }

    private static String valueOrNull(Object obj) {
        return obj == null ? "null" : obj.toString();
    }

    public boolean isUsingSsl() {
        return (protocol.equals(CoreProtocolType.HTTPS));
    }

    public void getIpv6Servicenet(String throwaway) {
    }

    public void setIpv6Public(String throwaway) {

    }

    public void setIpv4Servicenet(String throwaway) {
    }

    public void setIpv4Public(String throwaway) {
    }

    public VirtualIpDozerWrapper getVirtualIpDozerWrapper() {
        return new VirtualIpDozerWrapper(loadBalancerJoinVipSet);
    }

    public void setVirtualIpDozerWrapper(VirtualIpDozerWrapper virtualIpDozerWrapper) {
        this.virtualIpDozerWrapper = virtualIpDozerWrapper;
        this.setLoadBalancerJoinVipSet(this.virtualIpDozerWrapper.getLoadBalancerJoinVipSet());
    }

    public SessionPersistence getSessionPersistence() {
        return sessionPersistence;
    }

    public void setSessionPersistence(SessionPersistence sessionPersistence) {
        this.sessionPersistence = sessionPersistence;
    }
}


text:
package episode

import (
	"fmt"
	"net/http"

	"github.com/aerogo/aero"
	"github.com/animenotifier/notify.moe/arn"
	minio "github.com/minio/minio-go/v7"
)

// Subtitles returns the subtitles.
func Subtitles(ctx aero.Context) error {
	id := ctx.Get("id")
	language := ctx.Get("language")

	// Get episode
	episode, err := arn.GetEpisode(id)

	if err != nil {
		return ctx.Error(http.StatusNotFound, "Episode not found", err)
	}

	// Get anime
	anime := episode.Anime()

	if anime == nil {
		return ctx.Error(http.StatusNotFound, "Anime not found", err)
	}

	ctx.Response().SetHeader("Access-Control-Allow-Origin", "*")
	ctx.Response().SetHeader("Content-Type", "text/vtt; charset=utf-8")

	obj, err := arn.Spaces.GetObject(ctx.Request().Context(), "arn", fmt.Sprintf("videos/anime/%s/%d.%s.vtt", anime.ID, episode.Number, language), minio.GetObjectOptions{})

	if err != nil {
		return ctx.Error(http.StatusInternalServerError, err)
	}

	defer obj.Close()
	return ctx.ReadAll(obj)
}


text:
//
//  UIViewX.h
//
//  Copyright (c) 2014 Anthony Shoumikhin. All rights reserved under MIT license.
//  mailto:anthony@shoumikh.in
//

#import <UIKit/UIKit.h>

#ifndef CGVECTOR_DEFINED
#define CGVECTOR_DEFINED 1
typedef struct
{
    CGFloat dx;
    CGFloat dy;
} CGVector;

CG_INLINE CGVector
CGVectorMake(CGFloat dx, CGFloat dy)
{
    CGVector vector; vector.dx = dx; vector.dy = dy; return vector;
}
#endif

@interface UIView (X)

@property (nonatomic) CGFloat x;
@property (nonatomic) CGFloat y;
@property (nonatomic) CGPoint origin;

@property (nonatomic) CGFloat width;
@property (nonatomic) CGFloat height;
@property (nonatomic) CGSize size;

@property (nonatomic) CGFloat dx;
@property (nonatomic) CGFloat dy;
@property (nonatomic) CGVector bound;

/**
 Get a parent view controller.

 @return Parent view controller.
 */
- (UIViewController *)viewController;

/**
 Get a superview of specific class.

 @param aClass Specific class to search.
 @return Superview of class specified.
 */
- (UIView *)superviewOfClass:(Class)aClass;

/**
 Search through the view hierarchy starting from this view and resign the first responder, if found.

 @return YES, if the first responder was resigned, NO otherwise.
 */
- (BOOL)resignFirstResponderRecursively;

/**
 Move view to a new position with animaton.

 @param destination New coordinates for view's frame origin.
 @param duration Duration of animation in seconds.
 @param options Animation options.
 */
- (void)moveTo:(CGPoint)destination duration:(NSTimeInterval)duration options:(UIViewAnimationOptions)options;

@end


text:
class CScriptGameObject;

template <typename _object_type>
class CActionPlannerScript : public CScriptActionPlanner {
protected:
    using inherited = CScriptActionPlanner;

public:
    _object_type* m_object;

    CActionPlannerScript() : m_object(nullptr) {}
    virtual void setup(_object_type* object) {
        VERIFY(object);
        inherited::setup(object->lua_game_object());
        m_object = object;
    }
    _object_type& object() const {
        return *m_object;
    }
};


text:
class PersonReg {
private:
    Person *persons;
    const int maxSize;
    int size;
public:
    PersonReg(int maxSize);
    int addPerson(Person *p_person);
    void removePerson(Person *p_person);
    Person* findPerson(std::string name);
    Person* find(string search, Person* person);
    void print();
    ~PersonReg();
};

#endif //LAB3_PERSONREG_H


text:
@interface WBStatusToolBarButton ()

@property (nonatomic, weak) UIImageView *line;

@end

@implementation WBStatusToolBarButton

- (instancetype)init
{
    self = [super init];
    if (self) {
        UIImageView *line = [[UIImageView alloc] init];
        line.contentMode = UIViewContentModeCenter;
        line.image = [UIImage imageNamed:@"timeline_card_bottom_line"];
        [self addSubview:line];
        self.line = line;
    }
    return self;
}

- (void)layoutSubviews
{
    [super layoutSubviews];

    self.line.frame = CGRectMake(self.bounds.size.width, 0, 1, self.bounds.size.height);

}

@end


text:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml;

namespace Loader
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            if (GetCurrentVersion())
            {
                updateController1.UpdateInteractive(this);

                Process proc = new Process();
                proc.StartInfo.FileName = "CLL.exe";
                proc.Start();
            }

            Close();
        }

        private bool GetCurrentVersion()
        {
            bool result = true;

            try
            {
                using (XmlReader reader = XmlReader.Create("Version.xml"))
                {
                    reader.Read();
                    reader.ReadStartElement("AppVersion");
                    reader.ReadStartElement("version");
                    updateController1.Version = new Version(reader.ReadString());
                    reader.ReadEndElement();
                    reader.ReadEndElement();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                result = false;
            }

            return result;
        }
    }
}