text:
package com.apple.laf;

import java.awt.*;
import java.awt.event.*;
import java.lang.reflect.*;
import java.security.*;
import java.util.*;

import javax.swing.*;

public class ScreenMenuBar extends MenuBar implements ContainerListener, ScreenMenuPropertyHandler, ComponentListener {
    static boolean sJMenuBarHasHelpMenus = false; //$ could check by calling getHelpMenu in a try block

    JMenuBar fSwingBar;
    Hashtable<JMenu, ScreenMenu> fSubmenus;

    ScreenMenuPropertyListener fPropertyListener;
    ScreenMenuPropertyListener fAccessibleListener;

    public ScreenMenuBar(final JMenuBar swingBar) {
        fSwingBar = swingBar;
        fSubmenus = new Hashtable<JMenu, ScreenMenu>(fSwingBar.getMenuCount());
    }

    public void addNotify() {
        super.addNotify();

        fSwingBar.addContainerListener(this);
        fPropertyListener = new ScreenMenuPropertyListener(this);
        fSwingBar.addPropertyChangeListener(fPropertyListener);
        fAccessibleListener = new ScreenMenuPropertyListener(this);
        fSwingBar.getAccessibleContext().addPropertyChangeListener(fAccessibleListener);

        // We disable component events when the menu bar is not parented.  So now we need to
        // sync back up with the current state of the JMenuBar.  We first add the menus we
        // don't have and then remove the items that are no longer on the JMenuBar.
        final int count = fSwingBar.getMenuCount();
        for(int i = 0; i < count ; i++) {
            final JMenu m = fSwingBar.getMenu(i);
            if (m != null) {
                addSubmenu(m);
            }
        }

        final Enumeration<JMenu> e = fSubmenus.keys();
        while (e.hasMoreElements()) {
            final JMenu m = e.nextElement();
            if (fSwingBar.getComponentIndex(m) == -1) {
                removeSubmenu(m);
            }
        }
    }

    public void removeNotify() {
        // KCH - 3974930 - We do null checks for fSwingBar and fSubmenus because some people are using
        // reflection to muck about with our ivars
        if (fSwingBar != null) {
            fSwingBar.removePropertyChangeListener(fPropertyListener);
            fSwingBar.getAccessibleContext().removePropertyChangeListener(fAccessibleListener);
            fSwingBar.removeContainerListener(this);
        }

        fPropertyListener = null;
        fAccessibleListener = null;

        if (fSubmenus != null) {
            // We don't listen to events when the menu bar is not parented.
            // Remove all the component listeners.
            final Enumeration<JMenu> e = fSubmenus.keys();
            while (e.hasMoreElements()) {
                final JMenu m = e.nextElement();
                m.removeComponentListener(this);
            }
        }

        super.removeNotify();
    }

    /**
     * Invoked when a component has been added to the container.
     */
    public void componentAdded(final ContainerEvent e) {
        final Component child = e.getChild();
        if (!(child instanceof JMenu)) return;
            addSubmenu((JMenu)child);
     }

    /**
     * Invoked when a component has been removed from the container.
     */
    public void componentRemoved(final ContainerEvent e) {
          final Component child = e.getChild();
          if (!(child instanceof JMenu)) return;
            removeSubmenu((JMenu)child);
        }

    /**
        * Invoked when the component's size changes.
     */
    public void componentResized(final ComponentEvent e)  {}

    /**
        * Invoked when the component's position changes.
     */
    public void componentMoved(final ComponentEvent e)  {}

    /**
        * Invoked when the component has been made visible.
     * See componentHidden - we should still have a MenuItem
     * it just isn't inserted
     */
    public void componentShown(final ComponentEvent e) {
        final Object source = e.getSource();
        if (!(source instanceof JMenuItem)) return;
        setChildVisible((JMenuItem)source, true);
    }

    /**
        * Invoked when the component has been made invisible.
     * MenuComponent.setVisible does nothing,
     * so we remove the ScreenMenuItem from the ScreenMenu
     * but leave it in fItems
     */
    public void componentHidden(final ComponentEvent e)  {
        final Object source = e.getSource();
        if (!(source instanceof JMenuItem)) return;
        setChildVisible((JMenuItem)source, false);
    }

    /*
     * MenuComponent.setVisible does nothing,
     * so we just add or remove the child from the ScreenMenuBar
     * but leave it in the list
     */
    public void setChildVisible(final JMenuItem child, final boolean b) {
        if (child instanceof JMenu) {
            if (b) {
                addSubmenu((JMenu)child);
            } else {
                final ScreenMenu sm = fSubmenus.get(child);
                if (sm != null)
                    remove(sm);
            }
        }
    }

    public void removeAll() {
        synchronized (getTreeLock()) {
            final int nitems = getMenuCount();
            for (int i = nitems-1 ; i >= 0 ; i--) {
                remove(i);
            }
        }
    }

    public void setIcon(final Icon i) {}
    public void setLabel(final String s) {}

    public void setEnabled(final boolean b) {
        final int count = fSwingBar.getMenuCount();
        for (int i = 0; i < count; i++) {
            fSwingBar.getMenu(i).setEnabled(b);
        }
    }

    public void setAccelerator(final KeyStroke ks) {}
    public void setToolTipText(final String tooltip) {}

    // only check and radio items can be indeterminate
    public void setIndeterminate(boolean indeterminate) { }

    ScreenMenu addSubmenu(final JMenu m) {
        ScreenMenu sm = fSubmenus.get(m);

        if (sm == null) {
            sm = new ScreenMenu(m);
            m.addComponentListener(this);
            fSubmenus.put(m, sm);
        }

        sm.setEnabled(m.isEnabled());

        // MenuComponents don't support setVisible, so we just don't add it to the menubar
        if (m.isVisible() && sm.getParent() == null) {
            int newIndex = 0, currVisibleIndex = 0;
            JMenu menu = null;
            final int menuCount = fSwingBar.getMenuCount();
            for (int i = 0; i < menuCount; i++) {
                menu = fSwingBar.getMenu(i);
                if (menu == m) {
                    newIndex = currVisibleIndex;
                    break;
                }
                if (menu != null && menu.isVisible()) {
                    currVisibleIndex++;
                }
            }
            add(sm, newIndex);
        }

        return sm;
    }

    /**
     * Remove the screen menu associated with the specifiec menu.  This
     * also removes any associated component listener on the screen menu
     * and removes the key/value (menu/screen menu) from the fSubmenus cache.
     *
     * @param menu The swing menu we want to remove the screen menu for.
     */
    private void removeSubmenu(final JMenu menu) {
        final ScreenMenu screenMenu = fSubmenus.get(menu);
        if (screenMenu == null) return;

            menu.removeComponentListener(this);
            remove(screenMenu);
            fSubmenus.remove(menu);
    }

    private static Field[] stolenFields = null;

    static {
        stolenFields = AccessController.doPrivileged(new PrivilegedAction<Field[]>() {
            public Field[] run() {
                try {
                    final Field[] localFields = new Field[2];
                    localFields[0] = MenuBar.class.getDeclaredField("menus");
                    localFields[1] = MenuComponent.class.getDeclaredField("parent");
                    AccessibleObject.setAccessible(localFields, true);
                    return localFields;
                } catch (final NoSuchFieldException nsf) {
                    // If this happens, Sun changed the definition of MenuBar and MenuComponent!
                    nsf.printStackTrace(System.err);
                    return null;
                }
            }
        });
    };

    public Menu add(final Menu m, final int index) {
        synchronized (getTreeLock()) {
            if (m.getParent() != null) {
                m.getParent().remove(m);
            }

            // Use nasty reflection to get at the menus array and parent fields.
            try {
                if (stolenFields == null) return m;

                final Vector<Menu> menus = (Vector<Menu>)stolenFields[0].get(this);
                    menus.insertElementAt(m, index);

                    stolenFields[1].set(m, this);

                    final sun.lwawt.macosx.CMenuBar peer = (sun.lwawt.macosx.CMenuBar)getPeer();
                if (peer == null) return m;

                        peer.setNextInsertionIndex(index);
                        if (m.getPeer() == null) {
                            m.addNotify();
                        }

                        peer.setNextInsertionIndex(-1);
            } catch (final IllegalAccessException iae) {
                iae.printStackTrace(System.err);
            }

            return m;
        }
    }
}


text:
Use this API in the `app.js` file that you process by browserify and run in the browser.

```js
var loopback = require('loopback');
var boot = require('loopback-boot');

var app = module.exports = loopback();
boot(app);
```

redpajama_set_name: RedPajamaGithub


text:
/* Code generated by IfcQuery EXPRESS generator, www.ifcquery.com */

#pragma once
#include <vector>
#include <map>
#include <sstream>
#include <string>
#include "ifcpp/model/GlobalDefines.h"
#include "ifcpp/model/BasicTypes.h"
#include "ifcpp/model/BuildingObject.h"

// TYPE IfcElectricTimeControlTypeEnum = ENUMERATION OF	(TIMECLOCK	,TIMEDELAY	,RELAY	,USERDEFINED	,NOTDEFINED);
class IFCQUERY_EXPORT IfcElectricTimeControlTypeEnum : virtual public BuildingObject
{
public:
	enum IfcElectricTimeControlTypeEnumEnum
	{
		ENUM_TIMECLOCK,
		ENUM_TIMEDELAY,
		ENUM_RELAY,
		ENUM_USERDEFINED,
		ENUM_NOTDEFINED
	};

	IfcElectricTimeControlTypeEnum() = default;
	IfcElectricTimeControlTypeEnum( IfcElectricTimeControlTypeEnumEnum e ) { m_enum = e; }
	~IfcElectricTimeControlTypeEnum() = default;
	virtual const char* className() const { return "IfcElectricTimeControlTypeEnum"; }
	virtual shared_ptr<BuildingObject> getDeepCopy( BuildingCopyOptions& options );
	virtual void getStepParameter( std::stringstream& stream, bool is_select_type = false ) const;
	virtual const std::wstring toString() const;
	static shared_ptr<IfcElectricTimeControlTypeEnum> createObjectFromSTEP( const std::wstring& arg, const std::map<int,shared_ptr<BuildingEntity> >& map );
	IfcElectricTimeControlTypeEnumEnum m_enum;
};


text:
namespace ConfigInjector.Infrastructure.SettingsOverriders
{
    public interface ISettingsOverrider
    {
        bool TryFindOverrideFor(string key, out string value);
    }
}


text:
"""The tests for the MQTT roller shutter platform."""
import unittest

from blumate.bootstrap import _setup_component
from blumate.const import STATE_OPEN, STATE_CLOSED, STATE_UNKNOWN
import blumate.components.rollershutter as rollershutter
from tests.common import mock_mqtt_component, fire_mqtt_message

from tests.common import get_test_home_assistant

class TestRollershutterMQTT(unittest.TestCase):
    """Test the MQTT roller shutter."""

    def setUp(self):  # pylint: disable=invalid-name
        """Setup things to be run when tests are started."""
        self.hass = get_test_home_assistant()
        self.mock_publish = mock_mqtt_component(self.hass)

    def tearDown(self):  # pylint: disable=invalid-name
        """Stop down everything that was started."""
        self.hass.stop()

    def test_controlling_state_via_topic(self):
        """Test the controlling state via topic."""
        self.hass.config.components = ['mqtt']
        assert _setup_component(self.hass, rollershutter.DOMAIN, {
            rollershutter.DOMAIN: {
                'platform': 'mqtt',
                'name': 'test',
                'state_topic': 'state-topic',
                'command_topic': 'command-topic',
                'qos': 0,
                'payload_up': 'UP',
                'payload_down': 'DOWN',
                'payload_stop': 'STOP'
            }
        })

        state = self.hass.states.get('rollershutter.test')
        self.assertEqual(STATE_UNKNOWN, state.state)

        fire_mqtt_message(self.hass, 'state-topic', '0')
        self.hass.pool.block_till_done()

        state = self.hass.states.get('rollershutter.test')
        self.assertEqual(STATE_CLOSED, state.state)

        fire_mqtt_message(self.hass, 'state-topic', '50')
        self.hass.pool.block_till_done()

        state = self.hass.states.get('rollershutter.test')
        self.assertEqual(STATE_OPEN, state.state)

        fire_mqtt_message(self.hass, 'state-topic', '100')
        self.hass.pool.block_till_done()

        state = self.hass.states.get('rollershutter.test')
        self.assertEqual(STATE_OPEN, state.state)

    def test_send_move_up_command(self):
        """Test the sending of move_up."""
        self.hass.config.components = ['mqtt']
        assert _setup_component(self.hass, rollershutter.DOMAIN, {
            rollershutter.DOMAIN: {
                'platform': 'mqtt',
                'name': 'test',
                'state_topic': 'state-topic',
                'command_topic': 'command-topic',
                'qos': 2
            }
        })

        state = self.hass.states.get('rollershutter.test')
        self.assertEqual(STATE_UNKNOWN, state.state)

        rollershutter.move_up(self.hass, 'rollershutter.test')
        self.hass.pool.block_till_done()

        self.assertEqual(('command-topic', 'UP', 2, False),
                         self.mock_publish.mock_calls[-1][1])
        state = self.hass.states.get('rollershutter.test')
        self.assertEqual(STATE_UNKNOWN, state.state)

    def test_send_move_down_command(self):
        """Test the sending of move_down."""
        self.hass.config.components = ['mqtt']
        assert _setup_component(self.hass, rollershutter.DOMAIN, {
            rollershutter.DOMAIN: {
                'platform': 'mqtt',
                'name': 'test',
                'state_topic': 'state-topic',
                'command_topic': 'command-topic',
                'qos': 2
            }
        })

        state = self.hass.states.get('rollershutter.test')
        self.assertEqual(STATE_UNKNOWN, state.state)

        rollershutter.move_down(self.hass, 'rollershutter.test')
        self.hass.pool.block_till_done()

        self.assertEqual(('command-topic', 'DOWN', 2, False),
                         self.mock_publish.mock_calls[-1][1])
        state = self.hass.states.get('rollershutter.test')
        self.assertEqual(STATE_UNKNOWN, state.state)

    def test_send_stop_command(self):
        """Test the sending of stop."""
        self.hass.config.components = ['mqtt']
        assert _setup_component(self.hass, rollershutter.DOMAIN, {
            rollershutter.DOMAIN: {
                'platform': 'mqtt',
                'name': 'test',
                'state_topic': 'state-topic',
                'command_topic': 'command-topic',
                'qos': 2
            }
        })

        state = self.hass.states.get('rollershutter.test')
        self.assertEqual(STATE_UNKNOWN, state.state)

        rollershutter.stop(self.hass, 'rollershutter.test')
        self.hass.pool.block_till_done()

        self.assertEqual(('command-topic', 'STOP', 2, False),
                         self.mock_publish.mock_calls[-1][1])
        state = self.hass.states.get('rollershutter.test')
        self.assertEqual(STATE_UNKNOWN, state.state)

    def test_state_attributes_current_position(self):
        """Test the current position."""
        self.hass.config.components = ['mqtt']
        assert _setup_component(self.hass, rollershutter.DOMAIN, {
            rollershutter.DOMAIN: {
                'platform': 'mqtt',
                'name': 'test',
                'state_topic': 'state-topic',
                'command_topic': 'command-topic',
                'payload_up': 'UP',
                'payload_down': 'DOWN',
                'payload_stop': 'STOP'
            }
        })

        state_attributes_dict = self.hass.states.get(
            'rollershutter.test').attributes
        self.assertFalse('current_position' in state_attributes_dict)

        fire_mqtt_message(self.hass, 'state-topic', '0')
        self.hass.pool.block_till_done()
        current_position = self.hass.states.get(
            'rollershutter.test').attributes['current_position']
        self.assertEqual(0, current_position)

        fire_mqtt_message(self.hass, 'state-topic', '50')
        self.hass.pool.block_till_done()
        current_position = self.hass.states.get(
            'rollershutter.test').attributes['current_position']
        self.assertEqual(50, current_position)

        fire_mqtt_message(self.hass, 'state-topic', '101')
        self.hass.pool.block_till_done()
        current_position = self.hass.states.get(
            'rollershutter.test').attributes['current_position']
        self.assertEqual(50, current_position)

        fire_mqtt_message(self.hass, 'state-topic', 'non-numeric')
        self.hass.pool.block_till_done()
        current_position = self.hass.states.get(
            'rollershutter.test').attributes['current_position']
        self.assertEqual(50, current_position)


text:
@interface ALBBOpenAccountLoginViewController : ALBBOpenAccountBaseController
@property (assign, nonatomic) BOOL isNeedBackButtonHidden;

//预留的外挂引用
@property (nonatomic, strong) IBOutletCollection(NSObject)  NSArray *outletCollection;

// wrapper
@property (weak, nonatomic) IBOutlet ALBBOpenAccountWrapperView *wrapperView;
// form
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *heightOfFormView;

//locale
@property (weak, nonatomic) IBOutlet UILabel *prefixLabel;
@property (weak, nonatomic) IBOutlet UIButton *prefixIcon;
// username
@property (weak, nonatomic) IBOutlet UILabel *usernameLabel;
@property (weak, nonatomic) IBOutlet UITextField *usernameField;
@property (weak, nonatomic) IBOutlet UIButton *historyButton;
@property (weak, nonatomic) IBOutlet UITableView *historyView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *heightOfHistoryView;
// password
@property (weak, nonatomic) IBOutlet UIView *passwordView;
@property (weak, nonatomic) IBOutlet UILabel *passwordLabel;
@property (weak, nonatomic) IBOutlet UITextField *passwordField;
@property (weak, nonatomic) IBOutlet UIButton *visibleButton;
// checkcode
@property (weak, nonatomic) IBOutlet UIView *checkcodeView;
@property (weak, nonatomic) IBOutlet UILabel *checkcodeLabel;
@property (weak, nonatomic) IBOutlet UITextField *checkcodeField;
@property (weak, nonatomic) IBOutlet UIImageView *checkcodeImageView;
@property (weak, nonatomic) IBOutlet UIButton *refreshButton;
// control
@property (weak, nonatomic) IBOutlet UIButton *submitButton;

- (IBAction)submitLogin;
// 前往国家列表
- (IBAction)prefixNumberChoose:(id)sender;

// sso
- (IBAction)taobaoSSO:(id)sender;
- (IBAction)weChatSSO:(id)sender;
- (IBAction)weiBoSSO:(id)sender;
- (IBAction)qqSSO:(id)sender;
@end


text:
package com.example;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class PentahoServlet1 extends HttpServlet
{

  @Override
  public void doGet(
    HttpServletRequest request,
    HttpServletResponse response)
    throws ServletException, IOException
  {

    doPost(request, response);

  }

  @Override
  public void doPost(
    HttpServletRequest request,
    HttpServletResponse response)
    throws ServletException, IOException
  {

    PrintWriter out = response.getWriter();
    out.println("PentahoServlet Executed");
    out.flush();
    out.close();

  }
}


text:
druap-system
============

system directory of durap framework

https://github.com/doujiang24/durap


text:
// |reftest| pref(javascript.options.xml.content,true)
/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

var summary = "11.1.4 - XML Initializer - Comment hiding parsing/scanning";
var BUGNUMBER = 311157;
var actual;
var expect;

printBugNumber(BUGNUMBER);
START(summary);

var x = <hi> <!-- duh -->
    there </hi>;

actual = x.toString();
expect = '\n    there ';

TEST(1, expect, actual);

END();


text:
@interface ExampleModel : JSONModel
@property (assign ,nonatomic) int code;
@property (strong ,nonatomic) NSString *message;
@end


text:
package resources

import (
	"testing"

	"github.com/google/kf/v2/pkg/apis/kf/v1alpha1"
	"github.com/google/kf/v2/pkg/kf/testutil"
	corev1 "k8s.io/api/core/v1"
	osbclient "sigs.k8s.io/go-open-service-broker-client/v2"
)

func fakeServiceInstance() *v1alpha1.ServiceInstance {
	instance := &v1alpha1.ServiceInstance{}
	instance.Name = "mydb"
	instance.Namespace = "test-ns"
	instance.UID = "00000000-0000-0000-0000-000008675309"
	instance.Spec.OSB = &v1alpha1.OSBInstance{
		ClassUID: "class-uid",
		PlanUID:  "plan-uid",
	}

	return instance
}

func TestMakeOSBDeprovisionRequest(t *testing.T) {
	t.Parallel()

	cases := map[string]struct {
		serviceInstance *v1alpha1.ServiceInstance
	}{
		"good": {
			serviceInstance: fakeServiceInstance(),
		},
	}

	for tn, tc := range cases {
		t.Run(tn, func(t *testing.T) {
			req := MakeOSBDeprovisionRequest(tc.serviceInstance)

			testutil.AssertGoldenJSONContext(t, "OSBDeprovisionRequest", req, map[string]interface{}{
				"serviceInstance": tc.serviceInstance,
			})
		})
	}
}

func TestMakeOSBLastOperationRequest(t *testing.T) {
	t.Parallel()

	exampleKey := "some-long-running-operation-key"

	cases := map[string]struct {
		serviceInstance *v1alpha1.ServiceInstance
		operationKey    *string
	}{
		"nil key": {
			serviceInstance: fakeServiceInstance(),
			operationKey:    nil,
		},
		"populated key": {
			serviceInstance: fakeServiceInstance(),
			operationKey:    &exampleKey,
		},
	}

	for tn, tc := range cases {
		t.Run(tn, func(t *testing.T) {
			req := MakeOSBLastOperationRequest(tc.serviceInstance, tc.operationKey)

			testutil.AssertGoldenJSONContext(t, "OSBLastOperationRequest", req, map[string]interface{}{
				"serviceInstance": tc.serviceInstance,
				"operationKey":    tc.operationKey,
			})
		})
	}
}

func TestMakeOSBProvisionRequest(t *testing.T) {
	t.Parallel()

	goodNamespace := &corev1.Namespace{}
	goodNamespace.Name = "some-ns"
	goodNamespace.UID = "11111111-1111-1111-1111-111111111111"

	goodSecret := &corev1.Secret{}
	goodSecret.Data = map[string][]byte{
		v1alpha1.ServiceInstanceParamsSecretKey: []byte(`{"foo":"bar"}`),
	}

	cases := map[string]struct {
		serviceInstance *v1alpha1.ServiceInstance
		namespace       *corev1.Namespace
		paramsSecret    *corev1.Secret

		// NOTE: check for the invariant rather than specific error strings.
		wantErr bool
	}{
		"missing serviceInstance": {
			serviceInstance: nil,
			namespace:       goodNamespace,
			paramsSecret:    goodSecret,
			wantErr:         true,
		},
		"missing namespace": {
			serviceInstance: fakeServiceInstance(),
			namespace:       nil,
			paramsSecret:    goodSecret,
			wantErr:         true,
		},
		"missing secret": {
			serviceInstance: fakeServiceInstance(),
			namespace:       goodNamespace,
			paramsSecret:    nil,
			wantErr:         true,
		},
		"blank secret": {
			serviceInstance: fakeServiceInstance(),
			namespace:       goodNamespace,
			paramsSecret:    &corev1.Secret{},
			wantErr:         true,
		},
		"bad json secret": {
			serviceInstance: fakeServiceInstance(),
			namespace:       goodNamespace,
			paramsSecret: &corev1.Secret{
				Data: map[string][]byte{
					v1alpha1.ServiceInstanceParamsSecretKey: []byte(`{[]}`),
				},
			},
			wantErr: true,
		},
		"good": {
			serviceInstance: fakeServiceInstance(),
			namespace:       goodNamespace,
			paramsSecret:    goodSecret,
		},
	}

	for tn, tc := range cases {
		t.Run(tn, func(t *testing.T) {
			req, err := MakeOSBProvisionRequest(
				tc.serviceInstance,
				tc.namespace,
				tc.paramsSecret,
			)

			if err != nil {
				// either request or err is nil
				testutil.AssertEqual(t, "request", (*osbclient.ProvisionRequest)(nil), req)
				testutil.AssertTrue(t, "wantErr", tc.wantErr)
			} else {
				testutil.AssertNotNil(t, "request", req) // either request or err is nil
				testutil.AssertGoldenJSONContext(t, "OSBProvisionRequest", req, map[string]interface{}{
					"serviceInstance": tc.serviceInstance,
					"namespace":       tc.namespace,
					"paramsSecret":    tc.paramsSecret,
				})
			}
		})
	}
}


text:
const symbol = {
  isClosed: Symbol('Whether the stream is closed'),
  isOpen: Symbol('Whether the stream is open'),
  callbacks: Symbol('Event callback list'),
  dispose: Symbol('Free stream resources'),
  observe: Symbol('Force the stream open'),
  resolve: Symbol('Completes the stream'),
  openStream: Symbol('Stream publisher'),
  complete: Symbol('Close the stream'),
  handler: Symbol('Stream callback'),
  push: Symbol('Publish a message'),
};

/**
 * References a callback subscription.
 * @class Subscription
 */
class Subscription {
  /**
   * @param  {Stream} stream - Current stream context.
   * @param  {Function} callback - The subscribed function.
   */
  constructor(stream, callback) {
    this[symbol.handler] = callback;
    this.stream = stream;
  }

  /**
   * Unsubscribes the callback.
   * @return {undefined}
   */
  dispose() {
    const { stream } = this;

    // Remove the listener.
    const filtered = this.stream[symbol.callbacks].filter(
      callback => callback !== this[symbol.handler]
    );

    stream[symbol.callbacks] = filtered;

    // The last listener unsubscribed.
    if (!filtered.length) {
      stream[symbol.isOpen] = false;

      if (stream[symbol.dispose]) {
        stream[symbol.dispose]();
      }
    }
  }
}

/**
 * Lazy, asynchronous, cacheless streams.
 * @class Stream
 */
export default class Stream {
  /**
   * Constructs a new Stream instance, `new` optional.
   * @param  {Function} publisher - Stream publisher.
   * @return {Stream} - The new stream instance.
   */
  static create(publisher) {
    return new Stream(publisher);
  }

  /**
   * Creates a stream from an event source.
   * @param  {EventEmitter} emitter
   * Really anything that looks like an event emitter.
   * @param  {String} event - The event name.
   * @return {Stream} - An event stream.
   */
  static fromEvent(emitter, event) {
    return new Stream(push => {
      const add = emitter.on || emitter.addEventListener;
      add.call(emitter, event, push);

      return () => {
        const remove = emitter.removeListener || emitter.removeEventListener;

        remove.call(emitter, event, push);
      };
    });
  }

  /**
   * Resolves when the stream closes.
   * @type {Promise}
   */
  complete = new Promise(res => {
    this[symbol.resolve] = res;
  });

  /**
   * @param {Function} publisher - Used to generate consumable data.
   */
  constructor(publisher) {
    if (!(publisher instanceof Function)) {
      throw new TypeError(
        `Stream(...) expects a function, was given "${publisher}"`
      );
    }

    this[symbol.openStream] = publisher;
    this[symbol.callbacks] = [];
  }

  /**
   * Subscribes to the event stream.
   * @param  {Function} callback - Invoked for every event.
   * @return {stream} - The current stream.
   */
  forEach(callback) {
    this[symbol.callbacks].push(callback);

    this[symbol.observe]();

    return new Subscription(this, callback);
  }

  /**
   * Pushes a new message.
   * @private
   * @throws {Error} - If given a value after the stream is closed.
   * @param  {any} message - A message in the stream.
   * @param  {any} [sender] - The producer instance.
   * @return {undefined}
   */
  [symbol.push] = (message, sender) => {
    if (this[symbol.isClosed]) {
      throw new Error('Cannot emit values after stream is closed.');
    }

    this[symbol.callbacks].forEach(callback => {
      callback(message, sender);
    });
  };

  /**
   * Terminates the stream permanently.
   * @private
   * @throws {Error} - If complete is called twice.
   * @return {undefined}
   */
  [symbol.complete] = () => {
    if (this[symbol.isClosed]) {
      throw new Error('Cannot close stream twice.');
    }

    this[symbol.isClosed] = true;
    this[symbol.callbacks] = [];
    this[symbol.resolve]();
  };

  /**
   * Forces the stream open.
   * @private
   * @return {undefined}
   */
  [symbol.observe]() {
    if (this[symbol.isOpen]) {
      return;
    }

    this[symbol.dispose] = this[symbol.openStream](
      this[symbol.push],
      this[symbol.complete]
    );

    this[symbol.isOpen] = true;
  }
}


text:
package fr.behindtheshell.multicastnetwork;

import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Collections;

public class NetworkInterfaceList extends ArrayList<NetworkInterface> {

    public NetworkInterfaceList() throws SocketException {
        for (NetworkInterface iface : Collections.list(NetworkInterface.getNetworkInterfaces())) {
            if (!iface.isLoopback() && !iface.isVirtual() && iface.isUp() && iface.supportsMulticast()) {
                add(iface);
            }
        }
    }
}


text:
		<?php dynamic_sidebar("Footer"); ?>

			<?php wp_nav_menu(array('theme_location' => 'utility', 'container' => false, 'menu_class' => 'inline-list')); ?>

© <?php echo date('Y'); ?> <?php bloginfo('name'); ?>

<?php wp_footer(); ?>
<?php basement_footer(); ?>


text:
function dashboard() {
    var width = $( document ).width();
    var height = $( document ).height();

    var heightTopics = height-410;
    var heightRPC = height-150;
    var heightTopicList = heightTopics*(40/100);

    $('#box-topic-flow').height(heightTopics*(60/100));
    $('#box-topic-list').height(heightTopicList);

    $('#box-rpc-list').height(heightRPC);
    $('#box-session-list').height(heightRPC);

    $('#clear-listener').css('top', heightTopicList+115);

    // Popups //
    $('#addTopic').css('top', (height-$('#addTopic').height())/2);
    $('#addTopic').css('left', (width-$('#addTopic').width())/2);

    $('#pubTopic').css('top', (height-$('#pubTopic').height())/2);
    $('#pubTopic').css('left', (width-$('#pubTopic').width())/2);

    $('#rpc-popup').css('top', (height-$('#rpc-popup').height())/2);
    $('#rpc-popup').css('left', (width-$('#rpc-popup').width())/2);
}


text:
// Copyright 2016 Mark Raasveldt
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Tibialyzer {
    static class HelperFunctions {
        public static bool isDigit(this char c) {
            return c >= '0' && c <= '9';
        }

        public static bool Contains(this byte[] array, int start, int length, string text) {
            for (int i = start; i < start + length; i++) {
                for (int j = 0; j < text.Length; j++) {
                    if (text[j] != array[i + j]) {
                        break;
                    }

                    if (j == text.Length - 1) {
                        return true;
                    }
                }
            }

            return false;
        }

        public static string ToTitle(this string str) {
            return System.Threading.Thread.CurrentThread.CurrentCulture.TextInfo.ToTitleCase(str);
        }

        public static bool Contains(this string s, string text, StringComparison stringComparison) {
            return s.IndexOf(text, stringComparison) > -1;
        }

        public static int IndexOf(this string[] s, string text) {
            for (int i = 0; i < s.Length; i++) {
                if (s[i] != null && s[i].Equals(text, StringComparison.InvariantCultureIgnoreCase)) {
                    return i;
                }
            }
            return -1;
        }

        public static float ClampPercentage(this float percentage) {
            if (float.IsNaN(percentage) || float.IsInfinity(percentage)) return 1;
            return Math.Min(Math.Max(percentage, 0), 1);
        }
        public static double ClampPercentage(this double percentage) {
            if (double.IsNaN(percentage) || double.IsInfinity(percentage)) return 1;
            return Math.Min(Math.Max(percentage, 0), 1);
        }

        public static Bitmap ToGrayscale(this Bitmap original) {
            //create a blank bitmap the same size as original
            Bitmap newBitmap = new Bitmap(original.Width, original.Height);

            //get a graphics object from the new image
            Graphics g = Graphics.FromImage(newBitmap);

            //create the grayscale ColorMatrix
            ColorMatrix colorMatrix = new ColorMatrix(
               new float[][]
               {
         new float[] {.3f, .3f, .3f, 0, 0},
         new float[] {.59f, .59f, .59f, 0, 0},
         new float[] {.11f, .11f, .11f, 0, 0},
         new float[] {0, 0, 0, 1, 0},
         new float[] {0, 0, 0, 0, 1}
               });

            //create some image attributes
            ImageAttributes attributes = new ImageAttributes();

            //set the color matrix attribute
            attributes.SetColorMatrix(colorMatrix);

            //draw the original image on the new image
            //using the grayscale color matrix
            g.DrawImage(original, new Rectangle(0, 0, original.Width, original.Height),
               0, 0, original.Width, original.Height, GraphicsUnit.Pixel, attributes);

            //dispose the Graphics object
            g.Dispose();
            return newBitmap;
        }

        public static Bitmap ToGrayscale(this Image original) {
            if (original is Bitmap) {
                return (original as Bitmap).ToGrayscale();
            }
            Bitmap bitmap = new Bitmap(original);
            Bitmap grayscale = bitmap.ToGrayscale();
            bitmap.Dispose();
            return grayscale;
        }

        public static Bitmap Clamp(this Bitmap original) {
            int minx = original.Width, miny = original.Height, maxx = 0, maxy = 0;
            for(int x = 0; x < original.Width; x++) {
                for(int y = 0; y < original.Height; y++) {
                    if (original.GetPixel(x, y).A > 0) {
                        if (x < minx) minx = x;
                        if (x > maxx) maxx = x;
                        if (y < miny) miny = y;
                        if (y > maxy) maxy = y;
                    }
                }
            }
            if (minx >= maxx || miny >= maxy) {
                return new Bitmap(original);
            } else {
                Bitmap bitmap = new Bitmap(maxx - minx, maxy - miny);
                using(Graphics gr = Graphics.FromImage(bitmap)) {
                    gr.DrawImage(original, new Rectangle(0, 0, bitmap.Width, bitmap.Height), new Rectangle(minx, miny, bitmap.Width, bitmap.Height), GraphicsUnit.Pixel);
                }
                return bitmap;
            }
        }

    }
}


text:
version = "0.1"
authors = ("Peter Stroia-Williams", '')
copyright = "© 2010"
comments = "A somewhat messily coded but functional match viewer."

import matchviewcanvas

import pygtk
pygtk.require("2.0")
import gtk
import os
import sys

class MatchViewerApp(object):

    matchListFN = None

    def on_window_destroy(self, widget) :
        gtk.main_quit()
        return True

    def saveProject(self) :
        projFile = open(self.projFN, "w")
        projDir = os.path.dirname(self.projFN)
        projFile.write(os.path.relpath(self.im1widgetHandler.imageFilename,projDir) + '\n')
        projFile.write(os.path.relpath(self.im2widgetHandler.imageFilename,projDir) + '\n')
        projFile.write(os.path.relpath(self.matchListFN,projDir) + '\n')
        if self.rowColRadioButton.get_active() :
            projFile.write("row col format\n")
        else :
            projFile.write("xy format\n")
        projFile.close()

    def openProject(self) :
        projFile = open(self.projFN, "r")
        projDir = os.path.dirname(self.projFN)

        line1 = projFile.readline()
        line2 = projFile.readline()
        line3 = projFile.readline()
        line4 = projFile.readline()

        projFile.close()

        self.im1widgetHandler.set_image_file(os.path.normpath(projDir + '/' + line1.strip()))
        self.im2widgetHandler.set_image_file(os.path.normpath(projDir + '/' + line2.strip()))

        matchListFN = os.path.normpath(projDir + '/' + line3.strip())

        if line4 == "row col format\n" :
            self.rowColRadioButton.set_active(True)
            self.xyRadioButton.set_active(False)
        else :
            self.rowColRadioButton.set_active(False)
            self.xyRadioButton.set_active(True)

        self.loadMatchList(matchListFN)

        self.builder.get_object("im1chooserbutton").set_filename(self.im1widgetHandler.imageFilename)
        self.builder.get_object("im2chooserbutton").set_filename(self.im2widgetHandler.imageFilename)
        self.builder.get_object("matchlistchooserbutton4").set_filename(matchListFN)

    def on_swapImages_menuitem_activate(self, widget) :
        tempImFN = self.im1widgetHandler.imageFilename
        self.im1widgetHandler.set_image_file(self.im2widgetHandler.imageFilename)
        self.im2widgetHandler.imageFilename = tempImFN

        self.builder.get_object("im1chooserbutton").set_filename(self.im1widgetHandler.imageFilename)
        self.builder.get_object("im2chooserbutton").set_filename(self.im2widgetHandler.imageFilename)

        self.redrawManager.force_redraw_all()

    def on_new_menuitem_activate(self, widget) :
        self.openWindow.show()

    def on_open_menuitem_activate(self, widget) :
        dialog = gtk.FileChooserDialog("Open Project", None, gtk.FILE_CHOOSER_ACTION_OPEN,
                                       (gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL,
                                        gtk.STOCK_OPEN, gtk.RESPONSE_OK))
        dialog.set_default_response(gtk.RESPONSE_OK)

        response = dialog.run()
        if response == gtk.RESPONSE_OK:
            self.projFN = dialog.get_filename()
            print dialog.get_filename(), 'selected'
            self.openProject()

        elif response == gtk.RESPONSE_CANCEL:
            print 'Closed, no files selected'
        dialog.hide()

    def on_saveAsMenuItem_activate(self, widget) :
        dialog = gtk.FileChooserDialog("Save Project As", None, gtk.FILE_CHOOSER_ACTION_SAVE,
                                       (gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL,
                                        gtk.STOCK_SAVE, gtk.RESPONSE_OK))
        dialog.set_default_response(gtk.RESPONSE_OK)
        dialog.set_do_overwrite_confirmation(True)

        response = dialog.run()
        if response == gtk.RESPONSE_OK:
            self.projFN = dialog.get_filename()

            self.saveProject()
        elif response == gtk.RESPONSE_CANCEL:
            print 'Closed, no files selected'
        dialog.hide()

    def on_saveMenuItem_activate(self, widget) :
        if self.projFN == None :
            self.on_saveAsMenuItem_activate(widget)
        else :
            self.saveProject()

    def on_openWindow_delete_event(self, widget, event = None) :
        self.openWindow.hide()
        return True
    def on_saveAsDialog_delete_event(self, widget, event = None) :
        self.saveAsDialog.hide()
        return True

    def loadMatchList(self, filename) :
        self.matchListFN = filename
        self.pointList1 = []
        matchListFile = open(self.matchListFN)
        matchList = []
        for line in matchListFile :
            matchList.append(line)

        pointList1, pointList2 = matchviewcanvas.loadMatchList(filename)

        self.im1widgetHandler.set_point_list(pointList1)
        self.im2widgetHandler.set_point_list(pointList2)

        self.redrawManager.force_redraw_all()

    def on_matchlistchooserbutton4_file_set(self, widget) :
        self.loadMatchList(widget.get_filename())

    def on_rowCol_radiobutton_toggled(self, widget, data=None) :
        if(self.matchListFN):
            self.loadMatchList(self.matchListFN)

    def on_numbermatchesmenuitem_toggled(self, widget) :
        self.im1widgetHandler.showNumbers = self.im2widgetHandler.showNumbers = widget.get_active()
        self.redrawManager.force_redraw_all()

    def on_aboutMenuItem_activate(self, widget) :
        dialog = gtk.AboutDialog()
        dialog.set_name("MatchViewer")
        dialog.set_version(version)
        dialog.set_authors(authors)
        dialog.set_copyright(copyright)
        dialog.set_comments(comments)

        dialog.run()
        dialog.destroy()

    def getGladeFilename(self):
        dir = os.path.dirname(__file__)
        print dir
        return os.path.join(dir, "MatchViewer.glade")

    def __init__(self):
        self.builder = gtk.Builder()
        self.builder.add_from_file(self.getGladeFilename())

        drawArea1 = self.builder.get_object("im1DrawingArea")
        drawArea2 = self.builder.get_object("im2DrawingArea")

        self.redrawManager = matchviewcanvas.RedrawManager([drawArea1, drawArea2])

        self.im1widgetHandler = matchviewcanvas.CairoImageWidgetEventHandler(drawArea1, self.redrawManager)
        self.im2widgetHandler = matchviewcanvas.CairoImageWidgetEventHandler(drawArea2, self.redrawManager)

        self.builder.connect_signals({ "on_window_destroy"              : self.on_window_destroy,
                                       "on_new_menuItem_activate" : self.on_new_menuitem_activate,
                                       "on_openWindow_delete_event" : self.on_openWindow_delete_event,
                                       "on_openWindowCloseButton_clicked" : self.on_openWindow_delete_event,
                                       "on_im1chooserbutton_file_set" : self.im1widgetHandler.on_file_set,
                                       "on_im2chooserbutton_file_set" : self.im2widgetHandler.on_file_set,
                                       "on_matchlistchooserbutton4_file_set" : self.on_matchlistchooserbutton4_file_set,
                                       "on_numbermatchesmenuitem_toggled" : self.on_numbermatchesmenuitem_toggled,
                                       "on_saveAsMenuItem_activate"       : self.on_saveAsMenuItem_activate,
                                       "on_saveAsDialog_delete_event" : self.on_saveAsDialog_delete_event,
                                       "on_saveMenuItem_activate" : self.on_saveMenuItem_activate,
                                       "on_open_menuitem_activate" : self.on_open_menuitem_activate,
                                       "on_aboutMenuItem_activate" : self.on_aboutMenuItem_activate,
                                       "on_rowCol_radiobutton_toggled" : self.on_rowCol_radiobutton_toggled,
                                       "on_swapImages_menuitem_activate" : self.on_swapImages_menuitem_activate
                                      })
        self.window = self.builder.get_object("window")
        self.window.show()

        self.openWindow = self.builder.get_object("openWindow")

        self.rowColRadioButton = self.builder.get_object("rowCol_radiobutton")
        self.xyRadioButton = self.builder.get_object("xy_radiobutton")

        self.rowColRadioButton.set_active(True)
        self.xyRadioButton.set_active(False)

        self.projFN = None

        if len(sys.argv) == 2 :
            self.projFN = sys.argv[1]
            if not os.path.isabs(self.projFN) :
                self.projFN = os.path.abspath(self.projFN)
            self.openProject()

if __name__ == "__main__":
#  pos = 10, 20
#  elipParams = 1, 20, 16
#  eliplse = Elipse(pos,elipParams)
    app = MatchViewerApp()
    gtk.main()


text:
const StraightQuestions = [
	{
		"id": 1,
		"question": "Would you go out for a movie on saturday night ?",
	},
	{
		"id": 2,
        "question": "Are you messy ?",
	},
	{
		"id": 3,
        "question": "Have you cheated anyone ?",
	},
	{
		"id": 4,
        "question": "Looking for a long term relationship ?",
	},
	{
		"id": 5,
        "question": "Netflix and chill ?",
	}

];

const LesbianQuestions = [
	{
		"id": 1,
		"question": "Would you go out for a movie on saturday night ?",
	},
	{
		"id": 2,
		"question": "Would you go out for a movie on saturday night ?",
	},
	{
		"id": 3,
		"question": "Would you go out for a movie on saturday night ?",
	},
	{
		"id": 3,
		"question": "Would you go out for a movie on saturday night ?",
	},
	{
		"id": 4,
		"question": "Would you go out for a movie on saturday night ?",
	}
];

const GayQuestions = [
	{
		"id": 1,
		"question": "Would you go out for a movie on saturday night ?",
	},
	{
		"id": 2,
		"question": "Would you go out for a movie on saturday night ?",
	},
	{
		"id": 3,
		"question": "Would you go out for a movie on saturday night ?",
	},
	{
		"id": 3,
		"question": "Would you go out for a movie on saturday night ?",
	},
	{
		"id": 4,
		"question": "Would you go out for a movie on saturday night ?",
	}
];

const BisexualQuestions = [
	{
		"id": 1,
		"question": "Would you go out for a movie on saturday night ?",
	},
	{
		"id": 2,
		"question": "Would you go out for a movie on saturday night ?",
	},
	{
		"id": 3,
		"question": "Would you go out for a movie on saturday night ?",
	},
	{
		"id": 3,
		"question": "Would you go out for a movie on saturday night ?",
	},
	{
		"id": 4,
		"question": "Would you go out for a movie on saturday night ?",
	}
];

function questionBank() {
	return {
		StraightQuestions: StraightQuestions,
		LesbianQuestions: LesbianQuestions,
		GayQuestions: GayQuestions,
		BisexualQuestions: BisexualQuestions
	}
}

module.exports = questionBank();


text:
class Profile;
class SyncedExtensionInstaller;

namespace apps_helper {

// Returns true iff |profile1| has same apps (hosted, legacy packaged and
// platform) as |profile2|.
bool HasSameApps(Profile* profile1, Profile* profile2);

// Returns true iff all existing profiles have the same apps (hosted,
// legacy packaged and platform).
bool AllProfilesHaveSameApps() WARN_UNUSED_RESULT;

// Installs the hosted app for the given index to |profile|, and returns the
// extension ID of the new app.
std::string InstallHostedApp(Profile* profile, int index);

// Installs the platform app for the given index to |profile|, and returns the
// extension ID of the new app. Indices passed to this method should be distinct
// from indices passed to InstallApp.
std::string InstallPlatformApp(Profile* profile, int index);

// Installs the hosted app for the given index to all profiles (including the
// verifier), and returns the extension ID of the new app.
std::string InstallHostedAppForAllProfiles(int index);

// Installs the web app for the given WebApplicationInfo and profile. This does
// not download icons or run OS integration installs.
web_app::AppId InstallWebApp(Profile* profile, const WebApplicationInfo& info);

// Uninstalls the app for the given index from |profile|. Assumes that it was
// previously installed.
void UninstallApp(Profile* profile, int index);

// Installs all pending synced apps for |profile|, including waiting for the
// App Service to settle.
void InstallAppsPendingForSync(Profile* profile);

// Waits for the App Service state for |profile| to settle.
void WaitForAppService(Profile* profile);

// Enables the app for the given index on |profile|.
void EnableApp(Profile* profile, int index);

// Disables the app for the given index on |profile|.
void DisableApp(Profile* profile, int index);

// Returns true if the app with index |index| is enabled on |profile|.
bool IsAppEnabled(Profile* profile, int index);

// Enables the app for the given index in incognito mode on |profile|.
void IncognitoEnableApp(Profile* profile, int index);

// Disables the app for the given index in incognito mode on |profile|.
void IncognitoDisableApp(Profile* profile, int index);

// Returns true if the app with index |index| is enabled in incognito mode on
// |profile|.
bool IsIncognitoEnabled(Profile* profile, int index);

// Gets the page ordinal value for the application at the given index on
// |profile|.
syncer::StringOrdinal GetPageOrdinalForApp(Profile* profile, int app_index);

// Sets a new |page_ordinal| value for the application at the given index
// on |profile|.
void SetPageOrdinalForApp(Profile* profile,
                          int app_index,
                          const syncer::StringOrdinal& page_ordinal);

// Gets the app launch ordinal value for the application at the given index on
// |profile|.
syncer::StringOrdinal GetAppLaunchOrdinalForApp(Profile* profile,
                                                int app_index);

// Sets a new |page_ordinal| value for the application at the given index
// on |profile|.
void SetAppLaunchOrdinalForApp(Profile* profile,
                               int app_index,
                               const syncer::StringOrdinal& app_launch_ordinal);

// Copy the page and app launch ordinal value for the application at the given
// index on |profile_source| to |profile_destination|.
// The main intention of this is to properly setup the values on the verifier
// profile in situations where the other profiles have conflicting values.
void CopyNTPOrdinals(Profile* source, Profile* destination, int index);

// Fix any NTP icon collisions that are currently in |profile|.
void FixNTPOrdinalCollisions(Profile* profile);

// Wait for all the web app install and uninstall tasks to finish.
void AwaitWebAppQuiescence(std::vector<Profile*> profiles);
}  // namespace apps_helper

// Checker to block for a set of profiles to have matching extensions lists. If
// the verifier profile is enabled, it will be included in the set of profiles
// to check against.
class AppsMatchChecker : public StatusChangeChecker,
                         public extensions::ExtensionRegistryObserver,
                         public extensions::ExtensionPrefsObserver,
                         public extensions::InstallObserver {
 public:
  AppsMatchChecker();

  AppsMatchChecker(const AppsMatchChecker&) = delete;
  AppsMatchChecker& operator=(const AppsMatchChecker&) = delete;

  ~AppsMatchChecker() override;

  // StatusChangeChecker implementation.
  bool IsExitConditionSatisfied(std::ostream* os) override;

  // extensions::ExtensionRegistryObserver implementation.
  void OnExtensionLoaded(content::BrowserContext* context,
                         const extensions::Extension* extension) override;
  void OnExtensionUnloaded(content::BrowserContext* context,
                           const extensions::Extension* extension,
                           extensions::UnloadedExtensionReason reason) override;
  void OnExtensionInstalled(content::BrowserContext* browser_context,
                            const extensions::Extension* extension,
                            bool is_update) override;
  void OnExtensionUninstalled(content::BrowserContext* browser_context,
                              const extensions::Extension* extension,
                              extensions::UninstallReason reason) override;

  // extensions::ExtensionPrefsObserver implementation.
  void OnExtensionDisableReasonsChanged(const std::string& extension_id,
                                        int disabled_reasons) override;
  void OnExtensionRegistered(const std::string& extension_id,
                             const base::Time& install_time,
                             bool is_enabled) override;
  void OnExtensionPrefsLoaded(const std::string& extension_id,
                              const extensions::ExtensionPrefs* prefs) override;
  void OnExtensionPrefsDeleted(const std::string& extension_id) override;
  void OnExtensionStateChanged(const std::string& extension_id,
                               bool state) override;

  // Implementation of extensions::InstallObserver.
  void OnAppsReordered(
      const absl::optional<std::string>& extension_id) override;

 private:
  std::vector<Profile*> profiles_;

  content::NotificationRegistrar registrar_;

  // This installs apps, too.
  std::vector<std::unique_ptr<SyncedExtensionInstaller>>
      synced_extension_installers_;

  base::ScopedMultiSourceObservation<extensions::InstallTracker,
                                     extensions::InstallObserver>
      install_tracker_observation_{this};
};

#endif  // CHROME_BROWSER_SYNC_TEST_INTEGRATION_APPS_HELPER_H_


text:
(function() {
    var self = this;
    var _, grammar, actualCharacters, nameSegmentRenderedInJavaScript, operatorRenderedInJavaScript, capitalise, reservedWords, escapeReservedWord;
    _ = require("underscore");
    grammar = require("../parser/grammar");
    exports.writeToBufferWithDelimiter = function(array, delimiter, buffer, scope) {
        var self = this;
        var writer, first;
        writer = void 0;
        if (scope instanceof Function) {
            writer = scope;
        } else {
            writer = function(item) {
                return buffer.write(item.generate(scope));
            };
        }
        first = true;
        return _(array).each(function(item) {
            if (!first) {
                buffer.write(delimiter);
            }
            first = false;
            return writer(item);
        });
    };
    actualCharacters = [ [ /\\/g, "\\\\" ], [ new RegExp("\b"), "\\b" ], [ /\f/g, "\\f" ], [ /\n/g, "\\n" ], [ /\0/g, "\\0" ], [ /\r/g, "\\r" ], [ /\t/g, "\\t" ], [ /\v/g, "\\v" ], [ /'/g, "\\'" ], [ /"/g, '\\"' ] ];
    exports.formatJavaScriptString = function(s) {
        var self = this;
        var gen1_items, gen2_i, mapping;
        gen1_items = actualCharacters;
        for (gen2_i = 0; gen2_i < gen1_items.length; ++gen2_i) {
            mapping = gen1_items[gen2_i];
            s = s.replace(mapping[0], mapping[1]);
        }
        return "'" + s + "'";
    };
    exports.concatName = function(nameSegments, options) {
        var self = this;
        var name, n, segment;
        name = "";
        for (n = 0; n < nameSegments.length; ++n) {
            segment = nameSegments[n];
            name = name + nameSegmentRenderedInJavaScript(segment, n === 0);
        }
        if (options && options.hasOwnProperty("escape") && options.escape) {
            return escapeReservedWord(name);
        } else {
            return name;
        }
    };
    nameSegmentRenderedInJavaScript = function(nameSegment, isFirst) {
        if (/[_$a-zA-Z0-9]+/.test(nameSegment)) {
            if (isFirst) {
                return nameSegment;
            } else {
                return capitalise(nameSegment);
            }
        } else {
            return operatorRenderedInJavaScript(nameSegment);
        }
    };
    operatorRenderedInJavaScript = function(operator) {
        var javaScriptName, n;
        javaScriptName = "";
        for (n = 0; n < operator.length; ++n) {
            javaScriptName = javaScriptName + "$" + operator.charCodeAt(n).toString(16);
        }
        return javaScriptName;
    };
    capitalise = function(s) {
        return s[0].toUpperCase() + s.substring(1);
    };
    reservedWords = {
        "class": true,
        "function": true,
        "else": true,
        "case": true,
        "switch": true
    };
    escapeReservedWord = function(word) {
        if (reservedWords.hasOwnProperty(word)) {
            return "$" + word;
        } else {
            return word;
        }
    };
    exports.concatArgs = function(args, gen3_options) {
        var self = this;
        var optionalArgs, asyncCallbackArg, terms;
        optionalArgs = gen3_options !== void 0 && Object.prototype.hasOwnProperty.call(gen3_options, "optionalArgs") && gen3_options.optionalArgs !== void 0 ? gen3_options.optionalArgs : void 0;
        asyncCallbackArg = gen3_options !== void 0 && Object.prototype.hasOwnProperty.call(gen3_options, "asyncCallbackArg") && gen3_options.asyncCallbackArg !== void 0 ? gen3_options.asyncCallbackArg : void 0;
        terms = gen3_options !== void 0 && Object.prototype.hasOwnProperty.call(gen3_options, "terms") && gen3_options.terms !== void 0 ? gen3_options.terms : void 0;
        var a;
        a = args.slice();
        if (optionalArgs && optionalArgs.length > 0) {
            a.push(terms.hash(optionalArgs));
        }
        if (asyncCallbackArg) {
            a.push(asyncCallbackArg);
        }
        return a;
    };
    exports.normaliseOperatorName = function(name) {
        var self = this;
        var op, match;
        op = new RegExp("^@(" + grammar.identifier + ")$");
        match = op.exec(name);
        if (match) {
            return match[1];
        } else {
            return name;
        }
    };
    exports.definedVariables = function(scope) {
        var self = this;
        return {
            variables: [],
            scope: scope,
            define: function(variable) {
                var self = this;
                scope.define(variable);
                return self.variables.push(variable);
            },
            defineWithTag: function(name, tag) {
                var self = this;
                return scope.defineWithTag(name, tag);
            },
            generateVariable: function(name) {
                var self = this;
                return scope.generateVariable(name);
            },
            isDefined: function(variable) {
                var self = this;
                return scope.isDefined(variable);
            },
            isDefinedInThisScope: function(variable) {
                var self = this;
                return scope.isDefinedInThisScope(variable);
            },
            names: function() {
                var self = this;
                return _.uniq(self.variables);
            }
        };
    };
}).call(this);


text:
struct sqlite3;
class SqliteStatementCache;
class SQLStatement;

namespace history {

// A visit database is one which stores visits for URLs, that is, times and
// linking information. A visit database must also be a URLDatabase, as this
// modifies tables used by URLs directly and could be thought of as inheriting
// from URLDatabase. However, this inheritance is not explicit as things would
// get too complicated and have multiple inheritance.
class VisitDatabase {
 public:
  // Must call InitVisitTable() before using to make sure the database is
  // initialized.
  VisitDatabase();
  virtual ~VisitDatabase();

  // Deletes the visit table. Used for rapidly clearing all visits. In this
  // case, InitVisitTable would be called immediately afterward to re-create it.
  // Returns true on success.
  bool DropVisitTable();

  // Adds a line to the visit database with the given information, returning
  // the added row ID on success, 0 on failure. The given visit is updated with
  // the new row ID on success.
  VisitID AddVisit(VisitRow* visit);

  // Deletes the given visit from the database. If a visit with the given ID
  // doesn't exist, it will not do anything.
  void DeleteVisit(const VisitRow& visit);

  // Query a VisitInfo giving an visit id, filling the given VisitRow.
  // Returns true on success.
  bool GetRowForVisit(VisitID visit_id, VisitRow* out_visit);

  // Updates an existing row. The new information is set on the row, using the
  // VisitID as the key. The visit must exist. Returns true on success.
  bool UpdateVisitRow(const VisitRow& visit);

  // Fills in the given vector with all of the visits for the given page ID,
  // sorted in ascending order of date. Returns true on success (although there
  // may still be no matches).
  bool GetVisitsForURL(URLID url_id, VisitVector* visits);

  // Fills all visits in the time range [begin, end) to the given vector. Either
  // time can be is_null(), in which case the times in that direction are
  // unbounded.
  //
  // If |max_results| is non-zero, up to that many results will be returned. If
  // there are more results than that, the oldest ones will be returned. (This
  // is used for history expiration.)
  //
  // The results will be in increasing order of date.
  void GetAllVisitsInRange(base::Time begin_time, base::Time end_time,
                           int max_results, VisitVector* visits);

  // Fills all visits with specified transition in the time range [begin, end)
  // to the given vector. Either time can be is_null(), in which case the times
  // in that direction are unbounded.
  //
  // If |max_results| is non-zero, up to that many results will be returned. If
  // there are more results than that, the oldest ones will be returned. (This
  // is used for history expiration.)
  //
  // The results will be in increasing order of date.
  void GetVisitsInRangeForTransition(base::Time begin_time,
                                     base::Time end_time,
                                     int max_results,
                                     PageTransition::Type transition,
                                     VisitVector* visits);

  // Fills all visits in the given time range into the given vector that should
  // be user-visible, which excludes things like redirects and subframes. The
  // begin time is inclusive, the end time is exclusive. Either time can be
  // is_null(), in which case the times in that direction are unbounded.
  //
  // Up to |max_count| visits will be returned. If there are more visits than
  // that, the most recent |max_count| will be returned. If 0, all visits in the
  // range will be computed.
  //
  // When |most_recent_visit_only| is set, only one visit for each URL will be
  // returned, and it will be the most recent one in the time range.
  void GetVisibleVisitsInRange(base::Time begin_time, base::Time end_time,
                               bool most_recent_visit_only,
                               int max_count,
                               VisitVector* visits);

  // Returns the visit ID for the most recent visit of the given URL ID, or 0
  // if there is no visit for the URL.
  //
  // If non-NULL, the given visit row will be filled with the information of
  // the found visit. When no visit is found, the row will be unchanged.
  VisitID GetMostRecentVisitForURL(URLID url_id,
                                   VisitRow* visit_row);

  // Returns the |max_results| most recent visit sessions for |url_id|.
  //
  // Returns false if there's a failure preparing the statement. True
  // otherwise. (No results are indicated with an empty |visits|
  // vector.)
  bool GetMostRecentVisitsForURL(URLID url_id,
                                 int max_results,
                                 VisitVector* visits);

  // Finds a redirect coming from the given |from_visit|. If a redirect is
  // found, it fills the visit ID and URL into the out variables and returns
  // true. If there is no redirect from the given visit, returns false.
  //
  // If there is more than one redirect, this will compute a random one. But
  // duplicates should be very rare, and we don't actually care which one we
  // get in most cases. These will occur when the user goes back and gets
  // redirected again.
  //
  // to_visit and to_url can be NULL in which case they are ignored.
  bool GetRedirectFromVisit(VisitID from_visit,
                            VisitID* to_visit,
                            GURL* to_url);

  // Similar to the above function except finds a redirect going to a given
  // |to_visit|.
  bool GetRedirectToVisit(VisitID to_visit,
                          VisitID* from_visit,
                          GURL* from_url);

  // Returns the number of visits to all urls on the scheme/host/post
  // identified by url. This is only valid for http and https urls (all other
  // schemes are ignored and false is returned).
  // count is set to the number of visits, first_visit is set to the first time
  // the host was visited. Returns true on success.
  bool GetVisitCountToHost(const GURL& url, int* count,
                           base::Time* first_visit);

  // Get the time of the first item in our database.
  bool GetStartDate(base::Time* first_visit);

 protected:
  // Returns the database and statement cache for the functions in this
  // interface. The decendent of this class implements these functions to
  // return its objects.
  virtual sqlite3* GetDB() = 0;
  virtual SqliteStatementCache& GetStatementCache() = 0;

  // Called by the derived classes on initialization to make sure the tables
  // and indices are properly set up. Must be called before anything else.
  bool InitVisitTable();

  // Convenience to fill a VisitRow. Assumes the visit values are bound starting
  // at index 0.
  static void FillVisitRow(SQLStatement& statement, VisitRow* visit);

  // Convenience to fill a VisitVector. Assumes that statement.step()
  // hasn't happened yet.
  static void FillVisitVector(SQLStatement& statement, VisitVector* visits);

 private:
  DISALLOW_EVIL_CONSTRUCTORS(VisitDatabase);
};

}  // history

#endif  // CHROME_BROWSER_HISTORY_VISIT_DATABASE_H__


text:
package controllers

import javax.inject._

import model.PlaceService
import shared.{Location, Place, SharedMessages}
import play.api.mvc._
import play.api.libs.json._
import play.api.libs.functional.syntax._

@Singleton
class Application @Inject()(cc: ControllerComponents) extends AbstractController(cc) {

    def index = Action {
        Ok(views.html.index(SharedMessages.itWorks))
    }

    implicit val locationWrites: Writes[Location] = (
            (JsPath \ "lat").write[Double] and
            (JsPath \ "long").write[Double]
        ) (unlift(Location.unapply))

    implicit val placeWrites: Writes[Place] = (
            (JsPath \ "name").write[String] and
            (JsPath \ "location").write[Location]
        ) (unlift(Place.unapply))

    def listPlaces = Action {
        val json = Json.toJson(PlaceService.list)
        Ok(json)
    }

}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">

    <title>User History</title>
	<link href="//netdna.bootstrapcdn.com/bootstrap/3.0.3/css/bootstrap.min.css" rel="stylesheet">

    <link href="{{asset('assets/bootstrap/css/bootstrap.min.css')}}" rel="stylesheet">

    <link href="{{asset('assets/bootstrap/css/4-col-portfolio.css')}}" rel="stylesheet">

                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
                    Toggle navigation

                </button>

                STYLESCOUTAPP
				BACK

                        About

                        Profile

                         HashtagList

						 Signout

{{$thisHash[0]}}
                    {{$thisCapt[0]}}

<?php
$a = 1;
$i = 0;
$images = DB::table('images')->where('hashtag','=',$thisHash)->lists('path');
$relate = DB::table('images')->where('hashtag','=',$thisHash)->lists('name');

?>

@foreach($images as $image)

        @if($a%4==1)

        	@endif

				<button></button>

        @if($a%4==4)

        @endif
       <?php
       $i++;
	   $a++;
	   ?>

@endforeach

Copyright © Your Website 2014


text:
using Lingua;

namespace Prolog.Grammar
{
    // Recognizes periods except when followed by an open parenthesis (i.e. a list functor).
    //
    [Terminal(@"\.(?!\()")]
    internal sealed class Period : PrologTerminal
    { }
}


text:
/**
 * @file reporting.c
 *
 * @short metrics computation and reporting.
 **/
#include "../bwlib/config.h"
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#include <stdlib.h>
#ifdef HAVE_STDINT_H
#include <stdint.h>
#endif
#include <float.h>
#include <math.h>
#include <string.h>
#include "reporting.h"
#ifndef THRULAY_REPORTING_SAMPLE_LOOP
#include "assertd.h"
#else
#include <assert.h>
#endif
#include "rcs.h"

RCS_ID("@(#) $Id: reporting.c,v 1.1.2.12 2006/08/20 18:06:19 fedemp Exp $")

#ifndef MIN
#define MIN(a,b)    ((a<b)?a:b)
#endif
#ifndef MAX
#define MAX(a,b)    ((a>b)?a:b)
#endif

/*
 * Reordering.
 */
#define loop(x)		((x) >= 0 ? (x) : (x) + (int)reordering_max)

/*
 * Duplication.
 */
static uint64_t *bitfield = NULL;	/* Bit field used to check for
					   duplicated packets. */

/*
 * Reordering.
 */
static uint64_t reordering_max; 	/* We have m[j-1] == number of */
static uint64_t *reordering_m;		/* We have m[j-1] == number of
					   j-reordered packets. */
static uint64_t *reordering_ring;	/* Last sequence numbers seen */
static int r = 0;			/* Ring pointer for next write. */
static int l = 0;			/* Counter of sequence numbers. */

/*
 * Quantiles.
 */
static uint16_t quantile_max_seq;       /* Maximum number of sequences */
static int *quantile_k;		/* number of elements in buffer */

static double **quantile_input;	/* This is the buffer where the
				   sequence of incoming packets is saved.
				   If we received enough packets, we will
				   write this buffer to a quantile buffer. */
static int *quantile_input_cnt;   /* number of elements in input buffer */
static int *quantile_empty_buffers;	/* number of empty buffers */

static int *quantile_b;		/* number of buffers */

static double **quantile_buf;

static int *quantile_alternate;     /* this is used to determine the offset in
				   COLLAPSE (if weight is even) */

static uint64_t *quantile_inf_cnt;	/* this counter is for the additional
				   -inf, +inf elements we added to NEW buffer
				   to fill it up. */

typedef struct quantile {
	struct quantile *next;	/* pointer to next quantile buffer */
	int weight;		/* 0 if buffer is empty, > 0 if buffer is
				 * full */
	int level;
	double *buffer;
	int pos;		/* current position in buffer; used in
				   quantile_collapse() */
} quantile_t;

static quantile_t **quantile_buffer_head;

int
reordering_init(uint64_t max)
{
	reordering_max = max;
	reordering_m = calloc(reordering_max, sizeof(uint64_t));
	reordering_ring = calloc(reordering_max, sizeof(uint64_t));
	if (reordering_m == NULL) {
		return -1;
	} else {
		return 0;
	}
}

int
reordering_checkin(uint64_t packet_sqn)
{
	int j;

	for (j = 0; j < MIN(l, (int)reordering_max) &&

		     packet_sqn < reordering_ring[loop(r-j-1)]; j++) {
		reordering_m[j]++;
	}
	reordering_ring[r] = packet_sqn;
	l++;
	r = (r + 1) % reordering_max;
	return 0;
}

double
reordering_output(uint64_t j)
{
	if (j >= reordering_max)
		return -1;
	else
		return (double)reordering_m[j] / (l - j - 1);
}

void
reordering_exit(void)
{
	free(reordering_ring);
	free(reordering_m);
}

int
duplication_init(uint64_t npackets)
{
	uint64_t bitfield_len = 0;	/* Number of sectors in bitfield */

	/* Allocate memory for bit field */
	bitfield_len = ((npackets % 64) ? (npackets / 64 + 1) : npackets / 64);
	bitfield = calloc(bitfield_len, sizeof(uint64_t));
	if (bitfield == NULL) {
		return -1;
	} else {
		return 0;
	}
}

int
duplication_check(uint64_t packet_sqn)
{
	uint64_t bitfield_sec;		/* Which sector in bitfield */
	uint64_t bitfield_bit;		/* Which bit in sector */

	/* Calculate sector */
	bitfield_sec = packet_sqn >> 6;

	/* Calculate bit in sector */
	bitfield_bit = (uint64_t)1 << (packet_sqn & 63);

	if (bitfield[bitfield_sec] & bitfield_bit) {
		/* Duplicated packet */
		return 1;
	} else {
		/* Unique packet */
		bitfield[bitfield_sec] |= bitfield_bit;
		return 0;
	}
}

void
duplication_exit(void)
{
	free(bitfield);
}

/* Calculate binomial coefficient C(n, k). */
int64_t
binomial (int n, int k)
{
	int64_t bc = 0;
	int i, m;

	/* C(n, k) = C(n, n-k) */
	k = MIN(k, n-k);

	if (k >= 0) {
		bc = 1;
		m = MAX(k, n-k);

		for (i = 1; i <= k; i++) {
			bc = (bc * (m + i)) / i;
		}
	}

	return bc;
}

int
quantile_compare(const void *d1, const void *d2)
{
	if (*(double *)d1 < *(double *)d2) {
		return -1;
	} else if (*(double *)d1 == *(double *)d2) {
		return 0;
	} else {
		assert(*(double *)d1 > *(double *)d2);
		return 1;
	}
}

void
quantile_sort (double *list, int length)
{
	qsort(list, length, sizeof(double), quantile_compare);
}

/**
 * Implementation of NEW operation from section 3.1 of paper [1].
 *
 * Takes as input an empty buffer. Simply populates the quantile buffer with
 * the next k elements from the input sequence, labels the buffer as full, and
 * assigns it a weight of 1.
 *
 * If there are not enough elements to fill up the buffer, we alternately add
 * -inf, +inf elements until buffer is full (-inf == 0, +inf == DBL_MAX).
 *
 * NOTE: We sort the elements in the input buffer before we copy them to
 * the quantile buffer.
 *
 * @param seq Sequence index.
 *
 * @return
 * @retval 0 on success.
 * @retval -2 need an empty buffer.
 * @retval -3 bad input sequence length.
 **/
int
quantile_new(uint16_t seq, quantile_t *q, double *input, int k, int level)
{
	int i;

	/* Check that buffer is really empty. */
	if (q->weight != 0) {
		return -2;
	}

	/* Sanity check for length of input sequence. */
	if (k > quantile_k[seq]) {
		return -3;
	}

	/* If there are not enough elements in the input buffer, fill it up
	 * with -inf, +inf elements. */
	for (i = k; i < quantile_k[seq]; i++) {
		if (i % 2) {
			input[i] = DBL_MAX;
		} else {
			input[i] = 0;
		}

		/* Increment counter that indicates how many additional
		 * elements we added to fill the buffer. */
		quantile_inf_cnt[seq]++;
	}

	quantile_sort(input, quantile_k[seq]);

	memcpy(q->buffer, input, sizeof(double) * quantile_k[seq]);

	/* Mark buffer as full and set level. */
	q->weight = 1;
	q->level = level;

	/* Update number of empty quantile buffers. */
	quantile_empty_buffers[seq]--;

	return 0;
}

/* Implementation of COLLAPSE operation from section 3.2 of paper [1].
 *
 * This is called from quantile_algorithm() if there are no empty buffers.
 * We COLLAPSE all the full buffers, where level has value `level'.
 * Output is written to the first buffer in linked list with level set to
 * `level'. The level of the output buffer is increased by 1.
 * All other buffers we used in the COLLAPSE are marked empty. */
int
quantile_collapse(uint16_t seq, int level)
{
	quantile_t *qp = NULL, *qp_out = NULL;
	int num_buffers = 0;	/* number of buffers with level `level' */
	int weight = 0;		/* weight of the output buffer */
	int offset;
	int i, j;
	double min_dbl;
	long next_pos;
	long merge_pos = 0;

	/* Check that there are at least two full buffers with given level.
	 * Also calculate weight of output buffer. */
	for (qp = quantile_buffer_head[seq]; qp != NULL; qp = qp->next) {
		if ((qp->weight != 0) && (qp->level == level)) {
			num_buffers++;
			weight += qp->weight;
			qp->pos = 0;
		} else {
			/* We mark the buffers that are not used in this
			 * COLLAPSE. */
			qp->pos = -1;
		}
	}
	if (num_buffers < 2) {
		return -4;
	}

	/* NOTE: The elements in full buffers are sorted. So we don't have to
	 * do that again.
	 */
	/* Search for first full buffer with matching level. This is the buffer
	 * where we save the output. */
	for (qp_out = quantile_buffer_head[seq]; qp_out != NULL;
			qp_out = qp_out->next) {
		if (qp_out->pos != -1) {
			break;
		}
	}

	/* Calculate offset */
	if (weight % 2) {
		/* odd */
		offset = (weight + 1) / 2;
	} else {
		/* even - we alternate between two choices in each COLLAPSE */
		if (quantile_alternate[seq] % 2) {
			offset = weight / 2;
		} else {
			offset = (weight + 2)/ 2;
		}
		quantile_alternate[seq] = (quantile_alternate[seq] + 1) % 2;
	}

	/* Initialize next position of element to save. Because first position
	 * is at 0, we have to decrement offset by 1. */
	next_pos = offset - 1;

	for (i = 0; i < quantile_k[seq]; ) {

		/* Search for current minimal element in all buffers.
		 * Because buffers are all sorted, we just have to check the
		 * element at current position. */
		min_dbl = DBL_MAX;
		for (qp = quantile_buffer_head[seq]; qp != NULL;
		     qp = qp->next) {
			/* Skip wrong buffers. */
			if (qp->pos == -1) {
				continue;
			}

			/* Check that we are not at the end of buffer. */
			if (qp->pos >= quantile_k[seq]) {
				continue;
			}

			/* Update minimum element. */
			min_dbl = MIN(min_dbl, qp->buffer[qp->pos]);
		}

		/* Now process this minimal element in all buffers. */
		for (qp = quantile_buffer_head[seq]; qp != NULL;
		     qp = qp->next) {
			/* Skip wrong buffers. */
			if (qp->pos == -1) {
				continue;
			}

			/* Now process minimal element in this buffer. */
			for (; (qp->buffer[qp->pos] == min_dbl) &&
					(qp->pos < quantile_k[seq]);
			     qp->pos++) {

				/* We run this loop `qp->weight' times.
				 * We check there if we are in a position
				 * so we have to save this element in our
				 * output buffer. */
				for (j = 0; j < qp->weight; j++) {

					if (next_pos == merge_pos) {
						quantile_buf[seq][i] = min_dbl;
						i++;

						if (i == quantile_k[seq]) {
							/* We have written
							 * all elements to
							 * output buffer, so
							 * exit global loop. */
							goto out;
						}

						/* Update next position. */
						next_pos += weight;
					}

					merge_pos++;
				} /* for(j = 0; j < qp->weight; j++) */
			} /* for (; (qp->buffer[qp->pos] == min_dbl) &&
			     (qp->pos < quantile_k[seq]); qp->pos++) */
		} /* for (qp = quantile_buffer_head[seq]; qp!=NULL;
		     qp = qp->next) */
	} /* for (i = 0; i < quantile_k[seq]; ) */

out:
	memcpy(qp_out->buffer, quantile_buf[seq],
	       sizeof(double) * quantile_k[seq]);

	/* Update weight of output buffer. */
	qp_out->weight = weight;
	qp_out->level = level+1;

	/* Update list of empty buffers. */
	for (qp = quantile_buffer_head[seq]; qp != NULL; qp = qp->next) {
		if ((qp->pos != -1) && (qp != qp_out)) {
			qp->weight = 0;
			qp->level = 0;
		}
	}
	quantile_empty_buffers[seq] += num_buffers - 1;
	return 0;
}

/**
 * Implementation of COLLAPSE policies from section 3.4 of paper [1].
 *
 * There are three different algorithms noted in the paper. We use the
 * "New Algorithm".
 *
 * @param seq Sequence index.
 *
 * @return
 * @retval 0 on success.
 * @retval -1 quantiles not initialized.
 * @retval -2 need an empty buffer for new operation.
 * @retval -3 bad input sequence length in new operation.
 * @retval -4 not enough buffers for collapse operation.
 **/
int
quantile_algorithm (uint16_t seq, double *input, int k)
{
	int rc;
	quantile_t *qp = NULL, *qp2 = NULL;
	int min_level = -1;

	/* This should always be true. */
	if (quantile_buffer_head[seq] != NULL) {
		min_level = quantile_buffer_head[seq]->level;
	} else {
		return -1;
	}

	/* Get minimum level of all currently full buffers. */
	for (qp = quantile_buffer_head[seq]; qp != NULL; qp = qp->next) {
		if (qp->weight != 0) {
			/* Full buffer. */
			min_level = MIN(min_level, qp->level);
		}
	}

	if (quantile_empty_buffers[seq] == 0) {
		/* There are no empty buffers. Invoke COLLAPSE on the set
		 * of buffers with minimum level. */

		rc = quantile_collapse(seq, min_level);
		if (rc < 0)
			return rc;
	} else if (quantile_empty_buffers[seq] == 1) {
		/* We have exactly one empty buffer. Invoke NEW and assign
		 * it level `min_level'. */

		/* Search the empty buffer. */
		for (qp = quantile_buffer_head[seq]; qp != NULL;
		     qp = qp->next) {
			if (qp->weight == 0) {
				/* Found empty buffer. */
				break;
			}
		}

		rc = quantile_new(seq, qp, input, k, min_level);
		if (rc < 0)
			return rc;
	} else {
		/* There are at least two empty buffers. Invoke NEW on each
		 * and assign level `0' to each. */

		/* Search for two empty buffers. */
		for (qp = quantile_buffer_head[seq]; qp != NULL;
		     qp = qp->next) {
			if (qp->weight == 0) {
				/* Found first empty buffer. */
				break;
			}
		}
		for (qp2 = qp->next; qp2 != NULL; qp2 = qp2->next) {
			if (qp2->weight == 0) {
				/* Found second empty buffer. */
				break;
			}
		}

		if (k <= quantile_k[seq]) {
			/* This could happen if we call this after we
			 * received all packets but don't have enough to
			 * fill up two buffers. */

			rc = quantile_new(seq, qp, input, k, 0);
			if (rc < 0)
				return rc;
		} else {
			/* We have enough input data for two buffers. */
			rc = quantile_new(seq, qp, input, quantile_k[seq], 0);
			if (rc < 0)
				return rc;
			rc = quantile_new(seq, qp2, input + quantile_k[seq],
					  k - quantile_k[seq], 0);
			if (rc < 0)
				return rc;
		}
	}
	return 0;
}

int
quantile_init_seq(uint16_t seq)
{
	quantile_t *qp = NULL;
	int i;

	if ( seq >= quantile_max_seq)
		return -5;

	/* Allocate memory for quantile buffers. Buffers are linked lists
	 * with a pointer to next buffer.
	 * We need `quantile_b' buffers, where each buffer has space for
	 * `quantile_k' elements. */
	for (i = 0; i < quantile_b[seq]; i++) {
		if (i == 0) {
			/* Initialize first buffer. */
			qp = malloc(sizeof(quantile_t));
			if (qp == NULL) {
				return -1;
			}
			quantile_buffer_head[seq] = qp;
		} else {
			qp->next = malloc(sizeof(quantile_t));
			if (qp->next == NULL) {
				return -1;
			}
			qp = qp->next;
		}

		/* `qp' points to buffer that should be initialized. */
		qp->next = NULL;
		qp->weight = 0;	/* empty buffers have weight of 0 */
		qp->level = 0;
		qp->buffer = malloc(sizeof(double) * quantile_k[seq]);
		if (qp->buffer == NULL) {
			return -1;
		}
	}
	/* Update number of empty quantile buffers. */
	quantile_empty_buffers[seq] = quantile_b[seq];

	return 0;
}

int
quantile_init (uint16_t max_seq, double eps, uint64_t N)
{
	int b, b_tmp = 0;
	int k, k_tmp = 0;
	int h, h_max = 0;
	int seq, rc;

	quantile_max_seq = max_seq;
	/* Allocate array for the requested number of sequences. */
	quantile_k = calloc(max_seq, sizeof(int));
	quantile_input = calloc(max_seq, sizeof(double*));
	quantile_input_cnt = calloc(max_seq, sizeof(int));
	quantile_empty_buffers = calloc(max_seq, sizeof(int));
	quantile_b = calloc(max_seq, sizeof(int));
	quantile_buf = calloc(max_seq, sizeof(double*));
	quantile_alternate = calloc(max_seq, sizeof(int));
	quantile_inf_cnt = calloc(max_seq, sizeof(uint64_t));
	quantile_buffer_head = calloc(max_seq, sizeof(quantile_t*));

	/* "In practice, optimal values for b and k can be computed by trying
	 * out different values of b in the range 1 and 30." */
	for (b = 2; b <= 30; b++) {

		/* For each b, compute the largest integral h that satisfies:
		 *   (h-2) * C(b+h-2, h-1) - C(b+h-3, h-3) +
		 *                                 C(b+h-3, h-2) <= 2 * eps * N
		 */
		for (h = 0; ; h++) {
			if (((h-2) * binomial(b+h-2, h-1) -
						binomial(b+h-3, h-3) +
						binomial(b+h-3, h-2)) >
					(2 * eps * N)) {
				/* This h does not satisfy the inequality from
				 * above. */
				break;
			}
			h_max = h;
		}

		/* Now compute the smallest integral k that satisfies:
		 *   k * C(b+h-2, h-1) => N. */
		k = ceil(N / (double)binomial(b+h_max-2, h_max-1));

		/* Identify that b that minimizes b*k. */
		if ((b_tmp == 0) && (k_tmp == 0)) {
			/* Initialize values */
			b_tmp = b;
			k_tmp = k;
		}

		if ((b * k) < (b_tmp * k_tmp)) {
			/* Found b and k for which the product is smaller
			 * than for the ones before. Because we want to
			 * minimize b*k (required memory), we save them. */
			b_tmp = b;
			k_tmp = k;
		}
	}

	/* Set global quantile values. For now, all sequences share
	   the same k and b values.*/
	for (seq = 0; seq < max_seq; seq++ ) {
		quantile_b[seq] = b_tmp;
		quantile_k[seq] = k_tmp;
	}

	/* Allocate memory for input buffer.
	 * We allocate enough space to save up to `2 * quantile_k' elements.
	 * This space is needed in the COLLAPSE policy if there are more
	 * than two empty buffers. Because then we have to invoke NEW on two
	 * buffers and thus need an input buffer with `2 * quantile_k'
	 * elements. */
	for (seq = 0; seq < quantile_max_seq; seq++) {
		quantile_input[seq] = malloc(sizeof(double) * 2 *
					     quantile_k[seq]);
		if (quantile_input[seq] == NULL) {
			return -1;
		}
		quantile_input_cnt[seq] = 0;
	}

	/* Allocate memory for output buffer.
	 * This buffer is used in COLLAPSE to store temporary output buffer
	 * before it gets copied to one of the buffers used in COLLAPSE. */
	for (seq = 0; seq < quantile_max_seq; seq++ ) {
		quantile_buf[seq] = malloc(sizeof(double) * quantile_k[seq]);
		if (quantile_buf[seq] == NULL) {
			return -1;
		}
	}

	for (seq = 0; seq < max_seq; seq++) {
		rc = quantile_init_seq(seq);
		if (rc < 0)
			return rc;
	}

	return 0;
}

int
quantile_value_checkin(uint16_t seq, double value)
{
	int rc = 0;

	if ( seq >= quantile_max_seq)
		return -5;

	quantile_input[seq][quantile_input_cnt[seq]++] = value;

	/* If we have at least two empty buffers,
	 * we need input for two buffers, to twice
	 * the value of `quantile_k'. */
	if (quantile_empty_buffers[seq] >= 2) {
		if (quantile_input_cnt[seq] ==
		    (2 * quantile_k[seq])) {
			rc = quantile_algorithm(seq, quantile_input[seq],
						quantile_input_cnt[seq]);
			/* Reset counter. */
			quantile_input_cnt[seq] = 0;
		}
	} else {
		/* There are 0 or 1 empty buffers */
		if (quantile_input_cnt[seq] == quantile_k[seq]) {
			rc = quantile_algorithm(seq, quantile_input[seq],
						quantile_input_cnt[seq]);
			/* Reset counter. */
			quantile_input_cnt[seq] = 0;
		}
	}
	return rc;
}

int
quantile_finish(uint16_t seq)
{
	int rc = 0;

	if ( seq >= quantile_max_seq)
		return -5;

	if (quantile_input_cnt[seq] > 0) {
		rc = quantile_algorithm(seq, quantile_input[seq],
					quantile_input_cnt[seq]);
	}
	return rc;
}

void
quantile_reset(uint16_t seq)
{
	quantile_input_cnt[seq] = 0;
	quantile_empty_buffers[seq] = quantile_b[seq];
	memset(quantile_buf[seq],0,sizeof(double) * quantile_k[seq]);
	memset(quantile_input[seq],0,sizeof(double) * quantile_k[seq]);
}

/**
 * Deinitialize one quantile sequence.
 **/
void
quantile_exit_seq(uint16_t seq)
{
	quantile_t *qp = NULL, *next;

	if (seq >= quantile_max_seq)
		return;

	qp = quantile_buffer_head[seq];
	while (qp != NULL) {
		/* Save pointer to next buffer. */
		next = qp->next;

		/* Free buffer and list entry. */
		free(qp->buffer);
		free(qp);

		/* Set current buffer to next one. */
		qp = next;
	}

	quantile_buffer_head[seq] = NULL;
	quantile_input_cnt[seq] = 0;
	quantile_empty_buffers[seq] = quantile_b[seq];
}

void
quantile_exit(void)
{
	int seq;

	/* Free per sequence structures */
	for (seq = 0; seq < quantile_max_seq; seq++) {
		quantile_exit_seq(seq);

		/* Free output buffer. */
		free(quantile_buf[seq]);

		/* Free input buffer. */
		free(quantile_input[seq]);
	}

	free(quantile_buffer_head);
	free(quantile_inf_cnt);
	free(quantile_alternate);
	free(quantile_buf);
	free(quantile_b);
	free(quantile_empty_buffers);
	free(quantile_input_cnt);
	free(quantile_input);
	free(quantile_k);
}

int
quantile_output (uint16_t seq, uint64_t npackets, double phi, double *result)
{
	quantile_t *qp = NULL;
	int num_buffers = 0;
	int weight = 0;
	int j;
	long next_pos = 0;
	long merge_pos = 0;
	double min_dbl;
	double beta;
	double phi2;		/* this is phi' */

	if ( seq >= quantile_max_seq)
		return -5;

	/* Check that there are at least two full buffers with given level. */
	for (qp = quantile_buffer_head[seq]; qp != NULL; qp = qp->next) {
		if (qp->weight != 0) {
			num_buffers++;
			weight += qp->weight;
			qp->pos = 0;
		} else {
			qp->pos = -1;
		}
	}
	if (num_buffers < 2) {
		/* XXX: In section 3.3 "OUTPUT operation" of paper [1] is says
		 * that OUTPUT takes c => 2 full input buffers. But what if we
		 * just have one full input buffer?
		 *
		 * For example this happens if you run a UDP test with a
		 * block size of 100k and a test duration of 3 seconds:
		 * $ ./thrulay -u 100k -t 3 localhost
		 */

		if (num_buffers != 1) {
			return -1;
		}
	}

	/* Calculate beta and phi' */
	beta = 1 + quantile_inf_cnt[seq] / (double)npackets;
	assert(beta >= 1.0);

	assert(phi >= 0.0 && phi <= 1.0);
	phi2 = (2 * phi + beta - 1) / (2 * beta);

	next_pos = ceil(phi2 * quantile_k[seq] * weight);

	/* XXX: If the client just sends a few packets, it is possible that
	 * next_pos is too large. If this is the case, decrease it. */
	if (next_pos >= (num_buffers * quantile_k[seq])) {
		next_pos --;
	}

	while (1) {

		/* Search for current minimal element in all buffers.
		 * Because buffers are all sorted, we just have to check the
		 * element at current position. */
		min_dbl = DBL_MAX;
		for (qp = quantile_buffer_head[seq]; qp != NULL;
		     qp = qp->next) {
			/* Skip wrong buffers. */
			if (qp->pos == -1) {
				continue;
			}

			/* Check that we are not at the end of buffer. */
			if (qp->pos >= quantile_k[seq]) {
				continue;
			}

			/* Update minimum element. */
			min_dbl = MIN(min_dbl, qp->buffer[qp->pos]);
		}

		/* Now process this minimal element in all buffers. */
		for (qp = quantile_buffer_head[seq]; qp != NULL;
		     qp = qp->next) {
			/* Skip wrong buffers. */
			if (qp->pos == -1) {
				continue;
			}

			/* Now process minimal element in this buffer. */
			for (; (qp->buffer[qp->pos] == min_dbl) &&
					(qp->pos < quantile_k[seq]);
			     qp->pos++) {

				/* Increment merge position `qp->weight'
				 * times. If we pass the position we seek,
				 * return current minimal element. */
				for (j = 0; j < qp->weight; j++) {
					if (next_pos == merge_pos) {
						*result = min_dbl;
						return 0;
					}
					merge_pos++;
				}
			}
		}
	}

	/* NOTREACHED */
}

#ifdef THRULAY_REPORTING_SAMPLE_LOOP

#include <stdio.h>
#include <strings.h>

#ifndef NAN
#define _ISOC99_SOURCE
#include <math.h>
#endif

#define ERR_FATAL       0
#define ERR_WARNING     1

void __attribute__((noreturn))
quantile_alg_error(int rc)
{
	switch (rc) {
	case -1:
		__android_log_print(ANDROID_LOG_DEBUG, "JNI_ERROR_LOG", "Error: quantiles not initialized.");
		break;
	case -2:
		__android_log_print(ANDROID_LOG_DEBUG, "JNI_ERROR_LOG", "Error: NEW needs an empty buffer.");
		break;
	case -3:
		__android_log_print(ANDROID_LOG_DEBUG, "JNI_ERROR_LOG", "Error: Bad input sequence length.");
		break;
	case -4:
		__android_log_print(ANDROID_LOG_DEBUG, "JNI_ERROR_LOG", "Error: Not enough buffers for COLLAPSE.");
		break;
	default:
		__android_log_print(ANDROID_LOG_DEBUG, "JNI_ERROR_LOG", "Error: Unknown quantile_algorithm error.");
	}
	//exit(1);
}

/**
 * Will read a sample data file (first and only parameter) whose lines
 * give two values per line (per received packet): measured packet
 * delay and packet sequence number (in "%lf %lu" format). As an
 * exception, the first line specifies the number of packets actually
 * sent. Example:
 * ----
 * 10
 * 0.101 0
 * 0.109 1
 * 0.12 1
 * 0.10 3
 * 0.14 4
 * 0.15 5
 * 0.13 2
 * 0.09 6
 * 0.1 8
 * 0.091 7
 * ----
 *
 * To compile this sample reporting main(), the following symbols
 * should be defined: HAVE_CONFIG_H and
 * HAVE_THRULAY_REPORTING_SAMPLE_LOOP. '..' should be specified as
 * include directory, and libm should be linked as well. For instance:
 *
 * gcc -std=c99 -Wno-long-long -Wall -pedantic -W -Wpointer-arith -Wnested-externs -DHAVE_CONFIG_H -DTHRULAY_REPORTING_SAMPLE_LOOP -I../ -o reporting reporting.c -lm
 *
 **/
int
main(int argc, char *argv[])
{
	FILE *sf;
	/* 'Measured data' */
	const int max_packets = 65535;
	/* 'Received' packets*/
	int npackets = 0;
	uint64_t packet_sqn[max_packets];    /* Fill in with sample data */
	double packet_delay[max_packets];    /* Fill in with sample data */
	uint64_t packets_sent = 0;           /* Fill in with sample data */
	/* reordering */
	const uint64_t reordering_max = 100;
	char buffer_reord[reordering_max * 80];
	size_t r = 0;
	uint64_t j = 0;
	/* Stats */
	uint64_t unique_packets = 0, packets_dup = 0;
	double quantile_25, quantile_50, quantile_75;
	double delay, jitter;
	double packet_loss;
	char report_buffer[1000];
	/* Auxiliary variables */
	int i, rc, rc2, rc3;

	memset(packet_sqn,0,sizeof(uint64_t)*max_packets);
	memset(packet_delay,0,sizeof(double)*max_packets);

	/* Inititalize duplication */
	rc = duplication_init(max_packets);
	if (-1 == rc) {
		perror("calloc");
		//exit(1);
	}

	/* Initialize quantiles */
	rc = quantile_init(1, QUANTILE_EPS, max_packets);
	if (-1 == rc) {
		perror("malloc");
		//exit(1);
	}

	/* Initialize reordering */
	rc = reordering_init(reordering_max);
	if (-1 == rc) {
		perror("calloc");
		//exit(1);
	}

	/* Open sample file */
	if (2 == argc) {
		sf = fopen(argv[1],"r");
	} else {
		//exit(1);
	}

	/* Process sample input file. */

	/* The sender somehow tells the receiver how many packets were
	   actually sent. */
	fscanf(sf,"%lu",&packets_sent);

	for (i = 0; i < max_packets && !feof(sf); i++) {

		fscanf(sf,"%lf %lu",&packet_delay[i],&packet_sqn[i]);
		npackets++;

		/*
		 * Duplication
		 */
		if (duplication_check(packet_sqn[i])) {
			/* Duplicated packet */
			packets_dup++;
			continue;
		} else {
			/* Unique packet */
			unique_packets++;
		}

		/*
		 * Delay quantiles.
		 */
		rc = quantile_value_checkin(0, packet_delay[i]);
		if (rc < 0)
			quantile_alg_error(rc);

		/*
		 * Reordering
		 */
		reordering_checkin(packet_sqn[i]);
	}

	/*
	 * Perform last algorithm operation with a possibly not full
	 * input buffer.
	 */
	rc = quantile_finish(0);
	if (rc < 0)
		quantile_alg_error(rc);

	rc = quantile_output(0, unique_packets, 0.25, &quantile_25);
	rc2 = quantile_output(0, unique_packets, 0.50, &quantile_50);
	rc3 = quantile_output(0, unique_packets, 0.75, &quantile_75);
	if (-1 == rc || -1 == rc2 || -1 == rc3) {
		__android_log_print(ANDROID_LOG_DEBUG, "JNI_ERROR_LOG","An error occurred while computing delay "
			"quantiles. %d %d %d\n",rc, rc2, rc3);
		//exit(1);
	}

	/* Delay and jitter computation */
	packet_loss = packets_sent > unique_packets?
		(100.0*(packets_sent - unique_packets))/packets_sent: 0;
	delay = (packet_loss > 50.0)? INFINITY : quantile_50;
	if (packet_loss < 25.0 ) {
		jitter = quantile_75 - quantile_25;
	} else if (packet_loss > 75.0) {
		jitter = NAN;
	} else {
		jitter = INFINITY;
	}

	/* Format final report */
	snprintf(report_buffer, sizeof(report_buffer),
		 "Delay: %3.3fms\n"
		 "Loss: %3.3f%%\n"
		 "Jitter: %3.3fms\n"
		 "Duplication: %3.3f%%\n"
		 "Reordering: %3.3f%\n",
		 1000.0 * delay,
		 packet_loss,
		 1000.0 * jitter,
		 100 * (double)packets_dup/npackets,
		 100.0 * reordering_output(0));

	printf(report_buffer);

	/* Deallocate resources for statistics. */
	reordering_exit();
	quantile_exit();
	duplication_exit();

	fclose(sf);

	//exit(0);
}

#endif /* THRULAY_REPORTING_SAMPLE_LOOP */


text:
i am brian

a software developer.

Media x Blog


text:
package AsposeSlidesCloud::Object::TextItems;

require 5.6.0;
use strict;
use warnings;
use utf8;
use JSON qw(decode_json);
use Data::Dumper;
use Module::Runtime qw(use_module);
use Log::Any qw($log);
use Date::Parse;
use DateTime;

use base "AsposeSlidesCloud::Object::BaseObject";

#
#
#
#NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually.
#

my $swagger_types = {
    'Items' => 'ARRAY[TextItem]',
    'SelfUri' => 'ResourceUri',
    'AlternateLinks' => 'ARRAY[ResourceUri]',
    'Links' => 'ARRAY[ResourceUri]'
};

my $attribute_map = {
    'Items' => 'Items',
    'SelfUri' => 'SelfUri',
    'AlternateLinks' => 'AlternateLinks',
    'Links' => 'Links'
};

# new object
sub new {
    my ($class, %args) = @_;
    my $self = {
        #
        'Items' => $args{'Items'},
        #
        'SelfUri' => $args{'SelfUri'},
        #
        'AlternateLinks' => $args{'AlternateLinks'},
        #
        'Links' => $args{'Links'}
    };

    return bless $self, $class;
}

# get swagger type of the attribute
sub get_swagger_types {
    return $swagger_types;
}

# get attribute mappping
sub get_attribute_map {
    return $attribute_map;
}

1;


text:
package ds.exercise.tree;

/**
 * Created by Administrator on 024 2017/5/24.
 */

public class BinaryTreeNode<T> {
    public T data;
    public BinaryTreeNode left;
    public BinaryTreeNode right;

    public BinaryTreeNode() {
        this.left = null;
        this.right = null;
    }

    public BinaryTreeNode(T data) {
        this.data = data;
        this.left = null;
        this.right = null;
    }
}


text:
#include <stdlib.h>

#include "py/obj.h"
#include "py/runtime.h"
#include "lib/timeutils/timeutils.h"
#include "shared-bindings/rtc/__init__.h"
#include "supervisor/port.h"
#include "supervisor/shared/translate.h"

// This is the time in seconds since 2000 that the RTC was started.
__attribute__((section(".uninitialized"))) static uint32_t rtc_offset[3];

// These values are placed before and after the current RTC count.  They are
// used to determine if the RTC count is valid.  These randomly-generated values
// will be set when the RTC value is set in order to mark the RTC as valid. If
// the system crashes or reboots, these values will remain undisturbed and the
// RTC offset will remain valid.
//
// If Circuit Python is updated or these symbols shift around, the prefix and
// suffix will no longer match, and the time will no longer be valid.
#define RTC_OFFSET_CHECK_PREFIX 0x25ea7e2a
#define RTC_OFFSET_CHECK_SUFFIX 0x2b80b69e

void common_hal_rtc_init(void) {
    // If the prefix and suffix are not valid, zero-initialize the RTC offset.
    if ((rtc_offset[0] != RTC_OFFSET_CHECK_PREFIX) || (rtc_offset[2] != RTC_OFFSET_CHECK_SUFFIX))
        rtc_offset[1] = 0;
}

void common_hal_rtc_get_time(timeutils_struct_time_t *tm) {
    uint64_t ticks_s = port_get_raw_ticks(NULL) / 1024;
    timeutils_seconds_since_2000_to_struct_time(rtc_offset[1] + ticks_s, tm);
}

void common_hal_rtc_set_time(timeutils_struct_time_t *tm) {
    uint64_t ticks_s = port_get_raw_ticks(NULL) / 1024;
    uint32_t epoch_s = timeutils_seconds_since_2000(
        tm->tm_year, tm->tm_mon, tm->tm_mday, tm->tm_hour, tm->tm_min, tm->tm_sec
    );
    rtc_offset[1] = epoch_s - ticks_s;

    // Set the prefix and suffix in order to indicate the time is valid.  This
    // must be done after the offset is updated, in case there is a crash or
    // power failure.
    rtc_offset[0] = RTC_OFFSET_CHECK_PREFIX;
    rtc_offset[2] = RTC_OFFSET_CHECK_SUFFIX;
}

int common_hal_rtc_get_calibration(void) {
    return 0;
}

void common_hal_rtc_set_calibration(int calibration) {
    mp_raise_NotImplementedError(translate("RTC calibration is not supported on this board"));
}