code stringlengths 4 1.01M |
|---|
<?php
namespace Sebastienheyd\Boilerplate\View\Composers;
use Illuminate\Support\Facades\App;
use Illuminate\View\View;
class DatatablesComposer
{
/**
* Called when view load/datatables.blade.php is called.
* This is defined in BoilerPlateServiceProvider.
*
* @param View $view
*/
public function compose(View $view)
{
$languages = collect(config('boilerplate.locale.languages'))->map(function ($element) {
return $element['datatable'];
})->toArray();
$view->with('locale', $languages[App::getLocale()] ?? 'English');
$plugins = [
'select',
'autoFill',
'buttons',
'colReorder',
'fixedHeader',
'keyTable',
'responsive',
'rowGroup',
'rowReorder',
'scroller',
'searchBuilder',
'searchPanes',
];
$view->with('plugins', $plugins);
}
}
|
<div id="certifications" class="section">
<h3>Certifications</h3>
<div class="certifications">
<div class="row">
{% for cert in site.certifications %}
{% assign odd = forloop.index | modulo: 2 %}
<div class="cert-wrapper col-sm-6 col-xs-12">
{% if cert.img %}
<a href="{{ cert.link }}">
<img class="greyscale" src="{{ cert.img }}" alt="{{ cert.name }}">
</a>
{% else %}
<figure class="cert reveal">
<a href="{{ cert.link }}">
<div class="name">{{ cert.name }}</div>
<i class="zmdi zmdi-badge-check"></i>
<div>Issuer: {{ cert.issuer }}</div>
</a>
</figure>
{% endif %}
</div>
{% if odd == 0 %}
<div class="clearfix visible-lg visible-md visible-sm"></div>
{% endif %}
{% endfor %}
</div>
</div>
</div>
|
import { Component, OnInit, ViewEncapsulation } from '@angular/core';
@Component({
selector: 'app-native',
templateUrl: './native.component.html',
styleUrls: ['./native.component.css'],
encapsulation: ViewEncapsulation.Native
})
export class NativeComponent implements OnInit {
constructor() { }
ngOnInit() {
}
}
|
// Copyright 2015 XLGAMES Inc.
//
// Distributed under the MIT License (See
// accompanying file "LICENSE" or the website
// http://www.opensource.org/licenses/mit-license.php)
#include "../Transform.h"
#include "../MainGeometry.h"
#include "../Surface.h"
#include "../ShadowProjection.h"
#include "../Vegetation/WindAnim.h"
#include "../Vegetation/InstanceVS.h"
#include "../Utility/ProjectionMath.h"
#define OPTIMISED_TRI 1
///////////////////////////////////////////////////////////////////////////////////////////////////
struct RTS_VSOutput
{
float4 position : POSITION;
#if OUTPUT_TEXCOORD==1
float2 texCoord : TEXCOORD;
#endif
#if (OUTPUT_WORLD_POSITION==1)
float3 worldPosition : WORLDPOSITION;
#endif
};
void vs_writetris(VSInput input, out RTS_VSOutput output)
{
float3 localPosition = VSIn_GetLocalPosition(input);
#if GEO_HAS_INSTANCE_ID==1
float3 objectCentreWorld;
float3 worldNormal;
float3 worldPosition = InstanceWorldPosition(input, worldNormal, objectCentreWorld);
#else
float3 worldPosition = mul(LocalToWorld, float4(localPosition,1)).xyz;
float3 objectCentreWorld = float3(LocalToWorld[0][3], LocalToWorld[1][3], LocalToWorld[2][3]);
float3 worldNormal = LocalToWorldUnitVector(VSIn_GetLocalNormal(input));
#endif
#if OUTPUT_TEXCOORD==1
output.texCoord = VSIn_GetTexCoord(input);
#endif
#if (GEO_HAS_NORMAL==1) || (GEO_HAS_TANGENT_FRAME==1)
#if (GEO_HAS_NORMAL==0) && (GEO_HAS_TANGENT_FRAME==1)
worldNormal = VSIn_GetWorldTangentFrame(input).normal;
#endif
worldPosition = PerformWindBending(worldPosition, worldNormal, objectCentreWorld, float3(1,0,0), VSIn_GetColour(input));
#endif
#if SHADOW_CASCADE_MODE==SHADOW_CASCADE_MODE_ARBITRARY
output.position = ShadowProjection_GetOutput(worldPosition, 0);
#elif SHADOW_CASCADE_MODE==SHADOW_CASCADE_MODE_ORTHOGONAL
float3 basePosition = mul(OrthoShadowWorldToProj, float4(worldPosition, 1));
float3 cascadePos = AdjustForOrthoCascade(basePosition, 0);
output.position = float4(cascadePos, 1.f);
#endif
#if OUTPUT_WORLD_POSITION==1
output.worldPosition = worldPosition.xyz;
#endif
}
struct RTSTriangle
{
#if (OPTIMISED_TRI==1)
float4 a_v0 : A;
float2 v1 : B;
float4 param : C;
float3 depths : D;
#else
float4 corners[3];
#endif
};
[maxvertexcount(1)]
void gs_writetris(
triangle RTS_VSOutput input[3],
inout PointStream<RTSTriangle> outputStream)
{
// Ideally we want the primitive id to be after frustum culling!
// But we can't get the size of the stream-output buffer from here
// So, the only way to do that is to use stream-output to collect all
// of the triangles first, and then rasterize them in a second step.
// Well, maybe that wouldn't be so bad.
if ( TriInFrustum(input[0].position, input[1].position, input[2].position)
&& BackfaceSign(input[0].position, input[1].position, input[2].position) > 0.f) {
#if (OPTIMISED_TRI==1)
RTSTriangle tri;
float2 a = input[0].position.xy / input[0].position.w;
float2 b = input[1].position.xy / input[1].position.w;
float2 c = input[2].position.xy / input[2].position.w;
float2 v0 = b - a, v1 = c - a;
float d00 = dot(v0, v0);
float d01 = dot(v0, v1);
float d11 = dot(v1, v1);
float invDenom = 1.0f / (d00 * d11 - d01 * d01);
tri.a_v0 = float4(a, v0);
tri.v1 = v1;
tri.param = float4(d00, d01, d11, invDenom);
tri.depths = float3(
input[0].position.z / input[0].position.w,
input[1].position.z / input[1].position.w,
input[2].position.z / input[2].position.w);
outputStream.Append(tri);
#else
RTSTriangle tri;
tri.corners[0] = input[0].position;
tri.corners[1] = input[1].position;
tri.corners[2] = input[2].position;
outputStream.Append(tri);
#endif
}
}
#if (OPTIMISED_TRI==1)
RTSTriangle vs_passthrough(RTSTriangle input) { return input; }
#else
void vs_passthrough(float4 position : POSITION, out float4 outPos : SV_Position) { outPos = position; }
#endif
///////////////////////////////////////////////////////////////////////////////////////////////////
struct RTS_GSInput
{
float4 position : POSITION;
};
struct RTS_GSOutput
{
float4 position : SV_Position;
nointerpolation uint triIndex : TRIINDEX;
};
///////////////////////////////////////////////////////////////////////////////////////////////////
struct ListNode
{
uint next;
uint triIndex;
};
RWTexture2D<uint> ListsHead : register(u1);
RWStructuredBuffer<ListNode> LinkedLists : register(u2);
#if (OUTPUT_PRIM_ID==1) // (set if we get the primitive id from the geometry shader)
#define TRI_INDEX_SEMANTIC PRIMID
#else
#define TRI_INDEX_SEMANTIC SV_PrimitiveID
#endif
uint ps_main(float4 pos : SV_Position, uint triIndex : TRI_INDEX_SEMANTIC) : SV_Target0
{
// it would be helpful for ListsHead where our bound render target.
// But we need to both read and write from it... That isn't possible
// without using a UAV. But it means that the pixel shader output
// is going to be discarded.
uint newNodeId = LinkedLists.IncrementCounter();
uint oldNodeId;
InterlockedExchange(ListsHead[uint2(pos.xy)], newNodeId+1, oldNodeId);
LinkedLists[newNodeId].triIndex = triIndex;
LinkedLists[newNodeId].next = oldNodeId;
// discard; // perhaps we can write out min/max here (instead of just discard)
return newNodeId;
}
|
t = PryTheme.create :name => 'pry-modern-16', :color_model => 16 do
author :name => 'Kyrylo Silin', :email => 'silin@kyrylo.org'
description 'Simplied version of pry-modern-256'
define_theme do
class_ 'bright_magenta'
class_variable 'bright_cyan'
comment 'blue'
constant 'bright_blue'
error 'black', 'white'
float 'bright_red'
global_variable 'bright_yellow'
inline_delimiter 'bright_green'
instance_variable 'bright_cyan'
integer 'bright_blue'
keyword 'bright_red'
method 'bright_yellow'
predefined_constant 'bright_cyan'
symbol 'bright_green'
regexp do
self_ 'bright_red'
char 'bright_red'
content 'magenta'
delimiter 'red'
modifier 'red'
escape 'red'
end
shell do
self_ 'bright_green'
char 'bright_green'
content 'green'
delimiter 'green'
escape 'green'
end
string do
self_ 'bright_green'
char 'bright_green'
content 'green'
delimiter 'green'
escape 'green'
end
end
end
PryTheme::ThemeList.add_theme(t)
|
/**
* Created by Wayne on 16/3/16.
*/
'use strict';
var tender = require('../controllers/tender'),
cardContr = require('../controllers/card'),
cardFilter = require('../../../libraries/filters/card'),
truckFileter = require('../../../libraries/filters/truck'),
driverFilter = require('../../../libraries/filters/driver');
module.exports = function (app) {
// app.route('/tender/wechat2/details').get(driverFilter.requi, cardContr.create);
// app.route('/tender/driver/card/bindTruck').post(driverFilter.requireDriver, cardFilter.requireById, truckFileter.requireById, cardContr.bindTruck);
};
|
<!DOCTYPE html>
<html lang="en">
<head>
<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>Zenrin Admin - Daily Report</title>
<!-- Bootstrap Core CSS -->
<link href="../vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">
<!-- MetisMenu CSS -->
<link href="../vendor/metisMenu/metisMenu.min.css" rel="stylesheet">
<!-- Custom CSS -->
<link href="../dist/css/sb-admin-2.css" rel="stylesheet">
<!-- Morris Charts CSS -->
<link href="../vendor/morrisjs/morris.css" rel="stylesheet">
<!-- Custom Fonts -->
<link href="../vendor/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div id="wrapper">
<!-- Navigation -->
<nav class="navbar navbar-default navbar-static-top" role="navigation" style="margin-bottom: 0">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="index.html">SB Admin v2.0</a>
</div>
<!-- /.navbar-header -->
<ul class="nav navbar-top-links navbar-right">
<li class="dropdown">
<a class="dropdown-toggle" data-toggle="dropdown" href="#">
<i class="fa fa-envelope fa-fw"></i> <i class="fa fa-caret-down"></i>
</a>
<ul class="dropdown-menu dropdown-messages">
<li>
<a href="#">
<div>
<strong>John Smith</strong>
<span class="pull-right text-muted">
<em>Yesterday</em>
</span>
</div>
<div>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque eleifend...</div>
</a>
</li>
<li class="divider"></li>
<li>
<a href="#">
<div>
<strong>John Smith</strong>
<span class="pull-right text-muted">
<em>Yesterday</em>
</span>
</div>
<div>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque eleifend...</div>
</a>
</li>
<li class="divider"></li>
<li>
<a href="#">
<div>
<strong>John Smith</strong>
<span class="pull-right text-muted">
<em>Yesterday</em>
</span>
</div>
<div>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque eleifend...</div>
</a>
</li>
<li class="divider"></li>
<li>
<a class="text-center" href="#">
<strong>Read All Messages</strong>
<i class="fa fa-angle-right"></i>
</a>
</li>
</ul>
<!-- /.dropdown-messages -->
</li>
<!-- /.dropdown -->
<li class="dropdown">
<a class="dropdown-toggle" data-toggle="dropdown" href="#">
<i class="fa fa-tasks fa-fw"></i> <i class="fa fa-caret-down"></i>
</a>
<ul class="dropdown-menu dropdown-tasks">
<li>
<a href="#">
<div>
<p>
<strong>Task 1</strong>
<span class="pull-right text-muted">40% Complete</span>
</p>
<div class="progress progress-striped active">
<div class="progress-bar progress-bar-success" role="progressbar" aria-valuenow="40" aria-valuemin="0" aria-valuemax="100" style="width: 40%">
<span class="sr-only">40% Complete (success)</span>
</div>
</div>
</div>
</a>
</li>
<li class="divider"></li>
<li>
<a href="#">
<div>
<p>
<strong>Task 2</strong>
<span class="pull-right text-muted">20% Complete</span>
</p>
<div class="progress progress-striped active">
<div class="progress-bar progress-bar-info" role="progressbar" aria-valuenow="20" aria-valuemin="0" aria-valuemax="100" style="width: 20%">
<span class="sr-only">20% Complete</span>
</div>
</div>
</div>
</a>
</li>
<li class="divider"></li>
<li>
<a href="#">
<div>
<p>
<strong>Task 3</strong>
<span class="pull-right text-muted">60% Complete</span>
</p>
<div class="progress progress-striped active">
<div class="progress-bar progress-bar-warning" role="progressbar" aria-valuenow="60" aria-valuemin="0" aria-valuemax="100" style="width: 60%">
<span class="sr-only">60% Complete (warning)</span>
</div>
</div>
</div>
</a>
</li>
<li class="divider"></li>
<li>
<a href="#">
<div>
<p>
<strong>Task 4</strong>
<span class="pull-right text-muted">80% Complete</span>
</p>
<div class="progress progress-striped active">
<div class="progress-bar progress-bar-danger" role="progressbar" aria-valuenow="80" aria-valuemin="0" aria-valuemax="100" style="width: 80%">
<span class="sr-only">80% Complete (danger)</span>
</div>
</div>
</div>
</a>
</li>
<li class="divider"></li>
<li>
<a class="text-center" href="#">
<strong>See All Tasks</strong>
<i class="fa fa-angle-right"></i>
</a>
</li>
</ul>
<!-- /.dropdown-tasks -->
</li>
<!-- /.dropdown -->
<li class="dropdown">
<a class="dropdown-toggle" data-toggle="dropdown" href="#">
<i class="fa fa-bell fa-fw"></i> <i class="fa fa-caret-down"></i>
</a>
<ul class="dropdown-menu dropdown-alerts">
<li>
<a href="#">
<div>
<i class="fa fa-comment fa-fw"></i> New Comment
<span class="pull-right text-muted small">4 minutes ago</span>
</div>
</a>
</li>
<li class="divider"></li>
<li>
<a href="#">
<div>
<i class="fa fa-twitter fa-fw"></i> 3 New Followers
<span class="pull-right text-muted small">12 minutes ago</span>
</div>
</a>
</li>
<li class="divider"></li>
<li>
<a href="#">
<div>
<i class="fa fa-envelope fa-fw"></i> Message Sent
<span class="pull-right text-muted small">4 minutes ago</span>
</div>
</a>
</li>
<li class="divider"></li>
<li>
<a href="#">
<div>
<i class="fa fa-tasks fa-fw"></i> New Task
<span class="pull-right text-muted small">4 minutes ago</span>
</div>
</a>
</li>
<li class="divider"></li>
<li>
<a href="#">
<div>
<i class="fa fa-upload fa-fw"></i> Server Rebooted
<span class="pull-right text-muted small">4 minutes ago</span>
</div>
</a>
</li>
<li class="divider"></li>
<li>
<a class="text-center" href="#">
<strong>See All Alerts</strong>
<i class="fa fa-angle-right"></i>
</a>
</li>
</ul>
<!-- /.dropdown-alerts -->
</li>
<!-- /.dropdown -->
<li class="dropdown">
<a class="dropdown-toggle" data-toggle="dropdown" href="#">
<i class="fa fa-user fa-fw"></i> <i class="fa fa-caret-down"></i>
</a>
<ul class="dropdown-menu dropdown-user">
<li><a href="#"><i class="fa fa-user fa-fw"></i> User Profile</a>
</li>
<li><a href="#"><i class="fa fa-gear fa-fw"></i> Settings</a>
</li>
<li class="divider"></li>
<li><a href="login.html"><i class="fa fa-sign-out fa-fw"></i> Logout</a>
</li>
</ul>
<!-- /.dropdown-user -->
</li>
<!-- /.dropdown -->
</ul>
<!-- /.navbar-top-links -->
<div class="navbar-default sidebar" role="navigation">
<div class="sidebar-nav navbar-collapse">
<ul class="nav" id="side-menu">
<li class="sidebar-search">
<div class="input-group custom-search-form">
<input type="text" class="form-control" placeholder="Search...">
<span class="input-group-btn">
<button class="btn btn-default" type="button">
<i class="fa fa-search"></i>
</button>
</span>
</div>
<!-- /input-group -->
</li>
<li>
<a href="index.html"><i class="fa fa-dashboard fa-fw"></i> Dashboard</a>
</li>
<li>
<a href="#"><i class="fa fa-bar-chart-o fa-fw"></i> Charts<span class="fa arrow"></span></a>
<ul class="nav nav-second-level">
<li>
<a href="flot.html">Flot Charts</a>
</li>
<li>
<a href="morris.html">Morris.js Charts</a>
</li>
</ul>
<!-- /.nav-second-level -->
</li>
<li>
<a href="tables.html"><i class="fa fa-table fa-fw"></i> Tables</a>
</li>
<li>
<a href="forms.html"><i class="fa fa-edit fa-fw"></i> Forms</a>
</li>
<li>
<a href="#"><i class="fa fa-wrench fa-fw"></i> UI Elements<span class="fa arrow"></span></a>
<ul class="nav nav-second-level">
<li>
<a href="panels-wells.html">Panels and Wells</a>
</li>
<li>
<a href="buttons.html">Buttons</a>
</li>
<li>
<a href="notifications.html">Notifications</a>
</li>
<li>
<a href="typography.html">Typography</a>
</li>
<li>
<a href="icons.html"> Icons</a>
</li>
<li>
<a href="grid.html">Grid</a>
</li>
</ul>
<!-- /.nav-second-level -->
</li>
<li>
<a href="#"><i class="fa fa-sitemap fa-fw"></i> Multi-Level Dropdown<span class="fa arrow"></span></a>
<ul class="nav nav-second-level">
<li>
<a href="#">Second Level Item</a>
</li>
<li>
<a href="#">Second Level Item</a>
</li>
<li>
<a href="#">Third Level <span class="fa arrow"></span></a>
<ul class="nav nav-third-level">
<li>
<a href="#">Third Level Item</a>
</li>
<li>
<a href="#">Third Level Item</a>
</li>
<li>
<a href="#">Third Level Item</a>
</li>
<li>
<a href="#">Third Level Item</a>
</li>
</ul>
<!-- /.nav-third-level -->
</li>
</ul>
<!-- /.nav-second-level -->
</li>
<li>
<a href="#"><i class="fa fa-files-o fa-fw"></i> Sample Pages<span class="fa arrow"></span></a>
<ul class="nav nav-second-level">
<li>
<a href="blank.html">Blank Page</a>
</li>
<li>
<a href="login.html">Login Page</a>
</li>
</ul>
<!-- /.nav-second-level -->
</li>
</ul>
</div>
<!-- /.sidebar-collapse -->
</div>
<!-- /.navbar-static-side -->
</nav>
<div id="page-wrapper">
<div class="row">
<div class="col-lg-12">
<h1 class="page-header">Flot</h1>
</div>
<!-- /.col-lg-12 -->
</div>
<!-- /.row -->
<div class="row">
<div class="col-lg-12">
<div class="panel panel-default">
<div class="panel-heading">
Line Chart Example
</div>
<!-- /.panel-heading -->
<div class="panel-body">
<div class="flot-chart">
<div class="flot-chart-content" id="flot-line-chart"></div>
</div>
</div>
<!-- /.panel-body -->
</div>
<!-- /.panel -->
</div>
<!-- /.col-lg-12 -->
<div class="col-lg-6">
<div class="panel panel-default">
<div class="panel-heading">
Pie Chart Example
</div>
<!-- /.panel-heading -->
<div class="panel-body">
<div class="flot-chart">
<div class="flot-chart-content" id="flot-pie-chart"></div>
</div>
</div>
<!-- /.panel-body -->
</div>
<!-- /.panel -->
</div>
<!-- /.col-lg-6 -->
<div class="col-lg-6">
<div class="panel panel-default">
<div class="panel-heading">
Multiple Axes Line Chart Example
</div>
<!-- /.panel-heading -->
<div class="panel-body">
<div class="flot-chart">
<div class="flot-chart-content" id="flot-line-chart-multi"></div>
</div>
</div>
<!-- /.panel-body -->
</div>
<!-- /.panel -->
</div>
<!-- /.col-lg-6 -->
<div class="col-lg-6">
<div class="panel panel-default">
<div class="panel-heading">
Moving Line Chart Example
</div>
<!-- /.panel-heading -->
<div class="panel-body">
<div class="flot-chart">
<div class="flot-chart-content" id="flot-line-chart-moving"></div>
</div>
</div>
<!-- /.panel-body -->
</div>
<!-- /.panel -->
</div>
<!-- /.col-lg-6 -->
<div class="col-lg-6">
<div class="panel panel-default">
<div class="panel-heading">
Bar Chart Example
</div>
<!-- /.panel-heading -->
<div class="panel-body">
<div class="flot-chart">
<div class="flot-chart-content" id="flot-bar-chart"></div>
</div>
</div>
<!-- /.panel-body -->
</div>
<!-- /.panel -->
</div>
<!-- /.col-lg-6 -->
<div class="col-lg-12">
<div class="panel panel-default">
<div class="panel-heading">
Flot Charts Usage
</div>
<!-- /.panel-heading -->
<div class="panel-body">
<p>Flot is a pure JavaScript plotting library for jQuery, with a focus on simple usage, attractive looks, and interactive features. In SB Admin, we are using the most recent version of Flot along with a few plugins to enhance the user experience. The Flot plugins being used are the tooltip plugin for hoverable tooltips, and the resize plugin for fully responsive charts. The documentation for Flot Charts is available on their website, <a target="_blank" href="http://www.flotcharts.org/">http://www.flotcharts.org/</a>.</p>
<a target="_blank" class="btn btn-default btn-lg btn-block" href="http://www.flotcharts.org/">View Flot Charts Documentation</a>
</div>
<!-- /.panel-body -->
</div>
<!-- /.panel -->
</div>
<!-- /.col-lg-6 -->
</div>
<!-- /.row -->
</div>
<!-- /#page-wrapper -->
</div>
<!-- /#wrapper -->
<!-- jQuery -->
<script src="../vendor/jquery/jquery.min.js"></script>
<!-- Bootstrap Core JavaScript -->
<script src="../vendor/bootstrap/js/bootstrap.min.js"></script>
<!-- Metis Menu Plugin JavaScript -->
<script src="../vendor/metisMenu/metisMenu.min.js"></script>
<!-- Flot Charts JavaScript -->
<script src="../vendor/flot/excanvas.min.js"></script>
<script src="../vendor/flot/jquery.flot.js"></script>
<script src="../vendor/flot/jquery.flot.pie.js"></script>
<script src="../vendor/flot/jquery.flot.resize.js"></script>
<script src="../vendor/flot/jquery.flot.time.js"></script>
<script src="../vendor/flot-tooltip/jquery.flot.tooltip.min.js"></script>
<script src="../data/flot-data.js"></script>
<!-- Custom Theme JavaScript -->
<script src="../dist/js/sb-admin-2.js"></script>
</body>
</html>
|
from rest_framework import test, status
from waldur_core.structure.models import CustomerRole, ProjectRole
from waldur_core.structure.tests import factories as structure_factories
from . import factories
class ServiceProjectLinkPermissionTest(test.APITransactionTestCase):
def setUp(self):
self.users = {
'owner': structure_factories.UserFactory(),
'admin': structure_factories.UserFactory(),
'manager': structure_factories.UserFactory(),
'no_role': structure_factories.UserFactory(),
'not_connected': structure_factories.UserFactory(),
}
# a single customer
self.customer = structure_factories.CustomerFactory()
self.customer.add_user(self.users['owner'], CustomerRole.OWNER)
# that has 3 users connected: admin, manager
self.connected_project = structure_factories.ProjectFactory(customer=self.customer)
self.connected_project.add_user(self.users['admin'], ProjectRole.ADMINISTRATOR)
self.connected_project.add_user(self.users['manager'], ProjectRole.MANAGER)
# has defined a service and connected service to a project
self.service = factories.OpenStackServiceFactory(customer=self.customer)
self.service_project_link = factories.OpenStackServiceProjectLinkFactory(
project=self.connected_project,
service=self.service)
# the customer also has another project with users but without a permission link
self.not_connected_project = structure_factories.ProjectFactory(customer=self.customer)
self.not_connected_project.add_user(self.users['not_connected'], ProjectRole.ADMINISTRATOR)
self.not_connected_project.save()
self.url = factories.OpenStackServiceProjectLinkFactory.get_list_url()
def test_anonymous_user_cannot_grant_service_to_project(self):
response = self.client.post(self.url, self._get_valid_payload())
self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
def test_user_can_connect_service_and_project_he_owns(self):
user = self.users['owner']
self.client.force_authenticate(user=user)
service = factories.OpenStackServiceFactory(customer=self.customer)
project = structure_factories.ProjectFactory(customer=self.customer)
payload = self._get_valid_payload(service, project)
response = self.client.post(self.url, payload)
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
def test_admin_cannot_connect_new_service_and_project_if_he_is_project_admin(self):
user = self.users['admin']
self.client.force_authenticate(user=user)
service = factories.OpenStackServiceFactory(customer=self.customer)
project = self.connected_project
payload = self._get_valid_payload(service, project)
response = self.client.post(self.url, payload)
# the new service should not be visible to the user
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
self.assertDictContainsSubset(
{'service': ['Invalid hyperlink - Object does not exist.']}, response.data)
def test_user_cannot_revoke_service_and_project_permission_if_he_is_project_manager(self):
user = self.users['manager']
self.client.force_authenticate(user=user)
url = factories.OpenStackServiceProjectLinkFactory.get_url(self.service_project_link)
response = self.client.delete(url)
self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
def _get_valid_payload(self, service=None, project=None):
return {
'service': factories.OpenStackServiceFactory.get_url(service),
'project': structure_factories.ProjectFactory.get_url(project)
}
|
#!/bin/env python
#
# The MIT License (MIT)
#
# Copyright (c) 2015 Billy Olsen
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
from email.mime.text import MIMEText
from jinja2 import Environment, FileSystemLoader
from datetime import datetime as dt
import os
import six
import smtplib
# Get the directory for this file.
SECRET_SANTA_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)),
'templates')
j2env = Environment(loader=FileSystemLoader(SECRET_SANTA_DIR),
trim_blocks=False)
class SantaMail(object):
"""
The SantaMail object is used to send email. This class will load email
templates that should be sent out (the master list email and the email
for each Secret Santa.
Templates will be loaded from the template directory and is configurable
via the template_master and template_santa configuration variables.
"""
REQUIRED_PARAMS = ['author', 'email', 'smtp', 'username', 'password']
def __init__(self, author, email, smtp, username, password,
template_master="master.tmpl", template_santa="santa.tmpl"):
self.author = author
self.email = email
self.smtp = smtp
self.username = username
self.password = password
self.template_master = template_master
self.template_santa = template_santa
def send(self, pairings):
"""
Sends the emails out to the secret santa participants.
The secret santa host (the user configured to send the email from)
will receive a copy of the master list.
Each Secret Santa will receive an email with the contents of the
template_santa template.
"""
for pair in pairings:
self._send_to_secret_santa(pair)
self._send_master_list(pairings)
def _do_send(self, toaddr, body, subject):
try:
msg = MIMEText(body)
msg['Subject'] = subject
msg['From'] = self.email
msg['To'] = toaddr
server = smtplib.SMTP(self.smtp)
server.starttls()
server.login(self.username, self.password)
server.sendmail(self.email, [toaddr], msg.as_string())
server.quit()
except:
print("Error sending email to %s!" % toaddr)
def _send_to_secret_santa(self, pair):
"""
Sends an email to the secret santa pairing.
"""
(giver, receiver) = pair
template = j2env.get_template(self.template_santa)
body = template.render(giver=giver, receiver=receiver)
year = dt.utcnow().year
subject = ('Your %s Farmer Family Secret Santa Match' % year)
self._do_send(giver.email, body, subject)
def _send_master_list(self, pairings):
"""
Sends an email to the game master.
"""
pair_list = []
for pair in pairings:
(giver, recipient) = pair
pair_list.append("%s -> %s" % (giver.name, recipient.name))
template = j2env.get_template(self.template_master)
body = template.render(pairs=pair_list)
year = dt.utcnow().year
subject = ('%s Farmer Family Secret Santa Master List' % year)
self._do_send(self.email, body, subject)
|
/**
* Imports
*/
import React from 'react';
import connectToStores from 'fluxible-addons-react/connectToStores';
import {RouteHandler} from 'react-router';
import {slugify} from '../../../utils/strings';
// Flux
import AccountStore from '../../../stores/Account/AccountStore';
import ApplicationStore from '../../../stores/Application/ApplicationStore';
import CollectionsStore from '../../../stores/Collections/CollectionsStore';
import DrawerStore from '../../../stores/Application/DrawerStore';
import IntlStore from '../../../stores/Application/IntlStore';
import NotificationQueueStore from '../../../stores/Application/NotificationQueueStore';
import PageLoadingStore from '../../../stores/Application/PageLoadingStore';
import popNotification from '../../../actions/Application/popNotification';
import triggerDrawer from '../../../actions/Application/triggerDrawer';
// Required components
import Drawer from '../../common/layout/Drawer/Drawer';
import Footer from '../../common/layout/Footer';
import Header from '../../common/layout/Header';
import Heading from '../../common/typography/Heading';
import OverlayLoader from '../../common/indicators/OverlayLoader';
import SideCart from '../../common/cart/SideCart';
import SideMenu from '../../common/navigation/SideMenu';
import PopTopNotification from '../../common/notifications/PopTopNotification';
/**
* Component
*/
class Application extends React.Component {
static contextTypes = {
executeAction: React.PropTypes.func.isRequired,
getStore: React.PropTypes.func.isRequired,
router: React.PropTypes.func.isRequired
};
//*** Initial State ***//
state = {
navCollections: this.context.getStore(CollectionsStore).getMainNavigationCollections(),
collectionsTree: this.context.getStore(CollectionsStore).getCollectionsTree(),
notification: this.context.getStore(NotificationQueueStore).pop(),
openedDrawer: this.context.getStore(DrawerStore).getOpenedDrawer(),
pageLoading: this.context.getStore(PageLoadingStore).isLoading()
};
//*** Component Lifecycle ***//
componentDidMount() {
// Load styles
require('./Application.scss');
}
componentWillReceiveProps(nextProps) {
this.setState({
navCollections: nextProps._navCollections,
collectionsTree: nextProps._collectionsTree,
notification: nextProps._notification,
openedDrawer: nextProps._openedDrawer,
pageLoading: nextProps._pageLoading
});
}
//*** View Controllers ***//
handleNotificationDismissClick = () => {
this.context.executeAction(popNotification);
};
handleOverlayClick = () => {
this.context.executeAction(triggerDrawer, null);
};
//*** Template ***//
render() {
let intlStore = this.context.getStore(IntlStore);
// Main navigation menu items
let collections = this.state.navCollections.map(function (collection) {
return {
name: intlStore.getMessage(collection.name),
to: 'collection-slug',
params: {
collectionId: collection.id,
collectionSlug: slugify(intlStore.getMessage(collection.name))
}
};
});
// Compute CSS classes for the overlay
let overlayClass = 'application__overlay';
if (this.state.openedDrawer === 'menu') {
overlayClass += ' application__overlay--left-drawer-open';
} else if (this.state.openedDrawer === 'cart') {
overlayClass += ' application__overlay--right-drawer-open';
}
// Compute CSS classes for the content
let contentClass = 'application__container';
if (this.state.openedDrawer === 'menu') {
contentClass += ' application__container--left-drawer-open';
} else if (this.state.openedDrawer === 'cart') {
contentClass += ' application__container--right-drawer-open';
}
// Check if user logged-in is an Admin
//let isAdmin = this.context.getStore(AccountStore).isAuthorized(['admin']);
// Return
return (
<div className="application">
{this.state.pageLoading ?
<OverlayLoader />
:
null
}
{this.state.notification ?
<PopTopNotification key={this.context.getStore(ApplicationStore).uniqueId()}
type={this.state.notification.type}
onDismissClick={this.handleNotificationDismissClick}>
{this.state.notification.message}
</PopTopNotification>
:
null
}
<Drawer position="left" open={this.state.openedDrawer === 'menu'}>
<SideMenu collections={collections} />
</Drawer>
<Drawer position="right" open={this.state.openedDrawer === 'cart'}>
<SideCart />
</Drawer>
<div className={overlayClass} onClick={this.handleOverlayClick}>
<div className="application__overlay-content"></div>
</div>
<div className={contentClass}>
<Header collections={collections} collectionsTree={this.state.collectionsTree} />
<div className="application__container-wrapper">
<div className="application__container-content">
<RouteHandler />
</div>
</div>
<Footer />
</div>
</div>
);
}
}
/**
* Flux
*/
Application = connectToStores(Application, [
AccountStore,
CollectionsStore,
DrawerStore,
NotificationQueueStore,
PageLoadingStore
], (context) => {
return {
_navCollections: context.getStore(CollectionsStore).getMainNavigationCollections(),
_collectionsTree: context.getStore(CollectionsStore).getCollectionsTree(),
_notification: context.getStore(NotificationQueueStore).pop(),
_openedDrawer: context.getStore(DrawerStore).getOpenedDrawer(),
_pageLoading: context.getStore(PageLoadingStore).isLoading()
};
});
/**
* Exports
*/
export default Application;
|
# frozen_string_literal: true
require 'spec_helper'
describe CloudPayments::Namespaces do
subject{ CloudPayments::Client.new }
describe '#payments' do
specify{ expect(subject.payments).to be_instance_of(CloudPayments::Namespaces::Payments) }
end
describe '#subscriptions' do
specify{ expect(subject.subscriptions).to be_instance_of(CloudPayments::Namespaces::Subscriptions) }
end
describe '#ping' do
context 'when successful response' do
before{ stub_api_request('ping/successful').perform }
specify{ expect(subject.ping).to be_truthy }
end
context 'when failed response' do
before{ stub_api_request('ping/failed').perform }
specify{ expect(subject.ping).to be_falsy }
end
context 'when empty response' do
before{ stub_api_request('ping/failed').to_return(body: '') }
specify{ expect(subject.ping).to be_falsy }
end
context 'when error response' do
before{ stub_api_request('ping/failed').to_return(status: 404) }
specify{ expect(subject.ping).to be_falsy }
end
context 'when exception occurs while request' do
before{ stub_api_request('ping/failed').to_raise(::Faraday::Error::ConnectionFailed) }
specify{ expect(subject.ping).to be_falsy }
end
context 'when timeout occurs while request' do
before{ stub_api_request('ping/failed').to_timeout }
specify{ expect(subject.ping).to be_falsy }
end
end
end
|
/**
* The main purpose of this in my mind is for navigation
* this way when this route is entered either via direct url
* or by a link-to etc you send a ping so that nav can be updated
* in the hierarchy.
*
* curious about feedback. I have used something similar in practice
* but it's mainly for keeping the ui correct and things like that
* without tightly coupling things together or at least that is my
* hope.
*/
export default Ember.Route.extend({
beforeModel: function(trans) {
trans.send('ping', this.routeName);
}
});
|
---
title: getMutation
description: getMutation API reference for redux-requests - declarative AJAX requests and automatic network state management for single-page applications
---
Almost the same as `getQuery`, it is just used for mutations:
```js
import { getMutation } from '@redux-requests/core';
const deleteBookMutation = getMutation(state, { type: 'DELETE_BOOK' });
/* for example {
loading: false,
error: null,
pending: 0 // number of pending requests
downloadProgress: null, // only when requestAction.meta.measureDownloadProgress is true
uploadProgress: null, // only when requestAction.meta.measureUploadProgress is true
} */
```
It accept `type` and optionally `requestKey` props, which work like for queries.
|
#!/bin/sh
# CYBERWATCH SAS - 2017
#
# Security fix for RHSA-2010:0221
#
# Security announcement date: 2010-03-30 17:00:57 UTC
# Script generation date: 2017-01-01 21:12:44 UTC
#
# Operating System: Red Hat 5
# Architecture: x86_64
#
# Vulnerable packages fix on version:
# - squid.x86_64:2.6.STABLE21-6.el5
# - squid-debuginfo.x86_64:2.6.STABLE21-6.el5
#
# Last versions recommanded by security team:
# - squid.x86_64:2.6.STABLE21-7.el5_10
# - squid-debuginfo.x86_64:2.6.STABLE21-7.el5_10
#
# CVE List:
# - CVE-2009-2855
# - CVE-2010-0308
#
# More details:
# - https://www.cyberwatch.fr/vulnerabilites
#
# Licence: Released under The MIT License (MIT), See LICENSE FILE
sudo yum install squid.x86_64-2.6.STABLE21 -y
sudo yum install squid-debuginfo.x86_64-2.6.STABLE21 -y
|
.titlebar-view {
color: #a6e22e;
z-index: 99;
}
.titlebar-view .message-box {
width: 500px;
height: 70px;
background-color: #272822;
border: 1px solid #000000;
border-radius: 5px;
border-radius: 5px;
position: absolute;
left: 50%;
margin-left: -200px;
box-shadow: 1px 1px 10px #000;
box-shadow: 1px 1px 10px #000;
text-align: center;
color: #a6e22e;
padding-top: 30px;
transform: translateY(-100px);
-webkit-transform: translateY(-100px);
-moz-transform: translateY(-100px);
-ms-transform: translateY(-100px);
-webkit-transition: all 0.3s;
-moz-transition: all 0.3s;
transition: all 0.3s;
}
.titlebar-view .message-box p {
opacity: 0;
-webkit-transition: all 0.3s;
-moz-transition: all 0.3s;
transition: all 0.3s;
}
.titlebar-view .message-box.open {
transform: translateY(-30px);
-moz-transform: translateY(-30px);
-webkit-transform: translateY(-30px);
-ms-transform: translateY(-30px);
}
.titlebar-view .message-box.open p {
opacity: 1;
}
.titlebar-view > ul {
margin: 0;
}
.titlebar-view > ul > li {
list-style-type: none;
float: left;
margin: 0;
position: relative;
margin-right: 40px;
}
.titlebar-view:not(.disabled) > ul > li {
cursor: pointer;
}
.titlebar-view.disabled a {
opacity: 0.5;
}
.titlebar-view > ul > li > a,
.titlebar-view > ul > li > ul > li > a {
-webkit-transition: all 0.5s;
-moz-transition: all 0.5s;
transition: all 0.5s;
}
.titlebar-view:not(.disabled) > ul > li:hover > a,
.titlebar-view:not(.disabled) > ul > li > ul > li:hover > a {
text-shadow: 1px 1px 25px #fff;
}
.titlebar-view:not(.disabled) > ul > li:hover > ul,
.titlebar-view:not(.disabled) > ul > li:active > ul
{
display: block;
}
.titlebar-view > ul > li > ul {
width: 170px;
padding: 20px;
position: absolute;
z-index: 0;
box-shadow: 1px 1px 50px #000;
box-shadow: 1px 1px 50px #000;
border-radius: 10px;
border-radius: 10px;
top: 30px;
background-color: #272822;
display: none;
}
.titlebar-view > ul > li > ul > .triangle {
width: 0px;
height: 0px;
border-style: solid;
border-width: 0 25px 25px 25px;
border-color: transparent transparent #272822 transparent;
position: absolute;
top: -20px;
}
.titlebar-view > ul > li > ul > li {
list-style-type: none;
margin-top: 20px;
}
.titlebar-view .version {
float: right;
margin-right: 50px;
font-size: 12px;
}
|
using Windows.UI.Xaml.Controls;
namespace ZhihuDaily.Models
{
public enum ArticleParagraphType
{
ArticleParagraphTypeText,
ArticleParagraphTypeImage,
ArticleParagraphTypeRichText,
ArticleParagraphTypeLink,
ArticleParagraphTypeLiangpingLink,
ArticleParagraphTypeHrLine,
//引用
ArticleParagraphTypeBlockquote,
//标题
ArticleParagraphTypeH1,
//引用
ArticleParagraphTypePre,
//作者信息
ArticleParagraphTypeAuthor,
//空行
ArticleParagraphTypeEmptyLine,
//加粗
ArticleParagraphTypeStrongText,
//视频
ArticleParagraphTypeVideo,
//头像
ArticleParagraphTypeAvatar,
//没有长评论
ArticleParagraphTypeNoLongComment,
//评论
ArticleParagraphTypeComment,
//广告
ArticleParagraphTypeAd,
//评论标题
ArticleParagraphTypeCommentTitle,
}
public class ArticleParagraph
{
public ArticleParagraphType Type { get; set; }
public string Content { get; set; }
public string Value { get; set; }
public string SubValue { get; set; }
public object TagValue { get; set; }
public RichTextBlock RichTextBlock { get; set; }
}
}
|
// Copyright (c) the authors of nanoGames. All rights reserved.
// Licensed under the MIT license. See LICENSE.txt in the project root.
using OpenTK.Graphics.OpenGL4;
using System;
using System.Text;
namespace NanoGames.Engine.OpenGLWrappers
{
/// <summary>
/// Represents a shader program.
/// </summary>
internal sealed class Shader : IDisposable
{
private readonly int _id;
/// <summary>
/// Initializes a new instance of the <see cref="Shader"/> class
/// loaded and compiled from an embedded resource.
/// </summary>
/// <param name="name">The name/path of the resource to load.</param>
public Shader(string name)
{
int vertexShaderId = LoadProgram(name + ".vs.glsl", ShaderType.VertexShader);
int fragmentShaderId = LoadProgram(name + ".fs.glsl", ShaderType.FragmentShader);
_id = GL.CreateProgram();
GL.AttachShader(_id, vertexShaderId);
GL.AttachShader(_id, fragmentShaderId);
GL.LinkProgram(_id);
int status;
GL.GetProgram(_id, GetProgramParameterName.LinkStatus, out status);
if (status == 0)
{
throw new Exception("Error linking shader: " + GL.GetProgramInfoLog(_id));
}
}
/// <inheritdoc/>
public void Dispose()
{
GL.DeleteProgram(_id);
}
/// <summary>
/// Binds the shader to the OpenGL context.
/// </summary>
public void Bind()
{
GL.UseProgram(_id);
}
private static int LoadProgram(string path, ShaderType type)
{
var source = LoadResource(path);
var id = GL.CreateShader(type);
GL.ShaderSource(id, source);
GL.CompileShader(id);
int status;
GL.GetShader(id, ShaderParameter.CompileStatus, out status);
if (status == 0)
{
throw new Exception("Error compiling shader: " + GL.GetShaderInfoLog(id));
}
return id;
}
private static string LoadResource(string path)
{
var stream = typeof(Shader).Assembly.GetManifestResourceStream(path);
using (var reader = new System.IO.StreamReader(stream, Encoding.UTF8))
{
return reader.ReadToEnd();
}
}
}
}
|
//
// NSData+QGOCCAES256.h
// QGOCCategory
//
// Created by 张如泉 on 15/10/4.
// Copyright © 2015年 QuanGe. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface NSData (QGOCCAES256)
/**
* 对NSData进行AES256加密
* @param key:加密钥匙
* return 加密后的NSData
*/
- (NSData *)qgocc_aes256_encrypt:(NSString *)key;
/**
* 对NSData进行AES256解密
* @param key:加密钥匙
* return 解密后的NSData
*/
- (NSData *)qgocc_aes256_decrypt:(NSString *)key;
@end
|
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Yet Another Patcher")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Martomo")]
[assembly: AssemblyProduct("Yet Another Patcher")]
[assembly: AssemblyCopyright("Copyright © Martomo 2012")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("92a94924-f318-4a9d-a3a1-33db6edbdbbf")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
|
require File.expand_path('../boot', __FILE__)
require 'rack/contrib'
require "rails"
# Pick the frameworks you want:
require "active_model/railtie"
require "active_job/railtie"
require "active_record/railtie"
require "action_controller/railtie"
require "action_mailer/railtie"
require "action_view/railtie"
# require "sprockets/railtie"
# require "rails/test_unit/railtie"
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)
module IdeaPool
class Application < Rails::Application
config.middleware.use Rack::JSONP
# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
# Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
# Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC.
# config.time_zone = 'Central Time (US & Canada)'
config.time_zone = 'Taipei'
# The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.
# config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s]
# config.i18n.default_locale = :de
# Do not swallow errors in after_commit/after_rollback callbacks.
config.active_record.raise_in_transactional_callbacks = true
config.autoload_paths += %W(#{config.root}/app/uploaders)
end
end
|
package main
import (
"fmt"
"io"
"io/ioutil"
"log"
"net"
"net/http"
)
func main() {
http.HandleFunc("/host", hostFinder)
http.HandleFunc("/ip", sourceIp)
http.HandleFunc("/date", GetJosnTime)
fmt.Println("Listening on 0.0.0.0:8000")
err := http.ListenAndServe("0.0.0.0:8000", nil)
if err != nil {
log.Fatal(err)
}
}
func hostFinder(rw http.ResponseWriter, req *http.Request) {
hostPort := req.Host
host, port, _ := net.SplitHostPort(hostPort)
io.WriteString(rw, "<html>")
io.WriteString(rw, "Host Name : "+host+" <br>")
io.WriteString(rw, "Port Number : "+port)
io.WriteString(rw, "</br>")
io.WriteString(rw, req.RemoteAddr)
io.WriteString(rw, "</html>")
// io.WriteString(w, s)
}
func sourceIp(rw http.ResponseWriter, req *http.Request) {
host, _, _ := net.SplitHostPort(req.RemoteAddr)
io.WriteString(rw, "<h1> Your Ip address : "+host)
}
func GetJosnTime(rw http.ResponseWriter, req *http.Request) {
rw.Header().Set("Content-type", "application/json")
rw.Header().Add("Content-type", "charset=utf-8")
response, _ := http.Get("http://date.jsontest.com/")
defer response.Body.Close()
data, _ := ioutil.ReadAll(response.Body)
io.WriteString(rw, string(data))
}
|
//
// MUTextKitContext.h
// MUKit_Example
//
// Created by Jekity on 2018/9/6.
// Copyright © 2018年 Jeykit. All rights reserved.
//
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
@interface MUTextKitContext : NSObject
/**
Initializes a context and its associated TextKit components.
Initialization of TextKit components is a globally locking operation so be careful of bottlenecks with this class.
*/
- (instancetype)initWithAttributedString:(NSAttributedString *)attributedString
lineBreakMode:(NSLineBreakMode)lineBreakMode
maximumNumberOfLines:(NSUInteger)maximumNumberOfLines
exclusionPaths:(NSArray *)exclusionPaths
constrainedSize:(CGSize)constrainedSize;
/**
All operations on TextKit values MUST occur within this locked context. Simultaneous access (even non-mutative) to
TextKit components may cause crashes.
The block provided MUST not call out to client code from within its scope or it is possible for this to cause deadlocks
in your application. Use with EXTREME care.
Callers MUST NOT keep a ref to these internal objects and use them later. This WILL cause crashes in your application.
__attribute__((noescape)) 标记一个block
*/
- (void)performBlockWithLockedTextKitComponents:( void (^)(NSLayoutManager *layoutManager,
NSTextStorage *textStorage,
NSTextContainer *textContainer))block;
@property (nonatomic, strong ,readonly) NSLayoutManager *layoutManager;
@property (nonatomic, strong ,readonly) NSTextStorage *textStorage;
@property (nonatomic, strong ,readonly) NSTextContainer *textContainer;
@end
|
// Copyright (c) 2016 Yusuke Sasaki
//
// This software is released under the MIT License.
// See http://opensource.org/licenses/mit-license.php or <LICENSE>.
use ffi;
use itertools::{Itertools, Zip};
use std::mem::transmute;
use std::ops::Deref;
use std::ptr::null;
use std::os::raw;
use error::{Error, Result};
use model::{Model, Var, ConstrSense};
use model::expr::LinExpr;
use util;
// Location where the callback called.
const POLLING: i32 = 0;
const PRESOLVE: i32 = 1;
const SIMPLEX: i32 = 2;
const MIP: i32 = 3;
const MIPSOL: i32 = 4;
const MIPNODE: i32 = 5;
const MESSAGE: i32 = 6;
const BARRIER: i32 = 7;
const PRE_COLDEL: i32 = 1000;
const PRE_ROWDEL: i32 = 1001;
const PRE_SENCHG: i32 = 1002;
const PRE_BNDCHG: i32 = 1003;
const PRE_COECHG: i32 = 1004;
const SPX_ITRCNT: i32 = 2000;
const SPX_OBJVAL: i32 = 2001;
const SPX_PRIMINF: i32 = 2002;
const SPX_DUALINF: i32 = 2003;
const SPX_ISPERT: i32 = 2004;
const MIP_OBJBST: i32 = 3000;
const MIP_OBJBND: i32 = 3001;
const MIP_NODCNT: i32 = 3002;
const MIP_SOLCNT: i32 = 3003;
const MIP_CUTCNT: i32 = 3004;
const MIP_NODLFT: i32 = 3005;
const MIP_ITRCNT: i32 = 3006;
#[allow(dead_code)]
const MIP_OBJBNDC: i32 = 3007;
const MIPSOL_SOL: i32 = 4001;
const MIPSOL_OBJ: i32 = 4002;
const MIPSOL_OBJBST: i32 = 4003;
const MIPSOL_OBJBND: i32 = 4004;
const MIPSOL_NODCNT: i32 = 4005;
const MIPSOL_SOLCNT: i32 = 4006;
#[allow(dead_code)]
const MIPSOL_OBJBNDC: i32 = 4007;
const MIPNODE_STATUS: i32 = 5001;
const MIPNODE_REL: i32 = 5002;
const MIPNODE_OBJBST: i32 = 5003;
const MIPNODE_OBJBND: i32 = 5004;
const MIPNODE_NODCNT: i32 = 5005;
const MIPNODE_SOLCNT: i32 = 5006;
#[allow(dead_code)]
const MIPNODE_BRVAR: i32 = 5007;
#[allow(dead_code)]
const MIPNODE_OBJBNDC: i32 = 5008;
const MSG_STRING: i32 = 6001;
const RUNTIME: i32 = 6002;
const BARRIER_ITRCNT: i32 = 7001;
const BARRIER_PRIMOBJ: i32 = 7002;
const BARRIER_DUALOBJ: i32 = 7003;
const BARRIER_PRIMINF: i32 = 7004;
const BARRIER_DUALINF: i32 = 7005;
const BARRIER_COMPL: i32 = 7006;
/// Location where the callback called
///
/// If you want to get more information, see [official
/// manual](https://www.gurobi.com/documentation/6.5/refman/callback_codes.html).
#[derive(Debug, Clone)]
pub enum Where {
/// Periodic polling callback
Polling,
/// Currently performing presolve
PreSolve {
/// The number of columns removed by presolve to this point.
coldel: i32,
/// The number of rows removed by presolve to this point.
rowdel: i32,
/// The number of constraint senses changed by presolve to this point.
senchg: i32,
/// The number of variable bounds changed by presolve to this point.
bndchg: i32,
/// The number of coefficients changed by presolve to this point.
coecfg: i32
},
/// Currently in simplex
Simplex {
/// Current simplex iteration count.
itrcnt: f64,
/// Current simplex objective value.
objval: f64,
/// Current primal infeasibility.
priminf: f64,
/// Current dual infeasibility.
dualinf: f64,
/// Is problem current perturbed?
ispert: i32
},
/// Currently in MIP
MIP {
/// Current best objective.
objbst: f64,
/// Current best objective bound.
objbnd: f64,
/// Current explored node count.
nodcnt: f64,
/// Current count of feasible solutions found.
solcnt: f64,
/// Current count of cutting planes applied.
cutcnt: i32,
/// Current unexplored node count.
nodleft: f64,
/// Current simplex iteration count.
itrcnt: f64
},
/// Found a new MIP incumbent
MIPSol {
/// Objective value for new solution.
obj: f64,
/// Current best objective.
objbst: f64,
/// Current best objective bound.
objbnd: f64,
/// Current explored node count.
nodcnt: f64,
/// Current count of feasible solutions found.
solcnt: f64
},
/// Currently exploring a MIP node
MIPNode {
/// Optimization status of current MIP node (see the Status Code section for further information).
status: i32,
/// Current best objective.
objbst: f64,
/// Current best objective bound.
objbnd: f64,
/// Current explored node count.
nodcnt: f64,
/// Current count of feasible solutions found.
solcnt: i32
},
/// Printing a log message
Message(String),
/// Currently in barrier.
Barrier {
/// Current barrier iteration count.
itrcnt: i32,
/// Primal objective value for current barrier iterate.
primobj: f64,
/// Dual objective value for current barrier iterate.
dualobj: f64,
/// Primal infeasibility for current barrier iterate.
priminf: f64,
/// Dual infeasibility for current barrier iterate.
dualinf: f64,
/// Complementarity violation for current barrier iterate.
compl: f64
}
}
impl Into<i32> for Where {
fn into(self) -> i32 {
match self {
Where::Polling => POLLING,
Where::PreSolve { .. } => PRESOLVE,
Where::Simplex { .. } => SIMPLEX,
Where::MIP { .. } => MIP,
Where::MIPSol { .. } => MIPSOL,
Where::MIPNode { .. } => MIPNODE,
Where::Message(_) => MESSAGE,
Where::Barrier { .. } => BARRIER,
}
}
}
/// The context object for Gurobi callback.
pub struct Callback<'a> {
cbdata: *mut ffi::c_void,
where_: Where,
model: &'a Model
}
pub trait New<'a> {
fn new(cbdata: *mut ffi::c_void, where_: i32, model: &'a Model) -> Result<Callback<'a>>;
}
impl<'a> New<'a> for Callback<'a> {
fn new(cbdata: *mut ffi::c_void, where_: i32, model: &'a Model) -> Result<Callback<'a>> {
let mut callback = Callback {
cbdata: cbdata,
where_: Where::Polling,
model: model
};
let where_ = match where_ {
POLLING => Where::Polling,
PRESOLVE => {
Where::PreSolve {
coldel: try!(callback.get_int(PRESOLVE, PRE_COLDEL)),
rowdel: try!(callback.get_int(PRESOLVE, PRE_ROWDEL)),
senchg: try!(callback.get_int(PRESOLVE, PRE_SENCHG)),
bndchg: try!(callback.get_int(PRESOLVE, PRE_BNDCHG)),
coecfg: try!(callback.get_int(PRESOLVE, PRE_COECHG))
}
}
SIMPLEX => {
Where::Simplex {
itrcnt: try!(callback.get_double(SIMPLEX, SPX_ITRCNT)),
objval: try!(callback.get_double(SIMPLEX, SPX_OBJVAL)),
priminf: try!(callback.get_double(SIMPLEX, SPX_PRIMINF)),
dualinf: try!(callback.get_double(SIMPLEX, SPX_DUALINF)),
ispert: try!(callback.get_int(SIMPLEX, SPX_ISPERT))
}
}
MIP => {
Where::MIP {
objbst: try!(callback.get_double(MIP, MIP_OBJBST)),
objbnd: try!(callback.get_double(MIP, MIP_OBJBND)),
nodcnt: try!(callback.get_double(MIP, MIP_NODCNT)),
solcnt: try!(callback.get_double(MIP, MIP_SOLCNT)),
cutcnt: try!(callback.get_int(MIP, MIP_CUTCNT)),
nodleft: try!(callback.get_double(MIP, MIP_NODLFT)),
itrcnt: try!(callback.get_double(MIP, MIP_ITRCNT))
}
}
MIPSOL => {
Where::MIPSol {
obj: try!(callback.get_double(MIPSOL, MIPSOL_OBJ)),
objbst: try!(callback.get_double(MIPSOL, MIPSOL_OBJBST)),
objbnd: try!(callback.get_double(MIPSOL, MIPSOL_OBJBND)),
nodcnt: try!(callback.get_double(MIPSOL, MIPSOL_NODCNT)),
solcnt: try!(callback.get_double(MIPSOL, MIPSOL_SOLCNT))
}
}
MIPNODE => {
Where::MIPNode {
status: try!(callback.get_int(MIPNODE, MIPNODE_STATUS)),
objbst: try!(callback.get_double(MIPNODE, MIPNODE_OBJBST)),
objbnd: try!(callback.get_double(MIPNODE, MIPNODE_OBJBND)),
nodcnt: try!(callback.get_double(MIPNODE, MIPNODE_NODCNT)),
solcnt: try!(callback.get_int(MIPNODE, MIPNODE_SOLCNT))
}
}
MESSAGE => Where::Message(try!(callback.get_string(MESSAGE, MSG_STRING)).trim().to_owned()),
BARRIER => {
Where::Barrier {
itrcnt: try!(callback.get_int(BARRIER, BARRIER_ITRCNT)),
primobj: try!(callback.get_double(BARRIER, BARRIER_PRIMOBJ)),
dualobj: try!(callback.get_double(BARRIER, BARRIER_DUALOBJ)),
priminf: try!(callback.get_double(BARRIER, BARRIER_PRIMINF)),
dualinf: try!(callback.get_double(BARRIER, BARRIER_DUALINF)),
compl: try!(callback.get_double(BARRIER, BARRIER_COMPL))
}
}
_ => panic!("Invalid callback location. {}", where_)
};
callback.where_ = where_;
Ok(callback)
}
}
impl<'a> Callback<'a> {
/// Retrieve the location where the callback called.
pub fn get_where(&self) -> Where { self.where_.clone() }
/// Retrive node relaxation solution values at the current node.
pub fn get_node_rel(&self, vars: &[Var]) -> Result<Vec<f64>> {
// memo: only MIPNode && status == Optimal
self.get_double_array(MIPNODE, MIPNODE_REL).map(|buf| vars.iter().map(|v| buf[v.index() as usize]).collect_vec())
}
/// Retrieve values from the current solution vector.
pub fn get_solution(&self, vars: &[Var]) -> Result<Vec<f64>> {
self.get_double_array(MIPSOL, MIPSOL_SOL).map(|buf| vars.iter().map(|v| buf[v.index() as usize]).collect_vec())
}
/// Provide a new feasible solution for a MIP model.
pub fn set_solution(&self, vars: &[Var], solution: &[f64]) -> Result<()> {
if vars.len() != solution.len() || vars.len() < self.model.vars.len() {
return Err(Error::InconsitentDims);
}
let mut buf = vec![0.0; self.model.vars.len()];
for (v, &sol) in Zip::new((vars.iter(), solution.iter())) {
let i = v.index() as usize;
buf[i] = sol;
}
self.check_apicall(unsafe { ffi::GRBcbsolution(self.cbdata, buf.as_ptr()) })
}
/// Retrieve the elapsed solver runtime [sec].
pub fn get_runtime(&self) -> Result<f64> {
if let Where::Polling = self.get_where() {
return Err(Error::FromAPI("bad call in callback".to_owned(), 40001));
}
self.get_double(self.get_where().into(), RUNTIME)
}
/// Add a new cutting plane to the MIP model.
pub fn add_cut(&self, lhs: LinExpr, sense: ConstrSense, rhs: f64) -> Result<()> {
let (vars, coeff, offset) = lhs.into();
self.check_apicall(unsafe {
ffi::GRBcbcut(self.cbdata,
coeff.len() as ffi::c_int,
vars.as_ptr(),
coeff.as_ptr(),
sense.into(),
rhs - offset)
})
}
/// Add a new lazy constraint to the MIP model.
pub fn add_lazy(&self, lhs: LinExpr, sense: ConstrSense, rhs: f64) -> Result<()> {
let (vars, coeff, offset) = lhs.into();
self.check_apicall(unsafe {
ffi::GRBcblazy(self.cbdata,
coeff.len() as ffi::c_int,
vars.as_ptr(),
coeff.as_ptr(),
sense.into(),
rhs - offset)
})
}
fn get_int(&self, where_: i32, what: i32) -> Result<i32> {
let mut buf = 0;
self.check_apicall(unsafe { ffi::GRBcbget(self.cbdata, where_, what, &mut buf as *mut i32 as *mut raw::c_void) }).and(Ok(buf.into()))
}
fn get_double(&self, where_: i32, what: i32) -> Result<f64> {
let mut buf = 0.0;
self.check_apicall(unsafe { ffi::GRBcbget(self.cbdata, where_, what, &mut buf as *mut f64 as *mut raw::c_void) }).and(Ok(buf.into()))
}
fn get_double_array(&self, where_: i32, what: i32) -> Result<Vec<f64>> {
let mut buf = vec![0.0; self.model.vars.len()];
self.check_apicall(unsafe { ffi::GRBcbget(self.cbdata, where_, what, transmute(buf.as_mut_ptr())) }).and(Ok(buf))
}
fn get_string(&self, where_: i32, what: i32) -> Result<String> {
let mut buf = null();
self.check_apicall(unsafe { ffi::GRBcbget(self.cbdata, where_, what, &mut buf as *mut *const i8 as *mut raw::c_void) })
.and(Ok(unsafe { util::from_c_str(buf) }))
}
fn check_apicall(&self, error: ffi::c_int) -> Result<()> {
if error != 0 {
return Err(Error::FromAPI("Callback error".to_owned(), 40000));
}
Ok(())
}
}
impl<'a> Deref for Callback<'a> {
type Target = Model;
fn deref(&self) -> &Model { self.model }
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace task_2
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Ohjelma laskee N ensimmäistä lukua yhteen.");
string userInput = Console.ReadLine();
int number = int.Parse(userInput);
int i = 1;
int f = 1;
int k = 1;
if (number < 0)
{
k = -1;
}
do
{
i = i + 1;
f = f + i;
} while (i < number*k);
Console.Write($"Syötit: {number}, Summa: {f*k}");
Console.ReadLine();
}
}
}
|
import React, { PropTypes } from 'react';
import { Provider } from 'react-redux';
import Routers from './Routers';
/**
* Component is exported for conditional usage in Root.js
*/
const Root = ({ store }) => (
/**
* Provider is a component provided to us by the 'react-redux' bindings that
* wraps our app - thus making the Redux store/state available to our 'connect()'
* calls in component hierarchy below.
*/
<Provider store={store}>
<div>
{Routers}
</div>
</Provider>
);
Root.propTypes = {
store: PropTypes.object.isRequired // eslint-disable-line react/forbid-prop-types
};
module.exports = Root;
|
local blinkTime = 250
local events = {}
local function removeBlink(id)
local creature = g_map.getCreatureById(id)
if creature and creature:getBlinkHitEffect() then
creature:setBlinkHitEffect(false)
end
removeEvent(events[id])
events[id] = nil
end
Blink = {}
Blink.remove =
function (id, instantly)
if instantly then
removeBlink(id)
return
end
removeEvent(events[id])
events[id] = scheduleEvent(function() removeBlink(id) end, blinkTime)
end
Blink.removeAll =
function (instantly)
for id, _ in ipairs(events) do
Blink.remove(id, instantly)
end
if instantly then
events = {}
end
end
Blink.add =
function (id)
local creature = g_map.getCreatureById(id)
if not creature then return end
-- Will keep enabled if another event is added before the last finishes
if creature:getBlinkHitEffect() and events[id] then
removeEvent(events[id])
end
creature:setBlinkHitEffect(true)
Blink.remove(id)
end
function init()
Blink.removeAll(true)
ProtocolGame.registerExtendedOpcode(GameServerOpcodes.GameServerBlinkHit, onBlinkHit)
end
function terminate()
Blink.removeAll(true)
ProtocolGame.unregisterExtendedOpcode(GameServerOpcodes.GameServerBlinkHit)
end
function onBlinkHit(protocol, opcode, buffer)
local params = string.split(buffer, ':')
local id = tonumber(params[1])
if not id then return end
Blink.add(id)
end
|
import actions from './shortcuts';
class MockClientStore {
update(cb) {
this.updateCallback = cb;
}
}
describe('manager.shortcuts.actions.shortcuts', () => {
describe('setOptions', () => {
test('should update options', () => {
const clientStore = new MockClientStore();
actions.setOptions({ clientStore }, { abc: 10 });
const state = {
shortcutOptions: { bbc: 50, abc: 40 },
};
const stateUpdates = clientStore.updateCallback(state);
expect(stateUpdates).toEqual({
shortcutOptions: { bbc: 50, abc: 10 },
});
});
test('should only update options for the key already defined', () => {
const clientStore = new MockClientStore();
actions.setOptions({ clientStore }, { abc: 10, kki: 50 });
const state = {
shortcutOptions: { bbc: 50, abc: 40 },
};
const stateUpdates = clientStore.updateCallback(state);
expect(stateUpdates).toEqual({
shortcutOptions: { bbc: 50, abc: 10 },
});
});
test('should warn about deprecated option names', () => {
const clientStore = new MockClientStore();
const spy = jest.spyOn(console, 'warn').mockImplementation(() => {});
actions.setOptions(
{ clientStore },
{
showLeftPanel: 1,
showDownPanel: 2,
downPanelInRight: 3,
}
);
const state = {
shortcutOptions: {},
};
const stateUpdates = clientStore.updateCallback(state);
expect(spy).toHaveBeenCalledTimes(3);
expect(stateUpdates).toEqual({
shortcutOptions: {
showStoriesPanel: 1,
showAddonPanel: 2,
addonPanelInRight: 3,
},
});
spy.mockReset();
spy.mockRestore();
});
});
});
|
/**
* Application compile time config settings.
*
* This file is empty and only serves to work around this problem, although
* this may be a good place to add any config handling code in future.
*/
#include "config.h"
// Make the SSerial port available if needed
#ifdef SOFTSERIAL_EN
SoftwareSerial SSerial(SOFTSERIAL_RX, SOFTSERIAL_TX);
#endif // SOFTSERIAL_EN
|
using Builder.Localization;
using Builder.Resolver;
using System.Collections.Generic;
namespace Builder.ParseTree
{
internal class FieldDefinition : TopLevelEntity, ICodeContainer
{
public Token NameToken { get; set; }
public Expression DefaultValue { get; set; }
public int MemberID { get; set; }
public int StaticMemberID { get; set; }
public AnnotationCollection Annotations { get; set; }
public List<Lambda> Lambdas { get; private set; }
public AType FieldType { get; private set; }
public ResolvedType ResolvedFieldType { get; private set; }
public HashSet<string> ArgumentNameLookup { get; private set; }
public FieldDefinition(
Token fieldToken,
AType fieldType,
Token nameToken,
ClassDefinition owner,
ModifierCollection modifiers,
AnnotationCollection annotations)
: base(fieldToken, owner, owner.FileScope, modifiers)
{
this.NameToken = nameToken;
this.FieldType = fieldType;
this.DefaultValue = null;
this.MemberID = -1;
this.Annotations = annotations;
this.Lambdas = new List<Lambda>();
this.ArgumentNameLookup = new HashSet<string>();
if (modifiers.HasAbstract) throw new ParserException(modifiers.AbstractToken, "Fields cannot be abstract.");
if (modifiers.HasOverride) throw new ParserException(modifiers.OverrideToken, "Fields cannot be marked as overrides.");
if (modifiers.HasFinal) throw new ParserException(modifiers.FinalToken, "Final fields are not supported yet.");
}
public override string GetFullyQualifiedLocalizedName(Locale locale)
{
string name = this.NameToken.Value;
if (this.TopLevelEntity != null)
{
name = this.TopLevelEntity.GetFullyQualifiedLocalizedName(locale) + "." + name;
}
return name;
}
internal override void Resolve(ParserContext parser)
{
this.DefaultValue = this.DefaultValue.Resolve(parser);
}
internal override void ResolveEntityNames(ParserContext parser)
{
if (this.DefaultValue != null)
{
parser.CurrentCodeContainer = this;
this.DefaultValue = this.DefaultValue.ResolveEntityNames(parser);
parser.CurrentCodeContainer = null;
}
}
internal override void ResolveSignatureTypes(ParserContext parser, TypeResolver typeResolver)
{
this.ResolvedFieldType = typeResolver.ResolveType(this.FieldType);
if (this.DefaultValue == null)
{
switch (this.ResolvedFieldType.Category)
{
case ResolvedTypeCategory.INTEGER:
this.DefaultValue = new IntegerConstant(this.FirstToken, 0, this);
break;
case ResolvedTypeCategory.FLOAT:
this.DefaultValue = new FloatConstant(this.FirstToken, 0.0, this);
break;
case ResolvedTypeCategory.BOOLEAN:
this.DefaultValue = new BooleanConstant(this.FirstToken, false, this);
break;
default:
this.DefaultValue = new NullConstant(this.FirstToken, this);
break;
}
}
}
internal override void EnsureModifierAndTypeSignatureConsistency(TypeContext tc)
{
bool isStatic = this.Modifiers.HasStatic;
ClassDefinition classDef = (ClassDefinition)this.Owner;
ClassDefinition baseClass = classDef.BaseClass;
bool hasBaseClass = baseClass != null;
if (!isStatic && classDef.Modifiers.HasStatic)
{
throw new ParserException(this, "Cannot have non-static fields in a static class.");
}
if (hasBaseClass && baseClass.GetMember(this.NameToken.Value, true) != null)
{
throw new ParserException(this, "This field definition hides a member in a base class.");
}
}
internal override void ResolveTypes(ParserContext parser, TypeResolver typeResolver)
{
this.DefaultValue.ResolveTypes(parser, typeResolver);
this.DefaultValue.ResolvedType.EnsureCanAssignToA(this.DefaultValue.FirstToken, this.ResolvedFieldType);
}
internal void ResolveVariableOrigins(ParserContext parser)
{
if (this.DefaultValue != null)
{
VariableScope varScope = VariableScope.NewEmptyScope(this.CompilationScope.IsStaticallyTyped);
this.DefaultValue.ResolveVariableOrigins(parser, varScope, VariableIdAllocPhase.REGISTER_AND_ALLOC);
if (varScope.Size > 0)
{
// Although if you manage to trigger this, I'd love to know how.
throw new ParserException(this, "Cannot declare a variable this way.");
}
Lambda.DoVarScopeIdAllocationForLambdaContainer(parser, varScope, this);
}
}
}
}
|
using System;
using System.Collections.Generic;
namespace Nucleo.Web
{
/// <summary>
/// Represents a CSS file reference. This file is not used directly within any custom controls/extenders you may develop, though you can use it for your own needs.
/// </summary>
public class CssReference
{
private string _path = null;
#region " Properties "
/// <summary>
/// Gets the path to the CSS file.
/// </summary>
public string Path
{
get { return _path; }
}
#endregion
#region " Constructors "
public CssReference(CssReferenceRequestDetails details)
: this(details.Path) { }
public CssReference(string path)
{
_path = path;
}
#endregion
}
}
|
ScalaJS.impls.scala_PartialFunction$class__orElse__Lscala_PartialFunction__Lscala_PartialFunction__Lscala_PartialFunction = (function($$this, that) {
return new ScalaJS.c.scala_PartialFunction$OrElse().init___Lscala_PartialFunction__Lscala_PartialFunction($$this, that)
});
ScalaJS.impls.scala_PartialFunction$class__andThen__Lscala_PartialFunction__Lscala_Function1__Lscala_PartialFunction = (function($$this, k) {
return new ScalaJS.c.scala_PartialFunction$AndThen().init___Lscala_PartialFunction__Lscala_Function1($$this, k)
});
ScalaJS.impls.scala_PartialFunction$class__lift__Lscala_PartialFunction__Lscala_Function1 = (function($$this) {
return new ScalaJS.c.scala_PartialFunction$Lifted().init___Lscala_PartialFunction($$this)
});
ScalaJS.impls.scala_PartialFunction$class__applyOrElse__Lscala_PartialFunction__O__Lscala_Function1__O = (function($$this, x, default$2) {
if ($$this.isDefinedAt__O__Z(x)) {
return $$this.apply__O__O(x)
} else {
return default$2.apply__O__O(x)
}
});
ScalaJS.impls.scala_PartialFunction$class__runWith__Lscala_PartialFunction__Lscala_Function1__Lscala_Function1 = (function($$this, action) {
return new ScalaJS.c.scala_scalajs_runtime_AnonFunction1().init___Lscala_scalajs_js_Function1((function(arg$outer, action$1) {
return (function(x) {
var z = arg$outer.applyOrElse__O__Lscala_Function1__O(x, ScalaJS.modules.scala_PartialFunction().scala$PartialFunction$$checkFallback__Lscala_PartialFunction());
if ((!ScalaJS.modules.scala_PartialFunction().scala$PartialFunction$$fallbackOccurred__O__Z(z))) {
action$1.apply__O__O(z);
var jsx$1 = true
} else {
var jsx$1 = false
};
return ScalaJS.bZ(jsx$1)
})
})($$this, action))
});
ScalaJS.impls.scala_PartialFunction$class__$init$__Lscala_PartialFunction__V = (function($$this) {
/*<skip>*/
});
//@ sourceMappingURL=PartialFunction$class.js.map
|
public class SockServer {
/**
* @param args
*/
public static void main(String[] args) {
SockServerController server = new SockServerController(9679);
server.runServer();
}
}
|
./ffmpeg -i $1 -c:v yuv4 $1.yuv
|
require 'spec_helper'
module JustShellScripts
describe Connection do
end
end
|
function autonomous_start() {
autonomousStartTime = gameVideo.currentTime;
initializeEvents();
} |
DO $$
BEGIN
DROP FUNCTION f_event_occurrences();
DROP VIEW v_event_occurrences;
CREATE OR REPLACE VIEW v_event_occurrences AS (
SELECT id, name, country, city, address, created_at, created_by, type, description, dojo_id, position, public,
status, recurring_type, dates, ticket_approval, notify_on_applicant, eventbrite_id, eventbrite_url, use_dojo_address,
start_time::timestamp, end_time::timestamp FROM (
SELECT *, unnest(dates)->>'startTime' as start_time, unnest(dates)->>'endTime' as end_time FROM cd_events
) x WHERE start_time IS NOT NULL AND start_time NOT LIKE 'Invalid%' AND end_time IS NOT NULL AND end_time NOT LIKE 'Invalid%'
);
END;
$$ |
# This script runned on container start
# is will create database cluster (if none)
# and setup replication according to $REPLICA_MODE
# -------------------------------------------------------------------------------
# Create postgresql database cluster
dbinit() {
gosu postgres initdb \
&& sed -ri "s/^#(listen_addresses\s*=\s*)\S+/\1'*'/" $PGDATA/postgresql.conf \
&& echo "include_if_exists = 'replica.conf'" >> $PGDATA/postgresql.conf \
&& echo "include_if_exists = 'pg_stat.conf'" >> $PGDATA/postgresql.conf \
&& sed -ri "s/^#(local\s+replication\s+postgres\s+trust)/\1/" $PGDATA/pg_hba.conf \
&& echo "host all all 172.17.0.0/16 md5" >> $PGDATA/pg_hba.conf \
&& touch $PGDATA/replica.conf \
&& mv /etc/postgresql/pg_stat.conf $PGDATA \
&& echo "Database cluster created"
}
# -------------------------------------------------------------------------------
# change directory perms if host storage attached
if [ ! -d "$PGDATA" ]; then
mkdir -p -m 0700 "$PGDATA"
chown -R $PGUSER:$PGUSER "$PGDATA"
fi
# Setup PGDATA
if [ -z "$(ls -A "$PGDATA")" ]; then
# PGDATA is empty, create new cluster
dbinit
else
# PGDATA already exists, change container's user postgres UIG & GID to fit PGDATA
DIR_UID=$(stat -c "%u" $PGDATA)
if [[ "$DIR_UID" ]] && [[ $DIR_UID != $(id -u $PGUSER) ]]; then
usermod -u $DIR_UID $PGUSER
fi
DIR_GID=$(stat -c "%g" $PGDATA)
if [[ "$DIR_GID" ]] && [[ $DIR_GID != $(id -g $PGUSER) ]]; then
groupmod -g $DIR_GID $PGUSER
fi
chown -R $DIR_UID:$DIR_GID /var/run/postgresql
fi
#Setup replication
echo "** Replication mode: $REPLICA_MODE"
[ -d $REPLICA_ROOT ] || { mkdir -p $REPLICA_ROOT ; chown -R $DIR_UID:$DIR_GID $REPLICA_ROOT ; }
if [[ "$REPLICA_MODE" == "MASTER" ]] || [[ "$REPLICA_MODE" == "SLAVE" ]] ; then
[ -f $PGDATA/replica.conf ] && rm $PGDATA/replica.conf
if [[ "$REPLICA_MODE" == "MASTER" ]] ; then
[ -f $PGDATA/replica_master.conf ] || cp /etc/postgresql/replica_master.conf $PGDATA/
ln -s replica_master.conf $PGDATA/replica.conf
else #if [[ "$REPLICA_MODE" == "SLAVE" ]] ; then
[ -f $REPLICA_ROOT/base.tar.gz ] && [ ! -f $PGDATA/imported ] && {
echo "Loading database.tar.gz..."
rm -rf $PGDATA/*
tar -zxf $REPLICA_ROOT/base.tar.gz -C $PGDATA
touch $PGDATA/imported
}
[ -f $PGDATA/replica_slave.conf ] || cp /etc/postgresql/replica_slave.conf $PGDATA/
ln -s replica_slave.conf $PGDATA/replica.conf
[ -f $PGDATA/recovery.conf ] || cp /etc/postgresql/replica_recovery.conf $PGDATA/recovery.conf
fi
fi
# Setup tsearch if files exists
TSEARCH=/var/log/supervisor/pg-skel/tsearch_data
if [ -d $TSEARCH ] ; then
cp -rf $TSEARCH /usr/share/postgresql/$PG_MAJOR
fi
echo "Postgresql setup complete"
|
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript" charset="utf-8"></script>
<script src="specimen_files/easytabs.js" type="text/javascript" charset="utf-8"></script>
<link rel="stylesheet" href="specimen_files/specimen_stylesheet.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="stylesheet.css" type="text/css" charset="utf-8" />
<style type="text/css">
body{
font-family: 'source_sans_proregular';
}
</style>
<title>Source Sans Pro Regular Specimen</title>
<script type="text/javascript" charset="utf-8">
$(document).ready(function() {
$('#container').easyTabs({defaultContent:1});
});
</script>
</head>
<body>
<div id="container">
<div id="header">
Source Sans Pro Regular </div>
<ul class="tabs">
<li><a href="#specimen">Specimen</a></li>
<li><a href="#layout">Sample Layout</a></li>
<li><a href="#glyphs">Glyphs & Languages</a></li>
<li><a href="#installing">Installing Webfonts</a></li>
</ul>
<div id="main_content">
<div id="specimen">
<div class="section">
<div class="grid12 firstcol">
<div class="huge">AaBb</div>
</div>
</div>
<div class="section">
<div class="glyph_range">A​B​C​D​E​F​G​H​I​J​K​L​M​N​O​P​Q​R​S​T​U​V​W​X​Y​Z​a​b​c​d​e​f​g​h​i​j​k​l​m​n​o​p​q​r​s​t​u​v​w​x​y​z​1​2​3​4​5​6​7​8​9​0​&​.​,​?​!​@​(​)​#​$​%​*​+​-​=​:​;</div>
</div>
<div class="section">
<div class="grid12 firstcol">
<table class="sample_table">
<tr><td>10</td><td class="size10">abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ</td></tr>
<tr><td>11</td><td class="size11">abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ</td></tr>
<tr><td>12</td><td class="size12">abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ</td></tr>
<tr><td>13</td><td class="size13">abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ</td></tr>
<tr><td>14</td><td class="size14">abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ</td></tr>
<tr><td>16</td><td class="size16">abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ</td></tr>
<tr><td>18</td><td class="size18">abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ</td></tr>
<tr><td>20</td><td class="size20">abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ</td></tr>
<tr><td>24</td><td class="size24">abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ</td></tr>
<tr><td>30</td><td class="size30">abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ</td></tr>
<tr><td>36</td><td class="size36">abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ</td></tr>
<tr><td>48</td><td class="size48">abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ</td></tr>
<tr><td>60</td><td class="size60">abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ</td></tr>
<tr><td>72</td><td class="size72">abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ</td></tr>
<tr><td>90</td><td class="size90">abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ</td></tr>
</table>
</div>
</div>
<div class="section" id="bodycomparison">
<div id="xheight">
<div class="fontbody">◼◼◼◼◼◼◼◼◼◼◼◼◼◼◼◼◼◼◼◼◼◼◼◼◼◼◼◼◼◼◼◼◼◼◼◼◼◼◼◼◼◼◼◼◼◼◼◼◼◼◼◼◼◼◼◼◼◼◼◼◼◼◼◼◼◼◼◼◼◼◼◼◼◼◼◼◼◼◼◼◼◼◼◼◼◼◼◼◼◼◼◼◼◼◼◼◼◼◼body</div><div class="arialbody">body</div><div class="verdanabody">body</div><div class="georgiabody">body</div></div>
<div class="fontbody" style="z-index:1">
body<span>Source Sans Pro Regular</span>
</div>
<div class="arialbody" style="z-index:1">
body<span>Arial</span>
</div>
<div class="verdanabody" style="z-index:1">
body<span>Verdana</span>
</div>
<div class="georgiabody" style="z-index:1">
body<span>Georgia</span>
</div>
</div>
<div class="section psample psample_row1" id="">
<div class="grid2 firstcol">
<p class="size10"><span>10.</span>Aenean lacinia bibendum nulla sed consectetur. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus. Nullam id dolor id nibh ultricies vehicula ut id elit. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Nulla vitae elit libero, a pharetra augue.</p>
</div>
<div class="grid3">
<p class="size11"><span>11.</span>Aenean lacinia bibendum nulla sed consectetur. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus. Nullam id dolor id nibh ultricies vehicula ut id elit. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Nulla vitae elit libero, a pharetra augue.</p>
</div>
<div class="grid3">
<p class="size12"><span>12.</span>Aenean lacinia bibendum nulla sed consectetur. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus. Nullam id dolor id nibh ultricies vehicula ut id elit. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Nulla vitae elit libero, a pharetra augue.</p>
</div>
<div class="grid4">
<p class="size13"><span>13.</span>Aenean lacinia bibendum nulla sed consectetur. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus. Nullam id dolor id nibh ultricies vehicula ut id elit. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Nulla vitae elit libero, a pharetra augue.</p>
</div>
<div class="white_blend"></div>
</div>
<div class="section psample psample_row2" id="">
<div class="grid3 firstcol">
<p class="size14"><span>14.</span>Aenean lacinia bibendum nulla sed consectetur. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus. Nullam id dolor id nibh ultricies vehicula ut id elit. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Nulla vitae elit libero, a pharetra augue.</p>
</div>
<div class="grid4">
<p class="size16"><span>16.</span>Aenean lacinia bibendum nulla sed consectetur. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus. Nullam id dolor id nibh ultricies vehicula ut id elit. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Nulla vitae elit libero, a pharetra augue.</p>
</div>
<div class="grid5">
<p class="size18"><span>18.</span>Aenean lacinia bibendum nulla sed consectetur. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus. Nullam id dolor id nibh ultricies vehicula ut id elit. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Nulla vitae elit libero, a pharetra augue.</p>
</div>
<div class="white_blend"></div>
</div>
<div class="section psample psample_row3" id="">
<div class="grid5 firstcol">
<p class="size20"><span>20.</span>Aenean lacinia bibendum nulla sed consectetur. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus. Nullam id dolor id nibh ultricies vehicula ut id elit. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Nulla vitae elit libero, a pharetra augue.</p>
</div>
<div class="grid7">
<p class="size24"><span>24.</span>Aenean lacinia bibendum nulla sed consectetur. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus. Nullam id dolor id nibh ultricies vehicula ut id elit. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Nulla vitae elit libero, a pharetra augue.</p>
</div>
<div class="white_blend"></div>
</div>
<div class="section psample psample_row4" id="">
<div class="grid12 firstcol">
<p class="size30"><span>30.</span>Aenean lacinia bibendum nulla sed consectetur. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus. Nullam id dolor id nibh ultricies vehicula ut id elit. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Nulla vitae elit libero, a pharetra augue.</p>
</div>
<div class="white_blend"></div>
</div>
<div class="section psample psample_row1 fullreverse">
<div class="grid2 firstcol">
<p class="size10"><span>10.</span>Aenean lacinia bibendum nulla sed consectetur. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus. Nullam id dolor id nibh ultricies vehicula ut id elit. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Nulla vitae elit libero, a pharetra augue.</p>
</div>
<div class="grid3">
<p class="size11"><span>11.</span>Aenean lacinia bibendum nulla sed consectetur. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus. Nullam id dolor id nibh ultricies vehicula ut id elit. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Nulla vitae elit libero, a pharetra augue.</p>
</div>
<div class="grid3">
<p class="size12"><span>12.</span>Aenean lacinia bibendum nulla sed consectetur. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus. Nullam id dolor id nibh ultricies vehicula ut id elit. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Nulla vitae elit libero, a pharetra augue.</p>
</div>
<div class="grid4">
<p class="size13"><span>13.</span>Aenean lacinia bibendum nulla sed consectetur. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus. Nullam id dolor id nibh ultricies vehicula ut id elit. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Nulla vitae elit libero, a pharetra augue.</p>
</div>
<div class="black_blend"></div>
</div>
<div class="section psample psample_row2 fullreverse">
<div class="grid3 firstcol">
<p class="size14"><span>14.</span>Aenean lacinia bibendum nulla sed consectetur. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus. Nullam id dolor id nibh ultricies vehicula ut id elit. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Nulla vitae elit libero, a pharetra augue.</p>
</div>
<div class="grid4">
<p class="size16"><span>16.</span>Aenean lacinia bibendum nulla sed consectetur. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus. Nullam id dolor id nibh ultricies vehicula ut id elit. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Nulla vitae elit libero, a pharetra augue.</p>
</div>
<div class="grid5">
<p class="size18"><span>18.</span>Aenean lacinia bibendum nulla sed consectetur. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus. Nullam id dolor id nibh ultricies vehicula ut id elit. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Nulla vitae elit libero, a pharetra augue.</p>
</div>
<div class="black_blend"></div>
</div>
<div class="section psample fullreverse psample_row3" id="">
<div class="grid5 firstcol">
<p class="size20"><span>20.</span>Aenean lacinia bibendum nulla sed consectetur. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus. Nullam id dolor id nibh ultricies vehicula ut id elit. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Nulla vitae elit libero, a pharetra augue.</p>
</div>
<div class="grid7">
<p class="size24"><span>24.</span>Aenean lacinia bibendum nulla sed consectetur. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus. Nullam id dolor id nibh ultricies vehicula ut id elit. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Nulla vitae elit libero, a pharetra augue.</p>
</div>
<div class="black_blend"></div>
</div>
<div class="section psample fullreverse psample_row4" id="" style="border-bottom: 20px #000 solid;">
<div class="grid12 firstcol">
<p class="size30"><span>30.</span>Aenean lacinia bibendum nulla sed consectetur. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus. Nullam id dolor id nibh ultricies vehicula ut id elit. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Nulla vitae elit libero, a pharetra augue.</p>
</div>
<div class="black_blend"></div>
</div>
</div>
<div id="layout">
<div class="section">
<div class="grid12 firstcol">
<h1>Lorem Ipsum Dolor</h1>
<h2>Etiam porta sem malesuada magna mollis euismod</h2>
<p class="byline">By <a href="#link">Aenean Lacinia</a></p>
</div>
</div>
<div class="section">
<div class="grid8 firstcol">
<p class="large">Donec sed odio dui. Morbi leo risus, porta ac consectetur ac, vestibulum at eros. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus. </p>
<h3>Pellentesque ornare sem</h3>
<p>Maecenas sed diam eget risus varius blandit sit amet non magna. Maecenas faucibus mollis interdum. Donec ullamcorper nulla non metus auctor fringilla. Nullam id dolor id nibh ultricies vehicula ut id elit. Nullam id dolor id nibh ultricies vehicula ut id elit. </p>
<p>Aenean eu leo quam. Pellentesque ornare sem lacinia quam venenatis vestibulum. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. </p>
<p>Nulla vitae elit libero, a pharetra augue. Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Aenean lacinia bibendum nulla sed consectetur. </p>
<p>Nullam quis risus eget urna mollis ornare vel eu leo. Nullam quis risus eget urna mollis ornare vel eu leo. Maecenas sed diam eget risus varius blandit sit amet non magna. Donec ullamcorper nulla non metus auctor fringilla. </p>
<h3>Cras mattis consectetur</h3>
<p>Aenean eu leo quam. Pellentesque ornare sem lacinia quam venenatis vestibulum. Aenean lacinia bibendum nulla sed consectetur. Integer posuere erat a ante venenatis dapibus posuere velit aliquet. Cras mattis consectetur purus sit amet fermentum. </p>
<p>Nullam id dolor id nibh ultricies vehicula ut id elit. Nullam quis risus eget urna mollis ornare vel eu leo. Cras mattis consectetur purus sit amet fermentum.</p>
</div>
<div class="grid4 sidebar">
<div class="box reverse">
<p class="last">Nullam quis risus eget urna mollis ornare vel eu leo. Donec ullamcorper nulla non metus auctor fringilla. Cras mattis consectetur purus sit amet fermentum. Sed posuere consectetur est at lobortis. Lorem ipsum dolor sit amet, consectetur adipiscing elit. </p>
</div>
<p class="caption">Maecenas sed diam eget risus varius.</p>
<p>Vestibulum id ligula porta felis euismod semper. Integer posuere erat a ante venenatis dapibus posuere velit aliquet. Vestibulum id ligula porta felis euismod semper. Sed posuere consectetur est at lobortis. Maecenas sed diam eget risus varius blandit sit amet non magna. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus. </p>
<p>Duis mollis, est non commodo luctus, nisi erat porttitor ligula, eget lacinia odio sem nec elit. Aenean lacinia bibendum nulla sed consectetur. Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor. Aenean lacinia bibendum nulla sed consectetur. Nullam quis risus eget urna mollis ornare vel eu leo. </p>
<p>Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Donec ullamcorper nulla non metus auctor fringilla. Maecenas faucibus mollis interdum. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus. </p>
</div>
</div>
</div>
<div id="glyphs">
<div class="section">
<div class="grid12 firstcol">
<h1>Language Support</h1>
<p>The subset of Source Sans Pro Regular in this kit supports the following languages:<br />
English </p>
<h1>Glyph Chart</h1>
<p>The subset of Source Sans Pro Regular in this kit includes all the glyphs listed below. Unicode entities are included above each glyph to help you insert individual characters into your layout.</p>
<div id="glyph_chart">
<div><p>&#13;</p> </div>
<div><p>&#32;</p> </div>
<div><p>&#33;</p>!</div>
<div><p>&#35;</p>#</div>
<div><p>&#36;</p>$</div>
<div><p>&#38;</p>&</div>
<div><p>&#39;</p>'</div>
<div><p>&#40;</p>(</div>
<div><p>&#41;</p>)</div>
<div><p>&#42;</p>*</div>
<div><p>&#43;</p>+</div>
<div><p>&#44;</p>,</div>
<div><p>&#45;</p>-</div>
<div><p>&#46;</p>.</div>
<div><p>&#47;</p>/</div>
<div><p>&#48;</p>0</div>
<div><p>&#49;</p>1</div>
<div><p>&#50;</p>2</div>
<div><p>&#51;</p>3</div>
<div><p>&#52;</p>4</div>
<div><p>&#53;</p>5</div>
<div><p>&#54;</p>6</div>
<div><p>&#55;</p>7</div>
<div><p>&#56;</p>8</div>
<div><p>&#57;</p>9</div>
<div><p>&#60;</p><</div>
<div><p>&#62;</p>></div>
<div><p>&#63;</p>?</div>
<div><p>&#64;</p>@</div>
<div><p>&#65;</p>A</div>
<div><p>&#66;</p>B</div>
<div><p>&#67;</p>C</div>
<div><p>&#68;</p>D</div>
<div><p>&#69;</p>E</div>
<div><p>&#70;</p>F</div>
<div><p>&#71;</p>G</div>
<div><p>&#72;</p>H</div>
<div><p>&#73;</p>I</div>
<div><p>&#74;</p>J</div>
<div><p>&#75;</p>K</div>
<div><p>&#76;</p>L</div>
<div><p>&#77;</p>M</div>
<div><p>&#78;</p>N</div>
<div><p>&#79;</p>O</div>
<div><p>&#80;</p>P</div>
<div><p>&#81;</p>Q</div>
<div><p>&#82;</p>R</div>
<div><p>&#83;</p>S</div>
<div><p>&#84;</p>T</div>
<div><p>&#85;</p>U</div>
<div><p>&#86;</p>V</div>
<div><p>&#87;</p>W</div>
<div><p>&#88;</p>X</div>
<div><p>&#89;</p>Y</div>
<div><p>&#90;</p>Z</div>
<div><p>&#91;</p>[</div>
<div><p>&#92;</p>\</div>
<div><p>&#93;</p>]</div>
<div><p>&#94;</p>^</div>
<div><p>&#95;</p>_</div>
<div><p>&#97;</p>a</div>
<div><p>&#98;</p>b</div>
<div><p>&#99;</p>c</div>
<div><p>&#100;</p>d</div>
<div><p>&#101;</p>e</div>
<div><p>&#102;</p>f</div>
<div><p>&#103;</p>g</div>
<div><p>&#104;</p>h</div>
<div><p>&#105;</p>i</div>
<div><p>&#106;</p>j</div>
<div><p>&#107;</p>k</div>
<div><p>&#108;</p>l</div>
<div><p>&#109;</p>m</div>
<div><p>&#110;</p>n</div>
<div><p>&#111;</p>o</div>
<div><p>&#112;</p>p</div>
<div><p>&#113;</p>q</div>
<div><p>&#114;</p>r</div>
<div><p>&#115;</p>s</div>
<div><p>&#116;</p>t</div>
<div><p>&#117;</p>u</div>
<div><p>&#118;</p>v</div>
<div><p>&#119;</p>w</div>
<div><p>&#120;</p>x</div>
<div><p>&#121;</p>y</div>
<div><p>&#122;</p>z</div>
<div><p>&#123;</p>{</div>
<div><p>&#124;</p>|</div>
<div><p>&#125;</p>}</div>
<div><p>&#126;</p>~</div>
<div><p>&#160;</p> </div>
<div><p>&#161;</p>¡</div>
<div><p>&#162;</p>¢</div>
<div><p>&#163;</p>£</div>
<div><p>&#164;</p>¤</div>
<div><p>&#165;</p>¥</div>
<div><p>&#166;</p>¦</div>
<div><p>&#167;</p>§</div>
<div><p>&#169;</p>©</div>
<div><p>&#172;</p>¬</div>
<div><p>&#174;</p>®</div>
<div><p>&#176;</p>°</div>
<div><p>&#177;</p>±</div>
<div><p>&#181;</p>µ</div>
<div><p>&#182;</p>¶</div>
<div><p>&#191;</p>¿</div>
<div><p>&#198;</p>Æ</div>
<div><p>&#208;</p>Ð</div>
<div><p>&#215;</p>×</div>
<div><p>&#216;</p>Ø</div>
<div><p>&#222;</p>Þ</div>
<div><p>&#223;</p>ß</div>
<div><p>&#230;</p>æ</div>
<div><p>&#240;</p>ð</div>
<div><p>&#247;</p>÷</div>
<div><p>&#248;</p>ø</div>
<div><p>&#254;</p>þ</div>
<div><p>&#305;</p>ı</div>
<div><p>&#338;</p>Œ</div>
<div><p>&#339;</p>œ</div>
<div><p>&#768;</p>̀</div>
<div><p>&#769;</p>́</div>
<div><p>&#770;</p>̂</div>
<div><p>&#771;</p>̃</div>
<div><p>&#772;</p>̄</div>
<div><p>&#776;</p>̈</div>
<div><p>&#778;</p>̊</div>
<div><p>&#807;</p>̧</div>
<div><p>&#7491;</p>ᵃ</div>
<div><p>&#7506;</p>ᵒ</div>
<div><p>&#8192;</p> </div>
<div><p>&#8193;</p> </div>
<div><p>&#8194;</p> </div>
<div><p>&#8195;</p> </div>
<div><p>&#8196;</p> </div>
<div><p>&#8197;</p> </div>
<div><p>&#8198;</p> </div>
<div><p>&#8199;</p> </div>
<div><p>&#8200;</p> </div>
<div><p>&#8201;</p> </div>
<div><p>&#8202;</p> </div>
<div><p>&#8208;</p>‐</div>
<div><p>&#8209;</p>‑</div>
<div><p>&#8210;</p>‒</div>
<div><p>&#8211;</p>–</div>
<div><p>&#8212;</p>—</div>
<div><p>&#8216;</p>‘</div>
<div><p>&#8217;</p>’</div>
<div><p>&#8226;</p>•</div>
<div><p>&#8239;</p> </div>
<div><p>&#8249;</p>‹</div>
<div><p>&#8250;</p>›</div>
<div><p>&#8260;</p>⁄</div>
<div><p>&#8287;</p> </div>
<div><p>&#8364;</p>€</div>
<div><p>&#8482;</p>™</div>
<div><p>&#8722;</p>−</div>
<div><p>&#9724;</p>◼</div>
</div>
</div>
</div>
</div>
<div id="specs">
</div>
<div id="installing">
<div class="section">
<div class="grid7 firstcol">
<h1>Installing Webfonts</h1>
<p>Webfonts are supported by all major browser platforms but not all in the same way. There are currently four different font formats that must be included in order to target all browsers. This includes TTF, WOFF, EOT and SVG.</p>
<h2>1. Upload your webfonts</h2>
<p>You must upload your webfont kit to your website. They should be in or near the same directory as your CSS files.</p>
<h2>2. Include the webfont stylesheet</h2>
<p>A special CSS @font-face declaration helps the various browsers select the appropriate font it needs without causing you a bunch of headaches. Learn more about this syntax by reading the <a href="http://www.fontspring.com/blog/further-hardening-of-the-bulletproof-syntax">Fontspring blog post</a> about it. The code for it is as follows:</p>
<code>
@font-face{
font-family: 'MyWebFont';
src: url('WebFont.eot');
src: url('WebFont.eot?#iefix') format('embedded-opentype'),
url('WebFont.woff') format('woff'),
url('WebFont.ttf') format('truetype'),
url('WebFont.svg#webfont') format('svg');
}
</code>
<p>We've already gone ahead and generated the code for you. All you have to do is link to the stylesheet in your HTML, like this:</p>
<code><link rel="stylesheet" href="stylesheet.css" type="text/css" charset="utf-8" /></code>
<h2>3. Modify your own stylesheet</h2>
<p>To take advantage of your new fonts, you must tell your stylesheet to use them. Look at the original @font-face declaration above and find the property called "font-family." The name linked there will be what you use to reference the font. Prepend that webfont name to the font stack in the "font-family" property, inside the selector you want to change. For example:</p>
<code>p { font-family: 'WebFont', Arial, sans-serif; }</code>
<h2>4. Test</h2>
<p>Getting webfonts to work cross-browser <em>can</em> be tricky. Use the information in the sidebar to help you if you find that fonts aren't loading in a particular browser.</p>
</div>
<div class="grid5 sidebar">
<div class="box">
<h2>Troubleshooting<br />Font-Face Problems</h2>
<p>Having trouble getting your webfonts to load in your new website? Here are some tips to sort out what might be the problem.</p>
<h3>Fonts not showing in any browser</h3>
<p>This sounds like you need to work on the plumbing. You either did not upload the fonts to the correct directory, or you did not link the fonts properly in the CSS. If you've confirmed that all this is correct and you still have a problem, take a look at your .htaccess file and see if requests are getting intercepted.</p>
<h3>Fonts not loading in iPhone or iPad</h3>
<p>The most common problem here is that you are serving the fonts from an IIS server. IIS refuses to serve files that have unknown MIME types. If that is the case, you must set the MIME type for SVG to "image/svg+xml" in the server settings. Follow these instructions from Microsoft if you need help.</p>
<h3>Fonts not loading in Firefox</h3>
<p>The primary reason for this failure? You are still using a version Firefox older than 3.5. So upgrade already! If that isn't it, then you are very likely serving fonts from a different domain. Firefox requires that all font assets be served from the same domain. Lastly it is possible that you need to add WOFF to your list of MIME types (if you are serving via IIS.)</p>
<h3>Fonts not loading in IE</h3>
<p>Are you looking at Internet Explorer on an actual Windows machine or are you cheating by using a service like Adobe BrowserLab? Many of these screenshot services do not render @font-face for IE. Best to test it on a real machine.</p>
<h3>Fonts not loading in IE9</h3>
<p>IE9, like Firefox, requires that fonts be served from the same domain as the website. Make sure that is the case.</p>
</div>
</div>
</div>
</div>
</div>
<div id="footer">
<p>©2010-2011 Font Squirrel. All rights reserved.</p>
</div>
</div>
</body>
</html>
|
## bryanwtan.com
Check out humans.txt at:
http://www.bryanwtan.com/humans.txt
#### Node.js/io.js stuff
socket.io for client and server communication
Twilio integration for texting on page view. Scroll based to prevent reload activation
Facebook Graph API retrieves my photography page album metrics. I created nodes from like count and links when a person likes multiple albums. D3.js provided a force directed graph as a starting point. The cron retrieval runs daily.
#### Easter eggs:
Clicking the full screen purple cover swaps the background image.
The heart at the bottom of the page changes to twitter on hover.
Mobile users see fewer preview photos, the rest are gallery revealed.
Have a great day!
|
<?php
return array (
'id' => 'ght_chat_ver1',
'fallback' => 'generic_ght',
'capabilities' =>
array (
'mobile_browser' => 'MAUI Wap Browser',
'pointing_method' => 'touchscreen',
'mobile_browser_version' => '1.0',
'uaprof' => 'http://www.ghtmobile.com/ght/T500.xml',
'model_name' => 'Chat',
'brand_name' => 'BayMobile',
'release_date' => '2010_october',
'softkey_support' => 'true',
'table_support' => 'true',
'wml_1_3' => 'true',
'columns' => '16',
'rows' => '16',
'resolution_width' => '220',
'resolution_height' => '176',
'jpg' => 'true',
'gif' => 'true',
'bmp' => 'true',
'wbmp' => 'true',
'colors' => '4096',
'nokia_voice_call' => 'true',
'wta_phonebook' => 'true',
'max_deck_size' => '65536',
'wap_push_support' => 'true',
'mms_max_size' => '100000',
'mms_max_width' => '640',
'mms_spmidi' => 'true',
'mms_max_height' => '480',
'mms_gif_static' => 'true',
'mms_wav' => 'true',
'mms_vcard' => 'true',
'mms_midi_monophonic' => 'true',
'mms_bmp' => 'true',
'mms_wbmp' => 'true',
'mms_amr' => 'true',
'mms_jpeg_baseline' => 'true',
'wav' => 'true',
'sp_midi' => 'true',
'amr' => 'true',
'midi_monophonic' => 'true',
'imelody' => 'true',
'streaming_vcodec_h263_0' => '10',
'streaming_3gpp' => 'true',
'streaming_acodec_amr' => 'nb',
'streaming_video' => 'true',
'playback_vcodec_h263_3' => '10',
'playback_3gpp' => 'true',
'playback_acodec_amr' => 'nb',
),
);
|
<?php
class VMAlumno_Controller extends CI_Controller{
function index(){
$this->load->view('admin/VMA');
}
}
?> |
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
/**
* Demonstrate 2D array of GUI components. (This could all be done using a
* 1D array. See MiniColorChooserV1.java and MiniColorChooserV2.java).
*
* Get color from the clicked button, itself.
*
* @author CS121 Instructors
*/
@SuppressWarnings("serial")
public class TwoDColorChooser extends JPanel
{
private final Color[][] COLORS = { { Color.RED, Color.GREEN, Color.BLUE },
{ Color.YELLOW, Color.CYAN, Color.MAGENTA },
{ Color.WHITE, Color.BLACK, Color.GRAY },
{ Color.PINK, Color.ORANGE, Color.LIGHT_GRAY} };
private JButton[][] colorButtons;
private JPanel displayPanel;
/**
* main panel constructor
*/
private TwoDColorChooser()
{
//sub-panel for grid of color choices
JPanel gridPanel = new JPanel();
gridPanel.setLayout(new GridLayout(COLORS.length, COLORS[0].length));
gridPanel.setPreferredSize(new Dimension(300, 300));
//sub-panel to display chosen color
displayPanel = new JPanel();
displayPanel.setPreferredSize(new Dimension(300,300));
//instantiate a ColorButtonListener. all buttons should share the same instance.
ColorButtonListener listener = new ColorButtonListener();
//buttons
colorButtons = new JButton[COLORS.length][COLORS[0].length];
for (int i = 0; i < colorButtons.length; i++) {
for(int j = 0; j < colorButtons[0].length; j++) {
colorButtons[i][j] = new JButton();
colorButtons[i][j].setBackground(COLORS[i][j]);
colorButtons[i][j].addActionListener(listener);
gridPanel.add(colorButtons[i][j]);
}
}
//add sub-panels to this panel
this.add(gridPanel);
this.add(displayPanel);
}
private class ColorButtonListener implements ActionListener
{
@Override
public void actionPerformed(ActionEvent e)
{
// have to cast generic Object reference from e.getSource()
// to a JButton reference in order to use button method
// getBackground()
JButton source = (JButton)(e.getSource());
//set display panel to the color of the button that was clicked
displayPanel.setBackground(source.getBackground());
}
}
/**
* Initialize the GUI and make it visible
* @param args unused
*/
public static void main(String[] args)
{
JFrame frame = new JFrame("Mini-ColorChooser");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new TwoDColorChooser());
frame.pack();
frame.setVisible(true);
}
} |
// --------- This code has been automatically generated !!! Wed Jul 22 2015 13:15:44 GMT+0000 (UTC)
/**
* @module opcua.address_space.types
*/
var doDebug = false;
var assert = require("better-assert");
var util = require("util");
var _ = require("underscore");
var makeNodeId = require("../lib/datamodel/nodeid").makeNodeId;
var schema_helpers = require("../lib/misc/factories_schema_helpers");
var extract_all_fields = schema_helpers.extract_all_fields;
var resolve_schema_field_types = schema_helpers.resolve_schema_field_types;
var initialize_field = schema_helpers.initialize_field;
var initialize_field_array = schema_helpers.initialize_field_array;
var check_options_correctness_against_schema = schema_helpers.check_options_correctness_against_schema;
var _defaultTypeMap = require("../lib/misc/factories_builtin_types")._defaultTypeMap;
var ec= require("../lib/misc/encode_decode");
var encodeArray= ec.encodeArray;
var decodeArray= ec.decodeArray;
var makeExpandedNodeId= ec.makeExpandedNodeId;
var generate_new_id = require("../lib/misc/factories").generate_new_id;
var _enumerations = require("../lib/misc/factories_enumerations")._private._enumerations;
var schema = require("../schemas/ChannelSecurityToken_schema").ChannelSecurityToken_Schema;
var BaseUAObject = require("../lib/misc/factories_baseobject").BaseUAObject;
/**
*
* @class ChannelSecurityToken
* @constructor
* @extends BaseUAObject
* @param options {Object}
* @param [options.secureChannelId] {UInt32}
* @param [options.tokenId] {UInt32}
* @param [options.createdAt = Wed Jul 22 2015 13:15:44 GMT+0000 (UTC)] {UtcTime}
* @param [options.revisedLifeTime = 30000] {UInt32}
*/
function ChannelSecurityToken(options)
{
options = options || {};
/* istanbul ignore next */
if (doDebug) { check_options_correctness_against_schema(this,schema,options); }
var self = this;
assert(this instanceof BaseUAObject); // ' keyword "new" is required for constructor call')
resolve_schema_field_types(schema);
BaseUAObject.call(this,options);
/**
*
* @property secureChannelId
* @type {UInt32}
*/
self.secureChannelId = initialize_field(schema.fields[0], options.secureChannelId);
/**
*
* @property tokenId
* @type {UInt32}
*/
self.tokenId = initialize_field(schema.fields[1], options.tokenId);
/**
*
* @property createdAt
* @type {UtcTime}
* @default function () {
return new Date();
}
*/
self.createdAt = initialize_field(schema.fields[2], options.createdAt);
/**
*
* @property revisedLifeTime
* @type {UInt32}
* @default 30000
*/
self.revisedLifeTime = initialize_field(schema.fields[3], options.revisedLifeTime);
// Object.preventExtensions(self);
}
util.inherits(ChannelSecurityToken,BaseUAObject);
ChannelSecurityToken.prototype.encodingDefaultBinary =makeExpandedNodeId(443,0);
ChannelSecurityToken.prototype._schema = schema;
var encode_UInt32 = _defaultTypeMap.UInt32.encode;
var decode_UInt32 = _defaultTypeMap.UInt32.decode;
var encode_UtcTime = _defaultTypeMap.UtcTime.encode;
var decode_UtcTime = _defaultTypeMap.UtcTime.decode;
/**
* encode the object into a binary stream
* @method encode
*
* @param stream {BinaryStream}
*/
ChannelSecurityToken.prototype.encode = function(stream,options) {
// call base class implementation first
BaseUAObject.prototype.encode.call(this,stream,options);
encode_UInt32(this.secureChannelId,stream);
encode_UInt32(this.tokenId,stream);
encode_UtcTime(this.createdAt,stream);
encode_UInt32(this.revisedLifeTime,stream);
};
ChannelSecurityToken.prototype.decode = function(stream,options) {
// call base class implementation first
BaseUAObject.prototype.decode.call(this,stream,options);
this.secureChannelId = decode_UInt32(stream,options);
this.tokenId = decode_UInt32(stream,options);
this.createdAt = decode_UtcTime(stream,options);
this.revisedLifeTime = decode_UInt32(stream,options);
};
ChannelSecurityToken.possibleFields = function() {
return [
"secureChannelId",
"tokenId",
"createdAt",
"revisedLifeTime"
];
}();
exports.ChannelSecurityToken = ChannelSecurityToken;
var register_class_definition = require("../lib/misc/factories_factories").register_class_definition;
register_class_definition("ChannelSecurityToken",ChannelSecurityToken); |
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _css = require('antd/lib/message/style/css');
var _message = require('antd/lib/message');
var _message2 = _interopRequireDefault(_message);
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _react = require('react');
var _react2 = _interopRequireDefault(_react);
var _reactDom = require('react-dom');
var _reactDom2 = _interopRequireDefault(_reactDom);
var _draftJsWhkfzyx = require('draft-js-whkfzyx');
var _decoratorStyle = require('./decoratorStyle.css');
var _decoratorStyle2 = _interopRequireDefault(_decoratorStyle);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var ImageSpan = function (_Component) {
_inherits(ImageSpan, _Component);
function ImageSpan(props) {
_classCallCheck(this, ImageSpan);
var _this = _possibleConstructorReturn(this, (ImageSpan.__proto__ || Object.getPrototypeOf(ImageSpan)).call(this, props));
var entity = _draftJsWhkfzyx.Entity.get(_this.props.entityKey);
var _entity$getData = entity.getData(),
width = _entity$getData.width,
height = _entity$getData.height;
_this.state = {
width: width,
height: height,
imageSrc: ''
};
_this.onImageClick = _this._onImageClick.bind(_this);
_this.onDoubleClick = _this._onDoubleClick.bind(_this);
return _this;
}
_createClass(ImageSpan, [{
key: 'componentDidMount',
value: function componentDidMount() {
var _this2 = this;
var _state = this.state,
width = _state.width,
height = _state.height;
var entity = _draftJsWhkfzyx.Entity.get(this.props.entityKey);
var image = new Image();
var _entity$getData2 = entity.getData(),
src = _entity$getData2.src;
src = src.replace(/[?#&].*$/g, "");
this.setState({ imageSrc: src });
image.src = this.state.imageSrc;
image.onload = function () {
if (width == null || height == null) {
_this2.setState({ width: image.width, height: image.height });
_draftJsWhkfzyx.Entity.mergeData(_this2.props.entityKey, {
width: image.width,
height: image.height,
originalWidth: image.width,
originalHeight: image.height
});
}
};
}
}, {
key: 'render',
value: function render() {
var _this3 = this;
var _state2 = this.state,
width = _state2.width,
height = _state2.height;
var key = this.props.entityKey;
var entity = _draftJsWhkfzyx.Entity.get(key);
var _entity$getData3 = entity.getData(),
src = _entity$getData3.src;
var imageStyle = {
verticalAlign: 'bottom',
backgroundImage: 'url("' + this.state.imageSrc + '")',
backgroundSize: width + 'px ' + height + 'px',
lineHeight: height + 'px',
fontSize: height + 'px',
width: width,
height: height,
letterSpacing: width
};
return _react2.default.createElement(
'div',
{ className: 'editor-inline-image', onClick: this._onClick },
_react2.default.createElement('img', { src: '' + this.state.imageSrc, className: 'media-image', onClick: function onClick(event) {
_this3.onImageClick(event, key);event.stopPropagation();
}, onDoubleClick: this.onDoubleClick })
);
}
}, {
key: '_onDoubleClick',
value: function _onDoubleClick() {
var currentPicture = _reactDom2.default.findDOMNode(this).querySelector("img");
var pictureWidth = currentPicture.naturalWidth;
var pictureSrc = currentPicture.src;
}
}, {
key: '_onImageClick',
value: function _onImageClick(e, key) {
var currentPicture = _reactDom2.default.findDOMNode(this).querySelector("img");
var pictureWidth = currentPicture.naturalWidth;
var editorState = _draftJsWhkfzyx.EditorState.createEmpty();
var selection = editorState.getSelection();
var blockTree = editorState.getBlockTree(this.props.children[0].key);
if (pictureWidth == 0) {
_message2.default.error("图片地址错误!");
} else if (pictureWidth > 650) {
_message2.default.error("图片尺寸过大将会导致用户流量浪费!请调整至最大650px。", 10);
}
}
}, {
key: '_handleResize',
value: function _handleResize(event, data) {
var _data$size = data.size,
width = _data$size.width,
height = _data$size.height;
this.setState({ width: width, height: height });
_draftJsWhkfzyx.Entity.mergeData(this.props.entityKey, { width: width, height: height });
}
}]);
return ImageSpan;
}(_react.Component);
exports.default = ImageSpan;
ImageSpan.defaultProps = {
children: null,
entityKey: "",
className: ""
}; |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#000000" />
<meta
name="description"
content="Web site created using create-react-app"
/>
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700&display=swap" />
<link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
<!--
manifest.json provides metadata used when your web app is installed on a
user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/
-->
<link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
<!--
Notice the use of %PUBLIC_URL% in the tags above.
It will be replaced with the URL of the `public` folder during the build.
Only files inside the `public` folder can be referenced from the HTML.
Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
work correctly both with client-side routing and a non-root public URL.
Learn how to configure a non-root public URL by running `npm run build`.
-->
<title>Calculator</title>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
<!--
This HTML file is a template.
If you open it directly in the browser, you will see an empty page.
You can add webfonts, meta tags, or analytics to this file.
The build step will place the bundled scripts into the <body> tag.
To begin the development, run `npm start` or `yarn start`.
To create a production bundle, use `npm run build` or `yarn build`.
-->
</body>
</html>
|
using System;
using System.Collections.Generic;
using System.IO;
using Verse.EncoderDescriptors.Tree;
namespace Verse.Schemas.Protobuf
{
internal class Writer : IWriter<WriterState, ProtobufValue>
{
public WriterState Start(Stream stream, ErrorEvent error)
{
throw new NotImplementedException();
}
public void Stop(WriterState state)
{
throw new NotImplementedException();
}
public void WriteAsArray<TEntity>(WriterState state, IEnumerable<TEntity> elements,
WriterCallback<WriterState, ProtobufValue, TEntity> writer)
{
throw new NotImplementedException();
}
public void WriteAsObject<TEntity>(WriterState state, TEntity entity,
IReadOnlyDictionary<string, WriterCallback<WriterState, ProtobufValue, TEntity>> fields)
{
throw new NotImplementedException();
}
public void WriteAsValue(WriterState state, ProtobufValue value)
{
throw new NotImplementedException();
}
}
}
|
# -*- coding: utf-8 -*-
module Gtk
# message_detail_viewプラグインなどで使われている、ヘッダ部分のユーザ情報。
# コンストラクタにはUserではなくMessageなど、userを保持しているDivaを渡すことに注意。
# このウィジェットによって表示されるタイムスタンプをクリックすると、
# コンストラクタに渡されたModelのperma_linkを開くようになっている。
class DivaHeaderWidget < Gtk::EventBox
extend Memoist
def initialize(model, *args, intent_token: nil)
type_strict model => Diva::Model
super(*args)
ssc_atonce(:visibility_notify_event, &widget_style_setter)
add(Gtk::VBox.new(false, 0).
closeup(Gtk::HBox.new(false, 0).
closeup(icon(model.user).top).
closeup(Gtk::VBox.new(false, 0).
closeup(idname(model.user).left).
closeup(Gtk::Label.new(model.user[:name]).left))).
closeup(post_date(model, intent_token).right))
end
private
def background_color
style = Gtk::Style.new()
style.set_bg(Gtk::STATE_NORMAL, 0xFFFF, 0xFFFF, 0xFFFF)
style end
def icon(user)
icon_alignment = Gtk::Alignment.new(0.5, 0, 0, 0)
.set_padding(*[UserConfig[:profile_icon_margin]]*4)
icon = Gtk::EventBox.new.
add(icon_alignment.add(Gtk::WebIcon.new(user.icon_large, UserConfig[:profile_icon_size], UserConfig[:profile_icon_size])))
icon.ssc(:button_press_event, &icon_opener(user.icon_large))
icon.ssc_atonce(:realize, &cursor_changer(Gdk::Cursor.new(Gdk::Cursor::HAND2)))
icon.ssc_atonce(:visibility_notify_event, &widget_style_setter)
icon end
def idname(user)
label = Gtk::EventBox.new.
add(Gtk::Label.new.
set_markup("<b><u><span foreground=\"#0000ff\">#{Pango.escape(user.idname)}</span></u></b>"))
label.ssc(:button_press_event, &profile_opener(user))
label.ssc_atonce(:realize, &cursor_changer(Gdk::Cursor.new(Gdk::Cursor::HAND2)))
label.ssc_atonce(:visibility_notify_event, &widget_style_setter)
label end
def post_date(model, intent_token)
label = Gtk::EventBox.new.
add(Gtk::Label.new(model.created.strftime('%Y/%m/%d %H:%M:%S')))
label.ssc(:button_press_event, &(intent_token ? intent_forwarder(intent_token) : message_opener(model)))
label.ssc_atonce(:realize, &cursor_changer(Gdk::Cursor.new(Gdk::Cursor::HAND2)))
label.ssc_atonce(:visibility_notify_event, &widget_style_setter)
label end
def icon_opener(url)
proc do
Plugin.call(:open, url)
true end end
def profile_opener(user)
type_strict user => Diva::Model
proc do
Plugin.call(:open, user)
true end end
def intent_forwarder(token)
proc do
token.forward
true
end
end
def message_opener(token)
proc do
Plugin.call(:open, token)
true
end
end
memoize def cursor_changer(cursor)
proc do |w|
w.window.cursor = cursor
false end end
memoize def widget_style_setter
->(widget, *_rest) do
widget.style = background_color
false end end
end
RetrieverHeaderWidget = DivaHeaderWidget
end
|
(function () {
'use strict';
angular
.module("myApp.presents")
.factory("dataGiftService", dataGiftService);
function dataGiftService($mdToast, $mdDialog) {
var dataGiftService = {
notification: notification,
pleaseWaitDialog: pleaseWaitDialog
};
function notification(status, msg, time) {
if (angular.isUndefined(time))
time = 3000;
$mdToast.show(
$mdToast.simple()
.textContent(msg)
.position("top right")
.hideDelay(time)
.theme(status)
);
}
function pleaseWaitDialog(msg, parentEl) {
if (angular.isUndefined(parentEl)) {
parentEl = angular.element(document.body);
}
$mdDialog.show({
parent: parentEl,
template: '<md-dialog class="wait-dialog" aria-label="Please wait">' +
' <md-dialog-content layout="column" layour-align="center center">' +
'<h1 class="text-center">Proszę czekać</h1>' +
'<md-content class="text-center">' + msg + '</md-content>'+
' </md-dialog-content>' +
'</md-dialog>'
});
}
return dataGiftService;
}
})(); |
<?php
namespace Kraken\Runtime\Supervision\Cmd;
use Dazzle\Channel\Channel;
use Dazzle\Channel\ChannelInterface;
use Dazzle\Channel\Extra\Request;
use Kraken\Runtime\Supervision\Solver;
use Kraken\Supervision\SolverInterface;
use Kraken\Runtime\RuntimeCommand;
use Error;
use Exception;
class CmdEscalate extends Solver implements SolverInterface
{
/**
* @var string[]
*/
protected $requires = [
'hash'
];
/**
* @var ChannelInterface
*/
protected $channel;
/**
* @var string
*/
protected $parent;
/**
*
*/
protected function construct()
{
$this->channel = $this->runtime->getCore()->make('Kraken\Runtime\Service\ChannelInternal');
$this->parent = $this->runtime->getParent();
}
/**
*
*/
protected function destruct()
{
unset($this->channel);
unset($this->parent);
}
/**
* @param Error|Exception $ex
* @param mixed[] $params
* @return mixed
*/
protected function solver($ex, $params = [])
{
$req = $this->createRequest(
$this->channel,
$this->parent,
new RuntimeCommand('cmd:error', [
'exception' => get_class($ex),
'message' => $ex->getMessage(),
'hash' => $params['hash']
])
);
return $req->call();
}
/**
* Create Request.
*
* @param ChannelInterface $channel
* @param string $receiver
* @param string $command
* @return Request
*/
protected function createRequest(ChannelInterface $channel, $receiver, $command)
{
return new Request($channel, $receiver, $command);
}
}
|
// Copyright (c) 2011-2013 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "signverifymessagedialog.h"
#include "ui_signverifymessagedialog.h"
#include "addressbookpage.h"
#include "base58.h"
#include "guiutil.h"
#include "init.h"
#include "main.h"
#include "optionsmodel.h"
#include "walletmodel.h"
#include "wallet.h"
#include <QClipboard>
#include <string>
#include <vector>
SignVerifyMessageDialog::SignVerifyMessageDialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::SignVerifyMessageDialog),
model(0)
{
ui->setupUi(this);
#if (QT_VERSION >= 0x040700)
/* Do not move this to the XML file, Qt before 4.7 will choke on it */
ui->addressIn_SM->setPlaceholderText(tr("Enter a Amerios address (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)"));
ui->signatureOut_SM->setPlaceholderText(tr("Click \"Sign Message\" to generate signature"));
ui->addressIn_VM->setPlaceholderText(tr("Enter a Amerios address (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)"));
ui->signatureIn_VM->setPlaceholderText(tr("Enter Amerios signature"));
#endif
GUIUtil::setupAddressWidget(ui->addressIn_SM, this);
GUIUtil::setupAddressWidget(ui->addressIn_VM, this);
ui->addressIn_SM->installEventFilter(this);
ui->messageIn_SM->installEventFilter(this);
ui->signatureOut_SM->installEventFilter(this);
ui->addressIn_VM->installEventFilter(this);
ui->messageIn_VM->installEventFilter(this);
ui->signatureIn_VM->installEventFilter(this);
ui->signatureOut_SM->setFont(GUIUtil::bitcoinAddressFont());
ui->signatureIn_VM->setFont(GUIUtil::bitcoinAddressFont());
}
SignVerifyMessageDialog::~SignVerifyMessageDialog()
{
delete ui;
}
void SignVerifyMessageDialog::setModel(WalletModel *model)
{
this->model = model;
}
void SignVerifyMessageDialog::setAddress_SM(const QString &address)
{
ui->addressIn_SM->setText(address);
ui->messageIn_SM->setFocus();
}
void SignVerifyMessageDialog::setAddress_VM(const QString &address)
{
ui->addressIn_VM->setText(address);
ui->messageIn_VM->setFocus();
}
void SignVerifyMessageDialog::showTab_SM(bool fShow)
{
ui->tabWidget->setCurrentIndex(0);
if (fShow)
this->show();
}
void SignVerifyMessageDialog::showTab_VM(bool fShow)
{
ui->tabWidget->setCurrentIndex(1);
if (fShow)
this->show();
}
void SignVerifyMessageDialog::on_addressBookButton_SM_clicked()
{
if (model && model->getAddressTableModel())
{
AddressBookPage dlg(AddressBookPage::ForSending, AddressBookPage::ReceivingTab, this);
dlg.setModel(model->getAddressTableModel());
if (dlg.exec())
{
setAddress_SM(dlg.getReturnValue());
}
}
}
void SignVerifyMessageDialog::on_pasteButton_SM_clicked()
{
setAddress_SM(QApplication::clipboard()->text());
}
void SignVerifyMessageDialog::on_signMessageButton_SM_clicked()
{
/* Clear old signature to ensure users don't get confused on error with an old signature displayed */
ui->signatureOut_SM->clear();
CBitcoinAddress addr(ui->addressIn_SM->text().toStdString());
if (!addr.IsValid())
{
ui->addressIn_SM->setValid(false);
ui->statusLabel_SM->setStyleSheet("QLabel { color: red; }");
ui->statusLabel_SM->setText(tr("The entered address is invalid.") + QString(" ") + tr("Please check the address and try again."));
return;
}
CKeyID keyID;
if (!addr.GetKeyID(keyID))
{
ui->addressIn_SM->setValid(false);
ui->statusLabel_SM->setStyleSheet("QLabel { color: red; }");
ui->statusLabel_SM->setText(tr("The entered address does not refer to a key.") + QString(" ") + tr("Please check the address and try again."));
return;
}
WalletModel::UnlockContext ctx(model->requestUnlock());
if (!ctx.isValid())
{
ui->statusLabel_SM->setStyleSheet("QLabel { color: red; }");
ui->statusLabel_SM->setText(tr("Wallet unlock was cancelled."));
return;
}
CKey key;
if (!pwalletMain->GetKey(keyID, key))
{
ui->statusLabel_SM->setStyleSheet("QLabel { color: red; }");
ui->statusLabel_SM->setText(tr("Private key for the entered address is not available."));
return;
}
CDataStream ss(SER_GETHASH, 0);
ss << strMessageMagic;
ss << ui->messageIn_SM->document()->toPlainText().toStdString();
std::vector<unsigned char> vchSig;
if (!key.SignCompact(Hash(ss.begin(), ss.end()), vchSig))
{
ui->statusLabel_SM->setStyleSheet("QLabel { color: red; }");
ui->statusLabel_SM->setText(QString("<nobr>") + tr("Message signing failed.") + QString("</nobr>"));
return;
}
ui->statusLabel_SM->setStyleSheet("QLabel { color: green; }");
ui->statusLabel_SM->setText(QString("<nobr>") + tr("Message signed.") + QString("</nobr>"));
ui->signatureOut_SM->setText(QString::fromStdString(EncodeBase64(&vchSig[0], vchSig.size())));
}
void SignVerifyMessageDialog::on_copySignatureButton_SM_clicked()
{
QApplication::clipboard()->setText(ui->signatureOut_SM->text());
}
void SignVerifyMessageDialog::on_clearButton_SM_clicked()
{
ui->addressIn_SM->clear();
ui->messageIn_SM->clear();
ui->signatureOut_SM->clear();
ui->statusLabel_SM->clear();
ui->addressIn_SM->setFocus();
}
void SignVerifyMessageDialog::on_addressBookButton_VM_clicked()
{
if (model && model->getAddressTableModel())
{
AddressBookPage dlg(AddressBookPage::ForSending, AddressBookPage::SendingTab, this);
dlg.setModel(model->getAddressTableModel());
if (dlg.exec())
{
setAddress_VM(dlg.getReturnValue());
}
}
}
void SignVerifyMessageDialog::on_verifyMessageButton_VM_clicked()
{
CBitcoinAddress addr(ui->addressIn_VM->text().toStdString());
if (!addr.IsValid())
{
ui->addressIn_VM->setValid(false);
ui->statusLabel_VM->setStyleSheet("QLabel { color: red; }");
ui->statusLabel_VM->setText(tr("The entered address is invalid.") + QString(" ") + tr("Please check the address and try again."));
return;
}
CKeyID keyID;
if (!addr.GetKeyID(keyID))
{
ui->addressIn_VM->setValid(false);
ui->statusLabel_VM->setStyleSheet("QLabel { color: red; }");
ui->statusLabel_VM->setText(tr("The entered address does not refer to a key.") + QString(" ") + tr("Please check the address and try again."));
return;
}
bool fInvalid = false;
std::vector<unsigned char> vchSig = DecodeBase64(ui->signatureIn_VM->text().toStdString().c_str(), &fInvalid);
if (fInvalid)
{
ui->signatureIn_VM->setValid(false);
ui->statusLabel_VM->setStyleSheet("QLabel { color: red; }");
ui->statusLabel_VM->setText(tr("The signature could not be decoded.") + QString(" ") + tr("Please check the signature and try again."));
return;
}
CDataStream ss(SER_GETHASH, 0);
ss << strMessageMagic;
ss << ui->messageIn_VM->document()->toPlainText().toStdString();
CPubKey pubkey;
if (!pubkey.RecoverCompact(Hash(ss.begin(), ss.end()), vchSig))
{
ui->signatureIn_VM->setValid(false);
ui->statusLabel_VM->setStyleSheet("QLabel { color: red; }");
ui->statusLabel_VM->setText(tr("The signature did not match the message digest.") + QString(" ") + tr("Please check the signature and try again."));
return;
}
if (!(CBitcoinAddress(pubkey.GetID()) == addr))
{
ui->statusLabel_VM->setStyleSheet("QLabel { color: red; }");
ui->statusLabel_VM->setText(QString("<nobr>") + tr("Message verification failed.") + QString("</nobr>"));
return;
}
ui->statusLabel_VM->setStyleSheet("QLabel { color: green; }");
ui->statusLabel_VM->setText(QString("<nobr>") + tr("Message verified.") + QString("</nobr>"));
}
void SignVerifyMessageDialog::on_clearButton_VM_clicked()
{
ui->addressIn_VM->clear();
ui->signatureIn_VM->clear();
ui->messageIn_VM->clear();
ui->statusLabel_VM->clear();
ui->addressIn_VM->setFocus();
}
bool SignVerifyMessageDialog::eventFilter(QObject *object, QEvent *event)
{
if (event->type() == QEvent::MouseButtonPress || event->type() == QEvent::FocusIn)
{
if (ui->tabWidget->currentIndex() == 0)
{
/* Clear status message on focus change */
ui->statusLabel_SM->clear();
/* Select generated signature */
if (object == ui->signatureOut_SM)
{
ui->signatureOut_SM->selectAll();
return true;
}
}
else if (ui->tabWidget->currentIndex() == 1)
{
/* Clear status message on focus change */
ui->statusLabel_VM->clear();
}
}
return QDialog::eventFilter(object, event);
}
|
///////////////////////////////////////////////////////////////////////////
// Copyright © Esri. All Rights Reserved.
//
// 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.
///////////////////////////////////////////////////////////////////////////
define({
"_widgetLabel": "Penyaringan",
"geometryServicesNotFound": "Service geometri tidak tersedia.",
"unableToDrawBuffer": "Tidak dapat menggambar buffer. Harap coba lagi.",
"invalidConfiguration": "Konfigurasi tidak valid.",
"clearAOIButtonLabel": "Mulai Ulang",
"noGraphicsShapefile": "Shapefile yang diunggah tidak berisi grafis.",
"zoomToLocationTooltipText": "Zoom ke lokasi",
"noGraphicsToZoomMessage": "Tidak ada grafik yang ditemukan untuk memperbesar.",
"placenameWidget": {
"placenameLabel": "Cari lokasi"
},
"drawToolWidget": {
"useDrawToolForAOILabel": "Pilih mode gambar",
"toggleSelectability": "Klik untuk beralih selektabilitas",
"chooseLayerTitle": "Pilih layer yang dapat dipilih",
"selectAllLayersText": "Pilih Semua",
"layerSelectionWarningTooltip": "Setidaknya satu layer harus dipilih untuk membuat AOI",
"selectToolLabel": "Pilih alat"
},
"shapefileWidget": {
"shapefileLabel": "Unggah shapefile zip",
"uploadShapefileButtonText": "Unggah",
"unableToUploadShapefileMessage": "Tidak dapat mengunggah shapefile."
},
"coordinatesWidget": {
"selectStartPointFromSearchText": "Tentukan titik awal",
"addButtonTitle": "Tambah",
"deleteButtonTitle": "Hapus",
"mapTooltipForStartPoint": "Klik pada peta untuk menentukan titik awal",
"mapTooltipForUpdateStartPoint": "Klik pada peta untuk memperbarui titik awal",
"locateText": "Temukan",
"locateByMapClickText": "Pilih koordinat awal",
"enterBearingAndDistanceLabel": "Masukkan poros dan jarak dari titik awal",
"bearingTitle": "Poros",
"distanceTitle": "Jarak",
"planSettingTooltip": "Pengaturan Rencana",
"invalidLatLongMessage": "Harap masukkan nilai yang valid."
},
"bufferDistanceAndUnit": {
"bufferInputTitle": "Jarak buffer (opsional)",
"bufferInputLabel": "Tampilkan hasil dalam",
"bufferDistanceLabel": "Jarak buffer",
"bufferUnitLabel": "Unit buffer"
},
"traverseSettings": {
"bearingLabel": "Poros",
"lengthLabel": "Panjang",
"addButtonTitle": "Tambah",
"deleteButtonTitle": "Hapus",
"deleteBearingAndLengthLabel": "Hapus poros dan baris panjang",
"addButtonLabel": "Hapus poros dan panjang"
},
"planSettings": {
"expandGridTooltipText": "Perluas grid",
"collapseGridTooltipText": "Ciutkan grid",
"directionUnitLabelText": "Unit Arah",
"distanceUnitLabelText": "Unit Jarak dan Panjang",
"planSettingsComingSoonText": "Segera Datang"
},
"newTraverse": {
"invalidBearingMessage": "Poros Tidak Valid.",
"invalidLengthMessage": "Panjang Tidak Valid.",
"negativeLengthMessage": "Panjang Negatif"
},
"reportsTab": {
"aoiAreaText": "Area AOI",
"downloadButtonTooltip": "Unduh",
"printButtonTooltip": "Cetak",
"uploadShapefileForAnalysisText": "Unggah shapefile untuk disertakan dalam analisis",
"uploadShapefileForButtonText": "Telusuri",
"downloadLabelText": "Pilih Format :",
"downloadBtnText": "Unduh",
"noDetailsAvailableText": "Tidak ada hasil yang ditemukan",
"featureCountText": "Jumlah",
"featureAreaText": "Area",
"featureLengthText": "Panjang",
"attributeChooserTooltip": "Pilih atribut untuk ditampilkan",
"csv": "CSV",
"filegdb": "File Geodatabase",
"shapefile": "Shapefile",
"noFeaturesFound": "Tidak ada hasil yang ditemukan untuk format file yang dipilih",
"selectReportFieldTitle": "Pilih kolom",
"noFieldsSelected": "Tidak ada kolom yang dipilih",
"intersectingFeatureExceedsMsgOnCompletion": "Penghitungan jumlah maksimum catatan telah tercapai untuk satu atau beberapa layer.",
"unableToAnalyzeText": "Tidak dapat menganalisis, jumlah catatan maksimum telah tercapai.",
"errorInPrintingReport": "Tidak dapat mencetak laporan. Harap periksa apakah pengaturan laporan valid.",
"aoiInformationTitle": "Informasi Area Pilihan (AOI)",
"summaryReportTitle": "Ringkasan",
"notApplicableText": "T/A",
"downloadReportConfirmTitle": "Konfirmasi pengunduhan",
"downloadReportConfirmMessage": "Anda yakin ingin mengunduh?",
"noDataText": "Tidak Ada Data",
"createReplicaFailedMessage": "Operasi unduhan gagal untuk layer berikut: <br/> ${layerNames}",
"extractDataTaskFailedMessage": "Operasi mengunduh gagal.",
"printLayoutLabelText": "Tata Letak",
"printBtnText": "Cetak",
"printDialogHint": "Catatan: Judul laporan dan komentar dapat diedit dalam pratinjau laporan.",
"unableToDownloadFileGDBText": "Geodatabase file tidak dapat diunduh untuk AOI yang berisi lokasi titik atau garis",
"unableToDownloadShapefileText": "Shapefile tidak dapat diunduh untuk AOI yang berisi lokasi titik atau garis",
"analysisAreaUnitLabelText": "Tampilkan hasil luas dalam :",
"analysisLengthUnitLabelText": "Tampilkan hasil panjang dalam :",
"analysisUnitButtonTooltip": "Pilih unit untuk analisis",
"analysisCloseBtnText": "Tutup",
"areaSquareFeetUnit": "Kaki Persegi",
"areaAcresUnit": "Acre",
"areaSquareMetersUnit": "Meter Persegi",
"areaSquareKilometersUnit": "Kilometer Persegi",
"areaHectaresUnit": "Hektare",
"lengthFeetUnit": "Kaki",
"lengthMilesUnit": "Mil",
"lengthMetersUnit": "Meter",
"lengthKilometersUnit": "Kilometer",
"hectaresAbbr": "hektar",
"layerNotVisibleText": "Tidak dapat menganalisis. Layer dimatikan atau di luar rentang visibilitas skala.",
"refreshBtnTooltip": "Muat ulang laporan",
"featureCSVAreaText": "Area Berpotongan",
"featureCSVLengthText": "Panjang Berpotongan",
"errorInFetchingPrintTask": "Kesalahan saat mengambil informasi tugas cetak. Silakan coba lagi.",
"selectAllLabel": "Pilih Semua",
"errorInLoadingProjectionModule": "Kesalahan saat memuat dependensi modul proyeksi. Harap coba mengunduh file kembali.",
"expandCollapseIconLabel": "Fitur berpotongan",
"intersectedFeatureLabel": "Detail fitur berpotongan",
"valueAriaLabel": "Nilai",
"countAriaLabel": "Jumlah"
}
}); |
require 'bundler/setup'
module Bob
end
require_relative 'bob/config'
require_relative 'bob/engine'
config = Bob::Config.load
engine = Bob::Engine.new(config)
engine.run |
package jxdo.rjava;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.lang.reflect.Modifier;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
class JCSharp {
static String crlf;
static ClassLoader clazzLoader;
List<String> lstClassNames;
public JCSharp(String jarNames) throws Throwable{
if(crlf == null)crlf= System.getProperty("line.separator");
lstClassNames = new ArrayList<String>();
if(clazzLoader == null)
clazzLoader = this.getJarClassLoader(jarNames, this.getClass().getClassLoader());
}
@SuppressWarnings("unused")
private void addClassLaoder(String jarNames) throws Throwable {
lstClassNames.clear();
ClassLoader newClazzLoader = this.getJarClassLoader(jarNames, clazzLoader);
if(newClazzLoader != clazzLoader)clazzLoader = newClazzLoader;
}
private ClassLoader getJarClassLoader(String jarNames, ClassLoader parentClassLoader) throws Throwable{
List<URL> lstUrls = new ArrayList<URL>();
for(String jarName : jarNames.split(";")){
//System.out.println(jarName);
File file = new File(jarName);
if(file.getName().compareToIgnoreCase("jxdo.rjava.jar") == 0)continue;
if(!file.exists())
{
java.io.FileNotFoundException exp = new java.io.FileNotFoundException(jarName);
if(exp.getMessage() == null){
Throwable ta = exp.getCause();
if(ta!=null)throw ta;
}
throw exp;
}
this.fillClassNames(jarName);
URL jarUrl = new URL("jar", "","file:" + file.getAbsolutePath()+"!/");
lstUrls.add(jarUrl);
}
if(lstUrls.size()==0)
return parentClassLoader;
URL[] urls = lstUrls.toArray(new URL[0]);
return URLClassLoader.newInstance(urls, parentClassLoader);
}
private void fillClassNames(String jarFileName) throws Throwable{
JarFile jar = new JarFile(jarFileName);
Enumeration<JarEntry> entries = jar.entries();
while (entries.hasMoreElements()) {
String entry = entries.nextElement().getName();
if(!entry.endsWith(".class"))continue;
//System.out.println(entry);
String clsName = entry.replaceAll(".class", "").replaceAll("/", ".");
lstClassNames.add(clsName);
}
}
List<Class<?>> lstClasses;
public void fillClasses(String directoryName) throws Throwable{
if(lstClasses == null)
lstClasses = new ArrayList<Class<?>>();
else
lstClasses.clear();
//System.out.println(directoryName);
List<ClassFile> lst = new ArrayList<ClassFile>();
for(int i=0;i<lstClassNames.size();i++){
String name = lstClassNames.get(i);
if(name.indexOf("$") > 0){
continue;
}
ClassFile cd = new ClassFile();
cd.className = name;
lst.add(cd);
lstClassNames.remove(i);
i-=1;
}
java.io.File f = new File(directoryName);
if(!f.exists())f.mkdirs();
lstFileWriters = new ArrayList<FileWriter>();
this.ForEachCoder(lst,directoryName);
for(FileWriter fw : lstFileWriters)
fw.close();
}
List<FileWriter> lstFileWriters;
private void ForEachCoder(List<ClassFile> lst, String directoryName){
for(ClassFile cf : lst){
Class<?> clazz = cf.loadClass();
if(clazz == null)continue;
//C#¶ËµÄ½Ó¿Ú²»Ö§³ÖǶÌ×
boolean isInterface = clazz.isInterface();
FileWriter fwCurrent = isInterface ? cf.getFileWriter(directoryName) : cf.getParent(cf).getFileWriter(directoryName);
String tabs = isInterface ? "\t" : cf.getTabs();
if(!lstFileWriters.contains(fwCurrent))
lstFileWriters.add(fwCurrent);
JCSharpOuter jcOuter = new JCSharpOuter(clazz, fwCurrent, isInterface ? false : cf.Postion > 0);
jcOuter.writerNamespaceStart(tabs);
jcOuter.writerDefineStart();
System.out.println(tabs + cf.className);
this.ForEachCoder(cf.getNetseds(), directoryName);
jcOuter.writerDefineEnd();
jcOuter.writerNamespaceEnd();
}
}
public class ClassFile{
String className;
int Postion = 0;
ClassFile Parent;
public List<ClassFile> getNetseds(){
List<ClassFile> netseds = new ArrayList<ClassFile>();
for(int i=0;i<lstClassNames.size();i++){
String ns = lstClassNames.get(i);
if(!ns.startsWith(className))continue;
int level = ns.split("\\$").length - 1;
if(level == Postion +1)
{
ClassFile cd = new ClassFile();
cd.className = ns;
cd.Postion = level;
cd.Parent = this;
netseds.add(cd);
lstClassNames.remove(i);
i-=1;
}
}
return netseds;
}
ClassFile cfSearchParent;
private ClassFile getParent(ClassFile cf){
if(cfSearchParent == null)
searchParent(cf);
return cfSearchParent;
}
private void searchParent(ClassFile cf){
if(cf.Parent == null){
cfSearchParent = cf;
return;
}
searchParent(cf.Parent);
//cf.Level += 1;
}
Class<?> cls;
public Class<?> loadClass(){
if(cls == null){
try {
cls = clazzLoader.loadClass(this.className);
} catch (ClassNotFoundException e) {
return null;
}
int im = cls.getModifiers();
if(!Modifier.isPublic(im))
return null;
}
return cls;
}
String _tabs;
public String getTabs(){
if(_tabs == null){
String s = "\t";
for(int i=0;i<this.Postion;i++)
s += "\t";
_tabs = s;
}
return _tabs;
}
FileWriter fw;
public FileWriter getFileWriter(String directoryName){
if(fw == null){
String csFileName = className.replace('$', '.');
// if(csFileName.indexOf(".") > -1)
// csFileName = csFileName.substring(csFileName.indexOf(".") + 1, csFileName.length() + 2 - csFileName.indexOf("."));
// if(csFileName.indexOf("$") > -1)
// csFileName = csFileName.substring(csFileName.indexOf("$") + 1, csFileName.length() + 2 - csFileName.indexOf("$"));
File f = new File(directoryName + File.separator + csFileName + ".cs");
if(f.exists())f.delete();
boolean isCreated;
try {
isCreated = f.createNewFile();
} catch (IOException e) {
isCreated = false;
}
if(!isCreated)return null;
try {
fw = new FileWriter(f);
} catch (IOException e) {
return null;
}
}
return fw;
}
}
public static void main(String[] args) throws Throwable {
//home
// String fname = "E:\\DotNet2010\\NXDO.Mixed\\NXDO.Mixed.V2015\\Tester\\RJavaX64\\bin\\Debug\\jforloaded.jar";
// JCSharp jf = new JCSharp(fname);
// jf.fillClasses("E:\\DotNet2010\\NXDO.Mixed\\nxdo.jacoste");
//ltd
String fname = "E:\\DotNet2012\\CSharp2Java\\NXDO.Mixed.V2015\\Tester\\RJavaX64\\bin\\Debug\\jforloaded.jar";
JCSharp jf = new JCSharp(fname);
jf.fillClasses("E:\\DotNet2012\\CSharp2Java\\nxdo.jacoste");
}
}
|
package com.ado.java.odata.pool;
import java.sql.Connection;
import java.sql.SQLException;
public interface Pool {
/**
* Make a new connection
*
* @throws SQLException
*/
Connection makeConnection() throws SQLException;
/**
* Gets a valid connection from the connection pool
*
* @return a valid connection from the pool
* @throws SQLException
*/
Connection getConnection() throws SQLException;
/**
* Return a connection into the connection pool
*
* @param connection the connection to return to the pool
* @throws SQLException
*/
void returnConnection(Connection connection) throws SQLException;
}
|
using UnityEngine;
public class DamageOnCollision : MonoBehaviour
{
public float damage = 1f;
public bool damageSelf = true;
void OnCollisionEnter2D(Collision2D collision)
{
var health = collision.gameObject.GetComponent<HealthProperty>();
if (health != null) {
health.Damage(damage);
}
if (damageSelf) {
var rockHealth = GetComponent<HealthProperty>();
if (rockHealth != null) {
rockHealth.Damage(damage);
}
}
}
} |
module.exports = `
type SimpleBudgetDetail {
account_type: String,
account_name: String,
fund_name: String,
department_name: String,
division_name: String,
costcenter_name: String,
function_name: String,
charcode_name: String,
organization_name: String,
category_name: String,
budget_section_name: String,
object_name: String,
year: Int,
budget: Float,
actual: Float,
full_account_id: String,
org_id: String,
obj_id: String,
fund_id: String,
dept_id: String,
div_id: String,
cost_id: String,
func_id: String,
charcode: String,
category_id: String,
budget_section_id: String,
proj_id: String,
is_proposed: String
use_actual: String
}
type SimpleBudgetSummary {
account_type: String,
category_name: String,
year: Int,
total_budget: Float,
total_actual: Float
use_actual: String
}
type BudgetCashFlow {
account_type: String,
category_name: String,
category_id: String,
dept_id: String,
department_name: String,
fund_id: String,
fund_name: String,
budget: Float,
year: Int
}
type BudgetParameters {
start_year: Int
end_year: Int
in_budget_season: Boolean
}
`;
|
module.exports = client => {
console.log(`Reconnecting... [at ${new Date()}]`);
}; |
/**
* This class was created by <Vazkii>. It's distributed as
* part of the Botania Mod. Get the Source Code in github:
* https://github.com/Vazkii/Botania
*
* Botania is Open Source and distributed under the
* Botania License: http://botaniamod.net/license.php
*
* File Created @ [Feb 14, 2015, 3:28:54 PM (GMT)]
*/
package vazkii.botania.api.corporea;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.WeakHashMap;
import net.minecraft.inventory.IInventory;
import net.minecraft.inventory.ISidedInventory;
import net.minecraft.item.ItemStack;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.AxisAlignedBB;
import net.minecraft.world.World;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.common.util.ForgeDirection;
public final class CorporeaHelper {
private static final List<IInventory> empty = Collections.unmodifiableList(new ArrayList());
private static final WeakHashMap<List<ICorporeaSpark>, List<IInventory>> cachedNetworks = new WeakHashMap();
public static final String[] WILDCARD_STRINGS = new String[] {
"...", "~", "+", "?" , "*"
};
/**
* How many items were matched in the last request. If java had "out" params like C# this wouldn't be needed :V
*/
public static int lastRequestMatches = 0;
/**
* How many items were extracted in the last request.
*/
public static int lastRequestExtractions = 0;
/**
* Gets a list of all the inventories on this spark network. This list is cached for use once every tick,
* and if something changes during that tick it'll still have the first result.
*/
public static List<IInventory> getInventoriesOnNetwork(ICorporeaSpark spark) {
ICorporeaSpark master = spark.getMaster();
if(master == null)
return empty;
List<ICorporeaSpark> network = master.getConnections();
if(cachedNetworks.containsKey(network)) {
List<IInventory> cache = cachedNetworks.get(network);
if(cache != null)
return cache;
}
List<IInventory> inventories = new ArrayList();
if(network != null)
for(ICorporeaSpark otherSpark : network)
if(otherSpark != null) {
IInventory inv = otherSpark.getInventory();
if(inv != null)
inventories.add(inv);
}
cachedNetworks.put(network, inventories);
return inventories;
}
/**
* Gets the amount of available items in the network of the type passed in, checking NBT or not.
* The higher level functions that use a List< IInventory > or a Map< IInventory, Integer > should be
* called instead if the context for those exists to avoid having to get the values again.
*/
public static int getCountInNetwork(ItemStack stack, ICorporeaSpark spark, boolean checkNBT) {
List<IInventory> inventories = getInventoriesOnNetwork(spark);
return getCountInNetwork(stack, inventories, checkNBT);
}
/**
* Gets the amount of available items in the network of the type passed in, checking NBT or not.
* The higher level function that use a Map< IInventory, Integer > should be
* called instead if the context for this exists to avoid having to get the value again.
*/
public static int getCountInNetwork(ItemStack stack, List<IInventory> inventories, boolean checkNBT) {
Map<IInventory, Integer> map = getInventoriesWithItemInNetwork(stack, inventories, checkNBT);
return getCountInNetwork(stack, map, checkNBT);
}
/**
* Gets the amount of available items in the network of the type passed in, checking NBT or not.
*/
public static int getCountInNetwork(ItemStack stack, Map<IInventory, Integer> inventories, boolean checkNBT) {
int count = 0;
for(IInventory inv : inventories.keySet())
count += inventories.get(inv);
return count;
}
/**
* Gets a Map mapping IInventories to the amount of items of the type passed in that exist
* The higher level function that use a List< IInventory > should be
* called instead if the context for this exists to avoid having to get the value again.
*/
public static Map<IInventory, Integer> getInventoriesWithItemInNetwork(ItemStack stack, ICorporeaSpark spark, boolean checkNBT) {
List<IInventory> inventories = getInventoriesOnNetwork(spark);
return getInventoriesWithItemInNetwork(stack, inventories, checkNBT);
}
/**
* Gets a Map mapping IInventories to the amount of items of the type passed in that exist
* The deeper level function that use a List< IInventory > should be
* called instead if the context for this exists to avoid having to get the value again.
*/
public static Map<IInventory, Integer> getInventoriesWithItemInNetwork(ItemStack stack, List<IInventory> inventories, boolean checkNBT) {
Map<IInventory, Integer> countMap = new HashMap();
for(IInventory inv : inventories) {
int count = 0;
for(int i = 0; i < inv.getSizeInventory(); i++) {
if(!isValidSlot(inv, i))
continue;
ItemStack stackAt = inv.getStackInSlot(i);
if(stacksMatch(stack, stackAt, checkNBT))
count += stackAt.stackSize;
}
if(count > 0)
countMap.put(inv, count);
}
return countMap;
}
/**
* Bridge for requestItem() using an ItemStack.
*/
public static List<ItemStack> requestItem(ItemStack stack, ICorporeaSpark spark, boolean checkNBT, boolean doit) {
return requestItem(stack, stack.stackSize, spark, checkNBT, doit);
}
/**
* Bridge for requestItem() using a String and an item count.
*/
public static List<ItemStack> requestItem(String name, int count, ICorporeaSpark spark, boolean doit) {
return requestItem(name, count, spark, false, doit);
}
/**
* Requests list of ItemStacks of the type passed in from the network, or tries to, checking NBT or not.
* This will remove the items from the adequate inventories unless the "doit" parameter is false.
* Returns a new list of ItemStacks of the items acquired or an empty list if none was found.
* Case itemCount is -1 it'll find EVERY item it can.
* <br><br>
* The "matcher" parameter has to be an ItemStack or a String, if the first it'll check if the
* two stacks are similar using the "checkNBT" parameter, else it'll check if the name of the item
* equals or matches (case a regex is passed in) the matcher string.
*/
public static List<ItemStack> requestItem(Object matcher, int itemCount, ICorporeaSpark spark, boolean checkNBT, boolean doit) {
List<ItemStack> stacks = new ArrayList();
CorporeaRequestEvent event = new CorporeaRequestEvent(matcher, itemCount, spark, checkNBT, doit);
if(MinecraftForge.EVENT_BUS.post(event))
return stacks;
List<IInventory> inventories = getInventoriesOnNetwork(spark);
Map<ICorporeaInterceptor, ICorporeaSpark> interceptors = new HashMap();
lastRequestMatches = 0;
lastRequestExtractions = 0;
int count = itemCount;
for(IInventory inv : inventories) {
ICorporeaSpark invSpark = getSparkForInventory(inv);
if(inv instanceof ICorporeaInterceptor) {
ICorporeaInterceptor interceptor = (ICorporeaInterceptor) inv;
interceptor.interceptRequest(matcher, itemCount, invSpark, spark, stacks, inventories, doit);
interceptors.put(interceptor, invSpark);
}
for(int i = inv.getSizeInventory() - 1; i >= 0; i--) {
if(!isValidSlot(inv, i))
continue;
ItemStack stackAt = inv.getStackInSlot(i);
if(matcher instanceof ItemStack ? stacksMatch((ItemStack) matcher, stackAt, checkNBT) : matcher instanceof String ? stacksMatch(stackAt, (String) matcher) : false) {
int rem = Math.min(stackAt.stackSize, count == -1 ? stackAt.stackSize : count);
if(rem > 0) {
ItemStack copy = stackAt.copy();
if(rem < copy.stackSize)
copy.stackSize = rem;
stacks.add(copy);
}
lastRequestMatches += stackAt.stackSize;
lastRequestExtractions += rem;
if(doit && rem > 0) {
inv.decrStackSize(i, rem);
if(invSpark != null)
invSpark.onItemExtracted(stackAt);
}
if(count != -1)
count -= rem;
}
}
}
for(ICorporeaInterceptor interceptor : interceptors.keySet())
interceptor.interceptRequestLast(matcher, itemCount, interceptors.get(interceptor), spark, stacks, inventories, doit);
return stacks;
}
/**
* Gets the spark attached to the inventory passed case it's a TileEntity.
*/
public static ICorporeaSpark getSparkForInventory(IInventory inv) {
if(!(inv instanceof TileEntity))
return null;
TileEntity tile = (TileEntity) inv;
return getSparkForBlock(tile.getWorldObj(), tile.xCoord, tile.yCoord, tile.zCoord);
}
/**
* Gets the spark attached to the block in the coords passed in. Note that the coords passed
* in are for the block that the spark will be on, not the coords of the spark itself.
*/
public static ICorporeaSpark getSparkForBlock(World world, int x, int y, int z) {
List<ICorporeaSpark> sparks = world.getEntitiesWithinAABB(ICorporeaSpark.class, AxisAlignedBB.getBoundingBox(x, y + 1, z, x + 1, y + 2, z + 1));
return sparks.isEmpty() ? null : sparks.get(0);
}
/**
* Gets if the block in the coords passed in has a spark attached. Note that the coords passed
* in are for the block that the spark will be on, not the coords of the spark itself.
*/
public static boolean doesBlockHaveSpark(World world, int x, int y, int z) {
return getSparkForBlock(world, x, y, z) != null;
}
/**
* Gets if the slot passed in can be extracted from by a spark.
*/
public static boolean isValidSlot(IInventory inv, int slot) {
return !(inv instanceof ISidedInventory) || arrayHas(((ISidedInventory) inv).getAccessibleSlotsFromSide(ForgeDirection.UP.ordinal()), slot) && ((ISidedInventory) inv).canExtractItem(slot, inv.getStackInSlot(slot), ForgeDirection.UP.ordinal());
}
/**
* Gets if two stacks match.
*/
public static boolean stacksMatch(ItemStack stack1, ItemStack stack2, boolean checkNBT) {
return stack1 != null && stack2 != null && stack1.isItemEqual(stack2) && (!checkNBT || ItemStack.areItemStackTagsEqual(stack1, stack2));
}
/**
* Gets if the name of a stack matches the string passed in.
*/
public static boolean stacksMatch(ItemStack stack, String s) {
if(stack == null)
return false;
boolean contains = false;
for(String wc : WILDCARD_STRINGS) {
if(s.endsWith(wc)) {
contains = true;
s = s.substring(0, s.length() - wc.length());
}
else if(s.startsWith(wc)) {
contains = true;
s = s.substring(wc.length());
}
if(contains)
break;
}
String name = stack.getDisplayName().toLowerCase().trim();
return equalOrContain(name, s, contains) || equalOrContain(name + "s", s, contains) || equalOrContain(name + "es", s, contains) || name.endsWith("y") && equalOrContain(name.substring(0, name.length() - 1) + "ies", s, contains);
}
/**
* Clears the cached networks, called once per tick, should not be called outside
* of the botania code.
*/
public static void clearCache() {
cachedNetworks.clear();
}
/**
* Helper method to check if an int array contains an int.
*/
public static boolean arrayHas(int[] arr, int val) {
for (int element : arr)
if(element == val)
return true;
return false;
}
/**
* Helper method to make stacksMatch() less messy.
*/
public static boolean equalOrContain(String s1, String s2, boolean contain) {
return contain ? s1.contains(s2) : s1.equals(s2);
}
}
|
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link rel="apple-touch-icon" sizes="180x180" href="assets/ico/apple-touch-icon.png">
<link rel="icon" type="image/png" sizes="32x32" href="assets/ico/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="16x16" href="assets/ico/favicon-16x16.png">
<link rel="manifest" href="assets/ico/manifest.json">
<link rel="mask-icon" href="assets/ico/safari-pinned-tab.svg" color="#5bbad5">
<link rel="shortcut icon" href="assets/ico/favicon.ico">
<meta name="msapplication-config" content="assets/ico/browserconfig.xml">
<meta name="theme-color" content="#ffffff">
<title>Sweet Cups - Roll Ice Cream & Coffee</title>
<!-- CSS Plugins -->
<link rel="stylesheet" href="assets/plugins/font-awesome/css/font-awesome.min.css">
<link rel="stylesheet" href="assets/plugins/lightbox/css/lightbox.min.css">
<link rel="stylesheet" href="assets/plugins/flickity/flickity.min.css">
<!-- CSS Global -->
<!-- build:css assets/css/theme.min.css -->
<link rel="stylesheet" href="assets/css/theme.css">
<!-- endbuild -->
</head>
<body>
<!-- NAVBAR
================================================== -->
<nav class="navbar navbar-light navbar-expand-lg fixed-top">
<div class="container">
<!-- Navbar: Brand -->
<a class="navbar-brand navbar-brand_2 d-lg-none" href="index.html">Sweet Cups</a>
<!-- Navbar: Toggler -->
<button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<!-- Navbar: Collapse -->
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<!-- Navbar navigation: Left -->
<ul class="navbar-nav mr-auto">
<li class="nav-item">
<a class="nav-link" href="about-us.html">About Us</a>
</li>
<li class="nav-item">
<a class="nav-link" href="menu_no-images.html">Menu</a>
</li>
</ul>
<!-- Brand name -->
<a class="navbar-brand navbar-brand_2 d-none d-lg-flex" href="index.html">
Sweet Cups
</a>
<!-- Navbar navigation: Right -->
<ul class="navbar-nav ml-auto">
<li class="nav-item">
<a class="nav-link" href="gallery.html">Gallery</a>
</li>
<li class="nav-item active">
<a class="nav-link" href="contact-us.html">Contact</a>
</li>
</ul>
</div> <!-- / .navbar-collapse -->
</div> <!-- / .container -->
</nav> <!-- / .navbar -->
<!-- HEADER
================================================== -->
<section class="section section_header" data-parallax="scroll" data-image-src="assets/img/sweetcups/s3.jpg">
<div class="container">
<div class="row">
<div class="col">
<!-- Heading -->
<h1 class="section__heading section_header__heading text-center">
Contact Us
</h1>
</div>
</div> <!-- / .row -->
</div> <!-- / .container -->
</section>
<!-- CONTACT
================================================== -->
<section class="section section_contact">
<div class="container">
<div class="row">
<div class="col">
<!-- Heading -->
<h2 class="section__heading text-center">
Get in touch with us
</h2>
<!-- Subheading -->
<p class="section__subheading text-center">
Give us a call or send us an email and we will get back to you as soon as possible!
</p>
</div>
</div> <!-- / .row -->
<div class="row">
<div class="col-md-3 order-md-2">
<!-- Contact info -->
<div class="section_contact__info">
<div class="section_contact__info__item">
<h4 class="section_contact__info__item__heading">
Write us
</h4>
<p class="section_contact__info__item__content">
<a href="mailto:sweetcupskc@gmail.com">sweetcupskc@gmail.com</a>
</p>
</div>
<div class="section_contact__info__item">
<h4 class="section_contact__info__item__heading">
Call us
</h4>
<p class="section_contact__info__item__content">
<a href="tel:+18165840442">+1 (816) 584-0442</a>
</p>
</div>
<div class="section_contact__info__item">
<h4 class="section_contact__info__item__heading">
Visit us
</h4>
<p class="section_contact__info__item__content">
6513 NW Barry Rd Kansas City, MO 64154
</p>
</div>
<div class="section_contact__info__item">
<h4 class="section_contact__info__item__heading">
Social links
</h4>
<ul class="section_contact__info__item__content">
<li>
<a href="https://twitter.com/CupsKc" target="_blank">
<i class="fa fa-twitter"></i>
</a>
</li>
<li>
<a href="https://www.facebook.com/rollatbarryroad/" target="_blank">
<i class="fa fa-facebook"></i>
</a>
</li>
<li>
<a href="https://www.instagram.com/sweetcupsicecreamandcoffee/" target="_blank">
<i class="fa fa-instagram" ></i>
</a>
</li>
</ul>
</div>
</div>
</div>
<div class="col-md-9 order-md-1">
<!-- Contact form -->
<form class="section_contact__form" id="contact__form">
<div class="form-group">
<label for="contact__form__name" class="sr-only">Full name</label>
<input type="text" class="form-control" id="contact__form__name" name="contact__form__name" placeholder="Full name">
<div class="invalid-feedback"></div>
</div>
<div class="form-group">
<label for="contact__form__email" class="sr-only">E-mail address</label>
<input type="email" class="form-control" id="contact__form__email" name="contact__form__email" placeholder="E-mail address">
<div class="invalid-feedback"></div>
</div>
<div class="form-group">
<label for="contact__form__email" class="sr-only">Message</label>
<textarea class="form-control" id="contact__form__message" name="contact__form__message" rows="9" placeholder="Message"></textarea>
<div class="invalid-feedback"></div>
</div>
<button type="submit" class="btn btn-primary">
Send message
</button>
</form>
</div>
</div> <!-- / .row -->
</div> <!-- / .container -->
</section>
<!-- MAP
================================================== -->
<!-- FOOTER
================================================== -->
<footer class="section section_footer">
<div class="container">
<div class="row">
<div class="col-sm-4">
<!-- About Us -->
<h5 class="section_footer__heading">
About Us
</h5>
<p>
Thai inspired rolled ice cream, made in front of your eyes in Northland.
</p>
</div>
<div class="col-sm-4">
<!-- Contact info -->
<h5 class="section_footer__heading">
Contact info
</h5>
<ul class="section_footer__info">
<li>
<i class="fa fa-map-marker"></i> 6513 NW Barry Rd Kansas City, MO 64154
</li>
<li>
<i class="fa fa-phone"></i> +1 (816) 584-0442
</li>
<li>
<i class="fa fa-envelope-o"></i> <a href="mailto:sweetcupskc@gmail.com">sweetcupskc@gmail.com</a>
</li>
</ul>
</div>
<div class="col-sm-4">
<!-- Opening hours -->
<h5 class="section_footer__heading">
Opening hours
</h5>
<div class="section_footer__open">
<div class="section_footer__open__days">Sunday - Thursday</div>
<div class="section_footer__open__time">12:00 PM - 09:30 PM</div>
</div>
<div class="section_footer__open">
<div class="section_footer__open__days">Friday and Saturday</div>
<div class="section_footer__open__time">12:00 PM - 10:00 PM</div>
</div>
</div>
</div> <!-- / .row -->
<div class="row">
<div class="col-12">
<!-- Copyright -->
<div class="section_footer__copyright">
<i class="fa fa-copyright"></i> <span id="js-current-year"></span> Sweet Cups. All rights reserved.
</div>
</div>
</div> <!-- / .row -->
</div> <!-- / .container -->
</footer>
<!-- JAVASCRIPT
================================================== -->
<!-- JS Global -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="assets/bootstrap/js/bootstrap.bundle.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyAxu_OZVnly-RiNmUV530xrd-mqww6Zl6M"></script>
<!-- JS Plugins -->
<script src="assets/plugins/parallax/parallax.min.js"></script>
<script src="assets/plugins/isotope/lib/imagesloaded.pkgd.min.js"></script>
<script src="assets/plugins/isotope/isotope.pkgd.min.js"></script>
<script src="assets/plugins/flickity/flickity.pkgd.min.js"></script>
<script src="assets/plugins/lightbox/js/lightbox.min.js"></script>
<script src="assets/plugins/reservation/reservation.js"></script>
<script src="assets/plugins/contact/contact.js"></script>
<script src="assets/plugins/alerts/alerts.js"></script>
<!-- JS Custom -->
<!-- build:js assets/js/theme.min.js -->
<script src="assets/js/theme.js"></script>
<!-- endbuild -->
<script src="assets/js/custom.js"></script>
</body>
</html>
|
ig.module(
'game.entities.abstract.friendly-unit'
).requires(
'game.entities.abstract.unit'
).defines(function () {
FriendlyUnit = Unit.extend({
// Nothing yet!
});
}); |
REM ×¢ÊÍ
@echo off
set ocd=%cd%
cd /d %~dp0
echo ##### Ìáʾ£º¶ÁÈ¡ÅäÖÃÎļþ #####
if exist ..\config.bat call ..\config.bat
if exist ..\..\config.bat call ..\..\config.bat
if exist ..\..\..\config.bat call ..\..\..\config.bat
if exist ..\..\..\..\config.bat call ..\..\..\..\config.bat
if exist ..\..\..\..\..\config.bat call ..\..\..\..\..\config.bat
if exist ..\..\..\..\..\..\config.bat call ..\..\..\..\..\..\config.bat
if exist ..\..\..\..\..\..\..\config.bat call ..\..\..\..\..\..\..\config.bat
echo ##### Ìáʾ£º±äÁ¿ÅäÖà #####
set LIBCURL_VERSION_NAME=curl-7.33.0
SET DIOS_PREBUILT=%cd%\prebuilt
SET DIOS_PLATFORM=win32
set BIN_DIRECTORY_DEBUG=%DIOS_PREBUILT%\bin\%DIOS_PLATFORM%\debug
set BIN_DIRECTORY_RELEASE=%DIOS_PREBUILT%\bin\%DIOS_PLATFORM%\release
set LIBRARY_DIRECTORY_DEBUG=%DIOS_PREBUILT%\lib\%DIOS_PLATFORM%\debug
set LIBRARY_DIRECTORY_RELEASE=%DIOS_PREBUILT%\lib\%DIOS_PLATFORM%\release
set INCLUDE_DIRECTORY=%DIOS_PREBUILT%\inc\libcurl
echo ##### Ìáʾ£º½âѹ %LIBCURL_VERSION_NAME% #####
if not exist %LIBCURL_VERSION_NAME% (
rem ½âѹ²Ù×÷
%DIOS_TOOLS%\7za.exe x -y %LIBCURL_VERSION_NAME%.tar.bz2
%DIOS_TOOLS%\7za.exe x -y %LIBCURL_VERSION_NAME%.tar
del %LIBCURL_VERSION_NAME%.tar /Q
)
cd %LIBCURL_VERSION_NAME%
mkdir %BIN_DIRECTORY_DEBUG%
mkdir %BIN_DIRECTORY_RELEASE%
mkdir %LIBRARY_DIRECTORY_DEBUG%
mkdir %LIBRARY_DIRECTORY_RELEASE%
mkdir %INCLUDE_DIRECTORY%
echo ##### Ìáʾ£ºVC»·¾³ #####
mkdir vc
cd vc
cmake -G %DIOS_GENERATOR_X64% ..
echo ##### Ìáʾ£º±àÒë #####
BuildConsole.exe CURL.sln /prj=libcurl /Silent /Cfg="Debug|x64,Release|x64"
echo ##### Ìáʾ£º¿½±´ #####
copy /y ..\include\curl\*.h %INCLUDE_DIRECTORY%
copy /y lib\Debug\*.dll %BIN_DIRECTORY_DEBUG%
copy /y lib\Release\*.dll %BIN_DIRECTORY_RELEASE%
copy /Y lib\Debug\*.lib "%LIBRARY_DIRECTORY_DEBUG%"
copy /Y lib\Release\*.lib "%LIBRARY_DIRECTORY_RELEASE%"
rem ### cmake Ïà¹Ø
cd /d %~dp0
setlocal enabledelayedexpansion
call :GET_PATH_NAME %cd%
set project=%PATH_NAME%
if not exist proj.win64 md proj.win64
cd proj.win64
echo #####Ìáʾ£º¿ªÊ¼¹¹½¨#####
cmake -G %DIOS_GENERATOR_X64% -DDIOS_CMAKE_PLATFORM=WIN64 ..
if %errorlevel% neq 0 goto :cmEnd
cmake -G %DIOS_GENERATOR_X64% -DDIOS_CMAKE_PLATFORM=WIN64 ..
if %errorlevel% neq 0 goto :cmEnd
echo #####Ìáʾ£º¹¹½¨½áÊø#####
echo #####Ìáʾ£º¿ªÊ¼±àÒë#####
BuildConsole.exe %project%.sln /prj=ALL_BUILD /Silent /Cfg="Debug|x64,Release|x64"
if %errorlevel% neq 0 goto :cmEnd
echo #####Ìáʾ£º±àÒë½áÊø#####
echo #####Ìáʾ£º¿ªÊ¼°²×°#####
cmake -DBUILD_TYPE="Debug" -P cmake_install.cmake
if %errorlevel% neq 0 goto :cmEnd
cmake -DBUILD_TYPE="Release" -P cmake_install.cmake
if %errorlevel% neq 0 goto :cmEnd
echo #####Ìáʾ£º°²×°½áÊø#####
goto cmDone
:cmEnd
echo setup failed
pause
exit
:cmDone
cmake -P dios_cmake_compile_succeeded.cmake
cmake -P dios_cmake_install_succeeded.cmake
cd /d %ocd%
@echo on
goto :eof
:GET_PATH_NAME
set PATH_NAME=%~n1 |
## From 1.x to 2.x
Configuration must be updated, edit `~/.config/explorer/config.yml` and add the following:
```
remove:
# 'mv' will move files to a trash directory
# 'rm' will delete files
# empty to disable deletion
method: 'mv' #default is to move
path: './trash'
archive:
path: './tmp'
upload:
path: './upload'
concurrency: 10
dev: false
```
### From < 2.0.6 to 2.0.7+
Package name changed and is no longer published to `directory-listings`.
```
pm2 uninstall directory-listings
pm2 install xplorer
```
Configuration will not be removed.
|
/**
*
*/
package cn.sefa.test.combinator;
/**
* @author Lionel
*
*/
public class Result {
private String recognized ;
private String remaining;
private boolean succeeded ;
private Result(String recognized , String remaining , boolean succeeded){
this.recognized = recognized;
this.remaining = remaining;
this.succeeded = succeeded;
}
/**
* @return the recognized
*/
public String getRecognized() {
return recognized;
}
/**
* @param recognized the recognized to set
*/
public void setRecognized(String recognized) {
this.recognized = recognized;
}
/**
* @return the remaining
*/
public String getRemaining() {
return remaining;
}
public void setRemaining(String remaining) {
this.remaining = remaining;
}
public boolean isSucceeded() {
return succeeded;
}
public void setSucceeded(boolean succeeded) {
this.succeeded = succeeded;
}
public static Result succeed(String recognized , String remaining){
return new Result(recognized,remaining,true);
}
public static Result fail(){
return new Result("","",false);
}
}
|
<?php
/*
* This file is part of the Persian Framework.
*
* (c) Farhad Zandmoghadam <farhad.pd@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Core\MVC\Routing;
use Core\PF\Exception\RoutingException;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Matcher\UrlMatcher;
use Symfony\Component\Routing\RequestContext;
use Symfony\Component\Routing\RouteCollection;
use Symfony\Component\Routing\Route;
use Symfony\Component\Routing\Exception\ResourceNotFoundException;
class Router
{
/**
* private (string) $_controller, save controller name
*/
private $_controller;
private $routes;
/**
* private (string) $_method, save action name
*/
private $_method;
public function __construct()
{
$routesResource = include ROOT_DIR.'/application/Routes.php';
$this->routes = $routesResource;
$default_url = $_SERVER['PHP_SELF'];
$default_url = explode('.php/', $default_url);
$default_url[1] = isset($default_url[1]) ? $default_url[1] : '';
$context = new RequestContext();
// this is optional and can be done without a Request instance
$context->fromRequest(Request::createFromGlobals());
$matcher = new UrlMatcher($this->routes, $context);
$parameters = $matcher->match('/'.chop($default_url[1], '/'));
$parameter = array();
if(!isset($parameters['_controller'])) {
throw new RoutingException('_controller parameter in routes not exists');
}
list($getController, $getMethod) = split(':', $parameters['_controller']);
$this->_controller = ucfirst($getController);
$this->_method = ucfirst($getMethod);
if(count($parameters) > 2) {
unset($parameters['_controller']);
unset($parameters['_rout']);
foreach($parameters as $key => $value) {
$parameter[] = $value;
}
}
$this->_parameter = $parameter;
// check routes pattern exists
}
/**
* Get Controller Parameter
*
* @return String
*/
protected function getController()
{
return $this->_controller;
}
/**
* Get Called action
*
* @return String
*
*/
protected function getMethod()
{
return $this->_method;
}
/**
* Get Called actions Arguments
*
* @return Array
*
*/
protected function getParameter()
{
return $this->_parameter;
}
} |
CREATE TABLE [dbo].[hito](
[hitoid] [bigint] IDENTITY(1,1) NOT NULL,
[nhc] [bigint] NOT NULL,
[icu] [bigint] NOT NULL,
[facultativo] [nvarchar](255) NOT NULL,
[localizacion] [int] NOT NULL,
[hora_inicio] [datetime] NOT NULL,
[hora_fin] [datetime] NOT NULL,
[duracion] [int] NOT NULL,
[servicio] [nvarchar](50) NOT NULL,
[patienttype] [varchar](50) NULL,
CONSTRAINT [PK_hito] PRIMARY KEY CLUSTERED
(
[hitoid] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] |
class NullAcceptCreateColumnToDevices < ActiveRecord::Migration
def change
change_column :devices, :mac_address, :string, null: true, default: nil
change_column :devices, :device_name, :string, null: false
change_column :devices, :device_communication, :string, null: true, default: nil
end
end
|
/**
* Ajax函数
*/
// 创建一个XMLHttpRequest对象
var createXHR;
if (window.XMLHttpRequest) {
createXHR = function() {
return new XMLHttpRequest();
};
} else if (window.ActiveXObject) {
createXHR = function() {
return new ActiveXObject('Microsoft.XMLHTTP');
};
}
// 发起异步请求,默认为GET请求
function ajax(url, opts) {
var type = opts.type || 'get',
async = opts.async || true,
data = opts.data || null,
headers = opts.headers || {};
var xhr = createXHR();
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
opts.onsuccess && opts.onsuccess(xhr.responseText);
} else {
opts.onerror && opts.onerror();
}
};
xhr.open(url, type, async);
for (var p in headers) {
xhr.setRequestHeader(p, headers[p]);
}
xhr.send(data);
} |
<?php
namespace test\main\models;
/**
* @coversDefaultClass \main\models\Quotes
*/
class QuotesTest extends \test\helpers\cases\Model
{
protected $testedClass = '\main\models\Quotes';
protected $traitedMethods = ['deleteOnValues', 'insertAutoPrimary',
'selectAll'];
/**
* @covers ::Add
*/
public function testAdd()
{
$quote = 'lorem ipsum';
$this->testObj->expects($this->once())
->method('insertAutoPrimary')
->with($this->identicalTo(['quote' => $quote]));
$this->testObj->Add($quote);
}
/**
* @covers ::Delete
*/
public function testDelete()
{
$ids = [1, 4, 7];
$this->testObj->expects($this->once())
->method('deleteOnValues')
->with($this->identicalTo($ids));
$this->testObj->Delete($ids);
}
/**
* @covers ::getQuotes
*/
public function testGetQuotes()
{
$result = ['lorem', 'ipsum'];
$this->testObj->expects($this->once())
->method('selectAll')
->willReturn($result);
$this->assertEquals($result, $this->callMethod('getQuotes'));
}
}
|
import { addTimer } from './timer/timer';
import { showProfile } from './profile/profile';
import { showHelp } from './help/help';
import { getAllUsers } from './timer/listUtil/getAllUsers';
import { isWorking } from './timer/listUtil/isWorking';
import { timerTimeout } from './timer/listUtil/timerTimeout';
import { refreshPoints } from './timer/listUtil/refreshPoints';
import { minusStackCalculate } from './timer/listUtil/minusStackCalculate';
import { updUsrList } from './timer/listUtil/updUsrList';
const emojiMap = { '⏺': addTimer, '👤': showProfile, '❓': showHelp };
async function menuGUI(res, bot) {
const channel = bot.channel;
const timerList = {};
let userList = await getAllUsers(); // eslint-disable-line
const menuMsg = await channel.send('', {
embed: { description: '`⏺ Start Recording! | 👤 Your Profile | ❓ Need help?`' },
});
// add reactions to message
for (const emoji in emojiMap) {
await menuMsg.react(emoji);
}
await channel.send('▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬');
await menuMsg.createReactionCollector(async (reaction, user) => {
if (user.bot) return false;
// run the emoji command logic and remove the reaction
if (emojiMap[reaction.emoji.name]) {
emojiMap[reaction.emoji.name](bot, user, timerList);
}
await reaction.remove(user);
return false;
});
res();
setInterval(() => {
timerTimeout(bot, timerList);
}, 60000);
setInterval(async () => {
refreshPoints(timerList);
isWorking(userList, timerList);
minusStackCalculate();
updUsrList(userList);
}, 60000);
}
module.exports = {
init: (bot) => {
return new Promise((res) => {
menuGUI(res, bot);
});
},
};
|
-- Path of Building
--
-- Class: List Control
-- Basic list control.
--
-- This is an abstract base class; derived classes can supply these properties and methods to configure the list control:
-- .label [Adds a label above the top left corner]
-- .dragTargetList [List of controls that can receive drag events from this list control]
-- .showRowSeparators [Shows separators between rows]
-- :GetColumnOffset(column) [Called to get the offset of the given column]
-- :GetRowValue(column, index, value) [Required; called to retrieve the text for the given column of the given list value]
-- :AddValueTooltip(index, value) [Called to add the tooltip for the given list value]
-- :GetDragValue(index, value) [Called to retrieve the drag type and object for the given list value]
-- :CanReceiveDrag(type, value) [Called on drag target to determine if it can receive this value]
-- :ReceiveDrag(type, value, source) [Called on the drag target when a drag completes]
-- :OnDragSend(index, value, target) [Called after a drag event]
-- :OnOrderChange() [Called after list order is changed through dragging]
-- :OnSelect(index, value) [Called when a list value is selected]
-- :OnSelClick(index, value, doubleClick) [Called when a list value is clicked]
-- :OnSelCopy(index, value) [Called when Ctrl+C is pressed while a list value is selected]
-- :OnSelDelete(index, value) [Called when backspace or delete is pressed while a list value is selected]
-- :OnSelKeyDown(index, value) [Called when any other key is pressed while a list value is selected]
--
local launch, main = ...
local ipairs = ipairs
local t_insert = table.insert
local t_remove = table.remove
local m_min = math.min
local m_max = math.max
local m_floor = math.floor
local ListClass = common.NewClass("ListControl", "Control", "ControlHost", function(self, anchor, x, y, width, height, rowHeight, isMutable, list)
self.Control(anchor, x, y, width, height)
self.ControlHost()
self.rowHeight = rowHeight
self.isMutable = isMutable
self.list = list or { }
self.tooltip = common.New("Tooltip")
self.controls.scrollBar = common.New("ScrollBarControl", {"RIGHT",self,"RIGHT"}, -1, 0, 16, 0, rowHeight * 2)
self.controls.scrollBar.height = function()
local width, height = self:GetSize()
return height - 2
end
end)
function ListClass:SelectIndex(index)
self.selValue = self.list[index]
if self.selValue then
self.selIndex = index
local width, height = self:GetSize()
self.controls.scrollBar:SetContentDimension(#self.list * self.rowHeight, height - 4)
self.controls.scrollBar:ScrollIntoView((index - 2) * self.rowHeight, self.rowHeight * 3)
if self.OnSelect then
self:OnSelect(self.selIndex, self.selValue)
end
end
end
function ListClass:GetColumnOffset(column)
if column == 1 then
return 0
end
end
function ListClass:IsMouseOver()
if not self:IsShown() then
return
end
return self:IsMouseInBounds() or self:GetMouseOverControl()
end
function ListClass:Draw(viewPort)
local x, y = self:GetPos()
local width, height = self:GetSize()
local rowHeight = self.rowHeight
local list = self.list
local scrollBar = self.controls.scrollBar
scrollBar:SetContentDimension(#list * rowHeight, height - 4)
local cursorX, cursorY = GetCursorPos()
if self.selValue and self.selDragging and not self.selDragActive and (cursorX-self.selCX)*(cursorX-self.selCX)+(cursorY-self.selCY)*(cursorY-self.selCY) > 100 then
self.selDragActive = true
if self.dragTargetList then
self.dragType, self.dragValue = self:GetDragValue(self.selIndex, self.selValue)
for _, target in ipairs(self.dragTargetList) do
if not target.CanReceiveDrag or target:CanReceiveDrag(self.dragType, self.dragValue) then
target.otherDragSource = self
end
end
end
end
self.selDragIndex = nil
if (self.selDragActive or self.otherDragSource) and self.isMutable then
if cursorX >= x + 2 and cursorY >= y + 2 and cursorX < x + width - 18 and cursorY < y + height - 2 then
local index = math.floor((cursorY - y - 2 + scrollBar.offset) / rowHeight + 0.5) + 1
if not self.selIndex or index < self.selIndex or index > self.selIndex + 1 then
self.selDragIndex = m_min(index, #list + 1)
end
end
end
if self.selDragActive and self.dragTargetList then
self.dragTarget = nil
for _, target in ipairs(self.dragTargetList) do
if not self.dragTarget and target.otherDragSource == self and target:IsMouseOver() then
self.dragTarget = target
target.otherDragTargeting = true
else
target.otherDragTargeting = false
end
end
end
local label = self:GetProperty("label")
if label then
DrawString(x, y - 20, "LEFT", 16, "VAR", label)
end
if self.otherDragSource and not self.CanDragToValue then
SetDrawColor(0.2, 0.6, 0.2)
elseif self.hasFocus then
SetDrawColor(1, 1, 1)
else
SetDrawColor(0.5, 0.5, 0.5)
end
DrawImage(nil, x, y, width, height)
if self.otherDragSource and not self.CanDragToValue then
SetDrawColor(0, 0.05, 0)
else
SetDrawColor(0, 0, 0)
end
DrawImage(nil, x + 1, y + 1, width - 2, height - 2)
self:DrawControls(viewPort)
SetViewport(x + 2, y + 2, width - 20, height - 4)
local textOffsetY = self.showRowSeparators and 2 or 0
local textHeight = rowHeight - textOffsetY * 2
local ttIndex, ttValue, ttX, ttY, ttWidth
local minIndex = m_floor(scrollBar.offset / rowHeight + 1)
local maxIndex = m_min(m_floor((scrollBar.offset + height) / rowHeight + 1), #list)
local column = 1
local elipWidth = DrawStringWidth(textHeight, "VAR", "...")
while true do
local colOffset = self:GetColumnOffset(column)
if not colOffset then
break
end
local colWidth = (self:GetColumnOffset(column + 1) or width - 20) - colOffset
for index = minIndex, maxIndex do
local lineY = rowHeight * (index - 1) - scrollBar.offset
local value = list[index]
local text = self:GetRowValue(column, index, value)
local textWidth = DrawStringWidth(textHeight, "VAR", text)
if textWidth > colWidth - 2 then
local clipIndex = DrawStringCursorIndex(textHeight, "VAR", text, colWidth - elipWidth - 2, 0)
text = text:sub(1, clipIndex - 1) .. "..."
textWidth = DrawStringWidth(textHeight, "VAR", text)
end
if not scrollBar.dragging and (not self.selDragActive or (self.CanDragToValue and self:CanDragToValue(index, value, self.otherDragSource))) then
local cursorX, cursorY = GetCursorPos()
local relX = cursorX - (x + 2)
local relY = cursorY - (y + 2)
if relX >= colOffset and relX < width - 20 and relY >= 0 and relY >= lineY and relY < height - 2 and relY < lineY + rowHeight then
ttIndex = index
ttValue = value
ttX = x + 2 + colOffset
ttY = lineY + y + 2
ttWidth = m_max(textWidth + 8, relX - colOffset)
end
end
if self.showRowSeparators then
if self.hasFocus and value == self.selValue then
SetDrawColor(1, 1, 1)
elseif value == ttValue then
SetDrawColor(0.8, 0.8, 0.8)
else
SetDrawColor(0.5, 0.5, 0.5)
end
DrawImage(nil, colOffset, lineY, colWidth, rowHeight)
if (value == self.selValue or value == ttValue) then
SetDrawColor(0.33, 0.33, 0.33)
elseif self.otherDragSource and self.CanDragToValue and self:CanDragToValue(index, value, self.otherDragSource) then
SetDrawColor(0, 0.2, 0)
elseif index % 2 == 0 then
SetDrawColor(0.05, 0.05, 0.05)
else
SetDrawColor(0, 0, 0)
end
DrawImage(nil, colOffset, lineY + 1, colWidth, rowHeight - 2)
elseif value == self.selValue or value == ttValue then
if self.hasFocus and value == self.selValue then
SetDrawColor(1, 1, 1)
elseif value == ttValue then
SetDrawColor(0.8, 0.8, 0.8)
else
SetDrawColor(0.5, 0.5, 0.5)
end
DrawImage(nil, colOffset, lineY, colWidth, rowHeight)
if self.otherDragSource and self.CanDragToValue and self:CanDragToValue(index, value, self.otherDragSource) then
SetDrawColor(0, 0.2, 0)
else
SetDrawColor(0.15, 0.15, 0.15)
end
DrawImage(nil, colOffset, lineY + 1, colWidth, rowHeight - 2)
end
SetDrawColor(1, 1, 1)
DrawString(colOffset, lineY + textOffsetY, "LEFT", textHeight, "VAR", text)
end
column = column + 1
end
if #self.list == 0 and self.defaultText then
SetDrawColor(1, 1, 1)
DrawString(2, 2, "LEFT", 14, "VAR", self.defaultText)
end
if self.selDragIndex then
local lineY = rowHeight * (self.selDragIndex - 1) - scrollBar.offset
SetDrawColor(1, 1, 1)
DrawImage(nil, 0, lineY - 1, width - 20, 3)
SetDrawColor(0, 0, 0)
DrawImage(nil, 0, lineY, width - 20, 1)
end
SetViewport()
if self.selDragActive and self.dragTargetList and (not self.isMutable or not self:IsMouseOver()) then
main.showDragText = self:GetRowValue(1, self.selIndex, self.selValue)
end
self.hoverIndex = ttIndex
self.hoverValue = ttValue
if ttIndex and self.AddValueTooltip then
SetDrawLayer(nil, 100)
self:AddValueTooltip(self.tooltip, ttIndex, ttValue)
self.tooltip:Draw(ttX, ttY, ttWidth, rowHeight, viewPort)
SetDrawLayer(nil, 0)
end
end
function ListClass:OnKeyDown(key, doubleClick)
if not self:IsShown() or not self:IsEnabled() then
return
end
local mOverControl = self:GetMouseOverControl()
if mOverControl and mOverControl.OnKeyDown then
return mOverControl:OnKeyDown(key)
end
if not self:IsMouseOver() and key:match("BUTTON") then
return
end
if key == "LEFTBUTTON" then
self.selValue = nil
self.selIndex = nil
local x, y = self:GetPos()
local width, height = self:GetSize()
local cursorX, cursorY = GetCursorPos()
if cursorX >= x + 2 and cursorY >= y + 2 and cursorX < x + width - 18 and cursorY < y + height - 2 then
local index = math.floor((cursorY - y - 2 + self.controls.scrollBar.offset) / self.rowHeight) + 1
self.selValue = self.list[index]
if self.selValue then
self.selIndex = index
if (self.isMutable or self.dragTargetList) and self:IsShown() then
self.selCX = cursorX
self.selCY = cursorY
self.selDragging = true
self.selDragActive = false
end
if self.OnSelect then
self:OnSelect(self.selIndex, self.selValue)
end
if self.OnSelClick then
self:OnSelClick(self.selIndex, self.selValue, doubleClick)
end
end
end
elseif #self.list > 0 and not self.selDragActive then
if key == "UP" then
self:SelectIndex(((self.selIndex or 1) - 2) % #self.list + 1)
elseif key == "DOWN" then
self:SelectIndex((self.selIndex or #self.list) % #self.list + 1)
elseif key == "HOME" then
self:SelectIndex(1)
elseif key == "END" then
self:SelectIndex(#self.list)
elseif self.selValue then
if key == "c" and IsKeyDown("CTRL") then
if self.OnSelCopy then
self:OnSelCopy(self.selIndex, self.selValue)
end
elseif key == "x" and IsKeyDown("CTRL") then
if self.OnSelCut then
self:OnSelCut(self.selIndex, self.selValue)
end
elseif key == "BACK" or key == "DELETE" then
if self.OnSelDelete then
self:OnSelDelete(self.selIndex, self.selValue)
end
elseif self.OnSelKeyDown then
self:OnSelKeyDown(self.selIndex, self.selValue, key)
end
end
end
return self
end
function ListClass:OnKeyUp(key)
if not self:IsShown() or not self:IsEnabled() then
return
end
if key == "WHEELDOWN" then
self.controls.scrollBar:Scroll(1)
elseif key == "WHEELUP" then
self.controls.scrollBar:Scroll(-1)
elseif self.selValue then
if key == "LEFTBUTTON" then
self.selDragging = false
if self.selDragActive then
self.selDragActive = false
if self.selDragIndex and self.selDragIndex ~= self.selIndex then
t_remove(self.list, self.selIndex)
if self.selDragIndex > self.selIndex then
self.selDragIndex = self.selDragIndex - 1
end
t_insert(self.list, self.selDragIndex, self.selValue)
if self.OnOrderChange then
self:OnOrderChange()
end
self.selValue = nil
elseif self.dragTarget then
self.dragTarget:ReceiveDrag(self.dragType, self.dragValue, self)
if self.OnDragSend then
self:OnDragSend(self.selIndex, self.selValue, self.dragTarget)
end
self.selValue = nil
end
if self.dragTargetList then
for _, target in ipairs(self.dragTargetList) do
target.otherDragSource = nil
target.otherDragTargeting = false
end
end
self.dragType = nil
self.dragValue = nil
self.dragTarget = nil
end
end
end
return self
end |
/**
* Created by:homelan
* User: pijiu3302@outlook.com
* Date: 2017/7/31
* Time: 17:38
*
*/
import React from 'react';
import icons from '../utils/parseIcon';
import {connect} from 'react-redux';
import {lockPlayer} from '../store/action/actionindex';
class LockBar extends React.Component {
render() {
const {handleClick}=this.props;
let styleObj1={};
styleObj1.background='url('+icons.playbar+')';
return (
<div className="updn" >
<div className='lock-bg' style={styleObj1}>
<a className={this.props.locked?'btn':'btn-unlock'} style={styleObj1} onClick={e=>handleClick(e)}></a>
</div>
<div className="lock-bg2" style={styleObj1} ></div>
</div>
)
}
}
const mapStateToProps=(state)=>{
return {locked:state.locked}
}
const mapDispatchToProps=(dispatch)=> {
return {
handleClick: (e) => {
dispatch(lockPlayer())
e.preventDefault();
e.stopPropagation()
}
}
};
export default connect(mapStateToProps,mapDispatchToProps)(LockBar);//important
/*function mapDispatchToProps(dispatch) {
return {
handleClick: () => dispatch(lockPlayer())
};
}
connect(
mapDispatchToProps
)(LockBar);
*/
|
package com.cgroups.gendata;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Random;
public class RandomEntry {
private ArrayList<String> words;
private ArrayList<Double> weights;
Random random = null;
private double total_weight;
public RandomEntry(){
this.init_menbers();
}
/**
* @param word_path Path of the file listing the words
* @param weights_path Path of the file listing weights of each word
*/
public RandomEntry(String word_path, String weights_path){
this.init_menbers();
BufferedReader br1 = null;
BufferedReader br2 = null;
try{
br1 = new BufferedReader(new FileReader(word_path));
br2 = new BufferedReader(new FileReader(weights_path));
while (true){
String line1=null, line2=null;
line1 = br1.readLine();
line2 = br2.readLine();
if (line1==null || line2==null)
break;
double weight;
try{
weight = Double.parseDouble(line2);
}catch (NumberFormatException e){
continue;
}
words.add(line1);
weights.add(weight);
total_weight += weight;
}
}catch(IOException e){
e.printStackTrace();
}finally{
try{br1.close(); br2.close();} catch (Exception e){}
}
}
/**
* @return A random word
*/
public String getNextWord(){
double rnumber = random.nextDouble();
double offset = rnumber*total_weight;
//get the index
int i;
for (i=0; i<weights.size(); i++){
double weight = weights.get(i);
if (weight + 0.000001>=offset)
break;
offset = offset - weight;
}
if (i>=0 && i < weights.size())
return words.get(i);
return null;
}
private void init_menbers(){
random = new Random();
words = new ArrayList<String>();
weights = new ArrayList<Double>();
total_weight = 0.0;
}
public void addWordsWithEqualWeight(String path){
this.addWordsWithEqualWeight(path, 1.0);
}
public void addWordsWithEqualWeight(String path, double weight){
BufferedReader br = null;
try{
br = new BufferedReader(new FileReader(path));
while (true){
String line = br.readLine();
if (line == null)
break;
if (line.equals(""))
continue;
this.words.add(line);
this.weights.add(weight);
this.total_weight += weight;
}
}catch(IOException e){
e.printStackTrace();
}finally{
try{br.close();} catch(Exception e){}
}
}
public ArrayList<String> getAllWords(){
return this.words;
}
}
|
Copyright (c) 2014 Centril / Mazdak Farrokhzad <twingoow@gmail.com>
Copyright (c) 2013 Assemble
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
|
/*
* CompletionCheck.h
*
* Created on: 27/05/2011
* Author: vgil
*/
#ifndef COMPLETIONCHECK_H_
#define COMPLETIONCHECK_H_
#include "../RRTNode.h"
#include "RRTBaseAlgorithm.h"
#include "RRTMetric.h"
class CompletionCheck : public RRTBaseAlgorithm {
public:
CompletionCheck (RRTMetric* m = NULL);
virtual ~CompletionCheck ();
void increaseSteps ();
void increaseSucessfulSteps ();
void resetSteps ();
bool checkCompletion (RRTNode* node);
RRTNode* getGoal () const;
RRTMetric * getMetric () const;
unsigned int getMaxSteps () const;
unsigned int getMaxSuccessfulSteps () const;
unsigned int getCurrentSteps () const;
unsigned int getCurrentSuccessfulSteps () const;
void setGoal (RRTNode *goal);
void setMetric (RRTMetric *metric);
void setMaxSteps (unsigned int steps);
void setMaxSuccessfulSteps (unsigned int successful_steps);
protected:
virtual bool do_check_completion (RRTNode* node)=0;
RRTMetric* metric;
unsigned int steps;
unsigned int successful_steps;
RRTNode* goal;
// Values for the current step
unsigned int current_steps;
unsigned int current_successful_steps;
};
#endif /* COMPLETIONCHECK_H_ */
|
<h3>Dialogs</h3>
The most frequent dialogs are alert, confirm and prompt. In the case of an alert you just need to display a message to the user
and require no feedback besides user acknowledgement. Confirm dialog has similar purpose, but expects from the user a response
by accepting or declining the message. Prompt waits for user input. The w2ui library includes these dialogs for your convenience.
<div style="height: 20px"></div>
<h4>w2alert (msg, [title], [callBack])</h4>
The alert dialog can be called in the following way:
<textarea class="javascript">
w2alert('This is an alert');
</textarea>
First argument, msg, is a message to display. Second optional argument, title, is the title for the dialog. The third optional argument,
callBack, is a call back function when dialog is closed.
<div style="height: 20px"></div>
<textarea class="javascript">
w2alert('This is an alert').done(function () {
// call back when alert closed
});
</textarea>
<h4>w2confirm (msg, [title], [callBack])</h4>
The confirm dialog can be called in the following way:
<textarea class="javascript">
w2confirm('Are you sure?', function btn(answer) {
console.log(answer); // Yes or No -- case-sensitive
});
</textarea>
The method takes up to three arguments <span class="method">w2confirm(msg, [title], [callBack])</span>, where msg is the message to display.
You can optionally supply title for the message and a call back function.
<div style="height: 20px"></div>
<h4>w2confirm(options)</h4>
You can optionally call w2confirm passing an object with options. This options object has following structure:
<textarea class="javascript">
options = {
msg : '',
title : 'Confirmation',
width : 450, // width of the dialog
height : 220, // height of the dialog
btn_yes : {
text : 'Yes', // text for yes button (or yes_text)
class : '', // class for yes button (or yes_class)
style : '', // style for yes button (or yes_style)
callBack : null // callBack for yes button (or yes_callBack)
},
btn_no : {
text : 'No', // text for no button (or no_text)
class : '', // class for no button (or no_class)
style : '', // style for no button (or no_style)
callBack : null // callBack for no button (or no_callBack)
},
callBack : null // common callBack
};
</textarea>
For convenience, w2confirm will return to you an object with yes() and no() methods that you can use in the following way:
<textarea class="javascript">
w2confirm('Are you sure?')
.yes(function () {
console.log('user clicked YES');
})
.no(function () {
console.log("user clicked NO")
});
</textarea>
<h4>w2prompt(label, [title], [callBack])</h4>
Prompts user to enter value. Instead of passing label, title, and callBack, you can call w2prompt in the following way:
<textarea class="javascript">
w2confirm({
label : 'Enter value',
value : '0',
attrs : 'size=6'
})
.change(function () {
console.log('Input value changed.');
})
.ok(function () {
console.log("User clicked ok.")
});
</textarea>
<h4>w2prompt(options)</h4>
Following properties are supported:
<textarea class="javascript">
options = {
label : '', // label for the input control
value : '', // initial value of input
attrs : '', // attributes for input control
title : 'Notification', // title of dialog
ok_text : 'Ok', // text of Ok button
cancel_text : 'Cancel', // text of Cancel button
width : 400, // width of the dialog
height : 220, // height of dialog
callBack : null // callBack function, if any
}
</textarea>
|
package bj174x.bj1740;
import java.io.PrintWriter;
import java.util.Scanner;
/**
* Created by jsong on 30/03/2017.
*
* @hackerrank https://www.hackerrank.com/jsong00505
* @backjoon https://www.acmicpc.net/user/jsong00505
* @github https://github.com/jsong00505
* @linkedin https://www.linkedin.com/in/junesongskorea/
* @email jsong00505@gmail.com
* @challenge Power of N
*/
public class Main {
/**
* Method Name: findNthNumbers
*
* @param n a 'n'th position
* @return a number at 'n'th position
*/
static long findNthNumbers(long n) {
long result = 0;
// the flag checking if the element is the last order
boolean isLast = false;
long t = 1;
while (n > 0) {
if ((n & 1) == 1) {
result += t;
}
n = n >> 1;
t *= 3;
}
return result;
}
public static void main(String[] args) {
try (Scanner in = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out); ) {
// get n
long n = in.nextLong();
// validation
assert (n >= 1 && n <= (5 * Math.pow(10, 11)));
out.println(findNthNumbers(n));
} catch (Exception e) {
e.printStackTrace();
}
}
}
|
/*
==============================================================================
This file is part of the JUCE library.
Copyright (c) 2017 - ROLI Ltd.
JUCE is an open source library subject to commercial or open-source
licensing.
By using JUCE, you agree to the terms of both the JUCE 5 End-User License
Agreement and JUCE 5 Privacy Policy (both updated and effective as of the
27th April 2017).
End User License Agreement: www.juce.com/juce-5-licence
Privacy Policy: www.juce.com/juce-5-privacy-policy
Or: You may also use this code under the terms of the GPL v3 (see
www.gnu.org/licenses).
JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
DISCLAIMED.
==============================================================================
*/
namespace juce
{
class CodeDocumentLine
{
public:
CodeDocumentLine (const String::CharPointerType startOfLine,
const String::CharPointerType endOfLine,
const int lineLen,
const int numNewLineChars,
const int startInFile)
: line (startOfLine, endOfLine),
lineStartInFile (startInFile),
lineLength (lineLen),
lineLengthWithoutNewLines (lineLen - numNewLineChars)
{
}
static void createLines (Array<CodeDocumentLine*>& newLines, StringRef text)
{
auto t = text.text;
int charNumInFile = 0;
bool finished = false;
while (! (finished || t.isEmpty()))
{
auto startOfLine = t;
auto startOfLineInFile = charNumInFile;
int lineLength = 0;
int numNewLineChars = 0;
for (;;)
{
auto c = t.getAndAdvance();
if (c == 0)
{
finished = true;
break;
}
++charNumInFile;
++lineLength;
if (c == '\r')
{
++numNewLineChars;
if (*t == '\n')
{
++t;
++charNumInFile;
++lineLength;
++numNewLineChars;
}
break;
}
if (c == '\n')
{
++numNewLineChars;
break;
}
}
newLines.add (new CodeDocumentLine (startOfLine, t, lineLength,
numNewLineChars, startOfLineInFile));
}
jassert (charNumInFile == text.length());
}
bool endsWithLineBreak() const noexcept
{
return lineLengthWithoutNewLines != lineLength;
}
void updateLength() noexcept
{
lineLength = 0;
lineLengthWithoutNewLines = 0;
for (auto t = line.getCharPointer();;)
{
auto c = t.getAndAdvance();
if (c == 0)
break;
++lineLength;
if (c != '\n' && c != '\r')
lineLengthWithoutNewLines = lineLength;
}
}
String line;
int lineStartInFile, lineLength, lineLengthWithoutNewLines;
};
//==============================================================================
CodeDocument::Iterator::Iterator (const CodeDocument& doc) noexcept
: document (&doc)
{}
CodeDocument::Iterator::Iterator (CodeDocument::Position p) noexcept
: document (p.owner),
line (p.getLineNumber()),
position (p.getPosition())
{
reinitialiseCharPtr();
for (int i = 0; i < p.getIndexInLine(); ++i)
{
charPointer.getAndAdvance();
if (charPointer.isEmpty())
{
position -= (p.getIndexInLine() - i);
break;
}
}
}
CodeDocument::Iterator::Iterator() noexcept
: document (nullptr)
{
}
CodeDocument::Iterator::~Iterator() noexcept {}
bool CodeDocument::Iterator::reinitialiseCharPtr() const
{
/** You're trying to use a default constructed iterator. Bad idea! */
jassert (document != nullptr);
if (charPointer.getAddress() == nullptr)
{
if (auto* l = document->lines[line])
charPointer = l->line.getCharPointer();
else
return false;
}
return true;
}
juce_wchar CodeDocument::Iterator::nextChar() noexcept
{
for (;;)
{
if (! reinitialiseCharPtr())
return 0;
if (auto result = charPointer.getAndAdvance())
{
if (charPointer.isEmpty())
{
++line;
charPointer = nullptr;
}
++position;
return result;
}
++line;
charPointer = nullptr;
}
}
void CodeDocument::Iterator::skip() noexcept
{
nextChar();
}
void CodeDocument::Iterator::skipToEndOfLine() noexcept
{
if (! reinitialiseCharPtr())
return;
position += (int) charPointer.length();
++line;
charPointer = nullptr;
}
void CodeDocument::Iterator::skipToStartOfLine() noexcept
{
if (! reinitialiseCharPtr())
return;
if (auto* l = document->lines [line])
{
auto startPtr = l->line.getCharPointer();
position -= (int) startPtr.lengthUpTo (charPointer);
charPointer = startPtr;
}
}
juce_wchar CodeDocument::Iterator::peekNextChar() const noexcept
{
if (! reinitialiseCharPtr())
return 0;
if (auto c = *charPointer)
return c;
if (auto* l = document->lines [line + 1])
return l->line[0];
return 0;
}
juce_wchar CodeDocument::Iterator::previousChar() noexcept
{
if (! reinitialiseCharPtr())
return 0;
for (;;)
{
if (auto* l = document->lines[line])
{
if (charPointer != l->line.getCharPointer())
{
--position;
--charPointer;
break;
}
}
if (line == 0)
return 0;
--line;
if (auto* prev = document->lines[line])
charPointer = prev->line.getCharPointer().findTerminatingNull();
}
return *charPointer;
}
juce_wchar CodeDocument::Iterator::peekPreviousChar() const noexcept
{
if (! reinitialiseCharPtr())
return 0;
if (auto* l = document->lines[line])
{
if (charPointer != l->line.getCharPointer())
return *(charPointer - 1);
if (auto* prev = document->lines[line - 1])
return *(prev->line.getCharPointer().findTerminatingNull() - 1);
}
return 0;
}
void CodeDocument::Iterator::skipWhitespace() noexcept
{
while (CharacterFunctions::isWhitespace (peekNextChar()))
skip();
}
bool CodeDocument::Iterator::isEOF() const noexcept
{
return charPointer.getAddress() == nullptr && line >= document->lines.size();
}
bool CodeDocument::Iterator::isSOF() const noexcept
{
return position == 0;
}
CodeDocument::Position CodeDocument::Iterator::toPosition() const
{
if (auto* l = document->lines[line])
{
reinitialiseCharPtr();
int indexInLine = 0;
auto linePtr = l->line.getCharPointer();
while (linePtr != charPointer && ! linePtr.isEmpty())
{
++indexInLine;
++linePtr;
}
return CodeDocument::Position (*document, line, indexInLine);
}
if (isEOF())
{
if (auto* last = document->lines.getLast())
{
auto lineIndex = document->lines.size() - 1;
return CodeDocument::Position (*document, lineIndex, last->lineLength);
}
}
return CodeDocument::Position (*document, 0, 0);
}
//==============================================================================
CodeDocument::Position::Position() noexcept
{
}
CodeDocument::Position::Position (const CodeDocument& ownerDocument,
const int lineNum, const int index) noexcept
: owner (const_cast<CodeDocument*> (&ownerDocument)),
line (lineNum), indexInLine (index)
{
setLineAndIndex (lineNum, index);
}
CodeDocument::Position::Position (const CodeDocument& ownerDocument, int pos) noexcept
: owner (const_cast<CodeDocument*> (&ownerDocument))
{
setPosition (pos);
}
CodeDocument::Position::Position (const Position& other) noexcept
: owner (other.owner), characterPos (other.characterPos), line (other.line),
indexInLine (other.indexInLine)
{
jassert (*this == other);
}
CodeDocument::Position::~Position()
{
setPositionMaintained (false);
}
CodeDocument::Position& CodeDocument::Position::operator= (const Position& other)
{
if (this != &other)
{
const bool wasPositionMaintained = positionMaintained;
if (owner != other.owner)
setPositionMaintained (false);
owner = other.owner;
line = other.line;
indexInLine = other.indexInLine;
characterPos = other.characterPos;
setPositionMaintained (wasPositionMaintained);
jassert (*this == other);
}
return *this;
}
bool CodeDocument::Position::operator== (const Position& other) const noexcept
{
jassert ((characterPos == other.characterPos)
== (line == other.line && indexInLine == other.indexInLine));
return characterPos == other.characterPos
&& line == other.line
&& indexInLine == other.indexInLine
&& owner == other.owner;
}
bool CodeDocument::Position::operator!= (const Position& other) const noexcept
{
return ! operator== (other);
}
void CodeDocument::Position::setLineAndIndex (const int newLineNum, const int newIndexInLine)
{
jassert (owner != nullptr);
if (owner->lines.size() == 0)
{
line = 0;
indexInLine = 0;
characterPos = 0;
}
else
{
if (newLineNum >= owner->lines.size())
{
line = owner->lines.size() - 1;
auto& l = *owner->lines.getUnchecked (line);
indexInLine = l.lineLengthWithoutNewLines;
characterPos = l.lineStartInFile + indexInLine;
}
else
{
line = jmax (0, newLineNum);
auto& l = *owner->lines.getUnchecked (line);
if (l.lineLengthWithoutNewLines > 0)
indexInLine = jlimit (0, l.lineLengthWithoutNewLines, newIndexInLine);
else
indexInLine = 0;
characterPos = l.lineStartInFile + indexInLine;
}
}
}
void CodeDocument::Position::setPosition (const int newPosition)
{
jassert (owner != nullptr);
line = 0;
indexInLine = 0;
characterPos = 0;
if (newPosition > 0)
{
int lineStart = 0;
auto lineEnd = owner->lines.size();
for (;;)
{
if (lineEnd - lineStart < 4)
{
for (int i = lineStart; i < lineEnd; ++i)
{
auto& l = *owner->lines.getUnchecked (i);
auto index = newPosition - l.lineStartInFile;
if (index >= 0 && (index < l.lineLength || i == lineEnd - 1))
{
line = i;
indexInLine = jmin (l.lineLengthWithoutNewLines, index);
characterPos = l.lineStartInFile + indexInLine;
}
}
break;
}
else
{
auto midIndex = (lineStart + lineEnd + 1) / 2;
if (newPosition >= owner->lines.getUnchecked (midIndex)->lineStartInFile)
lineStart = midIndex;
else
lineEnd = midIndex;
}
}
}
}
void CodeDocument::Position::moveBy (int characterDelta)
{
jassert (owner != nullptr);
if (characterDelta == 1)
{
setPosition (getPosition());
// If moving right, make sure we don't get stuck between the \r and \n characters..
if (line < owner->lines.size())
{
auto& l = *owner->lines.getUnchecked (line);
if (indexInLine + characterDelta < l.lineLength
&& indexInLine + characterDelta >= l.lineLengthWithoutNewLines + 1)
++characterDelta;
}
}
setPosition (characterPos + characterDelta);
}
CodeDocument::Position CodeDocument::Position::movedBy (const int characterDelta) const
{
CodeDocument::Position p (*this);
p.moveBy (characterDelta);
return p;
}
CodeDocument::Position CodeDocument::Position::movedByLines (const int deltaLines) const
{
CodeDocument::Position p (*this);
p.setLineAndIndex (getLineNumber() + deltaLines, getIndexInLine());
return p;
}
juce_wchar CodeDocument::Position::getCharacter() const
{
if (auto* l = owner->lines [line])
return l->line [getIndexInLine()];
return 0;
}
String CodeDocument::Position::getLineText() const
{
if (auto* l = owner->lines [line])
return l->line;
return {};
}
void CodeDocument::Position::setPositionMaintained (const bool isMaintained)
{
if (isMaintained != positionMaintained)
{
positionMaintained = isMaintained;
if (owner != nullptr)
{
if (isMaintained)
{
jassert (! owner->positionsToMaintain.contains (this));
owner->positionsToMaintain.add (this);
}
else
{
// If this happens, you may have deleted the document while there are Position objects that are still using it...
jassert (owner->positionsToMaintain.contains (this));
owner->positionsToMaintain.removeFirstMatchingValue (this);
}
}
}
}
//==============================================================================
CodeDocument::CodeDocument() : undoManager (std::numeric_limits<int>::max(), 10000)
{
}
CodeDocument::~CodeDocument()
{
}
String CodeDocument::getAllContent() const
{
return getTextBetween (Position (*this, 0),
Position (*this, lines.size(), 0));
}
String CodeDocument::getTextBetween (const Position& start, const Position& end) const
{
if (end.getPosition() <= start.getPosition())
return {};
auto startLine = start.getLineNumber();
auto endLine = end.getLineNumber();
if (startLine == endLine)
{
if (auto* line = lines [startLine])
return line->line.substring (start.getIndexInLine(), end.getIndexInLine());
return {};
}
MemoryOutputStream mo;
mo.preallocate ((size_t) (end.getPosition() - start.getPosition() + 4));
auto maxLine = jmin (lines.size() - 1, endLine);
for (int i = jmax (0, startLine); i <= maxLine; ++i)
{
auto& line = *lines.getUnchecked(i);
auto len = line.lineLength;
if (i == startLine)
{
auto index = start.getIndexInLine();
mo << line.line.substring (index, len);
}
else if (i == endLine)
{
len = end.getIndexInLine();
mo << line.line.substring (0, len);
}
else
{
mo << line.line;
}
}
return mo.toUTF8();
}
int CodeDocument::getNumCharacters() const noexcept
{
if (auto* lastLine = lines.getLast())
return lastLine->lineStartInFile + lastLine->lineLength;
return 0;
}
String CodeDocument::getLine (const int lineIndex) const noexcept
{
if (auto* line = lines[lineIndex])
return line->line;
return {};
}
int CodeDocument::getMaximumLineLength() noexcept
{
if (maximumLineLength < 0)
{
maximumLineLength = 0;
for (auto* l : lines)
maximumLineLength = jmax (maximumLineLength, l->lineLength);
}
return maximumLineLength;
}
void CodeDocument::deleteSection (const Position& startPosition, const Position& endPosition)
{
deleteSection (startPosition.getPosition(), endPosition.getPosition());
}
void CodeDocument::deleteSection (const int start, const int end)
{
remove (start, end, true);
}
void CodeDocument::insertText (const Position& position, const String& text)
{
insertText (position.getPosition(), text);
}
void CodeDocument::insertText (const int insertIndex, const String& text)
{
insert (text, insertIndex, true);
}
void CodeDocument::replaceSection (const int start, const int end, const String& newText)
{
insertText (end, newText);
deleteSection (start, end);
}
void CodeDocument::applyChanges (const String& newContent)
{
const String corrected (StringArray::fromLines (newContent)
.joinIntoString (newLineChars));
TextDiff diff (getAllContent(), corrected);
for (auto& c : diff.changes)
{
if (c.isDeletion())
remove (c.start, c.start + c.length, true);
else
insert (c.insertedText, c.start, true);
}
}
void CodeDocument::replaceAllContent (const String& newContent)
{
remove (0, getNumCharacters(), true);
insert (newContent, 0, true);
}
bool CodeDocument::loadFromStream (InputStream& stream)
{
remove (0, getNumCharacters(), false);
insert (stream.readEntireStreamAsString(), 0, false);
setSavePoint();
clearUndoHistory();
return true;
}
bool CodeDocument::writeToStream (OutputStream& stream)
{
for (auto* l : lines)
{
auto temp = l->line; // use a copy to avoid bloating the memory footprint of the stored string.
const char* utf8 = temp.toUTF8();
if (! stream.write (utf8, strlen (utf8)))
return false;
}
return true;
}
void CodeDocument::setNewLineCharacters (const String& newChars) noexcept
{
jassert (newChars == "\r\n" || newChars == "\n" || newChars == "\r");
newLineChars = newChars;
}
void CodeDocument::newTransaction()
{
undoManager.beginNewTransaction (String());
}
void CodeDocument::undo()
{
newTransaction();
undoManager.undo();
}
void CodeDocument::redo()
{
undoManager.redo();
}
void CodeDocument::clearUndoHistory()
{
undoManager.clearUndoHistory();
}
void CodeDocument::setSavePoint() noexcept
{
indexOfSavedState = currentActionIndex;
}
bool CodeDocument::hasChangedSinceSavePoint() const noexcept
{
return currentActionIndex != indexOfSavedState;
}
//==============================================================================
static inline int getCharacterType (juce_wchar character) noexcept
{
return (CharacterFunctions::isLetterOrDigit (character) || character == '_')
? 2 : (CharacterFunctions::isWhitespace (character) ? 0 : 1);
}
CodeDocument::Position CodeDocument::findWordBreakAfter (const Position& position) const noexcept
{
auto p = position;
const int maxDistance = 256;
int i = 0;
while (i < maxDistance
&& CharacterFunctions::isWhitespace (p.getCharacter())
&& (i == 0 || (p.getCharacter() != '\n'
&& p.getCharacter() != '\r')))
{
++i;
p.moveBy (1);
}
if (i == 0)
{
auto type = getCharacterType (p.getCharacter());
while (i < maxDistance && type == getCharacterType (p.getCharacter()))
{
++i;
p.moveBy (1);
}
while (i < maxDistance
&& CharacterFunctions::isWhitespace (p.getCharacter())
&& (i == 0 || (p.getCharacter() != '\n'
&& p.getCharacter() != '\r')))
{
++i;
p.moveBy (1);
}
}
return p;
}
CodeDocument::Position CodeDocument::findWordBreakBefore (const Position& position) const noexcept
{
auto p = position;
const int maxDistance = 256;
int i = 0;
bool stoppedAtLineStart = false;
while (i < maxDistance)
{
auto c = p.movedBy (-1).getCharacter();
if (c == '\r' || c == '\n')
{
stoppedAtLineStart = true;
if (i > 0)
break;
}
if (! CharacterFunctions::isWhitespace (c))
break;
p.moveBy (-1);
++i;
}
if (i < maxDistance && ! stoppedAtLineStart)
{
auto type = getCharacterType (p.movedBy (-1).getCharacter());
while (i < maxDistance && type == getCharacterType (p.movedBy (-1).getCharacter()))
{
p.moveBy (-1);
++i;
}
}
return p;
}
void CodeDocument::findTokenContaining (const Position& pos, Position& start, Position& end) const noexcept
{
auto isTokenCharacter = [] (juce_wchar c) { return CharacterFunctions::isLetterOrDigit (c) || c == '.' || c == '_'; };
end = pos;
while (isTokenCharacter (end.getCharacter()))
end.moveBy (1);
start = end;
while (start.getIndexInLine() > 0
&& isTokenCharacter (start.movedBy (-1).getCharacter()))
start.moveBy (-1);
}
void CodeDocument::findLineContaining (const Position& pos, Position& s, Position& e) const noexcept
{
s.setLineAndIndex (pos.getLineNumber(), 0);
e.setLineAndIndex (pos.getLineNumber() + 1, 0);
}
void CodeDocument::checkLastLineStatus()
{
while (lines.size() > 0
&& lines.getLast()->lineLength == 0
&& (lines.size() == 1 || ! lines.getUnchecked (lines.size() - 2)->endsWithLineBreak()))
{
// remove any empty lines at the end if the preceding line doesn't end in a newline.
lines.removeLast();
}
const CodeDocumentLine* const lastLine = lines.getLast();
if (lastLine != nullptr && lastLine->endsWithLineBreak())
{
// check that there's an empty line at the end if the preceding one ends in a newline..
lines.add (new CodeDocumentLine (StringRef(), StringRef(), 0, 0,
lastLine->lineStartInFile + lastLine->lineLength));
}
}
//==============================================================================
void CodeDocument::addListener (CodeDocument::Listener* l) { listeners.add (l); }
void CodeDocument::removeListener (CodeDocument::Listener* l) { listeners.remove (l); }
//==============================================================================
struct CodeDocument::InsertAction : public UndoableAction
{
InsertAction (CodeDocument& doc, const String& t, const int pos) noexcept
: owner (doc), text (t), insertPos (pos)
{
}
bool perform() override
{
owner.currentActionIndex++;
owner.insert (text, insertPos, false);
return true;
}
bool undo() override
{
owner.currentActionIndex--;
owner.remove (insertPos, insertPos + text.length(), false);
return true;
}
int getSizeInUnits() override { return text.length() + 32; }
CodeDocument& owner;
const String text;
const int insertPos;
JUCE_DECLARE_NON_COPYABLE (InsertAction)
};
void CodeDocument::insert (const String& text, const int insertPos, const bool undoable)
{
if (text.isNotEmpty())
{
if (undoable)
{
undoManager.perform (new InsertAction (*this, text, insertPos));
}
else
{
Position pos (*this, insertPos);
auto firstAffectedLine = pos.getLineNumber();
auto* firstLine = lines[firstAffectedLine];
auto textInsideOriginalLine = text;
if (firstLine != nullptr)
{
auto index = pos.getIndexInLine();
textInsideOriginalLine = firstLine->line.substring (0, index)
+ textInsideOriginalLine
+ firstLine->line.substring (index);
}
maximumLineLength = -1;
Array<CodeDocumentLine*> newLines;
CodeDocumentLine::createLines (newLines, textInsideOriginalLine);
jassert (newLines.size() > 0);
auto* newFirstLine = newLines.getUnchecked (0);
newFirstLine->lineStartInFile = firstLine != nullptr ? firstLine->lineStartInFile : 0;
lines.set (firstAffectedLine, newFirstLine);
if (newLines.size() > 1)
lines.insertArray (firstAffectedLine + 1, newLines.getRawDataPointer() + 1, newLines.size() - 1);
int lineStart = newFirstLine->lineStartInFile;
for (int i = firstAffectedLine; i < lines.size(); ++i)
{
auto& l = *lines.getUnchecked (i);
l.lineStartInFile = lineStart;
lineStart += l.lineLength;
}
checkLastLineStatus();
auto newTextLength = text.length();
for (auto* p : positionsToMaintain)
if (p->getPosition() >= insertPos)
p->setPosition (p->getPosition() + newTextLength);
listeners.call ([&] (Listener& l) { l.codeDocumentTextInserted (text, insertPos); });
}
}
}
//==============================================================================
struct CodeDocument::DeleteAction : public UndoableAction
{
DeleteAction (CodeDocument& doc, int start, int end) noexcept
: owner (doc), startPos (start), endPos (end),
removedText (doc.getTextBetween (CodeDocument::Position (doc, start),
CodeDocument::Position (doc, end)))
{
}
bool perform() override
{
owner.currentActionIndex++;
owner.remove (startPos, endPos, false);
return true;
}
bool undo() override
{
owner.currentActionIndex--;
owner.insert (removedText, startPos, false);
return true;
}
int getSizeInUnits() override { return (endPos - startPos) + 32; }
CodeDocument& owner;
const int startPos, endPos;
const String removedText;
JUCE_DECLARE_NON_COPYABLE (DeleteAction)
};
void CodeDocument::remove (const int startPos, const int endPos, const bool undoable)
{
if (endPos <= startPos)
return;
if (undoable)
{
undoManager.perform (new DeleteAction (*this, startPos, endPos));
}
else
{
Position startPosition (*this, startPos);
Position endPosition (*this, endPos);
maximumLineLength = -1;
auto firstAffectedLine = startPosition.getLineNumber();
auto endLine = endPosition.getLineNumber();
auto& firstLine = *lines.getUnchecked (firstAffectedLine);
if (firstAffectedLine == endLine)
{
firstLine.line = firstLine.line.substring (0, startPosition.getIndexInLine())
+ firstLine.line.substring (endPosition.getIndexInLine());
firstLine.updateLength();
}
else
{
auto& lastLine = *lines.getUnchecked (endLine);
firstLine.line = firstLine.line.substring (0, startPosition.getIndexInLine())
+ lastLine.line.substring (endPosition.getIndexInLine());
firstLine.updateLength();
int numLinesToRemove = endLine - firstAffectedLine;
lines.removeRange (firstAffectedLine + 1, numLinesToRemove);
}
for (int i = firstAffectedLine + 1; i < lines.size(); ++i)
{
auto& l = *lines.getUnchecked (i);
auto& previousLine = *lines.getUnchecked (i - 1);
l.lineStartInFile = previousLine.lineStartInFile + previousLine.lineLength;
}
checkLastLineStatus();
auto totalChars = getNumCharacters();
for (auto* p : positionsToMaintain)
{
if (p->getPosition() > startPosition.getPosition())
p->setPosition (jmax (startPos, p->getPosition() + startPos - endPos));
if (p->getPosition() > totalChars)
p->setPosition (totalChars);
}
listeners.call ([=] (Listener& l) { l.codeDocumentTextDeleted (startPos, endPos); });
}
}
//==============================================================================
//==============================================================================
#if JUCE_UNIT_TESTS
struct CodeDocumentTest : public UnitTest
{
CodeDocumentTest()
: UnitTest ("CodeDocument", UnitTestCategories::text)
{}
void runTest() override
{
const juce::String jabberwocky ("'Twas brillig, and the slithy toves\n"
"Did gyre and gimble in the wabe;\n"
"All mimsy were the borogoves,\n"
"And the mome raths outgrabe.\n\n"
"'Beware the Jabberwock, my son!\n"
"The jaws that bite, the claws that catch!\n"
"Beware the Jubjub bird, and shun\n"
"The frumious Bandersnatch!'");
{
beginTest ("Basic checks");
CodeDocument d;
d.replaceAllContent (jabberwocky);
expectEquals (d.getNumLines(), 9);
expect (d.getLine (0).startsWith ("'Twas brillig"));
expect (d.getLine (2).startsWith ("All mimsy"));
expectEquals (d.getLine (4), String ("\n"));
}
{
beginTest ("Insert/replace/delete");
CodeDocument d;
d.replaceAllContent (jabberwocky);
d.insertText (CodeDocument::Position (d, 0, 6), "very ");
expect (d.getLine (0).startsWith ("'Twas very brillig"),
"Insert text within a line");
d.replaceSection (74, 83, "Quite hungry");
expectEquals (d.getLine (2), String ("Quite hungry were the borogoves,\n"),
"Replace section at start of line");
d.replaceSection (11, 18, "cold");
expectEquals (d.getLine (0), String ("'Twas very cold, and the slithy toves\n"),
"Replace section within a line");
d.deleteSection (CodeDocument::Position (d, 2, 0), CodeDocument::Position (d, 2, 6));
expectEquals (d.getLine (2), String ("hungry were the borogoves,\n"),
"Delete section within a line");
d.deleteSection (CodeDocument::Position (d, 2, 6), CodeDocument::Position (d, 5, 11));
expectEquals (d.getLine (2), String ("hungry Jabberwock, my son!\n"),
"Delete section across multiple line");
}
{
beginTest ("Line splitting and joining");
CodeDocument d;
d.replaceAllContent (jabberwocky);
expectEquals (d.getNumLines(), 9);
const String splitComment ("Adding a newline should split a line into two.");
d.insertText (49, "\n");
expectEquals (d.getNumLines(), 10, splitComment);
expectEquals (d.getLine (1), String ("Did gyre and \n"), splitComment);
expectEquals (d.getLine (2), String ("gimble in the wabe;\n"), splitComment);
const String joinComment ("Removing a newline should join two lines.");
d.deleteSection (CodeDocument::Position (d, 0, 35),
CodeDocument::Position (d, 1, 0));
expectEquals (d.getNumLines(), 9, joinComment);
expectEquals (d.getLine (0), String ("'Twas brillig, and the slithy tovesDid gyre and \n"), joinComment);
expectEquals (d.getLine (1), String ("gimble in the wabe;\n"), joinComment);
}
{
beginTest ("Undo/redo");
CodeDocument d;
d.replaceAllContent (jabberwocky);
d.newTransaction();
d.insertText (30, "INSERT1");
d.newTransaction();
d.insertText (70, "INSERT2");
d.undo();
expect (d.getAllContent().contains ("INSERT1"), "1st edit should remain.");
expect (! d.getAllContent().contains ("INSERT2"), "2nd edit should be undone.");
d.redo();
expect (d.getAllContent().contains ("INSERT2"), "2nd edit should be redone.");
d.newTransaction();
d.deleteSection (25, 90);
expect (! d.getAllContent().contains ("INSERT1"), "1st edit should be deleted.");
expect (! d.getAllContent().contains ("INSERT2"), "2nd edit should be deleted.");
d.undo();
expect (d.getAllContent().contains ("INSERT1"), "1st edit should be restored.");
expect (d.getAllContent().contains ("INSERT2"), "1st edit should be restored.");
d.undo();
d.undo();
expectEquals (d.getAllContent(), jabberwocky, "Original document should be restored.");
}
{
beginTest ("Positions");
CodeDocument d;
d.replaceAllContent (jabberwocky);
{
const String comment ("Keeps negative positions inside document.");
CodeDocument::Position p1 (d, 0, -3);
CodeDocument::Position p2 (d, -8);
expectEquals (p1.getLineNumber(), 0, comment);
expectEquals (p1.getIndexInLine(), 0, comment);
expectEquals (p1.getCharacter(), juce_wchar ('\''), comment);
expectEquals (p2.getLineNumber(), 0, comment);
expectEquals (p2.getIndexInLine(), 0, comment);
expectEquals (p2.getCharacter(), juce_wchar ('\''), comment);
}
{
const String comment ("Moving by character handles newlines correctly.");
CodeDocument::Position p1 (d, 0, 35);
p1.moveBy (1);
expectEquals (p1.getLineNumber(), 1, comment);
expectEquals (p1.getIndexInLine(), 0, comment);
p1.moveBy (75);
expectEquals (p1.getLineNumber(), 3, comment);
}
{
const String comment1 ("setPositionMaintained tracks position.");
const String comment2 ("setPositionMaintained tracks position following undos.");
CodeDocument::Position p1 (d, 3, 0);
p1.setPositionMaintained (true);
expectEquals (p1.getCharacter(), juce_wchar ('A'), comment1);
d.newTransaction();
d.insertText (p1, "INSERT1");
expectEquals (p1.getCharacter(), juce_wchar ('A'), comment1);
expectEquals (p1.getLineNumber(), 3, comment1);
expectEquals (p1.getIndexInLine(), 7, comment1);
d.undo();
expectEquals (p1.getIndexInLine(), 0, comment2);
d.newTransaction();
d.insertText (15, "\n");
expectEquals (p1.getLineNumber(), 4, comment1);
d.undo();
expectEquals (p1.getLineNumber(), 3, comment2);
}
}
{
beginTest ("Iterators");
CodeDocument d;
d.replaceAllContent (jabberwocky);
{
const String comment1 ("Basic iteration.");
const String comment2 ("Reverse iteration.");
const String comment3 ("Reverse iteration stops at doc start.");
const String comment4 ("Check iteration across line boundaries.");
CodeDocument::Iterator it (d);
expectEquals (it.peekNextChar(), juce_wchar ('\''), comment1);
expectEquals (it.nextChar(), juce_wchar ('\''), comment1);
expectEquals (it.nextChar(), juce_wchar ('T'), comment1);
expectEquals (it.nextChar(), juce_wchar ('w'), comment1);
expectEquals (it.peekNextChar(), juce_wchar ('a'), comment2);
expectEquals (it.previousChar(), juce_wchar ('w'), comment2);
expectEquals (it.previousChar(), juce_wchar ('T'), comment2);
expectEquals (it.previousChar(), juce_wchar ('\''), comment2);
expectEquals (it.previousChar(), juce_wchar (0), comment3);
expect (it.isSOF(), comment3);
while (it.peekNextChar() != juce_wchar ('D')) // "Did gyre..."
it.nextChar();
expectEquals (it.nextChar(), juce_wchar ('D'), comment3);
expectEquals (it.peekNextChar(), juce_wchar ('i'), comment3);
expectEquals (it.previousChar(), juce_wchar ('D'), comment3);
expectEquals (it.previousChar(), juce_wchar ('\n'), comment3);
expectEquals (it.previousChar(), juce_wchar ('s'), comment3);
}
{
const String comment1 ("Iterator created from CodeDocument::Position objects.");
const String comment2 ("CodeDocument::Position created from Iterator objects.");
const String comment3 ("CodeDocument::Position created from EOF Iterator objects.");
CodeDocument::Position p (d, 6, 0); // "The jaws..."
CodeDocument::Iterator it (p);
expectEquals (it.nextChar(), juce_wchar ('T'), comment1);
expectEquals (it.nextChar(), juce_wchar ('h'), comment1);
expectEquals (it.previousChar(), juce_wchar ('h'), comment1);
expectEquals (it.previousChar(), juce_wchar ('T'), comment1);
expectEquals (it.previousChar(), juce_wchar ('\n'), comment1);
expectEquals (it.previousChar(), juce_wchar ('!'), comment1);
const auto p2 = it.toPosition();
expectEquals (p2.getLineNumber(), 5, comment2);
expectEquals (p2.getIndexInLine(), 30, comment2);
while (! it.isEOF())
it.nextChar();
const auto p3 = it.toPosition();
expectEquals (p3.getLineNumber(), d.getNumLines() - 1, comment3);
expectEquals (p3.getIndexInLine(), d.getLine (d.getNumLines() - 1).length(), comment3);
}
}
}
};
static CodeDocumentTest codeDocumentTests;
#endif
} // namespace juce
|
Grules is a rule engine for data preprocessing. The rules are specified via internal Groovy DSL, which has a concise and simple syntax. For example:
```java
// isEmail is a Groovy/Java method that takes an email value as its parameter
email isEmail ["Invalid email"]
// invalidLoginMessage and dupLoginMessage are String error messages
login isLogin [invalidLoginMessage] >> isUnique [dupLoginMessage]
// The value gender defaults to "MALE"
gender["MALE"] toEnum(Gender)
// agreeToTerms is a message from a resource bundle
termsCondition[""] !isEmpty [m.agreeToTerms]
// you can use closures as well
weight toPositiveBigDecimal [decimalErr] >> {round(it / 1000)}
// Grules supports logical operators
endDate isAfterNow && isBefore(deadline) && {it.day != 1}
```
To build the project, you should run the following command in the grules folder:
cd grules
./gradlew
To run hello world example:
cd grulesHelloWorld
./gradlew
Documentation:
<a href="https://github.com/zhaber/grules/wiki">Wiki documentation</a><br>
<a href="http://digitalcommons.mcmaster.ca/cgi/viewcontent.cgi?article=8244&context=opendissertations">White paper</a><br>
<a href="http://www.youtube.com/watch?v=6RYbDRY6cvQ">Introduction video</a><br>
<a href="http://zhaber.github.io/grules/">Home page</a><br>
Requirements: JVM 8, Groovy 2.3
|
<?php
use yii\db\Schema;
use yii\db\Migration;
class m140924_133309_dropcols extends Migration
{
public function up()
{
$this->dropColumn('address', 'otherStreet');
$this->dropColumn('address', 'otherCity');
$this->dropColumn('address', 'otherZip');
}
public function down()
{
echo "m140924_133309_dropcols cannot be reverted.\n";
return false;
}
}
|
<?php
class ChartPage extends RunnerPage
{
/**
* The name of the dashboard the List is displayed on
* It's set up correctly in dash mode only
*/
public $dashElementName = "";
/**
* The corresponding dashboard name
* It's set up correctly in dash mode only
*/
public $dashTName = "";
/**
* show message block
*/
public $show_message_block = false;
/**
* @constructor
*/
function ChartPage(&$params = "")
{
parent::RunnerPage($params);
$this->jsSettings['tableSettings'][ $this->tName ]['simpleSearchActive'] = $this->searchClauseObj->simpleSearchActive;
}
/**
* Set the page's session prefix
*/
protected function assignSessionPrefix()
{
if( $this->mode == CHART_DASHBOARD )
$this->sessionPrefix = $this->dashTName."_".$this->tName;
else
$this->sessionPrefix = $this->tName;
}
/**
* Set session variables
*/
public function setSessionVariables()
{
parent::setSessionVariables();
// SearchClause class stuff
$agregateFields = $this->pSet->getListOfFieldsByExprType(true);
$this->searchClauseObj->haveAgregateFields = count($agregateFields) > 0;
$_SESSION[ $this->sessionPrefix.'_advsearch' ] = serialize( $this->searchClauseObj );
}
/**
* Build the activated Search panel
*/
public function buildSearchPanel()
{
if( $this->mode == CHART_DASHBOARD )
return;
parent::buildSearchPanel();
}
/**
* Process the page
*/
public function process()
{
// Before Process event
if( $this->eventsObject->exists("BeforeProcessChart") )
$this->eventsObject->BeforeProcessChart( $this );
$this->doCommonAssignments();
$this->addButtonHandlers();
$this->addCommonJs();
$this->commonAssign();
// display the 'Back to Master' link and master table info
$this->displayMasterTableInfo();
$this->showPage();
}
/**
* Get where clause for an active master-detail relationship
* @return string
*/
public function getMasterTableSQLClause()
{
if( $this->mode == CHART_DASHBOARD )
return "";
return parent::getMasterTableSQLClause();
}
/**
*
*/
public function doCommonAssignments() // TODO: make it protected
{
$this->xt->assign("id", $this->id);
//set the Search panel
$this->xt->assign("searchPanel", true);
if( $this->isShowMenu() )
$this->xt->assign("menu_block", true);
$this->xt->assign("chart_block", true);
$this->xt->assign("asearch_link", true);
$this->xt->assign("exportpdflink_attrs", "onclick='chart.saveAsPDF();'");
$this->xt->assign("advsearchlink_attrs", "id=\"advButton".$this->id."\"");
if( !GetChartXML( $this->shortTableName ) )
$this->xt->assign("chart_block", false);
if( ($this->mode == CHART_SIMPLE || $this->mode == CHART_DASHBOARD) && $this->pSet->noRecordsOnFirstPage() && !$this->searchClauseObj->isSearchFunctionalityActivated() )
{
$this->show_message_block = true;
$this->xt->displayBrickHidden("chart");
$this->xt->assign("chart_block", false);
$this->xt->assign("message_block", true);
$this->xt->assign("message", "No records found");
}
$this->assignChartElement();
if( $this->isDynamicPerm && IsAdmin() )
{
$this->xt->assign("adminarea_link", true);
$this->xt->assign("adminarealink_attrs", "id=\"adminArea".$id."\"");
}
$this->xt->assign("changepwd_link", $_SESSION["AccessLevel"] != ACCESS_LEVEL_GUEST && $_SESSION["fromFacebook"] == false);
$this->xt->assign("changepwdlink_attrs", "onclick=\"window.location.href='".GetTableLink("changepwd")."';return false;\"");
$this->body['begin'].= GetBaseScriptsForPage( $this->isDisplayLoading );
if( !isMobile() )
$this->body['begin'].= "<div id=\"search_suggest\" class=\"search_suggest\"></div>";
// assign body end
$this->body['end'] = array();
AssignMethod($this->body['end'], "assignBodyEnd", $this);
$this->xt->assignbyref('body', $this->body);
}
/**
* Set the chart xt variable
*/
public function assignChartElement()
{
//set params for the 'xt_showchart' method showing the chart
$chartXtParams = array(
"id" => $this->id,
"table" => $this->tName,
"ctype" => $this->pSet->getChartType(),
"resize" => $this->mode !== CHART_SIMPLE && $this->mode != CHART_DASHBOARD,
"chartname" => $this->shortTableName,
"chartPreview" => $this->mode !== CHART_SIMPLE && $this->mode != CHART_DASHBOARD
);
if( $this->mode == CHART_DASHBOARD || $this->mode == CHART_DASHDETAILS)
{
$dashSet = new ProjectSettings( $this->dashTName );
$dashElementData = $dashSet->getDashboardElementData( $this->dashElementName );
if( isset($dashElementData["width"]) || isset($dashElementData["height"]) ) //#10119
{
$chartXtParams["dashResize"] = true;
$chartXtParams["dashWidth"] = $dashElementData["width"];
$chartXtParams["dashHeight"] = $dashElementData["height"];
}
if( $this->mode == CHART_DASHBOARD )
{
$chartXtParams["dash"] = true;
$chartXtParams["dashTName"] = $this->dashTName;
$chartXtParams["dashElementName"] = $this->dashElementName;
}
}
$this->xt->assign_function( $this->shortTableName."_chart", "xt_showchart", $chartXtParams );
}
public function showPage()
{
if( $this->eventsObject->exists("BeforeShowChart") )
$this->eventsObject->BeforeShowChart($this->xt, $this->templatefile, $this);
if( $this->mode == CHART_DETAILS || $this->mode == CHART_DASHBOARD || $this->mode == CHART_DASHDETAILS )
{
$this->addControlsJSAndCSS();
$this->fillSetCntrlMaps();
$this->xt->unassign("header");
$this->xt->unassign("footer");
$this->body["begin"] = "";
$this->body["end"] = "";
$this->xt->assign("body", $this->body);
$bricksExcept = array("chart");
$this->xt->hideAllBricksExcept($bricksExcept);
if( $this->show_message_block )
$this->xt->assign("message_block", true);
$this->displayAJAX($this->templatefile, $this->id + 1);
exit();
}
if( $this->mode == CHART_POPUPDETAILS ) //currently unused
{
$bricksExcept = array("grid","pagination");
$this->xt->unassign('header');
$this->xt->unassign('footer');
$this->body["begin"] = '';
$this->body["end"] = '';
$this->xt->hideAllBricksExcept($bricksExcept);
$this->xt->prepare_template($this->templatefile);
$respArr = array();
$respArr['success'] = true;
$respArr['body'] = $this->xt->fetch_loaded("body");
$respArr['counter'] = postvalue('counter');
$this->xt->assign("container_master", false);
echo printJSON($respArr);
exit();
}
$this->display( $this->templatefile );
}
}
?> |
<?php
namespace ByteNoodles\Bundle\Symfony2ORMBundle\DependencyInjection;
use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;
/**
* This is the class that validates and merges configuration from your app/config files
*
* To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html#cookbook-bundles-extension-config-class}
*/
class Configuration implements ConfigurationInterface
{
/**
* {@inheritDoc}
*/
public function getConfigTreeBuilder()
{
$treeBuilder = new TreeBuilder();
$rootNode = $treeBuilder->root('byte_noodles_symfony2_orm');
// Here you should define the parameters that are allowed to
// configure your bundle. See the documentation linked above for
// more information on that topic.
return $treeBuilder;
}
}
|
# coding=utf-8
"""
Collect the elasticsearch stats for the local node
#### Dependencies
* urlib2
"""
import urllib2
import re
try:
import json
json # workaround for pyflakes issue #13
except ImportError:
import simplejson as json
import diamond.collector
RE_LOGSTASH_INDEX = re.compile('^(.*)-\d\d\d\d\.\d\d\.\d\d$')
class ElasticSearchCollector(diamond.collector.Collector):
def get_default_config_help(self):
config_help = super(ElasticSearchCollector,
self).get_default_config_help()
config_help.update({
'host': "",
'port': "",
'stats': "Available stats: \n"
+ " - jvm (JVM information) \n"
+ " - thread_pool (Thread pool information) \n"
+ " - indices (Individual index stats)\n",
'logstash_mode': "If 'indices' stats are gathered, remove "
+ "the YYYY.MM.DD suffix from the index name "
+ "(e.g. logstash-adm-syslog-2014.01.03) and use that "
+ "as a bucket for all 'day' index stats.",
})
return config_help
def get_default_config(self):
"""
Returns the default collector settings
"""
config = super(ElasticSearchCollector, self).get_default_config()
config.update({
'host': '127.0.0.1',
'port': 9200,
'path': 'elasticsearch',
'stats': ['jvm', 'thread_pool', 'indices'],
'logstash_mode': False,
})
return config
def _get(self, path):
url = 'http://%s:%i/%s' % (
self.config['host'], int(self.config['port']), path)
try:
response = urllib2.urlopen(url)
except Exception, err:
self.log.error("%s: %s", url, err)
return False
try:
return json.load(response)
except (TypeError, ValueError):
self.log.error("Unable to parse response from elasticsearch as a"
+ " json object")
return False
def _copy_one_level(self, metrics, prefix, data, filter=lambda key: True):
for key, value in data.iteritems():
if filter(key):
metric_path = '%s.%s' % (prefix, key)
self._set_or_sum_metric(metrics, metric_path, value)
def _copy_two_level(self, metrics, prefix, data, filter=lambda key: True):
for key1, d1 in data.iteritems():
self._copy_one_level(metrics, '%s.%s' % (prefix, key1), d1, filter)
def _index_metrics(self, metrics, prefix, index):
if self.config['logstash_mode']:
"""Remove the YYYY.MM.DD bit from logstash indices.
This way we keep using the same metric naming and not polute
our metrics system (e.g. Graphite) with new metrics every day."""
m = RE_LOGSTASH_INDEX.match(prefix)
if m:
prefix = m.group(1)
# keep a telly of the number of indexes
self._set_or_sum_metric(metrics,
'%s.indexes_in_group' % prefix, 1)
self._add_metric(metrics, '%s.docs.count' % prefix, index,
['docs', 'count'])
self._add_metric(metrics, '%s.docs.deleted' % prefix, index,
['docs', 'deleted'])
self._add_metric(metrics, '%s.datastore.size' % prefix, index,
['store', 'size_in_bytes'])
# publish all 'total' and 'time_in_millis' stats
self._copy_two_level(
metrics, prefix, index,
lambda key: key.endswith('total') or key.endswith('time_in_millis'))
def _add_metric(self, metrics, metric_path, data, data_path):
"""If the path specified by data_path (a list) exists in data,
add to metrics. Use when the data path may not be present"""
current_item = data
for path_element in data_path:
current_item = current_item.get(path_element)
if current_item is None:
return
self._set_or_sum_metric(metrics, metric_path, current_item)
def _set_or_sum_metric(self, metrics, metric_path, value):
"""If we already have a datapoint for this metric, lets add
the value. This is used when the logstash mode is enabled."""
if metric_path in metrics:
metrics[metric_path] += value
else:
metrics[metric_path] = value
def collect(self):
if json is None:
self.log.error('Unable to import json')
return {}
result = self._get('_nodes/_local/stats?all=true')
if not result:
return
metrics = {}
node = result['nodes'].keys()[0]
data = result['nodes'][node]
#
# http connections to ES
metrics['http.current'] = data['http']['current_open']
#
# indices
indices = data['indices']
metrics['indices.docs.count'] = indices['docs']['count']
metrics['indices.docs.deleted'] = indices['docs']['deleted']
metrics['indices.datastore.size'] = indices['store']['size_in_bytes']
transport = data['transport']
metrics['transport.rx.count'] = transport['rx_count']
metrics['transport.rx.size'] = transport['rx_size_in_bytes']
metrics['transport.tx.count'] = transport['tx_count']
metrics['transport.tx.size'] = transport['tx_size_in_bytes']
# elasticsearch < 0.90RC2
if 'cache' in indices:
cache = indices['cache']
self._add_metric(metrics, 'cache.bloom.size', cache,
['bloom_size_in_bytes'])
self._add_metric(metrics, 'cache.field.evictions', cache,
['field_evictions'])
self._add_metric(metrics, 'cache.field.size', cache,
['field_size_in_bytes'])
metrics['cache.filter.count'] = cache['filter_count']
metrics['cache.filter.evictions'] = cache['filter_evictions']
metrics['cache.filter.size'] = cache['filter_size_in_bytes']
self._add_metric(metrics, 'cache.id.size', cache,
['id_cache_size_in_bytes'])
# elasticsearch >= 0.90RC2
if 'filter_cache' in indices:
cache = indices['filter_cache']
metrics['cache.filter.evictions'] = cache['evictions']
metrics['cache.filter.size'] = cache['memory_size_in_bytes']
self._add_metric(metrics, 'cache.filter.count', cache, ['count'])
# elasticsearch >= 0.90RC2
if 'id_cache' in indices:
cache = indices['id_cache']
self._add_metric(metrics, 'cache.id.size', cache,
['memory_size_in_bytes'])
# elasticsearch >= 0.90
if 'fielddata' in indices:
fielddata = indices['fielddata']
self._add_metric(metrics, 'fielddata.size', fielddata,
['memory_size_in_bytes'])
self._add_metric(metrics, 'fielddata.evictions', fielddata,
['evictions'])
#
# process mem/cpu (may not be present, depending on access restrictions)
self._add_metric(metrics, 'process.cpu.percent', data,
['process', 'cpu', 'percent'])
self._add_metric(metrics, 'process.mem.resident', data,
['process', 'mem', 'resident_in_bytes'])
self._add_metric(metrics, 'process.mem.share', data,
['process', 'mem', 'share_in_bytes'])
self._add_metric(metrics, 'process.mem.virtual', data,
['process', 'mem', 'total_virtual_in_bytes'])
#
# filesystem (may not be present, depending on access restrictions)
if 'fs' in data and 'data' in data['fs'] and data['fs']['data']:
fs_data = data['fs']['data'][0]
self._add_metric(metrics, 'disk.reads.count', fs_data,
['disk_reads'])
self._add_metric(metrics, 'disk.reads.size', fs_data,
['disk_read_size_in_bytes'])
self._add_metric(metrics, 'disk.writes.count', fs_data,
['disk_writes'])
self._add_metric(metrics, 'disk.writes.size', fs_data,
['disk_write_size_in_bytes'])
#
# jvm
if 'jvm' in self.config['stats']:
jvm = data['jvm']
mem = jvm['mem']
for k in ('heap_used', 'heap_committed', 'non_heap_used',
'non_heap_committed'):
metrics['jvm.mem.%s' % k] = mem['%s_in_bytes' % k]
for pool, d in mem['pools'].iteritems():
pool = pool.replace(' ', '_')
metrics['jvm.mem.pools.%s.used' % pool] = d['used_in_bytes']
metrics['jvm.mem.pools.%s.max' % pool] = d['max_in_bytes']
metrics['jvm.threads.count'] = jvm['threads']['count']
gc = jvm['gc']
collection_count = 0
collection_time_in_millis = 0
for collector, d in gc['collectors'].iteritems():
metrics['jvm.gc.collection.%s.count' % collector] = d[
'collection_count']
collection_count += d['collection_count']
metrics['jvm.gc.collection.%s.time' % collector] = d[
'collection_time_in_millis']
collection_time_in_millis += d['collection_time_in_millis']
# calculate the totals, as they're absent in elasticsearch > 0.90.10
if 'collection_count' in gc:
metrics['jvm.gc.collection.count'] = gc['collection_count']
else:
metrics['jvm.gc.collection.count'] = collection_count
k = 'collection_time_in_millis'
if k in gc:
metrics['jvm.gc.collection.time'] = gc[k]
else:
metrics['jvm.gc.collection.time'] = collection_time_in_millis
#
# thread_pool
if 'thread_pool' in self.config['stats']:
self._copy_two_level(metrics, 'thread_pool', data['thread_pool'])
#
# network
self._copy_two_level(metrics, 'network', data['network'])
if 'indices' in self.config['stats']:
#
# individual index stats
result = self._get('_stats?clear=true&docs=true&store=true&'
+ 'indexing=true&get=true&search=true')
if not result:
return
_all = result['_all']
self._index_metrics(metrics, 'indices._all', _all['primaries'])
if 'indices' in _all:
indices = _all['indices']
elif 'indices' in result: # elasticsearch >= 0.90RC2
indices = result['indices']
else:
return
for name, index in indices.iteritems():
self._index_metrics(metrics, 'indices.%s' % name,
index['primaries'])
for key in metrics:
self.publish(key, metrics[key])
|
/*
* Copyright (c) 1995 The University of Utah and
* the Computer Systems Laboratory at the University of Utah (CSL).
* All rights reserved.
*
* Permission to use, copy, modify and distribute this software is hereby
* granted provided that (1) source code retains these copyright, permission,
* and disclaimer notices, and (2) redistributions including binaries
* reproduce the notices in supporting documentation, and (3) all advertising
* materials mentioning features or use of this software display the following
* acknowledgement: ``This product includes software developed by the
* Computer Systems Laboratory at the University of Utah.''
*
* THE UNIVERSITY OF UTAH AND CSL ALLOW FREE USE OF THIS SOFTWARE IN ITS "AS
* IS" CONDITION. THE UNIVERSITY OF UTAH AND CSL DISCLAIM ANY LIABILITY OF
* ANY KIND FOR ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE.
*
* CSL requests users of this software to return to csl-dist@cs.utah.edu any
* improvements that they make and grant CSL redistribution rights.
*/
/* 15-410 mods by de0u 2008-09-02 */
#include <stdio.h>
#include <console.h>
int putchar(int c)
{
return ((unsigned char)putbyte(c));
}
|
#!/bin/bash
# bomb on any error
set -e
# change to working directory
root="/opt/netflix-proxy"
pushd $root
# obtain the interface with the default gateway say
int=$(ip route | grep default | awk '{print $5}')
# obtain IP address of the Internet facing interface
ipaddr=$(ip addr show dev $int | grep inet | grep -v inet6 | awk '{print $2}' | grep -Po '[0-9]{1,3}+\.[0-9]{1,3}+\.[0-9]{1,3}+\.[0-9]{1,3}+(?=\/)')
# obtain client (home) ip address
clientip=$(echo $SSH_CONNECTION | awk '{print $1}')
# get the current date
date=$(/bin/date +'%Y%m%d')
# configure iptables
iptables -A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT
iptables -A INPUT -p icmp -j ACCEPT
iptables -A INPUT -i lo -j ACCEPT
iptables -A INPUT -p tcp -m state --state NEW -m tcp --dport 22 -j ACCEPT
iptables -A INPUT -s $clientip/32 -p tcp -m tcp --dport 80 -j ACCEPT
iptables -A INPUT -s $clientip/32 -p tcp -m tcp --dport 443 -j ACCEPT
iptables -A INPUT -j REJECT --reject-with icmp-host-prohibited
iptables -A FORWARD -j REJECT --reject-with icmp-host-prohibited
iptables -A DOCKER -m state --state RELATED,ESTABLISHED -j ACCEPT
iptables -A DOCKER -p icmp -j ACCEPT
iptables -A DOCKER -s $clientip/32 -p udp -m udp --dport 53 -j ACCEPT
iptables -A DOCKER -j REJECT --reject-with icmp-host-prohibited
iptables-save > /etc/iptables.rules
grep -q 'pre-up iptables-restore < /etc/iptables.rules' /etc/network/interfaces || printf '\tpre-up iptables-restore < /etc/iptables.rules\n' >> /etc/network/interfaces
echo "Updating db.override with ipaddr"=$ipaddr "and date="$date
$(which sed) -i "s/127.0.0.1/${ipaddr}/g" data/db.override
$(which sed) -i "s/YYYYMMDD/${date}/g" data/db.override
echo "Building docker containers"
#$(which docker) build -t bind docker-bind
#$(which docker) build -t sniproxy docker-sniproxy
echo "Starting Docker containers"
$(which docker) run --name bind -d -v /opt/netflix-proxy/data:/data -p 53:53/udp -t ab77/bind
$(which docker) run --name sniproxy -d -v /opt/netflix-proxy/data:/data --net=host -t ab77/sniproxy
echo "Testing DNS"
$(which dig) netflix.com @$ipaddr
echo "Testing proxy"
echo "GET /" | $(which openssl) s_client -servername netflix.com -connect $ipaddr:443
# configure upstart
cp init/* /etc/init
# change back to original directory
popd
echo "Change your DNS to" $ipaddr "and start watching Netflix out of region."
echo "Done!"
|
<?php
function removeSpecialChars($suaString) {
$string = preg_replace( '/[`^~\'"]/', null, iconv( 'UTF-8', 'ASCII//TRANSLIT', $suaString ) );
$string = htmlspecialchars($string);
return $string;
}
|
var express = require('express');
var app = module.exports = express();
var api = require('lib/db-api');
var config = require('lib/config');
var path = require('path');
var url = require('url');
var resolve = path.resolve;
var strip = require('strip');
var log = require('debug')('democracyos:facebook-card');
app.get('/topic/:id', function(req, res, next){
log('Facebook Request /topic/%s', req.params.id);
api.topic.get(req.params.id, function (err, topicDoc) {
if (err) return _handleError(err, req, res);
log('Serving Facebook topic %s', topicDoc.id);
var baseUrl = url.format({
protocol: config.protocol
, hostname: config.host
, port: config.publicPort
});
res.render(resolve(__dirname, 'topic.jade'),
{ topic: topicDoc,
baseUrl : baseUrl,
config : config,
strip: strip
});
});
})
app.get('*', function(req, res, next){
log('Facebook Request generic page');
var baseUrl = url.format({
protocol: config.protocol
, hostname: config.host
, port: config.publicPort
});
res.render(resolve(__dirname, 'generic.jade'),
{ baseUrl : baseUrl,
config : config});
}) |
import Html from "./Html";
import { YatinSelectMin, YatinSelectMax } from "../parts/YatinSelect";
export default class YatinSection extends Html {
constructor(min="", max="") {
super();
var $yatinSection = $(`
<section class="yatin-section">
<h2>¥家賃</h2>
<div class="center"></div>
</section>
`);
var selectMin = new YatinSelectMin(min);
var selectMax = new YatinSelectMax(max);
$yatinSection.find(".center").append( selectMin.getHtml() );
$yatinSection.find(".center").append( $(`<div class="kara">〜</div>`) );
$yatinSection.find(".center").append( selectMax.getHtml() );
this.$html = $yatinSection
}
} |
# frozen_string_literal: true
require "#{Rails.root}/lib/analytics/histogram_plotter"
class OresPlotController < ApplicationController
def course_plot
@course = Course.find_by slug: params[:id]
@ores_changes_plot = HistogramPlotter.plot(course: @course, opts: { simple: true })
render json: { plot_path: @ores_changes_plot }
end
end
|
import java.io.IOException;
import java.io.FileInputStream;
public class UsingFileInputStream{
public static void main(String[] main) throws IOException{
FileInputStream fis=new FileInputStream("file.txt");
int i;
while((i=fis.read())!=-1){
System.out.print((char)i);
}
fis.close();
}
} |
# CleoDB
C# Language Entities Oriented Database
___
## Nuget
`Install-Package CleoDB`
## What is CleoDB?
CleoDB is a data storage framework written entirely in C#, for C#. It is optimized for easily storing and restoring your POCOs (and more).
In its current state, CleoDB is in no way a competitor for professional database systems such as SQL Server or MySQL, but rather a simple framework that can be used by beginners who need to cache their memory objects and restore them at a later time.
CleoDB also resembles the syntax and semantics of Entity Framework, in order to make the transition as easy as possible.
## Getting started
First of all you will have to define where CleoDB looks for and saves the stored data. You do this by using the `SetWorkingDirectory` method :
```csharp
CleoDB.SetWorkingDirectory("C:\CleoDB\MyApp");
```
Then you will have to register your types. Once you do this, CleoDB will create a database table for each one.
```csharp
CleoDB.RegisterType<MyType>();
```
After registering all your types, you can call `LoadDatabase` in order to populate them with data from the Working Directory, if any.
```csharp
CleoDB.LoadDatabase();
```
You can access the set for any type using the generic method `Set` :
```csharp
CleoDB.Set<MyType>(); // returns ReadOnlyCollection<T>
```
You can add / remove objects using the generic methods `Add` and `Remove` :
```csharp
var obj = new MyType();
// database is automatically saved after every add / remove
CleoDB.Add<MyType>(obj);
CleoDB.Remove<MyType>(obj);
```
## Advanced features deep dive
* ID auto-increment (coming soon)
* Relationships (coming soon)
## Credits
[JSON.NET](https://github.com/JamesNK/Newtonsoft.Json) |
//
// AMSlideMenuLeftMenuSegue.h
// AMSlideMenu
//
// The MIT License (MIT)
//
// Created by : arturdev
// Copyright (c) 2014 SocialObjects Software. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE
#import <UIKit/UIKit.h>
@interface AMSlideMenuLeftMenuSegue : UIStoryboardSegue
@end
|
# defrredSupport
|
import { Fun, Optional } from '@ephox/katamari';
import { PlatformDetection } from '@ephox/sand';
import { fromRawEvent } from '../../impl/FilteredEvent';
import { EventHandler, EventUnbinder } from '../events/Types';
import { SugarElement } from '../node/SugarElement';
import * as Scroll from './Scroll';
export interface Bounds {
readonly x: number;
readonly y: number;
readonly width: number;
readonly height: number;
readonly right: number;
readonly bottom: number;
}
const get = (_win?: Window): Optional<VisualViewport> => {
const win = _win === undefined ? window : _win;
if (PlatformDetection.detect().browser.isFirefox()) {
// TINY-7984: Firefox 91 is returning incorrect values for visualViewport.pageTop, so disable it for now
return Optional.none();
} else {
return Optional.from(win.visualViewport);
}
};
const bounds = (x: number, y: number, width: number, height: number): Bounds => ({
x,
y,
width,
height,
right: x + width,
bottom: y + height
});
const getBounds = (_win?: Window): Bounds => {
const win = _win === undefined ? window : _win;
const doc = win.document;
const scroll = Scroll.get(SugarElement.fromDom(doc));
return get(win).fold(
() => {
const html = win.document.documentElement;
// Don't use window.innerWidth/innerHeight here, as we don't want to include scrollbars
// since the right/bottom position is based on the edge of the scrollbar not the window
const width = html.clientWidth;
const height = html.clientHeight;
return bounds(scroll.left, scroll.top, width, height);
},
(visualViewport) =>
// iOS doesn't update the pageTop/pageLeft when element.scrollIntoView() is called, so we need to fallback to the
// scroll position which will always be less than the page top/left values when page top/left are accurate/correct.
bounds(Math.max(visualViewport.pageLeft, scroll.left), Math.max(visualViewport.pageTop, scroll.top), visualViewport.width, visualViewport.height)
);
};
const bind = (name: string, callback: EventHandler, _win?: Window): EventUnbinder =>
get(_win).map((visualViewport) => {
const handler = (e: Event) => callback(fromRawEvent(e));
visualViewport.addEventListener(name, handler);
return {
unbind: () => visualViewport.removeEventListener(name, handler)
};
}).getOrThunk(() => ({
unbind: Fun.noop
}));
export {
bind,
get,
getBounds
};
|
<html><body>
<h4>Windows 10 x64 (18362.239)</h4><br>
<h2>_EXCEPTION_RECORD</h2>
<font face="arial"> +0x000 ExceptionCode : Int4B<br>
+0x004 ExceptionFlags : Uint4B<br>
+0x008 ExceptionRecord : Ptr64 <a href="./_EXCEPTION_RECORD.html">_EXCEPTION_RECORD</a><br>
+0x010 ExceptionAddress : Ptr64 Void<br>
+0x018 NumberParameters : Uint4B<br>
+0x020 ExceptionInformation : [15] Uint8B<br>
</font></body></html> |
Namespace Security.SystemOptions_Applications
Public Class ApplicationDrivers
Inherits SecurityItemBase
Public Sub New()
_ConceptItemName = "Application Drivers"
_ConceptName = "System Options_Applications"
_Description = "Allow access to 'Application Driver's Tab"
_IsEnterprise = True
_IsSmallBusiness = True
_IsViewer = False
_IsWeb = False
_IsWebPlus = False
End Sub
End Class
End Namespace
|
/*!
* \file force-atlas-2.c
* Sequential implementation for the Force Atlas 2 spring embedding algorithm.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <float.h>
#include <limits.h>
#include <assert.h>
#include "force-atlas-2.h"
#include "math.h"
#include "timer.h"
#include "vector.h"
#include "util.h"
/*!
* Calculates the number of neighbours for every node.
* \param[in] g The input graph.
* \param[out] numNeighbours An array containing the out-degree for each node in
* the given graph.
*/
void calcNumNeighbours(Graph* g, unsigned int* numNeighbours);
/*!
* Updates the current force on each vertex with the current gravity.
* \param g The graph on which to apply the update.
* \param forceX Array holding the x-direction forces on each vertex.
* \param forceY Array holding the y-direction forces on each vertex.
* \param deg Array holding the out-degree for each vertex.
*/
void fa2Gravity(Graph* g, float* forceX, float* forceY, unsigned int* deg);
/*!
* Applies repulsion forces on each vertex.
* \param g The graph that contains the vertices on which to apply the repulsion
* forces.
* \param forceX Array holding the x-direction forces on each vertex.
* \param forceY Array holding the y-direction forces on each vertex.
* \param deg Array holding the out-degree of each vertex.
*/
void fa2Repulsion(Graph* g, float* forceX, float* forceY, unsigned int* deg);
/*!
* Applies attraction forces on all pairs of vertices that are connected by an
* edge.
* \param g The graph which holds the vertices and edges on which to apply the
* attraction forces.
* \param forceX Array holding the x-direction forces on each vertex.
* \param forceY Array holding the y-direction forces on each vertex.
*/
void fa2Attraction(Graph* g, float* forceX, float* forceY);
/*!
* Updates the swing value of each vertex in the Graph.
* \param[in] g The graph to update.
* \param[in] forceX Array holding the x-direction forces on each vertex.
* \param[in] forceY Array holding the y-direction forces on each vertex.
* \param[in] oldForceX Array holding the x-direction forces on each vertex for the
* previous iteration.
* \param[in] oldForceY Array holding the y-direction forces on each vertex for the
* previous iteration.
* \param[out] swg An array holding the calculated swing values for each vertex.
*/
void fa2UpdateSwing(Graph* g, float* forceX, float* forceY, float* oldForceX,
float* oldForceY, float* swg);
/*!
* Updates the traction value of each vertex in the Graph.
* \param[in] g The graph to update.
* \param[in] forceX Array holding the x-direction forces on each vertex.
* \param[in] forceY Array holding the y-direction forces on each vertex.
* \param[in] oldForceX Array holding the x-direction forces on each vertex for the
* previous iteration.
* \param[in] oldForceY Array holding the y-direction forces on each vertex for the
* previous iteration.
* \param[out] tra An array holding the calculated traction values for each
* vertex.
*/
void fa2UpdateTract(Graph* g, float* forceX, float* forceY, float* oldForceX,
float* oldForceY, float* tra);
/*!
* Update the swing value of the Graph itself.
* \param[in] g The graph whose swing value should be calculated.
* \param[in] swg The array holding the swing values for each vertex in the
* graph.
* \param[in] deg The array holding the out degree values for each vertex in the
* graph.
* \param[out] gSwing A float pointer where the graph swing value should be
* stored.
*/
void fa2UpdateSwingGraph(Graph* g, float* swg, unsigned int* deg, float* gSwing);
/*!
* Update the traction value of the graph itself.
* \param[in] g The graph whoses traction should be calculated.
* \param[in] tra The array holding the traction values for each vertex in the
* graph.
* \param[in] deg The array holding the out degree values for each vertex in the
* graph.
* \param[out] gTract A float pointer where the graph traction value should be
* stored.
*/
void fa2UpdateTractGraph(Graph* g, float* tra, unsigned int* deg, float* gTract);
/*!
* Updates the speed value of the graph itself.
* \param[in] gSwing The graph swing value.
* \param[in] gTract The graph traction value.
* \param[out] gSpeed The graph speed value.
*/
void fa2UpdateSpeedGraph(float gSwing, float gTract, float* gSpeed);
/*!
* Updates the speed value for each vertex in the graph.
* \param[in] g The graph.
* \param[out] speed The array where the speed values should be stored.
* \param[in] swg The swing values for all vertices in the graph.
* \param[in] forceX The x forces for all vertices in the graph.
* \param[in] forceY The y forces for all vertices in the graph.
* \param[in] gs The graph speed value.
*/
void fa2UpdateSpeed(Graph* g, float* speed, float* swg, float* forceX,
float* forceY, float gs);
/*!
* Updates the displacement value for each vertex in the graph.
* \param[in] g The graph.
* \param[in] speed The array that holds the speed values for each vertex.
* \param[in] forceX The x forces for each vertex in the graph.
* \param[in] forceY The y forces for each vertex in the graph.
* \param[out] dispX The array where the x displacement for each vertex should
* be stored.
* \param[out] dispY The array where the y displacement for each vertex should
* be stored.
*/
void fa2UpdateDisplacement(Graph*, float*, float*, float*, float*, float*);
/*!
* Stores the forces from the current iteration as old forces. Deletes the
* forces from the previous iteration.
*
* \param[in] g The graph.
* \param[in] forceX The x forces of the current iteration.
* \param[in] forceY The y forces of the current iteration.
* \param[out] oldForceX The array that should be used to store the x forces of
* the current iteration.
* \param[out] oldForceY The array that should be used to store the y forces of
* the current iteration.
*/
void fa2SaveOldForces(Graph*, float*, float*, float*, float*);
/*!
* Updates the location of each vertex according to the given displacement.
*
* \param[in] g The graph.
* \param[in] xdisp The array of x displacement values for each vertex.
* \param[in] ydisp The array of y displacement values for each vertex.
*/
void fa2UpdateLocation(Graph* g, float* xdisp, float* ydisp);
void fa2Gravity(Graph* g, float* forceX, float* forceY, unsigned int* deg)
{
if (!g)
return;
for (size_t i = 0; i < g->vertices->numvertices; i++)
{
float vx = g->vertices->vertexXLocs[i];
float vy = g->vertices->vertexYLocs[i];
float vlen = vectorGetLength(vx, vy);
assert(vlen != 0);
vectorInverse(&vx, &vy);
vectorMultiply(&vx, &vy, K_G * (deg[i] + 1) / vlen);
if (i == 0)
{
DEBUG_PRINT("g:%f\n", vx);
}
vectorAdd(&forceX[i], &forceY[i], vx, vy);
}
}
void fa2Repulsion(Graph* g, float* forceX, float* forceY, unsigned int* deg)
{
if (!g)
return;
for (size_t i = 0; i < g->vertices->numvertices; i++)
{
for (size_t j = 0; j < g->vertices->numvertices; j++)
{
if (i == j)
continue;
float vx1 = g->vertices->vertexXLocs[i];
float vy1 = g->vertices->vertexYLocs[i];
float vx2 = g->vertices->vertexXLocs[j];
float vy2 = g->vertices->vertexYLocs[j];
vectorSubtract(&vx1, &vy1, vx2, vy2);
float dist = vectorGetLength(vx1, vy1);
if (dist > 0)
{
vectorNormalize(&vx1, &vy1);
vectorMultiply(&vx1, &vy1,
K_R * (((deg[i] + 1) * (deg[j] + 1)) / dist));
// vectorMultiply(&vx1, &vy1, 0.5);
vectorAdd(&forceX[i], &forceY[i], vx1, vy1);
}
}
}
}
void fa2Attraction(Graph* g, float* forceX, float* forceY)
{
if (!g)
return;
float* vxLocs = g->vertices->vertexXLocs;
float* vyLocs = g->vertices->vertexYLocs;
for (size_t gid = 0; gid < g->vertices->numvertices; gid++)
{
float vx1 = vxLocs[gid];
float vy1 = vyLocs[gid];
// Each thread goes through its array of edges.
unsigned int maxedges = g->edges->numedges[gid];
for (size_t i = 0; i < maxedges; i++)
{
unsigned int index = gid + (g->vertices->numvertices * i);
unsigned int target = g->edges->edgeTargets[index];
if (target == UINT_MAX)
continue;
// Compute attraction force.
float vx2 = vxLocs[target];
float vy2 = vyLocs[target];
vectorSubtract(&vx2, &vy2, vx1, vy1);
// vectorMultiply(&vx2, &vy2, 0.5);
vectorAdd(&forceX[gid], &forceY[gid], vx2, vy2);
if (gid == 0)
{
DEBUG_PRINT("a:%f\t%u\n", vx2, target);
}
}
}
}
// Updates the swing for each vertex, as described in the Force Atlas 2 paper.
void fa2UpdateSwing(Graph* g, float* forceX, float* forceY, float* oldForceX,
float* oldForceY, float* swg)
{
for (size_t i = 0; i < g->vertices->numvertices; i++)
{
float fx = oldForceX[i];
float fy = oldForceY[i];
vectorSubtract(&fx, &fy, forceX[i], forceY[i]);
float vlen = vectorGetLength(fx, fy);
swg[i] = vlen;
}
}
// Updates the traction for each vertex, as described in the Force Atlas 2
// paper.
void fa2UpdateTract(Graph* g, float* forceX, float* forceY, float* oldForceX,
float* oldForceY, float* tra)
{
for (size_t i = 0; i < g->vertices->numvertices; i++)
{
float fx = oldForceX[i];
float fy = oldForceY[i];
vectorAdd(&fx, &fy, forceX[i], forceY[i]);
float vlen = vectorGetLength(fx, fy);
tra[i] = vlen / 2;
}
}
// Calculate the current swing of the graph.
void fa2UpdateSwingGraph(Graph* g, float* swg, unsigned int* deg, float* gswing)
{
*gswing = 0;
for (size_t i = 0; i < g->vertices->numvertices; i++)
{
*gswing += (deg[i] + 1) * swg[i];
}
}
// Calculate the current traction of the graph.
void fa2UpdateTractGraph(Graph* g, float* tra, unsigned int* deg, float* gtract)
{
*gtract = 0;
for (size_t i = 0; i < g->vertices->numvertices; i++)
{
*gtract += (deg[i] + 1) * tra[i];
}
}
void fa2UpdateSpeedGraph(float gswing, float gtract, float* gspeed)
{
float oldSpeed = *gspeed;
if (gswing == 0)
{
gswing = FLOAT_EPSILON;
}
*gspeed = TAU * (gtract / gswing);
if (oldSpeed > 0 && *gspeed > 1.5 * oldSpeed)
{
*gspeed = 1.5 * oldSpeed;
}
}
void fa2UpdateSpeed(Graph* g, float* speed, float* swg, float* forceX,
float* forceY, float gs)
{
for (size_t i = 0; i < g->vertices->numvertices; i++)
{
float vSwg = swg[i];
if (vSwg <= 0)
vSwg = EPSILON;
float vForceLen = vectorGetLength(forceX[i], forceY[i]);
if (vForceLen <= 0)
vForceLen = EPSILON;
speed[i] = K_S * gs / (1 + (gs * sqrt(vSwg)));
}
}
// Save current forces as the previous forces for the next tick.
void fa2SaveOldForces(Graph* g, float* forceX, float* forceY, float* oldForceX,
float* oldForceY)
{
for (size_t i = 0; i < g->vertices->numvertices; i++)
{
oldForceX[i] = forceX[i];
oldForceY[i] = forceY[i];
}
}
void fa2UpdateDisplacement(Graph* g, float* speed, float* forceX, float* forceY,
float* dispX, float* dispY)
{
for (size_t i = 0; i < g->vertices->numvertices; i++)
{
dispX[i] = forceX[i];
dispY[i] = forceY[i];
vectorMultiply(&dispX[i], &dispY[i], speed[i]);
}
}
void fa2UpdateLocation(Graph* g, float* xdisp, float* ydisp)
{
for (size_t i = 0; i < g->vertices->numvertices; i++)
{
g->vertices->vertexXLocs[i] += xdisp[i];
g->vertices->vertexYLocs[i] += ydisp[i];
}
}
/*!
* Runs one iteration of the force atlas 2 spring embedding on the given graph.
*
* \param[in,out] g The graph to use for force atlas 2.
*/
void fa2RunOnce(Graph* g)
{
static int firstRun = 1;
static float* tra = NULL;
static float* swg = NULL;
static float* speed = NULL;
static float* forceX = NULL;
static float* forceY = NULL;
static float* oldForceX = NULL;
static float* oldForceY = NULL;
static float* dispX = NULL;
static float* dispY = NULL;
Timer* timer = timerNew();
float graphSwing = 0.0;
float graphTract = 0.0;
static float graphSpeed = 0.0;
if (firstRun)
{
tra = (float*) calloc(g->vertices->numvertices, sizeof(float));
swg = (float*) calloc(g->vertices->numvertices, sizeof(float));
speed = (float*) calloc(g->vertices->numvertices, sizeof(float));
forceX = (float*) calloc(g->vertices->numvertices, sizeof(float));
forceY = (float*) calloc(g->vertices->numvertices, sizeof(float));
oldForceX = (float*) calloc(g->vertices->numvertices, sizeof(float));
oldForceY = (float*) calloc(g->vertices->numvertices, sizeof(float));
dispX = (float*) calloc(g->vertices->numvertices, sizeof(float));
dispY = (float*) calloc(g->vertices->numvertices, sizeof(float));
firstRun = 0;
}
// Reset forces on vertices to 0.
memset(forceX, 0, sizeof(float) * g->vertices->numvertices);
memset(forceY, 0, sizeof(float) * g->vertices->numvertices);
// Gravity force
startTimer(timer);
fa2Gravity(g, forceX, forceY, g->edges->numedges);
stopTimer(timer);
DEBUG_PRINT_DEVICE(forceX, g->vertices->numvertices);
printTimer(timer, "force: gravity");
// Repulsion between vertices
startTimer(timer);
fa2Repulsion(g, forceX, forceY, g->edges->numedges);
stopTimer(timer);
DEBUG_PRINT_DEVICE(forceX, g->vertices->numvertices);
printTimer(timer, "force: repulsion");
// Attraction on edges
startTimer(timer);
fa2Attraction(g, forceX, forceY);
stopTimer(timer);
DEBUG_PRINT_DEVICE(forceX, g->vertices->numvertices);
printTimer(timer, "force: attraction");
// Calculate speed of vertices.
// Update swing of vertices.
fa2UpdateSwing(g, forceX, forceY, oldForceX, oldForceY, swg);
// Update traction of vertices.
fa2UpdateTract(g, forceX, forceY, oldForceX, oldForceY, tra);
DEBUG_PRINT_DEVICE(forceX, g->vertices->numvertices);
// Update swing of Graph.
fa2UpdateSwingGraph(g, swg, g->edges->numedges, &graphSwing);
// Update traction of Graph.
fa2UpdateTractGraph(g, tra, g->edges->numedges, &graphTract);
// Update speed of Graph.
fa2UpdateSpeedGraph(graphSwing, graphTract, &graphSpeed);
// Update speed of vertices.
fa2UpdateSpeed(g, speed, swg, forceX, forceY, graphSpeed);
// Update displacement of vertices.
fa2UpdateDisplacement(g, speed, forceX, forceY, dispX, dispY);
// Update vertex locations based on speed.
startTimer(timer);
fa2UpdateLocation(g, dispX, dispY);
stopTimer(timer);
printTimer(timer, "moving vertices");
// Set current forces as old forces in vertex data.
fa2SaveOldForces(g, forceX, forceY, oldForceX, oldForceY);
timerClean(timer);
}
void fa2RunOnGraph(Graph* g, unsigned int n)
{
Timer* timer = timerNew();
for (size_t i = 0; i < n; i++)
{
startTimer(timer);
fa2RunOnce(g);
stopTimer(timer);
printTimer(timer, "embedding iteration");
}
timerClean(timer);
}
|
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
$this->load->view("/usefulScreens/header");
$this->load->view("/usefulScreens/menu");
$this->load->view("/usefulScreens/body");
$this->load->view("/usefulScreens/footer");
//if(!empty($create))
//$this->load->view("/telas/" . $create);
|
//go:build go1.16
// +build go1.16
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
package armhanaonazure_test
import (
"context"
"log"
"time"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/to"
"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
"github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/hanaonazure/armhanaonazure"
)
// x-ms-original-file: specification/hanaonazure/resource-manager/Microsoft.HanaOnAzure/preview/2020-02-07-preview/examples/SapMonitors_List.json
func ExampleSapMonitorsClient_List() {
cred, err := azidentity.NewDefaultAzureCredential(nil)
if err != nil {
log.Fatalf("failed to obtain a credential: %v", err)
}
ctx := context.Background()
client := armhanaonazure.NewSapMonitorsClient("<subscription-id>", cred, nil)
pager := client.List(nil)
for {
nextResult := pager.NextPage(ctx)
if err := pager.Err(); err != nil {
log.Fatalf("failed to advance page: %v", err)
}
if !nextResult {
break
}
for _, v := range pager.PageResponse().Value {
log.Printf("Pager result: %#v\n", v)
}
}
}
// x-ms-original-file: specification/hanaonazure/resource-manager/Microsoft.HanaOnAzure/preview/2020-02-07-preview/examples/SapMonitors_Get.json
func ExampleSapMonitorsClient_Get() {
cred, err := azidentity.NewDefaultAzureCredential(nil)
if err != nil {
log.Fatalf("failed to obtain a credential: %v", err)
}
ctx := context.Background()
client := armhanaonazure.NewSapMonitorsClient("<subscription-id>", cred, nil)
res, err := client.Get(ctx,
"<resource-group-name>",
"<sap-monitor-name>",
nil)
if err != nil {
log.Fatal(err)
}
log.Printf("Response result: %#v\n", res.SapMonitorsClientGetResult)
}
// x-ms-original-file: specification/hanaonazure/resource-manager/Microsoft.HanaOnAzure/preview/2020-02-07-preview/examples/SapMonitors_Create.json
func ExampleSapMonitorsClient_BeginCreate() {
cred, err := azidentity.NewDefaultAzureCredential(nil)
if err != nil {
log.Fatalf("failed to obtain a credential: %v", err)
}
ctx := context.Background()
client := armhanaonazure.NewSapMonitorsClient("<subscription-id>", cred, nil)
poller, err := client.BeginCreate(ctx,
"<resource-group-name>",
"<sap-monitor-name>",
armhanaonazure.SapMonitor{
Location: to.StringPtr("<location>"),
Tags: map[string]*string{
"key": to.StringPtr("value"),
},
Properties: &armhanaonazure.SapMonitorProperties{
EnableCustomerAnalytics: to.BoolPtr(true),
LogAnalyticsWorkspaceArmID: to.StringPtr("<log-analytics-workspace-arm-id>"),
LogAnalyticsWorkspaceID: to.StringPtr("<log-analytics-workspace-id>"),
LogAnalyticsWorkspaceSharedKey: to.StringPtr("<log-analytics-workspace-shared-key>"),
MonitorSubnet: to.StringPtr("<monitor-subnet>"),
},
},
nil)
if err != nil {
log.Fatal(err)
}
res, err := poller.PollUntilDone(ctx, 30*time.Second)
if err != nil {
log.Fatal(err)
}
log.Printf("Response result: %#v\n", res.SapMonitorsClientCreateResult)
}
// x-ms-original-file: specification/hanaonazure/resource-manager/Microsoft.HanaOnAzure/preview/2020-02-07-preview/examples/SapMonitors_Delete.json
func ExampleSapMonitorsClient_BeginDelete() {
cred, err := azidentity.NewDefaultAzureCredential(nil)
if err != nil {
log.Fatalf("failed to obtain a credential: %v", err)
}
ctx := context.Background()
client := armhanaonazure.NewSapMonitorsClient("<subscription-id>", cred, nil)
poller, err := client.BeginDelete(ctx,
"<resource-group-name>",
"<sap-monitor-name>",
nil)
if err != nil {
log.Fatal(err)
}
_, err = poller.PollUntilDone(ctx, 30*time.Second)
if err != nil {
log.Fatal(err)
}
}
// x-ms-original-file: specification/hanaonazure/resource-manager/Microsoft.HanaOnAzure/preview/2020-02-07-preview/examples/SapMonitors_PatchTags_Delete.json
func ExampleSapMonitorsClient_Update() {
cred, err := azidentity.NewDefaultAzureCredential(nil)
if err != nil {
log.Fatalf("failed to obtain a credential: %v", err)
}
ctx := context.Background()
client := armhanaonazure.NewSapMonitorsClient("<subscription-id>", cred, nil)
res, err := client.Update(ctx,
"<resource-group-name>",
"<sap-monitor-name>",
armhanaonazure.Tags{
Tags: map[string]*string{},
},
nil)
if err != nil {
log.Fatal(err)
}
log.Printf("Response result: %#v\n", res.SapMonitorsClientUpdateResult)
}
|
<?php
declare(strict_types = 1);
namespace Innmind\Neo4j\ONM\CommandBus;
use Innmind\Neo4j\ONM\Manager;
use Innmind\CommandBus\CommandBus;
final class Flush implements CommandBus
{
private CommandBus $handle;
private Manager $manager;
public function __construct(CommandBus $handle, Manager $manager)
{
$this->handle = $handle;
$this->manager = $manager;
}
public function __invoke(object $command): void
{
($this->handle)($command);
$this->manager->flush();
}
}
|
require 'active_support/security_utils'
require 'vendor/box'
require 'jeweler/client'
require 'jeweler/connection'
require 'jeweler/writeable'
require 'jeweler/resource'
require 'jeweler/singleton_resource'
require 'jeweler/finders'
require 'jeweler/collection'
require 'jeweler/errors'
require 'keyline/errors'
require 'keyline/event'
require 'keyline/resources/printery'
require 'keyline/resources/document_callback'
require 'keyline/resources/means_of_production'
require 'keyline/resources/user'
require 'keyline/resources/person'
require 'keyline/resources/organization'
require 'keyline/resources/address_announcement'
require 'keyline/resources/assignment'
require 'keyline/resources/business_unit'
require 'keyline/resources/carrier'
require 'keyline/resources/order'
require 'keyline/resources/print_data_file'
require 'keyline/resources/print_data_erratum'
require 'keyline/resources/product'
require 'keyline/resources/packaging'
require 'keyline/resources/pick'
require 'keyline/resources/address'
require 'keyline/resources/origin_address'
require 'keyline/resources/production_flow_modification'
require 'keyline/resources/production_path'
require 'keyline/resources/imposing'
require 'keyline/resources/master_signature'
require 'keyline/resources/signature'
require 'keyline/resources/component'
require 'keyline/resources/finishing'
require 'keyline/resources/finishing_property'
require 'keyline/resources/variant'
require 'keyline/resources/circulation'
require 'keyline/resources/substrate'
require 'keyline/resources/desired_substrate_properties'
require 'keyline/resources/material'
require 'keyline/resources/material_quote'
require 'keyline/resources/material_storage_area'
require 'keyline/resources/material_preset'
require 'keyline/resources/stock_finishing'
require 'keyline/resources/stock_substrate'
require 'keyline/resources/stock_color'
require 'keyline/resources/stock_folding_pattern'
require 'keyline/resources/stock_product'
require 'keyline/resources/shipment'
require 'keyline/resources/parcel'
require 'keyline/resources/stock_task'
require 'keyline/resources/raw_material_requirement'
require 'keyline/resources/processing_requirement'
require 'keyline/resources/task'
require 'keyline/resources/material_demand'
require 'keyline/resources/production/product'
require 'keyline/resources/production/print_data_file'
require 'keyline/resources/production/packaging'
require 'keyline/resources/production/selected_production_path'
require 'keyline/resources/production/component'
require 'keyline/resources/production/finishing'
require 'keyline/resources/production/finishing_property'
require 'keyline/resources/production/variant'
require 'keyline/resources/production/material_preset'
require 'keyline/resources/production/stock_finishing'
require 'keyline/resources/production/substrate'
require 'keyline/resources/production/imposing'
require 'keyline/resources/production/master_signature'
require 'keyline/resources/production/signature'
require 'keyline/resources/production/material_demand'
require 'keyline/resources/production/task'
require 'keyline/resources/production/task_execution'
require 'keyline/resources/production/means_of_production'
require 'keyline/resources/production/order'
require 'keyline/resources/production/customer'
require 'keyline/resources/production/sheet'
require 'keyline/resources/invoice'
require 'keyline/resources/customer_invoice'
require 'keyline/resources/credit_note'
require 'keyline/resources/reversal_invoice'
require 'keyline/resources/recipient'
require 'keyline/resources/contact'
require 'keyline/resources/line_item'
require 'keyline/resources/accounting_category'
require 'keyline/resources/payment_term'
module Keyline
class Client
include Jeweler::Client
base_collections :parcels, :orders, :organizations, :people, :materials, :material_storage_areas,
:stock_substrates, :stock_finishings, :stock_products, :stock_tasks, :stock_colors,
:stock_folding_patterns, :business_units, :invoices, :customer_invoices, :credit_notes,
:reversal_invoices, :users, :products
def initialize(options = {})
super(
host: options[:host],
token: options[:token],
base_uri: '/api/v2/',
timeout: options[:timeout] || 5,
open_timeout: options[:open_timeout] || 10
)
end
def printery
@printery ||= Keyline::Printery.new(self, self.perform_request(:get, '/configuration/printery')).tap do |printery|
printery.extend(Jeweler::SingletonResource)
end
end
def production_products
Jeweler::Collection.new(
self,
-> { self.perform_request(:get, Keyline::Production::Product.path_for_index(nil)) },
Keyline::Production::Product
)
end
def production_tasks
Jeweler::Collection.new(
self,
-> { self.perform_request(:get, Keyline::Production::Task.path_for_index(nil)) },
Keyline::Production::Task
)
end
def logistics_shipments
Jeweler::Collection.new(
self,
-> { self.perform_request(:get, Keyline::Logistics::Shipment.path_for_index(nil)) },
Keyline::Logistics::Shipment
)
end
end
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.