code
stringlengths 3
1.05M
| repo_name
stringlengths 4
116
| path
stringlengths 3
942
| language
stringclasses 30
values | license
stringclasses 15
values | size
int32 3
1.05M
|
---|---|---|---|---|---|
---
title: A Quarter Turn of a Single Screw
layout: post
category: Ramblings
tags: [Motorcycling, DIY]
---
My motorcycle had some difficulty handling, so much even that in the winter weather, I was actually uncomfortable riding it.
It is the middle of winter now and the weather is cold and harsh. If possible, I still ride. But slowly my Beemer had started to feel heavier. It took some more effort to steer it and when braking, it felt as if it first 'dove' before any actual deceleration.
On a particularly slippery Thursday morning I almost fell when the car in front of me suddenly wasn't only non-stationary, but uncomfortably so. All I could do, was move sideways. The icy road did the rest and I was forced to park my Beemer on its cilinder protector.
I thought that my front shock absorber was gone. There's no shame in that, since it is already 15 years old. Old stuff breaks, especially when regularly used. However, I remembered something from my repair manual: those clever Germans made my front shock absorber adjustable. So before going shopping, I decided to take a look first.
I removed the side fairing and inspected the front shock absorber. It appeared dusty and grimy, but intact. Right on the left side, there was a screw, possibly a M6. After a quarter turn, I reinstalled the fairing and I rode off to work.
Even in my experienced hands, my Beemer suddenly appeared to jump forward upon accelerating. It handled more easily and the steering reminded me of a razor blade again.
So much difference for a quarter turn of a single screw...
Bizarre.
| derjoachim/derjoachim_nl_v3 | _posts/2015-01-31-a-quarter-turn-of-a-single-screw.md | Markdown | mit | 1,578 |
ospurge: OpenStack project resources cleaner
============================================
`ospurge` is a standalone, client-side, Python script that aims at
deleting all resources (taking into account their interdependencies)
in a specified OpenStack project. OSPurge ensures in a quick and
automated way that no resource is left behind when a project is
deleted.
`ospurge` can be used by a cloud administrator (with the admin role)
to cleanup any project or by a non-privileged user to cleanup his own
project.
Installation
------------
Create a Python virtual environment (requires package virtualenvwrapper):
$ mkvirtualenv ospurge
Install `ospurge`:
$ pip install ospurge
The script is installed and can be launched:
$ ospurge -h
Usage
-----
Available options can be displayed by using `ospurge -h`:
$ ospurge -h
usage: ospurge [-h] [--verbose] [--dry-run] [--dont-delete-project]
[--region-name REGION_NAME] [--endpoint-type ENDPOINT_TYPE]
--username USERNAME --password PASSWORD --admin-project
ADMIN_PROJECT --auth-url AUTH_URL
[--cleanup-project CLEANUP_PROJECT] [--own-project]
[--insecure]
Purge resources from an Openstack project.
optional arguments:
-h, --help show this help message and exit
--verbose Makes output verbose
--dry-run List project's resources
--dont-delete-project
Executes cleanup script without removing the project.
Warning: all project resources will still be deleted.
--region-name REGION_NAME
Region to use. Defaults to env[OS_REGION_NAME] or None
--endpoint-type ENDPOINT_TYPE
Endpoint type to use. Defaults to
env[OS_ENDPOINT_TYPE] or publicURL
--username USERNAME If --own-project is set : a user name with access to
the project being purged. If --cleanup-project is set
: a user name with admin role in project specified in
--admin-project. Defaults to env[OS_USERNAME]
--password PASSWORD The user's password. Defaults to env[OS_PASSWORD].
--admin-project ADMIN_PROJECT
Project name used for authentication. This project
will be purged if --own-project is set. Defaults to
env[OS_TENANT_NAME].
--auth-url AUTH_URL Authentication URL. Defaults to env[OS_AUTH_URL].
--cleanup-project CLEANUP_PROJECT
ID or Name of project to purge. Not required if --own-
project has been set. Using --cleanup-project requires
to authenticate with admin credentials.
--own-project Delete resources of the project used to authenticate.
Useful if you don't have the admin credentials of the
platform.
--insecure Explicitly allow all OpenStack clients to perform
insecure SSL (https) requests. The server's
certificate will not be verified against any
certificate authorities. This option should be used
with caution.
Error codes
-----------
The following error codes are returned when `ospurge` encounters
an error:
* Code 2: Project doesn't exist
* Code 3: Authentication failed (e.g. Bad username or password)
* Code 4: Resource deletion failed
* Code 5: Connection error while deleting a resource (e.g. Service not available)
* Code 6: Connection to endpoint failed (e.g. authentication url)
* Code 1: Unknown error
* Code 0: Process exited sucessfully
Example
-------
To remove a project, credentials have to be
provided. The usual OpenStack environment variables can be used. When
launching the `ospurge` script, the project to be cleaned up has
to be provided, by using either the `--cleanup-project` option or the
`--own-project` option. When the command returns, any resources associated
to the project will have been definitively deleted.
Setting OpenStack credentials:
$ export OS_USERNAME=admin
$ export OS_PASSWORD=password
$ export OS_TENANT_NAME=admin
$ export OS_AUTH_URL=http://localhost:5000/v2.0
Checking resources of the target project:
$ ./ospurge --dry-run --cleanup-project florent-demo
* Resources type: CinderSnapshots
* Resources type: NovaServers
server vm0 (id 8b0896d9-bcf3-4360-824a-a81865ad2385)
* Resources type: NeutronFloatingIps
* Resources type: NeutronInterfaces
* Resources type: NeutronRouters
* Resources type: NeutronNetworks
* Resources type: NeutronSecgroups
security group custom (id 8c13e635-6fdc-4332-ba19-c22a7a85c7cc)
* Resources type: GlanceImages
* Resources type: SwiftObjects
* Resources type: SwiftContainers
* Resources type: CinderVolumes
volume vol0 (id ce1380ef-2d66-47a2-9dbf-8dd5d9cd506d)
* Resources type: CeilometerAlarms
Removing resources without deleting the project:
$ ./ospurge --verbose --dont-delete-project --cleanup-project florent-demo
INFO:requests.packages.urllib3.connectionpool:Starting new HTTP connection (1): keystone.usr.lab0.aub.cw-labs.net
INFO:root:* Granting role admin to user e7f562a29da3492baba2cc7c5a1f2d84 on project florent-demo.
INFO:requests.packages.urllib3.connectionpool:Starting new HTTP connection (1): keystone-admin.usr.lab0.aub.cw-labs.net
INFO:requests.packages.urllib3.connectionpool:Starting new HTTP connection (1): keystone-admin.usr.lab0.aub.cw-labs.net
INFO:requests.packages.urllib3.connectionpool:Starting new HTTP connection (1): keystone-admin.usr.lab0.aub.cw-labs.net
INFO:requests.packages.urllib3.connectionpool:Starting new HTTP connection (1): keystone.usr.lab0.aub.cw-labs.net
INFO:root:* Purging CinderSnapshots
INFO:requests.packages.urllib3.connectionpool:Starting new HTTP connection (1): keystone.usr.lab0.aub.cw-labs.net
INFO:requests.packages.urllib3.connectionpool:Starting new HTTP connection (1): cinder.usr.lab0.aub.cw-labs.net
INFO:root:* Purging NovaServers
INFO:requests.packages.urllib3.connectionpool:Starting new HTTP connection (1): keystone.usr.lab0.aub.cw-labs.net
INFO:requests.packages.urllib3.connectionpool:Starting new HTTP connection (1): nova.usr.lab0.aub.cw-labs.net
INFO:root:* Deleting server vm0 (id 8b0896d9-bcf3-4360-824a-a81865ad2385).
INFO:root:* Purging NeutronFloatingIps
INFO:root:* Purging NeutronInterfaces
INFO:root:* Purging NeutronRouters
INFO:root:* Purging NeutronNetworks
INFO:root:* Purging NeutronSecgroups
INFO:root:* Deleting security group custom (id 8c13e635-6fdc-4332-ba19-c22a7a85c7cc).
INFO:root:* Purging GlanceImages
INFO:root:* Purging SwiftObjects
INFO:root:* Purging SwiftContainers
INFO:root:* Purging CinderVolumes
INFO:requests.packages.urllib3.connectionpool:Starting new HTTP connection (1): keystone.usr.lab0.aub.cw-labs.net
INFO:requests.packages.urllib3.connectionpool:Starting new HTTP connection (1): cinder.usr.lab0.aub.cw-labs.net
INFO:root:* Deleting volume vol0 (id ce1380ef-2d66-47a2-9dbf-8dd5d9cd506d).
INFO:requests.packages.urllib3.connectionpool:Starting new HTTP connection (1): cinder.usr.lab0.aub.cw-labs.net
INFO:root:* Purging CeilometerAlarms
Checking that resources have been correctly removed:
$ ./ospurge --dry-run --cleanup-project florent-demo
* Resources type: CinderSnapshots
* Resources type: NovaServers
* Resources type: NeutronFloatingIps
* Resources type: NeutronInterfaces
* Resources type: NeutronRouters
* Resources type: NeutronNetworks
* Resources type: NeutronSecgroups
* Resources type: GlanceImages
* Resources type: SwiftObjects
* Resources type: SwiftContainers
* Resources type: CinderVolumes
* Resources type: CeilometerAlarms
Removing project:
$ ./ospurge --cleanup-project florent-demo
$ ./ospurge --cleanup-project florent-demo
Project florent-demo doesn't exist
Deleted resources
-----------------
The following resources will be removed:
* ceilometer alarms
* floating IPs
* images / snapshots
* instances
* networks
* routers
* security groups
* swift containers
* swift objects
* volumes / snapshots
Notes
-----
Users can be deleted by using the `python-keystoneclient` CLI:
$ keystone user-delete <username_or_userid>
How to contribute
-----------------
Ospurge is hosted on Stackforge and is using Gerrit to manage
contributions. You can contribute to the project by following the
following workflow: https://wiki.openstack.org/wiki/Gerrit_Workflow
License / Copyright
-------------------
This software is released under the MIT License.
Copyright (c) 2014 Cloudwatt
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.
| FlorentFlament/ospurge-packaging | README.md | Markdown | mit | 10,098 |
from inspect import getsource
from utils import argmax, argmin
from games import TicTacToe, alphabeta_player, random_player, Fig52Extended, infinity
from logic import parse_definite_clause, standardize_variables, unify, subst
from learning import DataSet
from IPython.display import HTML, display
from collections import Counter, defaultdict
import matplotlib.pyplot as plt
import numpy as np
import os, struct
import array
import time
#______________________________________________________________________________
# Magic Words
def pseudocode(algorithm):
"""Print the pseudocode for the given algorithm."""
from urllib.request import urlopen
from IPython.display import Markdown
algorithm = algorithm.replace(' ', '-')
url = "https://raw.githubusercontent.com/aimacode/aima-pseudocode/master/md/{}.md".format(algorithm)
f = urlopen(url)
md = f.read().decode('utf-8')
md = md.split('\n', 1)[-1].strip()
md = '#' + md
return Markdown(md)
def psource(*functions):
"""Print the source code for the given function(s)."""
source_code = '\n\n'.join(getsource(fn) for fn in functions)
try:
from pygments.formatters import HtmlFormatter
from pygments.lexers import PythonLexer
from pygments import highlight
display(HTML(highlight(source_code, PythonLexer(), HtmlFormatter(full=True))))
except ImportError:
print(source_code)
# ______________________________________________________________________________
# Iris Visualization
def show_iris(i=0, j=1, k=2):
"""Plots the iris dataset in a 3D plot.
The three axes are given by i, j and k,
which correspond to three of the four iris features."""
from mpl_toolkits.mplot3d import Axes3D
plt.rcParams.update(plt.rcParamsDefault)
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
iris = DataSet(name="iris")
buckets = iris.split_values_by_classes()
features = ["Sepal Length", "Sepal Width", "Petal Length", "Petal Width"]
f1, f2, f3 = features[i], features[j], features[k]
a_setosa = [v[i] for v in buckets["setosa"]]
b_setosa = [v[j] for v in buckets["setosa"]]
c_setosa = [v[k] for v in buckets["setosa"]]
a_virginica = [v[i] for v in buckets["virginica"]]
b_virginica = [v[j] for v in buckets["virginica"]]
c_virginica = [v[k] for v in buckets["virginica"]]
a_versicolor = [v[i] for v in buckets["versicolor"]]
b_versicolor = [v[j] for v in buckets["versicolor"]]
c_versicolor = [v[k] for v in buckets["versicolor"]]
for c, m, sl, sw, pl in [('b', 's', a_setosa, b_setosa, c_setosa),
('g', '^', a_virginica, b_virginica, c_virginica),
('r', 'o', a_versicolor, b_versicolor, c_versicolor)]:
ax.scatter(sl, sw, pl, c=c, marker=m)
ax.set_xlabel(f1)
ax.set_ylabel(f2)
ax.set_zlabel(f3)
plt.show()
# ______________________________________________________________________________
# MNIST
def load_MNIST(path="aima-data/MNIST/Digits", fashion=False):
import os, struct
import array
import numpy as np
from collections import Counter
if fashion:
path = "aima-data/MNIST/Fashion"
plt.rcParams.update(plt.rcParamsDefault)
plt.rcParams['figure.figsize'] = (10.0, 8.0)
plt.rcParams['image.interpolation'] = 'nearest'
plt.rcParams['image.cmap'] = 'gray'
train_img_file = open(os.path.join(path, "train-images-idx3-ubyte"), "rb")
train_lbl_file = open(os.path.join(path, "train-labels-idx1-ubyte"), "rb")
test_img_file = open(os.path.join(path, "t10k-images-idx3-ubyte"), "rb")
test_lbl_file = open(os.path.join(path, 't10k-labels-idx1-ubyte'), "rb")
magic_nr, tr_size, tr_rows, tr_cols = struct.unpack(">IIII", train_img_file.read(16))
tr_img = array.array("B", train_img_file.read())
train_img_file.close()
magic_nr, tr_size = struct.unpack(">II", train_lbl_file.read(8))
tr_lbl = array.array("b", train_lbl_file.read())
train_lbl_file.close()
magic_nr, te_size, te_rows, te_cols = struct.unpack(">IIII", test_img_file.read(16))
te_img = array.array("B", test_img_file.read())
test_img_file.close()
magic_nr, te_size = struct.unpack(">II", test_lbl_file.read(8))
te_lbl = array.array("b", test_lbl_file.read())
test_lbl_file.close()
#print(len(tr_img), len(tr_lbl), tr_size)
#print(len(te_img), len(te_lbl), te_size)
train_img = np.zeros((tr_size, tr_rows*tr_cols), dtype=np.int16)
train_lbl = np.zeros((tr_size,), dtype=np.int8)
for i in range(tr_size):
train_img[i] = np.array(tr_img[i*tr_rows*tr_cols : (i+1)*tr_rows*tr_cols]).reshape((tr_rows*te_cols))
train_lbl[i] = tr_lbl[i]
test_img = np.zeros((te_size, te_rows*te_cols), dtype=np.int16)
test_lbl = np.zeros((te_size,), dtype=np.int8)
for i in range(te_size):
test_img[i] = np.array(te_img[i*te_rows*te_cols : (i+1)*te_rows*te_cols]).reshape((te_rows*te_cols))
test_lbl[i] = te_lbl[i]
return(train_img, train_lbl, test_img, test_lbl)
digit_classes = [str(i) for i in range(10)]
fashion_classes = ["T-shirt/top", "Trouser", "Pullover", "Dress", "Coat",
"Sandal", "Shirt", "Sneaker", "Bag", "Ankle boot"]
def show_MNIST(labels, images, samples=8, fashion=False):
if not fashion:
classes = digit_classes
else:
classes = fashion_classes
num_classes = len(classes)
for y, cls in enumerate(classes):
idxs = np.nonzero([i == y for i in labels])
idxs = np.random.choice(idxs[0], samples, replace=False)
for i , idx in enumerate(idxs):
plt_idx = i * num_classes + y + 1
plt.subplot(samples, num_classes, plt_idx)
plt.imshow(images[idx].reshape((28, 28)))
plt.axis("off")
if i == 0:
plt.title(cls)
plt.show()
def show_ave_MNIST(labels, images, fashion=False):
if not fashion:
item_type = "Digit"
classes = digit_classes
else:
item_type = "Apparel"
classes = fashion_classes
num_classes = len(classes)
for y, cls in enumerate(classes):
idxs = np.nonzero([i == y for i in labels])
print(item_type, y, ":", len(idxs[0]), "images.")
ave_img = np.mean(np.vstack([images[i] for i in idxs[0]]), axis = 0)
#print(ave_img.shape)
plt.subplot(1, num_classes, y+1)
plt.imshow(ave_img.reshape((28, 28)))
plt.axis("off")
plt.title(cls)
plt.show()
# ______________________________________________________________________________
# MDP
def make_plot_grid_step_function(columns, rows, U_over_time):
"""ipywidgets interactive function supports single parameter as input.
This function creates and return such a function by taking as input
other parameters."""
def plot_grid_step(iteration):
data = U_over_time[iteration]
data = defaultdict(lambda: 0, data)
grid = []
for row in range(rows):
current_row = []
for column in range(columns):
current_row.append(data[(column, row)])
grid.append(current_row)
grid.reverse() # output like book
fig = plt.imshow(grid, cmap=plt.cm.bwr, interpolation='nearest')
plt.axis('off')
fig.axes.get_xaxis().set_visible(False)
fig.axes.get_yaxis().set_visible(False)
for col in range(len(grid)):
for row in range(len(grid[0])):
magic = grid[col][row]
fig.axes.text(row, col, "{0:.2f}".format(magic), va='center', ha='center')
plt.show()
return plot_grid_step
def make_visualize(slider):
"""Takes an input a sliderand returns callback function
for timer and animation."""
def visualize_callback(Visualize, time_step):
if Visualize is True:
for i in range(slider.min, slider.max + 1):
slider.value = i
time.sleep(float(time_step))
return visualize_callback
# ______________________________________________________________________________
_canvas = """
<script type="text/javascript" src="./js/canvas.js"></script>
<div>
<canvas id="{0}" width="{1}" height="{2}" style="background:rgba(158, 167, 184, 0.2);" onclick='click_callback(this, event, "{3}")'></canvas>
</div>
<script> var {0}_canvas_object = new Canvas("{0}");</script>
""" # noqa
class Canvas:
"""Inherit from this class to manage the HTML canvas element in jupyter notebooks.
To create an object of this class any_name_xyz = Canvas("any_name_xyz")
The first argument given must be the name of the object being created.
IPython must be able to refernce the variable name that is being passed."""
def __init__(self, varname, width=800, height=600, cid=None):
self.name = varname
self.cid = cid or varname
self.width = width
self.height = height
self.html = _canvas.format(self.cid, self.width, self.height, self.name)
self.exec_list = []
display_html(self.html)
def mouse_click(self, x, y):
"""Override this method to handle mouse click at position (x, y)"""
raise NotImplementedError
def mouse_move(self, x, y):
raise NotImplementedError
def execute(self, exec_str):
"""Stores the command to be exectued to a list which is used later during update()"""
if not isinstance(exec_str, str):
print("Invalid execution argument:", exec_str)
self.alert("Recieved invalid execution command format")
prefix = "{0}_canvas_object.".format(self.cid)
self.exec_list.append(prefix + exec_str + ';')
def fill(self, r, g, b):
"""Changes the fill color to a color in rgb format"""
self.execute("fill({0}, {1}, {2})".format(r, g, b))
def stroke(self, r, g, b):
"""Changes the colors of line/strokes to rgb"""
self.execute("stroke({0}, {1}, {2})".format(r, g, b))
def strokeWidth(self, w):
"""Changes the width of lines/strokes to 'w' pixels"""
self.execute("strokeWidth({0})".format(w))
def rect(self, x, y, w, h):
"""Draw a rectangle with 'w' width, 'h' height and (x, y) as the top-left corner"""
self.execute("rect({0}, {1}, {2}, {3})".format(x, y, w, h))
def rect_n(self, xn, yn, wn, hn):
"""Similar to rect(), but the dimensions are normalized to fall between 0 and 1"""
x = round(xn * self.width)
y = round(yn * self.height)
w = round(wn * self.width)
h = round(hn * self.height)
self.rect(x, y, w, h)
def line(self, x1, y1, x2, y2):
"""Draw a line from (x1, y1) to (x2, y2)"""
self.execute("line({0}, {1}, {2}, {3})".format(x1, y1, x2, y2))
def line_n(self, x1n, y1n, x2n, y2n):
"""Similar to line(), but the dimensions are normalized to fall between 0 and 1"""
x1 = round(x1n * self.width)
y1 = round(y1n * self.height)
x2 = round(x2n * self.width)
y2 = round(y2n * self.height)
self.line(x1, y1, x2, y2)
def arc(self, x, y, r, start, stop):
"""Draw an arc with (x, y) as centre, 'r' as radius from angles 'start' to 'stop'"""
self.execute("arc({0}, {1}, {2}, {3}, {4})".format(x, y, r, start, stop))
def arc_n(self, xn, yn, rn, start, stop):
"""Similar to arc(), but the dimensions are normalized to fall between 0 and 1
The normalizing factor for radius is selected between width and height by
seeing which is smaller."""
x = round(xn * self.width)
y = round(yn * self.height)
r = round(rn * min(self.width, self.height))
self.arc(x, y, r, start, stop)
def clear(self):
"""Clear the HTML canvas"""
self.execute("clear()")
def font(self, font):
"""Changes the font of text"""
self.execute('font("{0}")'.format(font))
def text(self, txt, x, y, fill=True):
"""Display a text at (x, y)"""
if fill:
self.execute('fill_text("{0}", {1}, {2})'.format(txt, x, y))
else:
self.execute('stroke_text("{0}", {1}, {2})'.format(txt, x, y))
def text_n(self, txt, xn, yn, fill=True):
"""Similar to text(), but with normalized coordinates"""
x = round(xn * self.width)
y = round(yn * self.height)
self.text(txt, x, y, fill)
def alert(self, message):
"""Immediately display an alert"""
display_html('<script>alert("{0}")</script>'.format(message))
def update(self):
"""Execute the JS code to execute the commands queued by execute()"""
exec_code = "<script>\n" + '\n'.join(self.exec_list) + "\n</script>"
self.exec_list = []
display_html(exec_code)
def display_html(html_string):
display(HTML(html_string))
################################################################################
class Canvas_TicTacToe(Canvas):
"""Play a 3x3 TicTacToe game on HTML canvas"""
def __init__(self, varname, player_1='human', player_2='random',
width=300, height=350, cid=None):
valid_players = ('human', 'random', 'alphabeta')
if player_1 not in valid_players or player_2 not in valid_players:
raise TypeError("Players must be one of {}".format(valid_players))
Canvas.__init__(self, varname, width, height, cid)
self.ttt = TicTacToe()
self.state = self.ttt.initial
self.turn = 0
self.strokeWidth(5)
self.players = (player_1, player_2)
self.font("20px Arial")
self.draw_board()
def mouse_click(self, x, y):
player = self.players[self.turn]
if self.ttt.terminal_test(self.state):
if 0.55 <= x/self.width <= 0.95 and 6/7 <= y/self.height <= 6/7+1/8:
self.state = self.ttt.initial
self.turn = 0
self.draw_board()
return
if player == 'human':
x, y = int(3*x/self.width) + 1, int(3*y/(self.height*6/7)) + 1
if (x, y) not in self.ttt.actions(self.state):
# Invalid move
return
move = (x, y)
elif player == 'alphabeta':
move = alphabeta_player(self.ttt, self.state)
else:
move = random_player(self.ttt, self.state)
self.state = self.ttt.result(self.state, move)
self.turn ^= 1
self.draw_board()
def draw_board(self):
self.clear()
self.stroke(0, 0, 0)
offset = 1/20
self.line_n(0 + offset, (1/3)*6/7, 1 - offset, (1/3)*6/7)
self.line_n(0 + offset, (2/3)*6/7, 1 - offset, (2/3)*6/7)
self.line_n(1/3, (0 + offset)*6/7, 1/3, (1 - offset)*6/7)
self.line_n(2/3, (0 + offset)*6/7, 2/3, (1 - offset)*6/7)
board = self.state.board
for mark in board:
if board[mark] == 'X':
self.draw_x(mark)
elif board[mark] == 'O':
self.draw_o(mark)
if self.ttt.terminal_test(self.state):
# End game message
utility = self.ttt.utility(self.state, self.ttt.to_move(self.ttt.initial))
if utility == 0:
self.text_n('Game Draw!', offset, 6/7 + offset)
else:
self.text_n('Player {} wins!'.format("XO"[utility < 0]), offset, 6/7 + offset)
# Find the 3 and draw a line
self.stroke([255, 0][self.turn], [0, 255][self.turn], 0)
for i in range(3):
if all([(i + 1, j + 1) in self.state.board for j in range(3)]) and \
len({self.state.board[(i + 1, j + 1)] for j in range(3)}) == 1:
self.line_n(i/3 + 1/6, offset*6/7, i/3 + 1/6, (1 - offset)*6/7)
if all([(j + 1, i + 1) in self.state.board for j in range(3)]) and \
len({self.state.board[(j + 1, i + 1)] for j in range(3)}) == 1:
self.line_n(offset, (i/3 + 1/6)*6/7, 1 - offset, (i/3 + 1/6)*6/7)
if all([(i + 1, i + 1) in self.state.board for i in range(3)]) and \
len({self.state.board[(i + 1, i + 1)] for i in range(3)}) == 1:
self.line_n(offset, offset*6/7, 1 - offset, (1 - offset)*6/7)
if all([(i + 1, 3 - i) in self.state.board for i in range(3)]) and \
len({self.state.board[(i + 1, 3 - i)] for i in range(3)}) == 1:
self.line_n(offset, (1 - offset)*6/7, 1 - offset, offset*6/7)
# restart button
self.fill(0, 0, 255)
self.rect_n(0.5 + offset, 6/7, 0.4, 1/8)
self.fill(0, 0, 0)
self.text_n('Restart', 0.5 + 2*offset, 13/14)
else: # Print which player's turn it is
self.text_n("Player {}'s move({})".format("XO"[self.turn], self.players[self.turn]),
offset, 6/7 + offset)
self.update()
def draw_x(self, position):
self.stroke(0, 255, 0)
x, y = [i-1 for i in position]
offset = 1/15
self.line_n(x/3 + offset, (y/3 + offset)*6/7, x/3 + 1/3 - offset, (y/3 + 1/3 - offset)*6/7)
self.line_n(x/3 + 1/3 - offset, (y/3 + offset)*6/7, x/3 + offset, (y/3 + 1/3 - offset)*6/7)
def draw_o(self, position):
self.stroke(255, 0, 0)
x, y = [i-1 for i in position]
self.arc_n(x/3 + 1/6, (y/3 + 1/6)*6/7, 1/9, 0, 360)
class Canvas_minimax(Canvas):
"""Minimax for Fig52Extended on HTML canvas"""
def __init__(self, varname, util_list, width=800, height=600, cid=None):
Canvas.__init__(self, varname, width, height, cid)
self.utils = {node:util for node, util in zip(range(13, 40), util_list)}
self.game = Fig52Extended()
self.game.utils = self.utils
self.nodes = list(range(40))
self.l = 1/40
self.node_pos = {}
for i in range(4):
base = len(self.node_pos)
row_size = 3**i
for node in [base + j for j in range(row_size)]:
self.node_pos[node] = ((node - base)/row_size + 1/(2*row_size) - self.l/2,
self.l/2 + (self.l + (1 - 5*self.l)/3)*i)
self.font("12px Arial")
self.node_stack = []
self.explored = {node for node in self.utils}
self.thick_lines = set()
self.change_list = []
self.draw_graph()
self.stack_manager = self.stack_manager_gen()
def minimax(self, node):
game = self.game
player = game.to_move(node)
def max_value(node):
if game.terminal_test(node):
return game.utility(node, player)
self.change_list.append(('a', node))
self.change_list.append(('h',))
max_a = argmax(game.actions(node), key=lambda x: min_value(game.result(node, x)))
max_node = game.result(node, max_a)
self.utils[node] = self.utils[max_node]
x1, y1 = self.node_pos[node]
x2, y2 = self.node_pos[max_node]
self.change_list.append(('l', (node, max_node - 3*node - 1)))
self.change_list.append(('e', node))
self.change_list.append(('p',))
self.change_list.append(('h',))
return self.utils[node]
def min_value(node):
if game.terminal_test(node):
return game.utility(node, player)
self.change_list.append(('a', node))
self.change_list.append(('h',))
min_a = argmin(game.actions(node), key=lambda x: max_value(game.result(node, x)))
min_node = game.result(node, min_a)
self.utils[node] = self.utils[min_node]
x1, y1 = self.node_pos[node]
x2, y2 = self.node_pos[min_node]
self.change_list.append(('l', (node, min_node - 3*node - 1)))
self.change_list.append(('e', node))
self.change_list.append(('p',))
self.change_list.append(('h',))
return self.utils[node]
return max_value(node)
def stack_manager_gen(self):
self.minimax(0)
for change in self.change_list:
if change[0] == 'a':
self.node_stack.append(change[1])
elif change[0] == 'e':
self.explored.add(change[1])
elif change[0] == 'h':
yield
elif change[0] == 'l':
self.thick_lines.add(change[1])
elif change[0] == 'p':
self.node_stack.pop()
def mouse_click(self, x, y):
try:
self.stack_manager.send(None)
except StopIteration:
pass
self.draw_graph()
def draw_graph(self):
self.clear()
# draw nodes
self.stroke(0, 0, 0)
self.strokeWidth(1)
# highlight for nodes in stack
for node in self.node_stack:
x, y = self.node_pos[node]
self.fill(200, 200, 0)
self.rect_n(x - self.l/5, y - self.l/5, self.l*7/5, self.l*7/5)
for node in self.nodes:
x, y = self.node_pos[node]
if node in self.explored:
self.fill(255, 255, 255)
else:
self.fill(200, 200, 200)
self.rect_n(x, y, self.l, self.l)
self.line_n(x, y, x + self.l, y)
self.line_n(x, y, x, y + self.l)
self.line_n(x + self.l, y + self.l, x + self.l, y)
self.line_n(x + self.l, y + self.l, x, y + self.l)
self.fill(0, 0, 0)
if node in self.explored:
self.text_n(self.utils[node], x + self.l/10, y + self.l*9/10)
# draw edges
for i in range(13):
x1, y1 = self.node_pos[i][0] + self.l/2, self.node_pos[i][1] + self.l
for j in range(3):
x2, y2 = self.node_pos[i*3 + j + 1][0] + self.l/2, self.node_pos[i*3 + j + 1][1]
if i in [1, 2, 3]:
self.stroke(200, 0, 0)
else:
self.stroke(0, 200, 0)
if (i, j) in self.thick_lines:
self.strokeWidth(3)
else:
self.strokeWidth(1)
self.line_n(x1, y1, x2, y2)
self.update()
class Canvas_alphabeta(Canvas):
"""Alpha-beta pruning for Fig52Extended on HTML canvas"""
def __init__(self, varname, util_list, width=800, height=600, cid=None):
Canvas.__init__(self, varname, width, height, cid)
self.utils = {node:util for node, util in zip(range(13, 40), util_list)}
self.game = Fig52Extended()
self.game.utils = self.utils
self.nodes = list(range(40))
self.l = 1/40
self.node_pos = {}
for i in range(4):
base = len(self.node_pos)
row_size = 3**i
for node in [base + j for j in range(row_size)]:
self.node_pos[node] = ((node - base)/row_size + 1/(2*row_size) - self.l/2,
3*self.l/2 + (self.l + (1 - 6*self.l)/3)*i)
self.font("12px Arial")
self.node_stack = []
self.explored = {node for node in self.utils}
self.pruned = set()
self.ab = {}
self.thick_lines = set()
self.change_list = []
self.draw_graph()
self.stack_manager = self.stack_manager_gen()
def alphabeta_search(self, node):
game = self.game
player = game.to_move(node)
# Functions used by alphabeta
def max_value(node, alpha, beta):
if game.terminal_test(node):
self.change_list.append(('a', node))
self.change_list.append(('h',))
self.change_list.append(('p',))
return game.utility(node, player)
v = -infinity
self.change_list.append(('a', node))
self.change_list.append(('ab',node, v, beta))
self.change_list.append(('h',))
for a in game.actions(node):
min_val = min_value(game.result(node, a), alpha, beta)
if v < min_val:
v = min_val
max_node = game.result(node, a)
self.change_list.append(('ab',node, v, beta))
if v >= beta:
self.change_list.append(('h',))
self.pruned.add(node)
break
alpha = max(alpha, v)
self.utils[node] = v
if node not in self.pruned:
self.change_list.append(('l', (node, max_node - 3*node - 1)))
self.change_list.append(('e',node))
self.change_list.append(('p',))
self.change_list.append(('h',))
return v
def min_value(node, alpha, beta):
if game.terminal_test(node):
self.change_list.append(('a', node))
self.change_list.append(('h',))
self.change_list.append(('p',))
return game.utility(node, player)
v = infinity
self.change_list.append(('a', node))
self.change_list.append(('ab',node, alpha, v))
self.change_list.append(('h',))
for a in game.actions(node):
max_val = max_value(game.result(node, a), alpha, beta)
if v > max_val:
v = max_val
min_node = game.result(node, a)
self.change_list.append(('ab',node, alpha, v))
if v <= alpha:
self.change_list.append(('h',))
self.pruned.add(node)
break
beta = min(beta, v)
self.utils[node] = v
if node not in self.pruned:
self.change_list.append(('l', (node, min_node - 3*node - 1)))
self.change_list.append(('e',node))
self.change_list.append(('p',))
self.change_list.append(('h',))
return v
return max_value(node, -infinity, infinity)
def stack_manager_gen(self):
self.alphabeta_search(0)
for change in self.change_list:
if change[0] == 'a':
self.node_stack.append(change[1])
elif change[0] == 'ab':
self.ab[change[1]] = change[2:]
elif change[0] == 'e':
self.explored.add(change[1])
elif change[0] == 'h':
yield
elif change[0] == 'l':
self.thick_lines.add(change[1])
elif change[0] == 'p':
self.node_stack.pop()
def mouse_click(self, x, y):
try:
self.stack_manager.send(None)
except StopIteration:
pass
self.draw_graph()
def draw_graph(self):
self.clear()
# draw nodes
self.stroke(0, 0, 0)
self.strokeWidth(1)
# highlight for nodes in stack
for node in self.node_stack:
x, y = self.node_pos[node]
# alpha > beta
if node not in self.explored and self.ab[node][0] > self.ab[node][1]:
self.fill(200, 100, 100)
else:
self.fill(200, 200, 0)
self.rect_n(x - self.l/5, y - self.l/5, self.l*7/5, self.l*7/5)
for node in self.nodes:
x, y = self.node_pos[node]
if node in self.explored:
if node in self.pruned:
self.fill(50, 50, 50)
else:
self.fill(255, 255, 255)
else:
self.fill(200, 200, 200)
self.rect_n(x, y, self.l, self.l)
self.line_n(x, y, x + self.l, y)
self.line_n(x, y, x, y + self.l)
self.line_n(x + self.l, y + self.l, x + self.l, y)
self.line_n(x + self.l, y + self.l, x, y + self.l)
self.fill(0, 0, 0)
if node in self.explored and node not in self.pruned:
self.text_n(self.utils[node], x + self.l/10, y + self.l*9/10)
# draw edges
for i in range(13):
x1, y1 = self.node_pos[i][0] + self.l/2, self.node_pos[i][1] + self.l
for j in range(3):
x2, y2 = self.node_pos[i*3 + j + 1][0] + self.l/2, self.node_pos[i*3 + j + 1][1]
if i in [1, 2, 3]:
self.stroke(200, 0, 0)
else:
self.stroke(0, 200, 0)
if (i, j) in self.thick_lines:
self.strokeWidth(3)
else:
self.strokeWidth(1)
self.line_n(x1, y1, x2, y2)
# display alpha and beta
for node in self.node_stack:
if node not in self.explored:
x, y = self.node_pos[node]
alpha, beta = self.ab[node]
self.text_n(alpha, x - self.l/2, y - self.l/10)
self.text_n(beta, x + self.l, y - self.l/10)
self.update()
class Canvas_fol_bc_ask(Canvas):
"""fol_bc_ask() on HTML canvas"""
def __init__(self, varname, kb, query, width=800, height=600, cid=None):
Canvas.__init__(self, varname, width, height, cid)
self.kb = kb
self.query = query
self.l = 1/20
self.b = 3*self.l
bc_out = list(self.fol_bc_ask())
if len(bc_out) is 0:
self.valid = False
else:
self.valid = True
graph = bc_out[0][0][0]
s = bc_out[0][1]
while True:
new_graph = subst(s, graph)
if graph == new_graph:
break
graph = new_graph
self.make_table(graph)
self.context = None
self.draw_table()
def fol_bc_ask(self):
KB = self.kb
query = self.query
def fol_bc_or(KB, goal, theta):
for rule in KB.fetch_rules_for_goal(goal):
lhs, rhs = parse_definite_clause(standardize_variables(rule))
for theta1 in fol_bc_and(KB, lhs, unify(rhs, goal, theta)):
yield ([(goal, theta1[0])], theta1[1])
def fol_bc_and(KB, goals, theta):
if theta is None:
pass
elif not goals:
yield ([], theta)
else:
first, rest = goals[0], goals[1:]
for theta1 in fol_bc_or(KB, subst(theta, first), theta):
for theta2 in fol_bc_and(KB, rest, theta1[1]):
yield (theta1[0] + theta2[0], theta2[1])
return fol_bc_or(KB, query, {})
def make_table(self, graph):
table = []
pos = {}
links = set()
edges = set()
def dfs(node, depth):
if len(table) <= depth:
table.append([])
pos = len(table[depth])
table[depth].append(node[0])
for child in node[1]:
child_id = dfs(child, depth + 1)
links.add(((depth, pos), child_id))
return (depth, pos)
dfs(graph, 0)
y_off = 0.85/len(table)
for i, row in enumerate(table):
x_off = 0.95/len(row)
for j, node in enumerate(row):
pos[(i, j)] = (0.025 + j*x_off + (x_off - self.b)/2, 0.025 + i*y_off + (y_off - self.l)/2)
for p, c in links:
x1, y1 = pos[p]
x2, y2 = pos[c]
edges.add((x1 + self.b/2, y1 + self.l, x2 + self.b/2, y2))
self.table = table
self.pos = pos
self.edges = edges
def mouse_click(self, x, y):
x, y = x/self.width, y/self.height
for node in self.pos:
xs, ys = self.pos[node]
xe, ye = xs + self.b, ys + self.l
if xs <= x <= xe and ys <= y <= ye:
self.context = node
break
self.draw_table()
def draw_table(self):
self.clear()
self.strokeWidth(3)
self.stroke(0, 0, 0)
self.font("12px Arial")
if self.valid:
# draw nodes
for i, j in self.pos:
x, y = self.pos[(i, j)]
self.fill(200, 200, 200)
self.rect_n(x, y, self.b, self.l)
self.line_n(x, y, x + self.b, y)
self.line_n(x, y, x, y + self.l)
self.line_n(x + self.b, y, x + self.b, y + self.l)
self.line_n(x, y + self.l, x + self.b, y + self.l)
self.fill(0, 0, 0)
self.text_n(self.table[i][j], x + 0.01, y + self.l - 0.01)
#draw edges
for x1, y1, x2, y2 in self.edges:
self.line_n(x1, y1, x2, y2)
else:
self.fill(255, 0, 0)
self.rect_n(0, 0, 1, 1)
# text area
self.fill(255, 255, 255)
self.rect_n(0, 0.9, 1, 0.1)
self.strokeWidth(5)
self.stroke(0, 0, 0)
self.line_n(0, 0.9, 1, 0.9)
self.font("22px Arial")
self.fill(0, 0, 0)
self.text_n(self.table[self.context[0]][self.context[1]] if self.context else "Click for text", 0.025, 0.975)
self.update()
| SnShine/aima-python | notebook.py | Python | mit | 33,410 |
(function () {
var app = angular.module('store', ['ngMaterial', 'store-products']);
app.controller('StoreController', ['$http', function ($http) {
var storeController = this;
storeController.products = [];
$http({
method: 'GET',
url: './products.json'
})
.success(function (result) {
storeController.products = result;
});
}]);
app.controller('CardController', function () {
this.tab = 1;
this.selectTab = function (setTab) {
this.tab = setTab;
};
this.isSelected = function (checkTab) {
return this.tab === checkTab;
};
this.range = function (count) {
var ratings = [];
for (var i = 0; i < count; i++) {
ratings.push(i)
}
return ratings;
};
});
app.controller('ReviewController', function () {
this.reviewN = {};
this.addReview = function (product) {
var reviewCopy = JSON.parse(JSON.stringify(this.reviewN));
this.reviewN = {};
reviewCopy.stars = countToArray(reviewCopy.stars);
product.reviews.push(reviewCopy);
};
function countToArray(count) {
var ratings = [];
for (var i = 0; i < count; i++) {
ratings.push(i)
}
return ratings;
}
});
}());
| hackohackob/AngularJS-learning | Learning/00.ShapingUpWithAngular/app.js | JavaScript | mit | 1,474 |
var restart_interval,
table_links = $('.tr-has-link'),
diagram = new Diagram('diagram-container'),
toggle_active = function() {
"use strict";
// Add the pseudo hover state after the mouse has moved to
// avoid highlighting a row before use touches the screen
table_links.mouseover(function () {
$(this).addClass('active');
}
).mouseout(function () {
$(this).removeClass('active');
});
},
go_to_href = function(e) {
"use strict";
// Make the whole <tr> clickable
var href = $(this).find('a').attr('href');
ClickController.saveClick(e);
window.location = href;
},
clickable_icons = function () {
"use strict";
var className = $(this).parent().attr('class').split(' ')[1],
category = className.split('-')[0],
reset_markers = function() {
// Allow icons to be clickable, highlighting that category
diagram.showAllMarkers();
diagram.cycleThroughMarkers(2800, 'restroom');
};
// Clear the timer so it can be reset later
if (typeof restart_interval != 'undefined') {
clearTimeout(restart_interval);
}
// Determine the category name
diagram.fadeMarkerCategory(category);
diagram.stopCycle();
// Restart the cycle after a few seconds
restart_interval = setTimeout(reset_markers, 10000);
};
//table_links.mouseup(go_to_href);
table_links.on('click mouseup', go_to_href);
$('body').mousemove(toggle_active);
diagram.cycleThroughMarkers(2800, 'restroom');
$('.diagram-container .marker-box:not(.touch-directory) .marker-inner').mouseup(clickable_icons);
| umnsuaweb/touch-directory-software | static/js/pages/pages.js | JavaScript | mit | 1,782 |
#include <ImpGears/Core/Matrix3.h>
#include <cstring>
#include <cmath>
#include <ImpGears/Core/Matrix4.h>
IMPGEARS_BEGIN
//--------------------------------------------------------------
Matrix3::Matrix3()
: Matrix<3,3,float>()
{
}
//--------------------------------------------------------------
Matrix3::Matrix3(const float* buf, bool transp)
: Matrix<3,3,float>(buf,transp)
{
}
//--------------------------------------------------------------
Matrix3::Matrix3(const Vec3& c1,const Vec3& c2,const Vec3& c3)
{
at(0,0)=c1[0]; at(0,1)=c1[1]; at(0,2)=c1[2];
at(1,0)=c2[0]; at(1,1)=c2[1]; at(1,2)=c2[2];
at(2,0)=c3[0]; at(2,1)=c3[1]; at(2,2)=c3[2];
}
//--------------------------------------------------------------
Matrix3::~Matrix3()
{
}
//--------------------------------------------------------------
Matrix3& Matrix3::operator+=(const Matrix3& other)
{
for(int i=0; i<9; ++i) _data[i] += other._data[i];
return *this;
}
//--------------------------------------------------------------
Matrix3& Matrix3::operator-=(const Matrix3& other)
{
for(int i=0; i<9; ++i) _data[i] -= other._data[i];
return *this;
}
//--------------------------------------------------------------
Matrix3 Matrix3::operator+(const Matrix3& other) const
{
return Matrix3(*this) += other;
}
//--------------------------------------------------------------
Matrix3 Matrix3::operator-(const Matrix3& other) const
{
return Matrix3(*this) -= other;
}
//--------------------------------------------------------------
float Matrix3::det() const
{
float result =
at(0,0)*at(1,1)*at(2,2)
+ at(1,0)*at(2,1)*at(0,2)
+ at(2,0)*at(0,1)*at(1,2)
- at(2,0)*at(1,1)*at(0,2)
- at(2,1)*at(1,2)*at(0,0)
- at(2,2)*at(1,0)*at(0,1);
return result;
}
//--------------------------------------------------------------
Matrix3 Matrix3::inverse() const
{
Matrix3 mat;
mat(0,0) = at(1,1)*at(2,2) - at(2,1)*at(1,2);
mat(0,1) = at(2,0)*at(1,2) - at(1,0)*at(2,2);
mat(0,2) = at(1,0)*at(2,1) - at(2,0)*at(1,1);
mat(1,0) = at(2,1)*at(0,2) - at(0,1)*at(2,2);
mat(1,1) = at(0,0)*at(2,2) - at(2,0)*at(0,2);
mat(1,2) = at(2,0)*at(0,1) - at(0,0)*at(2,1);
mat(2,0) = at(0,1)*at(1,2) - at(1,1)*at(0,2);
mat(2,1) = at(1,0)*at(0,2) - at(0,0)*at(1,2);
mat(2,2) = at(0,0)*at(1,1) - at(1,0)*at(0,1);
return mat.transpose() * (1.f/det());
}
//--------------------------------------------------------------
Matrix3 Matrix3::rotationX(float rad)
{
float c = std::cos(rad);
float s = std::sin(rad);
const float values[9] = { 1.f,0.f,0.f,0.f,c,-s,0.f,s,c};
return Matrix3(values,true);
}
//--------------------------------------------------------------
Matrix3 Matrix3::rotationY(float rad)
{
float c = std::cos(rad);
float s = std::sin(rad);
const float values[9] = { c,0.f,s,0.f,1.f,0.f,-s,0.f,c};
return Matrix3(values,true);
}
//--------------------------------------------------------------
Matrix3 Matrix3::rotationZ(float rad)
{
float c = std::cos(rad);
float s = std::sin(rad);
const float values[9] = { c,-s,0.f,s,c,0.f,0.f,0.f,1.f};
return Matrix3(values,true);
}
//--------------------------------------------------------------
Matrix3 Matrix3::rotationXYZ(const Vec3& r)
{
return rotationX(r[0]) * rotationY(r[1]) * rotationZ(r[2]);
}
//--------------------------------------------------------------
Matrix3 Matrix3::scale(float sx, float sy, float sz)
{
const float data[9] =
{
sx, 0.f, 0.f,
0.f, sy, 0.f,
0.f, 0.f, sz
};
return Matrix3(data);
}
//--------------------------------------------------------------
Matrix3 Matrix3::scale(const Vec3& s)
{
return scale(s[0],s[1],s[2]);
}
IMPGEARS_END
| Lut1n/ImpGears | src/ImpGears/Core/Matrix3.cpp | C++ | mit | 3,644 |
// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2015 The Bitcoin Core developers
// Copyright (c) 2015-2017 The Bitcoin Unlimited developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "txmempool.h"
#include "clientversion.h"
#include "consensus/consensus.h"
#include "consensus/validation.h"
#include "main.h"
#include "policy/fees.h"
#include "streams.h"
#include "timedata.h"
#include "unlimited.h"
#include "util.h"
#include "utilmoneystr.h"
#include "utiltime.h"
#include "version.h"
using namespace std;
CTxMemPoolEntry::CTxMemPoolEntry()
: tx(), nFee(), nTime(0), entryPriority(0), entryHeight(0), hadNoDependencies(0), inChainInputValue(0),
spendsCoinbase(false), sigOpCount(0), lockPoints()
{
nTxSize = 0;
nModSize = 0;
nUsageSize = 0;
nCountWithDescendants = 0;
feeDelta = 0;
sighashType = 0;
}
CTxMemPoolEntry::CTxMemPoolEntry(const CTransaction &_tx,
const CAmount &_nFee,
int64_t _nTime,
double _entryPriority,
unsigned int _entryHeight,
bool poolHasNoInputsOf,
CAmount _inChainInputValue,
bool _spendsCoinbase,
unsigned int _sigOps,
LockPoints lp)
: tx(_tx), nFee(_nFee), nTime(_nTime), entryPriority(_entryPriority), entryHeight(_entryHeight),
hadNoDependencies(poolHasNoInputsOf), inChainInputValue(_inChainInputValue), spendsCoinbase(_spendsCoinbase),
sigOpCount(_sigOps), lockPoints(lp)
{
nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
nModSize = tx.CalculateModifiedSize(nTxSize);
nUsageSize = RecursiveDynamicUsage(tx);
nCountWithDescendants = 1;
nSizeWithDescendants = nTxSize;
nModFeesWithDescendants = nFee;
CAmount nValueIn = tx.GetValueOut() + nFee;
assert(inChainInputValue <= nValueIn);
sighashType = 0;
feeDelta = 0;
}
CTxMemPoolEntry::CTxMemPoolEntry(const CTxMemPoolEntry &other) { *this = other; }
double CTxMemPoolEntry::GetPriority(unsigned int currentHeight) const
{
double deltaPriority = ((double)(currentHeight - entryHeight) * inChainInputValue) / nModSize;
double dResult = entryPriority + deltaPriority;
if (dResult < 0) // This should only happen if it was called with a height below entry height
dResult = 0;
return dResult;
}
void CTxMemPoolEntry::UpdateFeeDelta(int64_t newFeeDelta)
{
nModFeesWithDescendants += newFeeDelta - feeDelta;
feeDelta = newFeeDelta;
}
void CTxMemPoolEntry::UpdateLockPoints(const LockPoints &lp) { lockPoints = lp; }
void CTxMemPoolEntry::UpdateRuntimeSigOps(uint64_t _runtimeSigOpCount, uint64_t _runtimeSighashBytes)
{
runtimeSigOpCount = _runtimeSigOpCount;
runtimeSighashBytes = _runtimeSighashBytes;
}
// Update the given tx for any in-mempool descendants.
// Assumes that setMemPoolChildren is correct for the given tx and all
// descendants.
bool CTxMemPool::UpdateForDescendants(txiter updateIt,
int maxDescendantsToVisit,
cacheMap &cachedDescendants,
const std::set<uint256> &setExclude)
{
// Track the number of entries (outside setExclude) that we'd need to visit
// (will bail out if it exceeds maxDescendantsToVisit)
int nChildrenToVisit = 0;
setEntries stageEntries, setAllDescendants;
stageEntries = GetMemPoolChildren(updateIt);
while (!stageEntries.empty())
{
const txiter cit = *stageEntries.begin();
if (cit->IsDirty())
{
// Don't consider any more children if any descendant is dirty
return false;
}
setAllDescendants.insert(cit);
stageEntries.erase(cit); // BU its ok to erase here because GetMemPoolChildren does not dereference cit
const setEntries &setChildren = GetMemPoolChildren(cit);
BOOST_FOREACH (const txiter childEntry, setChildren)
{
cacheMap::iterator cacheIt = cachedDescendants.find(childEntry);
if (cacheIt != cachedDescendants.end())
{
// We've already calculated this one, just add the entries for this set
// but don't traverse again.
BOOST_FOREACH (const txiter cacheEntry, cacheIt->second)
{
// update visit count only for new child transactions
// (outside of setExclude and stageEntries)
if (setAllDescendants.insert(cacheEntry).second &&
!setExclude.count(cacheEntry->GetTx().GetHash()) && !stageEntries.count(cacheEntry))
{
nChildrenToVisit++;
}
}
}
else if (!setAllDescendants.count(childEntry))
{
// Schedule for later processing and update our visit count
if (stageEntries.insert(childEntry).second && !setExclude.count(childEntry->GetTx().GetHash()))
{
nChildrenToVisit++;
}
}
if (nChildrenToVisit > maxDescendantsToVisit)
{
return false;
}
}
}
// setAllDescendants now contains all in-mempool descendants of updateIt.
// Update and add to cached descendant map
int64_t modifySize = 0;
CAmount modifyFee = 0;
int64_t modifyCount = 0;
BOOST_FOREACH (txiter cit, setAllDescendants)
{
if (!setExclude.count(cit->GetTx().GetHash()))
{
modifySize += cit->GetTxSize();
modifyFee += cit->GetModifiedFee();
modifyCount++;
cachedDescendants[updateIt].insert(cit);
}
}
mapTx.modify(updateIt, update_descendant_state(modifySize, modifyFee, modifyCount));
return true;
}
// vHashesToUpdate is the set of transaction hashes from a disconnected block
// which has been re-added to the mempool.
// for each entry, look for descendants that are outside hashesToUpdate, and
// add fee/size information for such descendants to the parent.
void CTxMemPool::UpdateTransactionsFromBlock(const std::vector<uint256> &vHashesToUpdate)
{
LOCK(cs);
// For each entry in vHashesToUpdate, store the set of in-mempool, but not
// in-vHashesToUpdate transactions, so that we don't have to recalculate
// descendants when we come across a previously seen entry.
cacheMap mapMemPoolDescendantsToUpdate;
// Use a set for lookups into vHashesToUpdate (these entries are already
// accounted for in the state of their ancestors)
std::set<uint256> setAlreadyIncluded(vHashesToUpdate.begin(), vHashesToUpdate.end());
// Iterate in reverse, so that whenever we are looking at at a transaction
// we are sure that all in-mempool descendants have already been processed.
// This maximizes the benefit of the descendant cache and guarantees that
// setMemPoolChildren will be updated, an assumption made in
// UpdateForDescendants.
BOOST_REVERSE_FOREACH (const uint256 &hash, vHashesToUpdate)
{
// we cache the in-mempool children to avoid duplicate updates
setEntries setChildren;
// calculate children from mapNextTx
txiter it = mapTx.find(hash);
if (it == mapTx.end())
{
continue;
}
std::map<COutPoint, CInPoint>::iterator iter = mapNextTx.lower_bound(COutPoint(hash, 0));
// First calculate the children, and update setMemPoolChildren to
// include them, and update their setMemPoolParents to include this tx.
for (; iter != mapNextTx.end() && iter->first.hash == hash; ++iter)
{
const uint256 &childHash = iter->second.ptx->GetHash();
txiter childIter = mapTx.find(childHash);
assert(childIter != mapTx.end());
// We can skip updating entries we've encountered before or that
// are in the block (which are already accounted for).
if (setChildren.insert(childIter).second && !setAlreadyIncluded.count(childHash))
{
UpdateChild(it, childIter, true);
UpdateParent(childIter, it, true);
}
}
if (!UpdateForDescendants(it, 100, mapMemPoolDescendantsToUpdate, setAlreadyIncluded))
{
// Mark as dirty if we can't do the calculation.
mapTx.modify(it, set_dirty());
}
}
}
bool CTxMemPool::CalculateMemPoolAncestors(const CTxMemPoolEntry &entry,
setEntries &setAncestors,
uint64_t limitAncestorCount,
uint64_t limitAncestorSize,
uint64_t limitDescendantCount,
uint64_t limitDescendantSize,
std::string &errString,
bool fSearchForParents /* = true */)
{
setEntries parentHashes;
const CTransaction &tx = entry.GetTx();
if (fSearchForParents)
{
// Get parents of this transaction that are in the mempool
// GetMemPoolParents() is only valid for entries in the mempool, so we
// iterate mapTx to find parents.
for (unsigned int i = 0; i < tx.vin.size(); i++)
{
txiter piter = mapTx.find(tx.vin[i].prevout.hash);
if (piter != mapTx.end())
{
parentHashes.insert(piter);
if (parentHashes.size() + 1 > limitAncestorCount)
{
errString = strprintf("too many unconfirmed parents [limit: %u]", limitAncestorCount);
return false;
}
}
}
}
else
{
// If we're not searching for parents, we require this to be an
// entry in the mempool already.
txiter it = mapTx.iterator_to(entry);
parentHashes = GetMemPoolParents(it);
}
size_t totalSizeWithAncestors = entry.GetTxSize();
while (!parentHashes.empty())
{
txiter stageit = *parentHashes.begin();
setAncestors.insert(stageit);
// parentHashes.erase(stageit); // BU: Core bug, use after free, moved below
totalSizeWithAncestors += stageit->GetTxSize();
if (stageit->GetSizeWithDescendants() + entry.GetTxSize() > limitDescendantSize)
{
errString = strprintf("exceeds descendant size limit for tx %s [limit: %u]",
stageit->GetTx().GetHash().ToString(), limitDescendantSize);
return false;
}
else if (stageit->GetCountWithDescendants() + 1 > limitDescendantCount)
{
errString = strprintf("too many descendants for tx %s [limit: %u]", stageit->GetTx().GetHash().ToString(),
limitDescendantCount);
return false;
}
else if (totalSizeWithAncestors > limitAncestorSize)
{
errString = strprintf("exceeds ancestor size limit [limit: %u]", limitAncestorSize);
return false;
}
const setEntries &setMemPoolParents = GetMemPoolParents(stageit);
BOOST_FOREACH (const txiter &phash, setMemPoolParents)
{
// If this is a new ancestor, add it.
if (setAncestors.count(phash) == 0)
{
parentHashes.insert(phash);
}
// removed +1 from test below as per BU: Fix use after free bug
if (parentHashes.size() + setAncestors.size() > limitAncestorCount)
{
errString = strprintf("too many unconfirmed ancestors [limit: %u]", limitAncestorCount);
return false;
}
}
parentHashes.erase(stageit); // BU: Fix use after free bug by moving this last
}
return true;
}
void CTxMemPool::UpdateAncestorsOf(bool add, txiter it, setEntries &setAncestors)
{
setEntries parentIters = GetMemPoolParents(it);
// add or remove this tx as a child of each parent
BOOST_FOREACH (txiter piter, parentIters)
{
UpdateChild(piter, it, add);
}
const int64_t updateCount = (add ? 1 : -1);
const int64_t updateSize = updateCount * it->GetTxSize();
const CAmount updateFee = updateCount * it->GetModifiedFee();
BOOST_FOREACH (txiter ancestorIt, setAncestors)
{
mapTx.modify(ancestorIt, update_descendant_state(updateSize, updateFee, updateCount));
}
}
void CTxMemPool::UpdateChildrenForRemoval(txiter it)
{
const setEntries &setMemPoolChildren = GetMemPoolChildren(it);
BOOST_FOREACH (txiter updateIt, setMemPoolChildren)
{
UpdateParent(updateIt, it, false);
}
}
void CTxMemPool::UpdateForRemoveFromMempool(const setEntries &entriesToRemove)
{
// For each entry, walk back all ancestors and decrement size associated with this
// transaction
const uint64_t nNoLimit = std::numeric_limits<uint64_t>::max();
BOOST_FOREACH (txiter removeIt, entriesToRemove)
{
setEntries setAncestors;
const CTxMemPoolEntry &entry = *removeIt;
std::string dummy;
// Since this is a tx that is already in the mempool, we can call CMPA
// with fSearchForParents = false. If the mempool is in a consistent
// state, then using true or false should both be correct, though false
// should be a bit faster.
// However, if we happen to be in the middle of processing a reorg, then
// the mempool can be in an inconsistent state. In this case, the set
// of ancestors reachable via mapLinks will be the same as the set of
// ancestors whose packages include this transaction, because when we
// add a new transaction to the mempool in addUnchecked(), we assume it
// has no children, and in the case of a reorg where that assumption is
// false, the in-mempool children aren't linked to the in-block tx's
// until UpdateTransactionsFromBlock() is called.
// So if we're being called during a reorg, ie before
// UpdateTransactionsFromBlock() has been called, then mapLinks[] will
// differ from the set of mempool parents we'd calculate by searching,
// and it's important that we use the mapLinks[] notion of ancestor
// transactions as the set of things to update for removal.
CalculateMemPoolAncestors(entry, setAncestors, nNoLimit, nNoLimit, nNoLimit, nNoLimit, dummy, false);
// Note that UpdateAncestorsOf severs the child links that point to
// removeIt in the entries for the parents of removeIt. This is
// fine since we don't need to use the mempool children of any entries
// to walk back over our ancestors (but we do need the mempool
// parents!)
UpdateAncestorsOf(false, removeIt, setAncestors);
}
// After updating all the ancestor sizes, we can now sever the link between each
// transaction being removed and any mempool children (ie, update setMemPoolParents
// for each direct child of a transaction being removed).
BOOST_FOREACH (txiter removeIt, entriesToRemove)
{
UpdateChildrenForRemoval(removeIt);
}
}
void CTxMemPoolEntry::SetDirty()
{
nCountWithDescendants = 0;
nSizeWithDescendants = nTxSize;
nModFeesWithDescendants = GetModifiedFee();
}
void CTxMemPoolEntry::UpdateState(int64_t modifySize, CAmount modifyFee, int64_t modifyCount)
{
if (!IsDirty())
{
nSizeWithDescendants += modifySize;
assert(int64_t(nSizeWithDescendants) > 0);
nModFeesWithDescendants += modifyFee;
nCountWithDescendants += modifyCount;
assert(int64_t(nCountWithDescendants) > 0);
}
}
CTxMemPool::CTxMemPool(const CFeeRate &_minReasonableRelayFee) : nTransactionsUpdated(0)
{
_clear(); // lock free clear
// Sanity checks off by default for performance, because otherwise
// accepting transactions becomes O(N^2) where N is the number
// of transactions in the pool
nCheckFrequency = 0;
minerPolicyEstimator = new CBlockPolicyEstimator(_minReasonableRelayFee);
minReasonableRelayFee = _minReasonableRelayFee;
}
CTxMemPool::~CTxMemPool() { delete minerPolicyEstimator; }
bool CTxMemPool::isSpent(const COutPoint &outpoint)
{
LOCK(cs);
return mapNextTx.count(outpoint);
}
unsigned int CTxMemPool::GetTransactionsUpdated() const
{
LOCK(cs);
return nTransactionsUpdated;
}
void CTxMemPool::AddTransactionsUpdated(unsigned int n)
{
LOCK(cs);
nTransactionsUpdated += n;
}
bool CTxMemPool::addUnchecked(const uint256 &hash,
const CTxMemPoolEntry &entry,
setEntries &setAncestors,
bool fCurrentEstimate)
{
// Add to memory pool without checking anything.
// Used by main.cpp AcceptToMemoryPool(), which DOES do
// all the appropriate checks.
LOCK(cs);
indexed_transaction_set::iterator newit = mapTx.insert(entry).first;
mapLinks.insert(make_pair(newit, TxLinks()));
// Update transaction for any feeDelta created by PrioritiseTransaction
// TODO: refactor so that the fee delta is calculated before inserting
// into mapTx.
std::map<uint256, std::pair<double, CAmount> >::const_iterator pos = mapDeltas.find(hash);
if (pos != mapDeltas.end())
{
const std::pair<double, CAmount> &deltas = pos->second;
if (deltas.second)
{
mapTx.modify(newit, update_fee_delta(deltas.second));
}
}
// Update cachedInnerUsage to include contained transaction's usage.
// (When we update the entry for in-mempool parents, memory usage will be
// further updated.)
cachedInnerUsage += entry.DynamicMemoryUsage();
const CTransaction &tx = newit->GetTx();
std::set<uint256> setParentTransactions;
for (unsigned int i = 0; i < tx.vin.size(); i++)
{
mapNextTx[tx.vin[i].prevout] = CInPoint(&tx, i);
setParentTransactions.insert(tx.vin[i].prevout.hash);
}
// Don't bother worrying about child transactions of this one.
// Normal case of a new transaction arriving is that there can't be any
// children, because such children would be orphans.
// An exception to that is if a transaction enters that used to be in a block.
// In that case, our disconnect block logic will call UpdateTransactionsFromBlock
// to clean up the mess we're leaving here.
// Update ancestors with information about this tx
BOOST_FOREACH (const uint256 &phash, setParentTransactions)
{
txiter pit = mapTx.find(phash);
if (pit != mapTx.end())
{
UpdateParent(newit, pit, true);
}
}
UpdateAncestorsOf(true, newit, setAncestors);
nTransactionsUpdated++;
totalTxSize += entry.GetTxSize();
txAdded += 1; // BU
poolSize() = totalTxSize; // BU
minerPolicyEstimator->processTransaction(entry, fCurrentEstimate);
return true;
}
void CTxMemPool::removeUnchecked(txiter it)
{
const uint256 hash = it->GetTx().GetHash();
BOOST_FOREACH (const CTxIn &txin, it->GetTx().vin)
mapNextTx.erase(txin.prevout);
totalTxSize -= it->GetTxSize();
cachedInnerUsage -= it->DynamicMemoryUsage();
cachedInnerUsage -= memusage::DynamicUsage(mapLinks[it].parents) + memusage::DynamicUsage(mapLinks[it].children);
mapLinks.erase(it);
mapTx.erase(it);
nTransactionsUpdated++;
minerPolicyEstimator->removeTx(hash);
}
// Calculates descendants of entry that are not already in setDescendants, and adds to
// setDescendants. Assumes entryit is already a tx in the mempool and setMemPoolChildren
// is correct for tx and all descendants.
// Also assumes that if an entry is in setDescendants already, then all
// in-mempool descendants of it are already in setDescendants as well, so that we
// can save time by not iterating over those entries.
void CTxMemPool::CalculateDescendants(txiter entryit, setEntries &setDescendants)
{
setEntries stage;
if (setDescendants.count(entryit) == 0)
{
stage.insert(entryit);
}
// Traverse down the children of entry, only adding children that are not
// accounted for in setDescendants already (because those children have either
// already been walked, or will be walked in this iteration).
while (!stage.empty())
{
txiter it = *stage.begin();
setDescendants.insert(it);
stage.erase(it); // BU its ok to erase here because GetMemPoolChildren does not dereference it
const setEntries &setChildren = GetMemPoolChildren(it);
BOOST_FOREACH (const txiter &childiter, setChildren)
{
if (!setDescendants.count(childiter))
{
stage.insert(childiter);
}
}
}
}
void CTxMemPool::remove(const CTransaction &origTx, std::list<CTransaction> &removed, bool fRecursive)
{
// Remove transaction from memory pool
{
LOCK(cs);
setEntries txToRemove;
txiter origit = mapTx.find(origTx.GetHash());
if (origit != mapTx.end())
{
txToRemove.insert(origit);
}
else if (fRecursive)
{
// If recursively removing but origTx isn't in the mempool
// be sure to remove any children that are in the pool. This can
// happen during chain re-orgs if origTx isn't re-accepted into
// the mempool for any reason.
for (unsigned int i = 0; i < origTx.vout.size(); i++)
{
std::map<COutPoint, CInPoint>::iterator it = mapNextTx.find(COutPoint(origTx.GetHash(), i));
if (it == mapNextTx.end())
continue;
txiter nextit = mapTx.find(it->second.ptx->GetHash());
assert(nextit != mapTx.end());
txToRemove.insert(nextit);
}
}
setEntries setAllRemoves;
if (fRecursive)
{
BOOST_FOREACH (txiter it, txToRemove)
{
CalculateDescendants(it, setAllRemoves);
}
}
else
{
setAllRemoves.swap(txToRemove);
}
BOOST_FOREACH (txiter it, setAllRemoves)
{
removed.push_back(it->GetTx());
}
RemoveStaged(setAllRemoves);
}
}
void CTxMemPool::removeForReorg(const CCoinsViewCache *pcoins, unsigned int nMemPoolHeight, int flags)
{
// Remove transactions spending a coinbase which are now immature and no-longer-final transactions
LOCK(cs);
list<CTransaction> transactionsToRemove;
for (indexed_transaction_set::const_iterator it = mapTx.begin(); it != mapTx.end(); it++)
{
const CTransaction &tx = it->GetTx();
LockPoints lp = it->GetLockPoints();
bool validLP = TestLockPointValidity(&lp);
if (!CheckFinalTx(tx, flags) || !CheckSequenceLocks(tx, flags, &lp, validLP))
{
// Note if CheckSequenceLocks fails the LockPoints may still be invalid
// So it's critical that we remove the tx and not depend on the LockPoints.
transactionsToRemove.push_back(tx);
}
else if (it->GetSpendsCoinbase())
{
BOOST_FOREACH (const CTxIn &txin, tx.vin)
{
indexed_transaction_set::const_iterator it2 = mapTx.find(txin.prevout.hash);
if (it2 != mapTx.end())
continue;
const Coin &coin = pcoins->AccessCoin(txin.prevout);
if (nCheckFrequency != 0)
assert(!coin.IsSpent());
if (coin.IsSpent() ||
(coin.IsCoinBase() && ((signed long)nMemPoolHeight) - coin.nHeight < COINBASE_MATURITY))
{
transactionsToRemove.push_back(tx);
break;
}
}
}
if (!validLP)
{
mapTx.modify(it, update_lock_points(lp));
}
}
BOOST_FOREACH (const CTransaction &tx, transactionsToRemove)
{
list<CTransaction> removed;
remove(tx, removed, true);
}
}
void CTxMemPool::removeConflicts(const CTransaction &tx, std::list<CTransaction> &removed)
{
// Remove transactions which depend on inputs of tx, recursively
list<CTransaction> result;
LOCK(cs);
BOOST_FOREACH (const CTxIn &txin, tx.vin)
{
std::map<COutPoint, CInPoint>::iterator it = mapNextTx.find(txin.prevout);
if (it != mapNextTx.end())
{
const CTransaction &txConflict = *it->second.ptx;
if (txConflict != tx)
{
remove(txConflict, removed, true);
ClearPrioritisation(txConflict.GetHash());
}
}
}
}
/**
* Called when a block is connected. Removes from mempool and updates the miner fee estimator.
*/
void CTxMemPool::removeForBlock(const std::vector<CTransaction> &vtx,
unsigned int nBlockHeight,
std::list<CTransaction> &conflicts,
bool fCurrentEstimate)
{
LOCK(cs);
std::vector<CTxMemPoolEntry> entries;
BOOST_FOREACH (const CTransaction &tx, vtx)
{
uint256 hash = tx.GetHash();
indexed_transaction_set::iterator i = mapTx.find(hash);
if (i != mapTx.end())
entries.push_back(*i);
}
BOOST_FOREACH (const CTransaction &tx, vtx)
{
std::list<CTransaction> dummy;
remove(tx, dummy, false);
removeConflicts(tx, conflicts);
ClearPrioritisation(tx.GetHash());
}
// After the txs in the new block have been removed from the mempool, update policy estimates
minerPolicyEstimator->processBlock(nBlockHeight, entries, fCurrentEstimate);
lastRollingFeeUpdate = GetTime();
blockSinceLastRollingFeeBump = true;
}
void CTxMemPool::_clear()
{
mapLinks.clear();
mapTx.clear();
mapNextTx.clear();
totalTxSize = 0;
cachedInnerUsage = 0;
lastRollingFeeUpdate = GetTime();
blockSinceLastRollingFeeBump = false;
rollingMinimumFeeRate = 0;
++nTransactionsUpdated;
}
void CTxMemPool::clear()
{
LOCK(cs);
_clear();
}
void CTxMemPool::check(const CCoinsViewCache *pcoins) const
{
if (nCheckFrequency == 0)
return;
if (insecure_rand() >= nCheckFrequency)
return;
LogPrint("mempool", "Checking mempool with %u transactions and %u inputs\n", (unsigned int)mapTx.size(),
(unsigned int)mapNextTx.size());
uint64_t checkTotal = 0;
uint64_t innerUsage = 0;
CCoinsViewCache mempoolDuplicate(const_cast<CCoinsViewCache *>(pcoins));
LOCK(cs);
list<const CTxMemPoolEntry *> waitingOnDependants;
for (indexed_transaction_set::const_iterator it = mapTx.begin(); it != mapTx.end(); it++)
{
unsigned int i = 0;
checkTotal += it->GetTxSize();
innerUsage += it->DynamicMemoryUsage();
const CTransaction &tx = it->GetTx();
txlinksMap::const_iterator linksiter = mapLinks.find(it);
assert(linksiter != mapLinks.end());
const TxLinks &links = linksiter->second;
innerUsage += memusage::DynamicUsage(links.parents) + memusage::DynamicUsage(links.children);
bool fDependsWait = false;
setEntries setParentCheck;
BOOST_FOREACH (const CTxIn &txin, tx.vin)
{
// Check that every mempool transaction's inputs refer to available coins, or other mempool tx's.
indexed_transaction_set::const_iterator it2 = mapTx.find(txin.prevout.hash);
if (it2 != mapTx.end())
{
const CTransaction &tx2 = it2->GetTx();
assert(tx2.vout.size() > txin.prevout.n && !tx2.vout[txin.prevout.n].IsNull());
fDependsWait = true;
setParentCheck.insert(it2);
}
else
{
assert(pcoins->HaveCoin(txin.prevout));
}
// Check whether its inputs are marked in mapNextTx.
std::map<COutPoint, CInPoint>::const_iterator it3 = mapNextTx.find(txin.prevout);
assert(it3 != mapNextTx.end());
assert(it3->second.ptx == &tx);
assert(it3->second.n == i);
i++;
}
assert(setParentCheck == GetMemPoolParents(it));
// Check children against mapNextTx
CTxMemPool::setEntries setChildrenCheck;
std::map<COutPoint, CInPoint>::const_iterator iter = mapNextTx.lower_bound(COutPoint(it->GetTx().GetHash(), 0));
int64_t childSizes = 0;
CAmount childModFee = 0;
for (; iter != mapNextTx.end() && iter->first.hash == it->GetTx().GetHash(); ++iter)
{
txiter childit = mapTx.find(iter->second.ptx->GetHash());
assert(childit != mapTx.end()); // mapNextTx points to in-mempool transactions
if (setChildrenCheck.insert(childit).second)
{
childSizes += childit->GetTxSize();
childModFee += childit->GetModifiedFee();
}
}
assert(setChildrenCheck == GetMemPoolChildren(it));
// Also check to make sure size is greater than sum with immediate children.
// just a sanity check, not definitive that this calc is correct...
if (!it->IsDirty())
{
assert(it->GetSizeWithDescendants() >= childSizes + it->GetTxSize());
}
else
{
assert(it->GetSizeWithDescendants() == it->GetTxSize());
assert(it->GetModFeesWithDescendants() == it->GetModifiedFee());
}
if (fDependsWait)
waitingOnDependants.push_back(&(*it));
else
{
CValidationState state;
assert(CheckInputs(tx, state, mempoolDuplicate, false, 0, false, NULL));
UpdateCoins(tx, state, mempoolDuplicate, 1000000);
}
}
unsigned int stepsSinceLastRemove = 0;
while (!waitingOnDependants.empty())
{
const CTxMemPoolEntry *entry = waitingOnDependants.front();
waitingOnDependants.pop_front();
CValidationState state;
if (!mempoolDuplicate.HaveInputs(entry->GetTx()))
{
waitingOnDependants.push_back(entry);
stepsSinceLastRemove++;
assert(stepsSinceLastRemove < waitingOnDependants.size());
}
else
{
assert(CheckInputs(entry->GetTx(), state, mempoolDuplicate, false, 0, false, NULL));
UpdateCoins(entry->GetTx(), state, mempoolDuplicate, 1000000);
stepsSinceLastRemove = 0;
}
}
for (std::map<COutPoint, CInPoint>::const_iterator it = mapNextTx.begin(); it != mapNextTx.end(); it++)
{
uint256 hash = it->second.ptx->GetHash();
indexed_transaction_set::const_iterator it2 = mapTx.find(hash);
const CTransaction &tx = it2->GetTx();
assert(it2 != mapTx.end());
assert(&tx == it->second.ptx);
assert(tx.vin.size() > it->second.n);
assert(it->first == it->second.ptx->vin[it->second.n].prevout);
}
assert(totalTxSize == checkTotal);
assert(innerUsage == cachedInnerUsage);
}
void CTxMemPool::queryHashes(vector<uint256> &vtxid)
{
vtxid.clear();
LOCK(cs);
vtxid.reserve(mapTx.size());
for (indexed_transaction_set::iterator mi = mapTx.begin(); mi != mapTx.end(); ++mi)
vtxid.push_back(mi->GetTx().GetHash());
}
bool CTxMemPool::lookup(uint256 hash, CTxMemPoolEntry &result) const
{
LOCK(cs);
indexed_transaction_set::const_iterator i = mapTx.find(hash);
if (i == mapTx.end())
return false;
result = *i;
return true;
}
bool CTxMemPool::lookup(uint256 hash, CTransaction &result) const
{
LOCK(cs);
indexed_transaction_set::const_iterator i = mapTx.find(hash);
if (i == mapTx.end())
return false;
result = i->GetTx();
return true;
}
CFeeRate CTxMemPool::estimateFee(int nBlocks) const
{
LOCK(cs);
return minerPolicyEstimator->estimateFee(nBlocks);
}
CFeeRate CTxMemPool::estimateSmartFee(int nBlocks, int *answerFoundAtBlocks) const
{
LOCK(cs);
return minerPolicyEstimator->estimateSmartFee(nBlocks, answerFoundAtBlocks, *this);
}
double CTxMemPool::estimatePriority(int nBlocks) const
{
LOCK(cs);
return minerPolicyEstimator->estimatePriority(nBlocks);
}
double CTxMemPool::estimateSmartPriority(int nBlocks, int *answerFoundAtBlocks) const
{
LOCK(cs);
return minerPolicyEstimator->estimateSmartPriority(nBlocks, answerFoundAtBlocks, *this);
}
bool CTxMemPool::WriteFeeEstimates(CAutoFile &fileout) const
{
try
{
LOCK(cs);
fileout << 109900; // version required to read: 0.10.99 or later
fileout << CLIENT_VERSION; // version that wrote the file
minerPolicyEstimator->Write(fileout);
}
catch (const std::exception &)
{
LogPrintf("CTxMemPool::WriteFeeEstimates(): unable to write policy estimator data (non-fatal)\n");
return false;
}
return true;
}
bool CTxMemPool::ReadFeeEstimates(CAutoFile &filein)
{
try
{
int nVersionRequired, nVersionThatWrote;
filein >> nVersionRequired >> nVersionThatWrote;
if (nVersionRequired > CLIENT_VERSION)
return error("CTxMemPool::ReadFeeEstimates(): up-version (%d) fee estimate file", nVersionRequired);
LOCK(cs);
minerPolicyEstimator->Read(filein);
}
catch (const std::exception &)
{
LogPrintf("CTxMemPool::ReadFeeEstimates(): unable to read policy estimator data (non-fatal)\n");
return false;
}
return true;
}
void CTxMemPool::PrioritiseTransaction(const uint256 hash,
const string strHash,
double dPriorityDelta,
const CAmount &nFeeDelta)
{
{
LOCK(cs);
std::pair<double, CAmount> &deltas = mapDeltas[hash];
deltas.first += dPriorityDelta;
deltas.second += nFeeDelta;
txiter it = mapTx.find(hash);
if (it != mapTx.end())
{
mapTx.modify(it, update_fee_delta(deltas.second));
// Now update all ancestors' modified fees with descendants
setEntries setAncestors;
uint64_t nNoLimit = std::numeric_limits<uint64_t>::max();
std::string dummy;
CalculateMemPoolAncestors(*it, setAncestors, nNoLimit, nNoLimit, nNoLimit, nNoLimit, dummy, false);
BOOST_FOREACH (txiter ancestorIt, setAncestors)
{
mapTx.modify(ancestorIt, update_descendant_state(0, nFeeDelta, 0));
}
}
}
LogPrintf("PrioritiseTransaction: %s priority += %f, fee += %d\n", strHash, dPriorityDelta, FormatMoney(nFeeDelta));
}
void CTxMemPool::ApplyDeltas(const uint256 hash, double &dPriorityDelta, CAmount &nFeeDelta) const
{
LOCK(cs);
std::map<uint256, std::pair<double, CAmount> >::const_iterator pos = mapDeltas.find(hash);
if (pos == mapDeltas.end())
return;
const std::pair<double, CAmount> &deltas = pos->second;
dPriorityDelta += deltas.first;
nFeeDelta += deltas.second;
}
void CTxMemPool::ClearPrioritisation(const uint256 hash)
{
LOCK(cs);
mapDeltas.erase(hash);
}
bool CTxMemPool::HasNoInputsOf(const CTransaction &tx) const
{
for (unsigned int i = 0; i < tx.vin.size(); i++)
if (exists(tx.vin[i].prevout.hash))
return false;
return true;
}
CCoinsViewMemPool::CCoinsViewMemPool(CCoinsView *baseIn, const CTxMemPool &mempoolIn)
: CCoinsViewBacked(baseIn), mempool(mempoolIn)
{
}
bool CCoinsViewMemPool::GetCoin(const COutPoint &outpoint, Coin &coin) const
{
// If an entry in the mempool exists, always return that one, as it's guaranteed to never
// conflict with the underlying cache, and it cannot have pruned entries (as it contains full)
// transactions. First checking the underlying cache risks returning a pruned entry instead.
CTransaction tx;
if (mempool.lookup(outpoint.hash, tx))
{
if (outpoint.n < tx.vout.size())
{
coin = Coin(tx.vout[outpoint.n], MEMPOOL_HEIGHT, false);
return true;
}
else
{
return false;
}
}
return (base->GetCoin(outpoint, coin) && !coin.IsSpent());
}
bool CCoinsViewMemPool::HaveCoin(const COutPoint &outpoint) const
{
return mempool.exists(outpoint) || base->HaveCoin(outpoint);
}
size_t CTxMemPool::DynamicMemoryUsage() const
{
LOCK(cs);
// Estimate the overhead of mapTx to be 12 pointers + an allocation, as no exact formula for
// boost::multi_index_contained is implemented.
return memusage::MallocUsage(sizeof(CTxMemPoolEntry) + 12 * sizeof(void *)) * mapTx.size() +
memusage::DynamicUsage(mapNextTx) + memusage::DynamicUsage(mapDeltas) + memusage::DynamicUsage(mapLinks) +
cachedInnerUsage;
}
void CTxMemPool::RemoveStaged(setEntries &stage)
{
AssertLockHeld(cs);
UpdateForRemoveFromMempool(stage);
BOOST_FOREACH (const txiter &it, stage)
{
removeUnchecked(it);
}
}
int CTxMemPool::Expire(int64_t time, std::vector<COutPoint> &vCoinsToUncache)
{
LOCK(cs);
indexed_transaction_set::index<entry_time>::type::iterator it = mapTx.get<entry_time>().begin();
setEntries toremove;
while (it != mapTx.get<entry_time>().end() && it->GetTime() < time)
{
toremove.insert(mapTx.project<0>(it));
it++;
}
setEntries stage;
for (txiter removeit : toremove)
CalculateDescendants(removeit, stage);
for (txiter it : stage)
for (const CTxIn &txin : it->GetTx().vin)
vCoinsToUncache.push_back(txin.prevout);
RemoveStaged(stage);
return stage.size();
}
bool CTxMemPool::addUnchecked(const uint256 &hash, const CTxMemPoolEntry &entry, bool fCurrentEstimate)
{
LOCK(cs);
setEntries setAncestors;
uint64_t nNoLimit = std::numeric_limits<uint64_t>::max();
std::string dummy;
CalculateMemPoolAncestors(entry, setAncestors, nNoLimit, nNoLimit, nNoLimit, nNoLimit, dummy);
return addUnchecked(hash, entry, setAncestors, fCurrentEstimate);
}
void CTxMemPool::UpdateChild(txiter entry, txiter child, bool add)
{
setEntries s;
if (add && mapLinks[entry].children.insert(child).second)
{
cachedInnerUsage += memusage::IncrementalDynamicUsage(s);
}
else if (!add && mapLinks[entry].children.erase(child))
{
cachedInnerUsage -= memusage::IncrementalDynamicUsage(s);
}
}
void CTxMemPool::UpdateParent(txiter entry, txiter parent, bool add)
{
setEntries s;
if (add && mapLinks[entry].parents.insert(parent).second)
{
cachedInnerUsage += memusage::IncrementalDynamicUsage(s);
}
else if (!add && mapLinks[entry].parents.erase(parent))
{
cachedInnerUsage -= memusage::IncrementalDynamicUsage(s);
}
}
const CTxMemPool::setEntries &CTxMemPool::GetMemPoolParents(txiter entry) const
{
assert(entry != mapTx.end());
txlinksMap::const_iterator it = mapLinks.find(entry);
assert(it != mapLinks.end());
return it->second.parents;
}
const CTxMemPool::setEntries &CTxMemPool::GetMemPoolChildren(txiter entry) const
{
assert(entry != mapTx.end());
txlinksMap::const_iterator it = mapLinks.find(entry);
assert(it != mapLinks.end());
return it->second.children;
}
CFeeRate CTxMemPool::GetMinFee(size_t sizelimit) const
{
LOCK(cs);
if (!blockSinceLastRollingFeeBump || rollingMinimumFeeRate == 0)
return CFeeRate(rollingMinimumFeeRate);
int64_t time = GetTime();
if (time > lastRollingFeeUpdate + 10)
{
double halflife = ROLLING_FEE_HALFLIFE;
if (DynamicMemoryUsage() < sizelimit / 4)
halflife /= 4;
else if (DynamicMemoryUsage() < sizelimit / 2)
halflife /= 2;
rollingMinimumFeeRate = rollingMinimumFeeRate / pow(2.0, (time - lastRollingFeeUpdate) / halflife);
lastRollingFeeUpdate = time;
if (rollingMinimumFeeRate < minReasonableRelayFee.GetFeePerK() / 2)
{
rollingMinimumFeeRate = 0;
return CFeeRate(0);
}
}
return std::max(CFeeRate(rollingMinimumFeeRate), minReasonableRelayFee);
}
void CTxMemPool::trackPackageRemoved(const CFeeRate &rate)
{
AssertLockHeld(cs);
if (rate.GetFeePerK() > rollingMinimumFeeRate)
{
rollingMinimumFeeRate = rate.GetFeePerK();
blockSinceLastRollingFeeBump = false;
}
}
void CTxMemPool::TrimToSize(size_t sizelimit, std::vector<COutPoint> *pvNoSpendsRemaining)
{
LOCK(cs);
unsigned nTxnRemoved = 0;
CFeeRate maxFeeRateRemoved(0);
while (DynamicMemoryUsage() > sizelimit)
{
indexed_transaction_set::index<descendant_score>::type::iterator it = mapTx.get<descendant_score>().begin();
// We set the new mempool min fee to the feerate of the removed set, plus the
// "minimum reasonable fee rate" (ie some value under which we consider txn
// to have 0 fee). This way, we don't allow txn to enter mempool with feerate
// equal to txn which were removed with no block in between.
CFeeRate removed(it->GetModFeesWithDescendants(), it->GetSizeWithDescendants());
removed += minReasonableRelayFee;
trackPackageRemoved(removed);
maxFeeRateRemoved = std::max(maxFeeRateRemoved, removed);
setEntries stage;
CalculateDescendants(mapTx.project<0>(it), stage);
nTxnRemoved += stage.size();
std::vector<CTransaction> txn;
if (pvNoSpendsRemaining)
{
txn.reserve(stage.size());
BOOST_FOREACH (txiter it, stage)
txn.push_back(it->GetTx());
}
RemoveStaged(stage);
if (pvNoSpendsRemaining)
{
BOOST_FOREACH (const CTransaction &tx, txn)
{
BOOST_FOREACH (const CTxIn &txin, tx.vin)
{
if (exists(txin.prevout.hash))
continue;
if (!mapNextTx.count(txin.prevout))
{
pvNoSpendsRemaining->push_back(txin.prevout);
}
}
}
}
}
if (maxFeeRateRemoved > CFeeRate(0))
LogPrint(
"mempool", "Removed %u txn, rolling minimum fee bumped to %s\n", nTxnRemoved, maxFeeRateRemoved.ToString());
}
void CTxMemPool::UpdateTransactionsPerSecond()
{
boost::mutex::scoped_lock lock(cs_txPerSec);
static int64_t nLastTime = GetTime();
double nSecondsToAverage = 60; // Length of time in seconds to smooth the tx rate over
int64_t nNow = GetTime();
// Decay the previous tx rate.
int64_t nDeltaTime = nNow - nLastTime;
if (nDeltaTime > 0)
{
nTxPerSec -= (nTxPerSec / nSecondsToAverage) * nDeltaTime;
nLastTime = nNow;
}
// Add the new tx to the rate
nTxPerSec += 1 / nSecondsToAverage; // The amount that the new tx will add to the tx rate
if (nTxPerSec < 0)
nTxPerSec = 0;
}
SaltedTxidHasher::SaltedTxidHasher()
: k0(GetRand(std::numeric_limits<uint64_t>::max())), k1(GetRand(std::numeric_limits<uint64_t>::max()))
{
}
| Bitcoin-com/BUcash | src/txmempool.cpp | C++ | mit | 43,040 |
/*
* This file is part of Sponge, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* 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.
*/
package org.spongepowered.common.mixin.core.status;
import com.google.common.base.Charsets;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import net.minecraft.network.NetworkSystem;
import net.minecraft.network.PingResponseHandler;
import net.minecraft.network.ServerStatusResponse;
import net.minecraft.server.MinecraftServer;
import org.apache.logging.log4j.Logger;
import org.spongepowered.asm.mixin.Final;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Overwrite;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.common.network.status.SpongeLegacyMinecraftVersion;
import org.spongepowered.common.network.status.SpongeStatusResponse;
import java.net.InetSocketAddress;
@Mixin(PingResponseHandler.class)
public abstract class MixinPingResponseHandler extends ChannelInboundHandlerAdapter {
@Shadow @Final private static Logger logger;
@Shadow private NetworkSystem networkSystem;
@Shadow abstract void writeAndFlush(ChannelHandlerContext ctx, ByteBuf data);
@Shadow abstract ByteBuf getStringBuffer(String string);
private ByteBuf buf;
@Override
public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
this.buf = ctx.alloc().buffer();
}
@Override
public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
if (this.buf != null) {
this.buf.release();
this.buf = null;
}
}
@Override
@Overwrite
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
ByteBuf m = (ByteBuf) msg;
this.buf.writeBytes(m);
m.release();
this.buf.markReaderIndex();
boolean result = false;
try {
result = readLegacy(ctx, this.buf);
} finally {
this.buf.resetReaderIndex();
if (!result) {
ByteBuf buf = this.buf;
this.buf = null;
ctx.pipeline().remove("legacy_query");
ctx.fireChannelRead(buf);
}
}
}
private boolean readLegacy(ChannelHandlerContext ctx, ByteBuf buf) {
if (buf.readUnsignedByte() != 0xFE) {
return false;
}
MinecraftServer server = this.networkSystem.getServer();
InetSocketAddress client = (InetSocketAddress) ctx.channel().remoteAddress();
ServerStatusResponse response;
int i = buf.readableBytes();
switch (i) {
case 0:
logger.debug("Ping: (<=1.3) from {}:{}", client.getAddress(), client.getPort());
response = SpongeStatusResponse.postLegacy(server, client, SpongeLegacyMinecraftVersion.V1_3, null);
if (response != null) {
this.writeResponse(ctx, String.format("%s§%d§%d",
SpongeStatusResponse.getUnformattedMotd(response),
response.getPlayerCountData().getOnlinePlayerCount(),
response.getPlayerCountData().getMaxPlayers()));
} else {
ctx.close();
}
break;
case 1:
if (buf.readUnsignedByte() != 0x01) {
return false;
}
logger.debug("Ping: (1.4-1.5) from {}:{}", client.getAddress(), client.getPort());
response = SpongeStatusResponse.postLegacy(server, client, SpongeLegacyMinecraftVersion.V1_5, null);
if (response != null) {
this.writeResponse(ctx, String.format("§1\u0000%d\u0000%s\u0000%s\u0000%d\u0000%d",
response.getProtocolVersionInfo().getProtocol(),
response.getProtocolVersionInfo().getName(),
SpongeStatusResponse.getMotd(response),
response.getPlayerCountData().getOnlinePlayerCount(),
response.getPlayerCountData().getMaxPlayers()));
} else {
ctx.close();
}
break;
default:
if (buf.readUnsignedByte() != 0x01 || buf.readUnsignedByte() != 0xFA) {
return false;
}
if (!buf.isReadable(2)) {
break;
}
short length = buf.readShort();
if (!buf.isReadable(length * 2)) {
break;
}
if (!buf.readBytes(length * 2).toString(Charsets.UTF_16BE).equals("MC|PingHost")) {
return false;
}
if (!buf.isReadable(2)) {
break;
}
length = buf.readShort();
if (!buf.isReadable(length)) {
break;
}
int protocol = buf.readUnsignedByte();
length = buf.readShort();
String host = buf.readBytes(length * 2).toString(Charsets.UTF_16BE);
int port = buf.readInt();
logger.debug("Ping: (1.6) from {}:{}", client.getAddress(), client.getPort());
response =
SpongeStatusResponse.postLegacy(server, client,
new SpongeLegacyMinecraftVersion(SpongeLegacyMinecraftVersion.V1_6, protocol),
InetSocketAddress.createUnresolved(host, port));
if (response != null) {
this.writeResponse(ctx, String.format("§1\u0000%d\u0000%s\u0000%s\u0000%d\u0000%d",
response.getProtocolVersionInfo().getProtocol(),
response.getProtocolVersionInfo().getName(),
SpongeStatusResponse.getMotd(response),
response.getPlayerCountData().getOnlinePlayerCount(),
response.getPlayerCountData().getMaxPlayers()));
} else {
ctx.close();
}
break;
}
return true;
}
private void writeResponse(ChannelHandlerContext ctx, String response) {
writeAndFlush(ctx, getStringBuffer(response));
}
}
| hsyyid/SpongeCommon | src/main/java/org/spongepowered/common/mixin/core/status/MixinPingResponseHandler.java | Java | mit | 7,649 |
from .base import CreateBaseCommand
class IndicesOpenCommand(CreateBaseCommand):
command_name = "elasticsearch:indices-open"
def is_enabled(self):
return True
def run_request(self, index=None):
if index is None:
self.show_index_list_panel(self.run)
return
options = dict(
index=index
)
return self.client.indices.open(**options)
| KunihikoKido/sublime-elasticsearch-client | commands/indices_open.py | Python | mit | 423 |
package net.arbium.simplex.rest.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Marker annotation for the HTTP request method PUT.
*
* @author Robin Morris <[email protected]>
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface PUT {
}
| arbiem/simplex | SimpleX/src/net/arbium/simplex/rest/annotation/PUT.java | Java | mit | 430 |
import { shorten } from '../utils/requests';
const requestGetShortenLink = (urlData) => {
return shorten
.post('/shorten', urlData);
};
const requestGetShortenStatus = (shortenUrl) => {
return shorten
.get(`/${shortenUrl}/stats`);
};
export {
requestGetShortenLink,
requestGetShortenStatus,
};
| jlmonroy13/Impraise-shorten-url | src/requests/links.js | JavaScript | mit | 313 |
<?php
class ConnectionException extends Exception
{
}
/**
* Wrap Credis to add namespace support and various helper methods.
*
* @package Resque/Redis
* @author Chris Boulton <[email protected]>
* @license http://www.opensource.org/licenses/mit-license.php
*/
class Resque_Redis
{
/**
* Redis namespace
* @var string
*/
private static $defaultNamespace = 'resque:';
private $server;
private $database;
private $driver;
/**
* @var array List of all commands in Redis that supply a key as their
* first argument. Used to prefix keys with the Resque namespace.
*/
private $keyCommands = array(
'exists',
'del',
'type',
'keys',
'expire',
'ttl',
'move',
'set',
'setex',
'get',
'getset',
'setnx',
'incr',
'incrby',
'decr',
'decrby',
'rpush',
'lpush',
'llen',
'lrange',
'ltrim',
'lindex',
'lset',
'lrem',
'lpop',
'blpop',
'rpop',
'sadd',
'srem',
'spop',
'scard',
'sismember',
'smembers',
'srandmember',
'zadd',
'zrem',
'zrange',
'zrevrange',
'zrangebyscore',
'zcard',
'zscore',
'zremrangebyscore',
'sort',
'watch',
'ping'
);
// sinterstore
// sunion
// sunionstore
// sdiff
// sdiffstore
// sinter
// smove
// rename
// rpoplpush
// mget
// msetnx
// mset
// renamenx
/**
* Set Redis namespace (prefix) default: resque
* @param string $namespace
*/
public static function prefix($namespace)
{
if (strpos($namespace, ':') === false) {
$namespace .= ':';
}
self::$defaultNamespace = $namespace;
}
/**
* Resque_Redis constructor.
* @param $server
* @param null $database
* @throws CredisException
*/
public function __construct($server, $database = null)
{
$this->server = $server;
$this->database = $database;
$this->connect();
}
/**
* @throws CredisException
*/
public function connect()
{
try {
if (is_array($this->server)) {
$this->driver = new Credis_Cluster($this->server);
} else {
$port = null;
$password = null;
$host = $this->server;
// If not a UNIX socket path or tcp:// formatted connections string
// assume host:port combination.
if (strpos($this->server, '/') === false) {
$parts = explode(':', $this->server);
if (isset($parts[1])) {
$port = $parts[1];
}
$host = $parts[0];
} else {
if (strpos($this->server, 'redis://') !== false) {
// Redis format is:
// redis://[user]:[password]@[host]:[port]
list($userpwd, $hostport) = explode('@', $this->server);
$userpwd = substr($userpwd, strpos($userpwd, 'redis://') + 8);
list($host, $port) = explode(':', $hostport);
list($user, $password) = explode(':', $userpwd);
}
}
$this->driver = new Credis_Client($host, $port);
$this->driver->setReadTimeout(5000);
if (isset($password)) {
$this->driver->auth($password);
}
}
if ($this->database !== null) {
$this->driver->select($this->database);
}
} catch (\Exception $e) {
throw new CredisException('Error communicating with Redis: ' . $e->getMessage(), 0, $e);
}
}
/**
* Magic method to handle all function requests and prefix key based
* operations with the {self::$defaultNamespace} key prefix.
*
* @param string $name The name of the method called.
* @param array $args Array of supplied arguments to the method.
* @return mixed Return value from Resident::call() based on the command.
*/
public function __call($name, $args) {
if(in_array($name, $this->keyCommands)) {
if(is_array($args[0])) {
foreach($args[0] AS $i => $v) {
$args[0][$i] = self::$defaultNamespace . $v;
}
} else {
$args[0] = self::$defaultNamespace . $args[0];
}
}
$connected = true;
while (true) {
try {
if (!$connected) {
try {
$this->connect();
Resque::$redis = null;
} catch (CredisException $e) {
throw new ConnectionException($e);
}
}
return $this->driver->__call($name, $args);
} catch (ConnectionException $e) {
$connected = false;
usleep(Resque::DEFAULT_INTERVAL * 1000000);
continue;
} catch (Exception $e) {
try {
$this->driver->ping();
} catch (CredisException $e) {
$connected = false;
usleep(Resque::DEFAULT_INTERVAL * 1000000);
continue;
}
return false;
}
}
}
public static function getPrefix()
{
return self::$defaultNamespace;
}
public static function removePrefix($string)
{
$prefix=self::getPrefix();
if (substr($string, 0, strlen($prefix)) == $prefix) {
$string = substr($string, strlen($prefix), strlen($string) );
}
return $string;
}
}
| Symplicity/php-resque | lib/Resque/Redis.php | PHP | mit | 4,836 |
'use strict';
define(['utils', 'loop'], function (Utils, Loop) {
'use strict';
var index = 0;
var imageQueue = [];
var loadLimit = 3;
var loading = 0;
var loadingBar = null;
var visualProgress = 0;
var onLoadCallback = null;
var loaded = 0;
var loadTotal = 0;
/**
* FUNCTION DEFINITIONS
*/
function setOnLoad(onLoad) {
onLoadCallback = onLoad;
document.body.removeChild(getLoadingBar());
}
function loadImage(url, onLoad) {
var image = new Image();
image.onload = function (event) {
onLoad.call(image, event);
loading--;
loaded++;
checkLoad();
};
image.crossOrigin = '';
imageQueue.push({
image: image,
url: url
});
loadTotal++;
checkLoad();
return image;
}
function loadFile(url, onLoad) {
loadTotal++;
Utils.loadAsync(url, function (result) {
loaded++;
onLoad(result);
});
}
function checkLoad() {
while (index < imageQueue.length && loading < loadLimit) {
imageQueue[index].image.src = imageQueue[index].url;
index++;
loading++;
}
if (index === imageQueue.length) {
index = 0;
imageQueue.length = 0;
loaded = 0;
loadTotal = 0;
}
}
function getLoadingProgress() {
return !loadTotal ? 1 : loaded / loadTotal;
}
function refreshLoadingBar() {
if (loadingBar) {
var ctx = loadingBar.getContext("2d");
var actualProgress = getLoadingProgress();
visualProgress = Math.max(0, visualProgress + (actualProgress - visualProgress) / 10);
if (actualProgress >= 1) {
visualProgress = 1;
Loop.removeLoop(refreshLoadingBar);
}
ctx.fillRect(10, 10, (loadingBar.width - 20) * visualProgress, loadingBar.height - 20);
if (actualProgress >= 1) {
if (onLoadCallback) {
setTimeout(onLoadCallback, 100);
}
}
}
}
function getLoadingBar() {
if (!loadingBar) {
loadingBar = document.createElement("canvas");
loadingBar.id = "loading";
loadingBar.width = Math.round(innerWidth * 2 * 2 / 3);
loadingBar.height = 50;
loadingBar.style.left = innerWidth / 2 - loadingBar.width / 4 + "px";
loadingBar.style.top = innerHeight / 2 - loadingBar.height / 4 + "px";
loadingBar.style.width = loadingBar.width / 2 + "px";
loadingBar.style.height = loadingBar.height / 2 + "px";
loadingBar.style.position = "absolute";
loadingBar.style.backgroundColor = "white";
loadingBar.style.border = "10px double #00DDDD";
var ctx = loadingBar.getContext("2d");
ctx.fillStyle = "#0066aa";
Loop.addLoop(refreshLoadingBar);
}
document.body.appendChild(loadingBar);
return loadingBar;
}
function destroyEverything() {
imageQueue.length = 0;
}
/**
* PUBLIC DECLARATIONS
*/
function Loader() {}
Loader.loadImage = loadImage;
Loader.loadFile = loadFile;
Loader.getLoadingProgress = getLoadingProgress;
Loader.getLoadingBar = getLoadingBar;
Loader.setOnLoad = setOnLoad;
Utils.onDestroy(destroyEverything);
return Loader;
});
//# sourceMappingURL=loader.js.map | jacklehamster/dok | dist/loader.js | JavaScript | mit | 3,623 |
'use strict';
var Alert = require('./Alert');
var Instance = require('../classes/Instance');
var SearchContext = require('./SearchContext');
var WebElement = require('./WebElement');
var Cookie = require('../classes/Cookie');
var Dimension = require('../classes/Dimension');
var Long = require('../imports').Long;
var Point = require('../classes/Point');
var extend = require('../utils').extend;
var addFinalProp = require('../utils').addFinalProp;
var collectionToArray = require('../utils').collectionToArray;
var assert = require('../assert');
var TimeUnit = require('../enums/TimeUnit');
module.exports = WebDriver;
extend(WebDriver, SearchContext);
function WebDriver(_instance) {
addFinalProp(this, '_instance', _instance);
}
WebDriver.prototype.close = function() {
this._instance.closeSync();
};
WebDriver.prototype.get = function(src) {
this._instance.getSync(src);
};
WebDriver.prototype.getCurrentUrl = function() {
return this._instance.getCurrentUrlSync();
};
WebDriver.prototype.getPageSource = function() {
return this._instance.getPageSourceSync();
};
WebDriver.prototype.getTitle = function() {
return this._instance.getTitleSync();
};
WebDriver.prototype.getWindowHandle = function() {
return this._instance.getWindowHandle();
};
WebDriver.prototype.getWindowHandles = function() {
return collectionToArray(this._instance.getWindowHandlesSync());
};
//TODO
WebDriver.prototype.manage = function() {
return new Options(this._instance.manageSync());
};
WebDriver.prototype.navigate = function() {
return new Navigation(this._instance.navigateSync());
};
WebDriver.prototype.quit = function() {
this._instance.quitSync();
};
WebDriver.prototype.switchTo = function() {
return new TargetLocator(this._instance.switchToSync());
};
WebDriver.prototype.ImeHandler = ImeHandler;
WebDriver.prototype.Navigation = Navigation;
WebDriver.prototype.Options = Options;
WebDriver.prototype.TargetLocator = TargetLocator;
WebDriver.prototype.Timeouts = Timeouts;
WebDriver.prototype.Window = Window;
//IME HANDLER
function ImeHandler(instance) {
addFinalProp(this, '_instance', instance);
}
ImeHandler.prototype.activateEngine = function(engine) {
this._instance.activateEngineSync(engine);
};
ImeHandler.prototype.deactivate = function() {
this._instance.deactivateSync();
};
ImeHandler.prototype.getActiveEngine = function() {
return this._instance.getActiveEngineSync();
};
ImeHandler.prototype.getAvailableEngines = function() {
return collectionToArray(this._instance.getAvailableEnginesSync);
};
ImeHandler.prototype.isActivated = function() {
return this._instance.isActivatedSync();
};
//NAVIGATION
function Navigation(instance) {
addFinalProp(this, '_instance', instance);
}
Navigation.prototype.back = function() {
this._instance.backSync();
};
Navigation.prototype.forward = function() {
this._instance.forwardSync();
};
Navigation.prototype.refresh = function() {
this._instance.refreshSync();
};
Navigation.prototype.to = function(url) {
this._instance.toSync(url);
};
//OPTIONS
function Options(instance) {
addFinalProp(this, '_instance', instance);
}
Options.prototype.addCookie = function(cookie) {
assertIsCookie(cookie);
this._instance.addCookieSync(cookie._instance);
};
Options.prototype.deleteAllCookies = function() {
this._instance.deleteAllCookiesSync();
};
Options.prototype.deleteCookie = function(cookie) {
assertIsCookie(cookie);
this._instance.deleteCookieSync(cookie._instance);
};
Options.prototype.deleteCookieNamed = function(name) {
this._instance.deleteCookieNamedSync(name);
};
Options.prototype.getCookieNamed = function(name) {
var proposedCookie = this._instance.getCookieNamedSync(name);
if (proposedCookie) {
return new Cookie(new Instance(proposedCookie));
}
return null;
};
Options.prototype.getCookies = function() {
var cookies = this._instance.getCookiesSync();
var arr = collectionToArray(cookies, function(item) {
return new Cookie(new Instance(item));
});
return arr;
};
Options.prototype.ime = function() {
return new ImeHandler(this._instance.imeSync());
};
Options.prototype.timeouts = function() {
return new Timeouts(this._instance.timeoutsSync());
};
Options.prototype.window = function() {
return new Window(this._instance.windowSync());
};
//TARGET LOCATOR
function TargetLocator(instance) {
addFinalProp(this, '_instance', instance);
}
TargetLocator.prototype.activeElement = function() {
return new WebElement(
this._instance.activeElementSync()
);
};
TargetLocator.prototype.alert = function() {
return new Alert(this._instance.alertSync());
};
TargetLocator.prototype.defaultContent = function() {
return new WebDriver(this._instance.defaultContentSync());
};
TargetLocator.prototype.frame = function(proposed) {
var arg;
if (proposed instanceof WebElement) {
arg = proposed._instance;
} else {
arg = proposed;
}
return new WebDriver(this._instance.frameSync(arg));
};
TargetLocator.prototype.window = function(name) {
return new WebDriver(this._instance.windowSync(name));
};
function Timeouts(instance) {
addFinalProp(this, '_instance', instance);
}
Timeouts.prototype.implicitlyWait = function(time, unit) {
assertIsTimeUnit(unit);
return new this.constructor(
this._instance.implicitlyWaitSync(new Long(time), unit._instance)
);
};
Timeouts.prototype.pageLoadTimeout = function(time, unit) {
assertIsTimeUnit(unit);
return new this.constructor(
this._instance.pageLoadTimeoutSync(new Long(time), unit._instance)
);
};
Timeouts.prototype.setScriptTimeout = function(time, unit) {
assertIsTimeUnit(unit);
return new this.constructor(
this._instance.setScriptTimeoutSync(new Long(time), unit._instance)
);
};
function Window(instance) {
addFinalProp(this, '_instance', instance);
}
Window.prototype.getPosition = function() {
return new Point(this._instance.getPositionSync());
};
Window.prototype.getSize = function() {
return new Dimension(this._instance.getSizeSync());
};
Window.prototype.maximize = function() {
this._instance.maximizeSync();
};
Window.prototype.setPosition = function(targetPosition) {
if (!(targetPosition instanceof Point)) {
throw new Error('argument must be a Point');
}
this._instance.setPositionSync(targetPosition._instance);
};
Window.prototype.setSize = function(targetSize) {
if (!(targetSize instanceof Dimension)) {
throw new Error('argument must be a Dimension');
}
this._instance.setSizeSync(targetSize._instance);
};
//utils
function assertIsCookie(cookie) {
if (!(cookie instanceof Cookie)) {
throw new Error('argument wasn\'t an instance of Cookie.');
}
}
function assertIsTimeUnit(unit){
assert(unit)
.extends(TimeUnit)
.throws('unit must be an instance of TimeUnit');
} | jsdevel/travis-debugging | src/interfaces/WebDriver.js | JavaScript | mit | 6,798 |
import * as d3 from 'd3-collection';
import Vue from 'vue';
import shortid from 'shortid';
import {camelCase} from '../utils';
import staticPresets from './presets/static';
import dynamicPresets from './presets/dynamic';
let initialFilters = {
group_root: {
parent: null,
key: 'and',
content: [],
id: 'root',
display: {
name: '',
hidden: false,
temp: false
}
}
};
let filters = {
namespaced: true,
modules: {
staticPresets,
dynamicPresets
},
state: {
items: {...initialFilters},
parsingError: null
},
getters: {
count: (state) => (ignoreTemp) => {
return d3.entries(state.items).filter(c => ignoreTemp ? !c.value.display.temp : true).length;
},
getFilterById: (state) => (id) => {
return state.items[id];
},
getChildren: (state) => (id, asArray) => {
let children = d3.entries(state.items)
.filter(f => f.value.parent === id);
if (asArray) {
return children;
}
else {
return d3.nest()
.key(d => d.key)
.rollup(d => d[0].value)
.object(children);
}
},
getNestLevel: (state, getters) => (id) => {
let filter = getters.getFilterById(id);
let nestLevel = 0;
while (filter.parent !== null) {
nestLevel++;
filter = getters.getFilterById(filter.parent);
}
return nestLevel;
},
queryfy: (state, getters) => (id, ignoreTemp) => {
let data = state.items[id];
let queryData = {};
let isGroup = id.startsWith('group_');
if (!isGroup) {
queryData[data.key] = data.content;
}
else {
let children = getters.getChildren(id, true)
.filter(c => ignoreTemp ? !c.value.display.temp : true);
if (children.length > 0) {
let childData = children.map(c => getters.queryfy(c.key, ignoreTemp)).filter(c => c !== undefined);
if (childData.length > 0) {
queryData[data.key] = childData;
}
}
else {
return;
}
}
return queryData;
},
hasFilter: (state) => (payload) => {
// TODO: check for equality in a better/more consistent way
let filterContent = JSON.stringify(payload.content);
return d3.values(state.items).some(i => {
return payload.parent === i.parent && payload.key === i.key && filterContent === JSON.stringify(i.content);
})
},
presets: (state, getters) => {
return $.extend(getters['staticPresets/presets'], getters['dynamicPresets/presets'])
},
temporaryFilters: (state) => {
return d3.entries(state.items).filter(f => f.value.display.temp);
}
},
mutations: {
setFromQuery(state, query) {
let currentState = {...state.items};
try {
if (query.filters === undefined) {
state.items = {...initialFilters};
}
else {
let dequeryfy = (items, parent) => {
let itemList = {};
items.forEach((i) => {
let item = d3.entries(i)[0];
if (Array.isArray(item.value)) {
let groupId = parent === null ? 'group_root' : `group_${shortid.generate()}`;
itemList[groupId] = {
parent: parent,
key: item.key,
content: [],
display: {}
};
d3.entries(dequeryfy(item.value, groupId)).forEach((f) => {
itemList[f.key] = f.value;
});
}
else {
itemList[`term_${shortid.generate()}`] = {
parent: parent,
key: item.key,
content: item.value,
display: {}
}
}
});
return itemList;
};
let dequeried = dequeryfy([query.filters], null);
state.items = {...dequeried};
}
state.parsingError = null;
} catch (e) {
state.parsingError = e;
// revert back to previous state
state.items = {...currentState};
}
},
changeKey(state, payload) {
Vue.set(state.items[payload.id], 'key', payload.key);
},
changeContent(state, payload) {
Vue.set(state.items[payload.id], 'content', payload.content);
},
changeName(state, payload) {
Vue.set(state.items[payload.id].display, 'name', payload.name);
},
deleteFilter(state, filterId) {
if (state.items[filterId].parent === null) {
return;
}
Vue.delete(state.items, filterId)
},
resetFilters(state) {
state.items = {...initialFilters};
},
addFilter(state, payload) {
let newFilter = {
parent: payload.parent,
key: payload.key,
content: payload.content,
id: payload.id || shortid.generate(),
display: {
name: payload.display.name || '',
hidden: payload.display.hidden || false,
temp: payload.display.temp || false
}
};
let filterKey;
if (newFilter.display.name !== '') {
filterKey = camelCase(newFilter.display.name);
}
else {
filterKey = newFilter.id;
}
let filterName = `${payload.type}_${filterKey}`;
Vue.set(state.items, filterName, newFilter);
}
},
actions: {
addGroup(context, payload) {
payload.display = payload.display || {};
let newGroup = {
parent: payload.parent,
key: 'and',
content: [],
id: payload.id || shortid.generate(),
type: 'group',
display: {
name: payload.display.name || '',
hidden: payload.display.hidden || false,
temp: payload.display.temp || false
}
};
context.commit('addFilter', newGroup)
},
addTerm(context, payload) {
payload.display = payload.display || {};
let newTerm = {
parent: payload.parent,
key: payload.key,
content: payload.content,
id: payload.id || shortid.generate(),
type: 'term',
display: {
name: payload.display.name || '',
hidden: payload.display.hidden || false,
temp: payload.display.temp || false
}
};
context.commit('addFilter', newTerm)
},
addPreset(context, payload) {
let preset;
if (context.getters['staticPresets/keys'].includes(payload.key)) {
preset = context.state.staticPresets[payload.key];
}
else if (context.getters['dynamicPresets/keys'].includes(payload.key)) {
let presetDetails = context.state.dynamicPresets[payload.key];
let args = {};
presetDetails.args.state.forEach(s => {
args[s] = context.rootState[s];
});
presetDetails.args.getters.forEach(g => {
args[g] = context.rootGetters[g]
});
preset = context.getters[`dynamicPresets/${payload.key}`](args);
}
else {
return;
}
payload.display = payload.display || {};
let newFilter = {
parent: payload.parent,
key: preset.key,
content: preset.content,
id: camelCase(preset.display.name) + payload.parent.replace('group_', ''),
type: preset.type,
display: {
name: preset.display.name || '',
hidden: payload.display.hidden || false,
temp: payload.display.temp || false
}
};
if (!context.getters.hasFilter(newFilter)) {
context.commit('addFilter', newFilter);
return true;
}
return false;
},
deleteTemporaryFilters(context) {
let deleteCount = 0;
d3.entries(context.state.items).filter(f => f.value.display.temp).forEach(f => {
context.commit('deleteFilter', f.key);
deleteCount++;
});
return deleteCount;
},
}
};
export default filters; | NaturalHistoryMuseum/ckanext-nhm | ckanext/nhm/theme/assets/scripts/apps/search/src/store/query/filters.js | JavaScript | mit | 10,063 |
/*******************************************************************************
* Copyright (c) 2012 Romain Quinio (http://code.google.com/p/l10n-maven-plugin)
*
* 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.
******************************************************************************/
package com.googlecode.l10nmavenplugin.model;
import java.util.Locale;
import java.util.Properties;
import java.util.Set;
/**
* Wrapper around a {@link java.util.Properties} object, to add info on the file itself.
*
* @since 1.4
* @author romain.quinio
*
*/
public interface PropertiesFile {
/**
* The file name (ex: bundle_en.properties), the naming convention being bundleName_locale.properties.
* <p>
* It may contain sub-folders, i.e. "com/mycompany/a/bundle_en.properties".
*
* @return
*/
String getFileName();
/**
* The name of the bundle (i.e file name without locale nor file extension), i.e "MyBundle".
* <p>
* In case the bundle is in a sub-folder, paths to the root folder are separated by ".", i.e "com.mycompany.a.MyBundle" and "com.mycompany.b.MyBundle"
*/
String getBundleName();
/**
* The {@link Locale} of the file
*
* @return null if unknown, or file is root
*/
Locale getLocale();
/**
* The {@link Properties} object loaded from the file
*
* @return
*/
Properties getProperties();
/**
* Set of keys for resources whose value is not unique in the file
*
* @return
*/
Set<String> getDuplicatedResourceKeys();
}
| rquinio/l10n-maven-plugin | src/main/java/com/googlecode/l10nmavenplugin/model/PropertiesFile.java | Java | mit | 2,519 |
module Rglossa
class CorpusText < ActiveRecord::Base
self.table_name = "rglossa_corpus_texts"
belongs_to :corpus
has_and_belongs_to_many :metadata_values, join_table: 'rglossa_corpus_texts_metadata_values',
foreign_key: 'rglossa_corpus_text_id',
association_foreign_key: 'rglossa_metadata_value_id'
class << self
def by_tid(tid)
joins('INNER JOIN rglossa_corpus_texts_metadata_values j ON ' +
'j.rglossa_corpus_text_id = rglossa_corpus_texts.id')
.joins('INNER JOIN rglossa_metadata_values v ON j.rglossa_metadata_value_id = v.id')
.joins('INNER JOIN rglossa_metadata_categories c ON v.metadata_category_id = c.id')
.where(c: {short_name: 'tid'}, v: { text_value: tid })
end
# Returns start and stop positions of all corpus texts that are associated with the
# metadata values that have the given database ids, with an OR relationship between values
# within the same category and an AND relationship between categories.
# TODO: This is MySQL-specific syntax - implement for other databases as well
def print_positions_matching_metadata(metadata, positions_filename)
cat_sqls = ["SELECT DISTINCT #{position_field_str} FROM rglossa_corpus_texts t"]
i = 0
conditions = []
metadata.each do |category_id, value_ids|
i += 1
if i == 1
cat_sqls << "rglossa_corpus_texts_metadata_values j1 " +
"ON j1.rglossa_corpus_text_id = t.id " +
"INNER JOIN rglossa_metadata_values v1 " +
"ON j1.rglossa_metadata_value_id = v1.id"
else
cat_sqls << "rglossa_corpus_texts_metadata_values j#{i} " +
"ON j#{i}.rglossa_corpus_text_id = j#{i - 1}.rglossa_corpus_text_id " +
"INNER JOIN rglossa_metadata_values v#{i} " +
"ON j#{i}.rglossa_metadata_value_id = v#{i}.id "
end
conditions << sanitize_sql(["v#{i}.id IN (?) AND v#{i}.metadata_category_id = ?",
value_ids.map(&:to_i), category_id.to_i])
end
sql = cat_sqls.join(' INNER JOIN ')
write_positions(positions_filename, conditions, sql)
end
########
private
########
# Overridden by Speaker
def position_field_str
'startpos, endpos'
end
# Overridden by Speaker
def run_query(sql)
connection.select_rows(sql)
end
# Overridden by Speaker
def write_positions(filename, conditions, sql)
if ENV['DATABASE_URL'].start_with?('sqlite3')
# for SQLite
sql << " WHERE #{conditions.join(" AND ")} AND positions IS NOT NULL"
rows = run_query(sql)
# in CorpusText, each row contains a pair of start and end positions that
# need to be joined by tab before being written to file
File.write(filename, rows.map {|r| r.join("\t")}.join("\n"))
else
# for MySQL
sql << " WHERE #{conditions.join(" AND ")} INTO OUTFILE '#{filename}'"
connection.execute(sql)
end
end
end
end
end
| textlab/glossa | app/models/rglossa/corpus_text.rb | Ruby | mit | 3,243 |
/*
Copyright (c) 2003-2019, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
*/
CKEDITOR.plugins.setLang( 'showblocks', 'hi', {
toolbar: 'ब्लॉक दिखायें'
} );
| otto-torino/gino | ckeditor/plugins/showblocks/lang/hi.js | JavaScript | mit | 276 |
SBPHP - PHP framework for kids
==============================
The SpongeBob PHP framework.
SBPHP框架 - 幼齿专用
====================
难以置信的简单, 无与伦比的优雅.
| allengaller/the-sbphp-framework | website/README.md | Markdown | mit | 189 |
<?php
namespace Asignaciones\UsuarioBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
class UsuarioType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('username')
->add('password', 'password')
->add('salt')
->add('nombre')
->add('apellido')
->add('email', 'email')
->add('role', 'choice', array('choices' => array('ROLE_ADMIN' => 'Administrador', 'ROLE_USER' => 'Usuario')))
->add('esta_activo', 'checkbox')
;
}
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'Asignaciones\UsuarioBundle\Entity\Usuario'
));
}
public function getName()
{
return 'usuario';
}
}
| drko-dev/asignaciones | src/Asignaciones/UsuarioBundle/Form/UsuarioType.php | PHP | mit | 1,002 |
""" From chapter 6 about the "ness" of word vectors:
Compose a word vector for each "ness" like placeness, humanness, femaleness, etc
Provide a nessvector for any given word
>>> nessvector('Seattle')
placeness 0.257971
peopleness -0.059435
animalness -0.014691
conceptness 0.175459
femaleness -0.359303
dtype: float64
>>> nessvector('Portland')
placeness 0.365310
peopleness -0.198677
animalness 0.065087
conceptness 0.020675
femaleness -0.252396
dtype: float64
>>> nessvector('Marie_Curie')
placeness -0.463387
peopleness 0.354787
animalness 0.171099
conceptness -0.320268
femaleness 0.257770
dtype: float64
>>> nessvector('Timbers')
placeness -0.039665
peopleness 0.279271
animalness -0.328952
conceptness 0.187153
femaleness -0.097807
dtype: float64
>>> nessvector('Marie_Curie').round(2)
placeness -0.46
peopleness 0.35
animalness 0.17
conceptness -0.32
femaleness 0.26
dtype: float64
Now try to find the answer to the original question... it's hard.
>>> WV.most_similar(
... 'French France woman famous scientist chemistry Nobel_Prize radiation physics name person human'.split(),
... negative='man man man man school ecole place country'.split())
...
[('Pierre_Curie', 0.48349958658218384),
('Henri_Becquerel', 0.47997117042541504),
('Otto_Warburg', 0.4735907316207886),
('blackbody_radiation', 0.47254103422164917),
('Nobelist', 0.46358683705329895),
('Kary_Mullis', 0.4630542993545532),
('Seoul_Soongsil_University', 0.461331844329834),
('George_Gamow', 0.45909202098846436),
('Nobel_Chemistry', 0.45735475420951843),
('Alivisatos', 0.45495474338531494)]
>>> WV.most_similar(
... 'Pierre_Curie Nobel_Prize famous smart French physics woman women person name'.split(),
... negative='man male male geography city Pierre prize'.split())
...
[('Madame_Curie', 0.441272497177124),
('Ada_Lovelace', 0.4309345483779907),
('economist_Franco_Modigliani', 0.42140281200408936),
('physicist_Niels_Bohr', 0.4198070168495178),
('Murray_Gell_Mann', 0.41829752922058105),
('George_Gamow', 0.4176127314567566),
('brilliant_mathematician', 0.41744932532310486),
('Bertha_von_Suttner', 0.4144267439842224),
('Norbert_Wiener', 0.41063863039016724),
('Charles_Babbage', 0.40797877311706543)]
TODO:
automate the search for synonyms with higher than 60% similarity, walking a shallow graph
"""
import os
from collections import OrderedDict
import pandas as pd
from nlpia.data.loaders import get_data, BIGDATA_PATH
from gensim.models import KeyedVectors
word_vectors = get_data('word2vec') # not in book
wordvector_path = os.path.join(BIGDATA_PATH, 'GoogleNews-vectors-negative300.bin.gz') # not in book, reader required to compose this path
if 'word_vectors' not in globals(): # not in book
WV = word_vectors = get_data('word2vec')
word_vectors = KeyedVectors.load_word2vec_format(wordvector_path, binary=True)
###################################################
# Still need to create a class derived from gensim's Word2vec model instead of relying on word_vectors globals
COMPONENT_WORDS = OrderedDict([
('placeness', ('geography Geography geographic geographical geographical_location location ' +
'locale locations proximity').split()),
('peopleness', 'human Humans homo_sapiens peole people individuals humankind people men women'.split()),
('animalness', 'animal mammal carnivore animals Animal animal_welfare dog pet cats ani_mal'.split()),
('conceptness', 'concept concepts idea'.split()),
('femaleness', 'female Female females femal woman girl lady'.split()),
])
def component_vector(words):
vector = np.zeros(300)
for word in words:
v = word_vectors[word]
vector += v / len(words)
return vector
COMPONENTS = pd.DataFrame([component_vector(words) for (component, words) in COMPONENT_WORDS.items()],
index=[component for (component, words) in COMPONENT_WORDS.items()])
def nessvector(target, components=COMPONENTS):
target = word_vectors[target] if isinstance(target, str) else target
vector = word_vectors.cosine_similarities(target, components.values)
return pd.Series((vector - vector.mean()) / .15, index=components.index)
#
##############################################################
def nessvector_marie_curie():
global word_vectors # so the indexing doesn't have to be done again
word_vectors['Marie_Curie']
word_vectors['place'].std()
word_vectors['place'].min()
word_vectors['place'].max()
word_vectors.most_similar('place')
word_vectors.most_similar('location')
word_vectors.most_similar('geography')
placeness = np.zeros(300)
for word in COMPONENT_WORDS['placeness']:
v = word_vectors[word]
print(v.min(), v.max())
placeness += v
placeness /= 9.
word_vectors.cosine_similarities(placeness,
[word_vectors[word] for word in
'place geography location address position'.split()])
word_vectors.most_similar('animal')
animalness = np.zeros(300)
animalness = np.zeros(300)
for word in 'animal mammal carnivore animals Animal animal_welfare dog pet cats ani_mal'.split():
v = word_vectors[word]
print(v.min(), v.max())
animalness += v / 10.
word_vectors.similar_by_vector(animalness)
word_vectors.most_similar('people')
word_vectors.most_similar('humans')
peopleness = np.zeros(300)
for word in 'human Humans homo_sapiens peole people individuals humankind people men women'.split():
v = word_vectors[word]
print(v.min(), v.max())
peopleness += v / 10.
word_vectors.similar_by_vector(peopleness)
word_vectors.similar_by_vector(animalness)
word_vectors.similar_by_vector(placeness)
target = word_vectors['Marie_Curie']
word_vectors.cosine_similarities(target, [peopleness, animalness, placeness])
word_vectors.most_similar('concept')
conceptness = np.zeros(300)
for word in 'concept concepts idea'.split():
v = word_vectors[word]
print(v.min(), v.max())
conceptness += v / 3.
target = word_vectors['Marie_Curie']
word_vectors.cosine_similarities(target, [peopleness, animalness, placeness, conceptness])
word_vectors.most_similar('female')
word_vectors.most_similar('woman')
femaleness = np.zeros(300)
for word in 'female Female females femal woman girl lady'.split():
v = word_vectors[word]
femaleness += v / 7.
word_vectors.similar_by_vector(conceptness)
word_vectors.similar_by_vector(femaleness)
target = word_vectors['Marie_Curie']
mc_nessvector = word_vectors.cosine_similarities(
target,
[peopleness, animalness, placeness, conceptness, femaleness])
return mc_nessvector
def semantic_search():
global word_vectors # so the indexing doesn't have to be done again
word_vectors.most_similar(
'French France woman famous scientist chemistry Nobel_Prize radiation physics name person human'.split(),
negative='man man man man school ecole place country'.split())
# [('Pierre_Curie', 0.48349958658218384),
# ('Henri_Becquerel', 0.47997117042541504),
# ('Otto_Warburg', 0.4735907316207886),
# ('blackbody_radiation', 0.47254103422164917),
# ('Nobelist', 0.46358683705329895),
# ('Kary_Mullis', 0.4630542993545532),
# ('Seoul_Soongsil_University', 0.461331844329834),
# ('George_Gamow', 0.45909202098846436),
# ('Nobel_Chemistry', 0.45735475420951843),
# ('Alivisatos', 0.45495474338531494)]
word_vectors.most_similar(
'Pierre_Curie Nobel_Prize famous smart French physics woman women person name'.split(),
negative='man male male geography city Pierre prize'.split())
if __name__ == '__main__':
print(nessvector_marie_curie())
| totalgood/nlpia | src/nlpia/book/examples/ch06_nessvectors.py | Python | mit | 7,975 |
package parser
import (
"bytes"
"encoding/json"
"fmt"
"strings"
"google.golang.org/protobuf/encoding/protojson"
)
func ExampleDiffParser() {
const sample = `diff --git a/gofmt.go b/gofmt.go
--- a/gofmt.go 2020-07-26 08:01:09.260800318 +0000
+++ b/gofmt.go 2020-07-26 08:01:09.260800318 +0000
@@ -1,6 +1,6 @@
package testdata
-func fmt () {
+func fmt() {
// test
// test line
// test line
@@ -10,11 +10,11 @@
// test line
// test line
-println(
- "hello, gofmt test" )
-//comment
+ println(
+ "hello, gofmt test")
+ //comment
}
+type s struct{ A int }
-type s struct { A int }
func (s s) String() { return "s" }
`
const strip = 1
p := NewDiffParser(strip)
diagnostics, err := p.Parse(strings.NewReader(sample))
if err != nil {
panic(err)
}
for _, d := range diagnostics {
rdjson, _ := protojson.MarshalOptions{Indent: " "}.Marshal(d)
var out bytes.Buffer
json.Indent(&out, rdjson, "", " ")
fmt.Println(out.String())
}
// Output:
// {
// "location": {
// "path": "gofmt.go",
// "range": {
// "start": {
// "line": 3
// },
// "end": {
// "line": 3
// }
// }
// },
// "suggestions": [
// {
// "range": {
// "start": {
// "line": 3
// },
// "end": {
// "line": 3
// }
// },
// "text": "func fmt() {"
// }
// ],
// "originalOutput": "gofmt.go:3:-func fmt () {\ngofmt.go:3:+func fmt() {"
// }
// {
// "location": {
// "path": "gofmt.go",
// "range": {
// "start": {
// "line": 13
// },
// "end": {
// "line": 15
// }
// }
// },
// "suggestions": [
// {
// "range": {
// "start": {
// "line": 13
// },
// "end": {
// "line": 15
// }
// },
// "text": "\tprintln(\n\t\t\"hello, gofmt test\")\n\t//comment"
// }
// ],
// "originalOutput": "gofmt.go:13:-println(\ngofmt.go:14:-\t\t\"hello, gofmt test\" )\ngofmt.go:15:-//comment\ngofmt.go:13:+\tprintln(\ngofmt.go:14:+\t\t\"hello, gofmt test\")\ngofmt.go:15:+\t//comment"
// }
// {
// "location": {
// "path": "gofmt.go",
// "range": {
// "start": {
// "line": 18,
// "column": 1
// },
// "end": {
// "line": 18,
// "column": 1
// }
// }
// },
// "suggestions": [
// {
// "range": {
// "start": {
// "line": 18,
// "column": 1
// },
// "end": {
// "line": 18,
// "column": 1
// }
// },
// "text": "type s struct{ A int }\n"
// }
// ],
// "originalOutput": "gofmt.go:18:+type s struct{ A int }"
// }
// {
// "location": {
// "path": "gofmt.go",
// "range": {
// "start": {
// "line": 19
// },
// "end": {
// "line": 19
// }
// }
// },
// "suggestions": [
// {
// "range": {
// "start": {
// "line": 19
// },
// "end": {
// "line": 19
// }
// }
// }
// ],
// "originalOutput": "gofmt.go:19:-type s struct { A int }"
// }
}
| haya14busa/reviewdog | parser/diff_test.go | GO | mit | 3,332 |
using System.ComponentModel.DataAnnotations;
namespace CarSystem.Web.Models.Account
{
public class LoginViewModel
{
[Required]
[Display(Name = "Email")]
[EmailAddress]
public string Email { get; set; }
[Required]
[DataType(DataType.Password)]
[Display(Name = "Password")]
public string Password { get; set; }
[Display(Name = "Remember me?")]
public bool RememberMe { get; set; }
}
} | Azonic89/My-ASP.NET-MVC-Project | CarSystem/Web/CarSystem.Web/Models/Account/LoginViewModel.cs | C# | mit | 480 |
var
fs = require('fs'),
join = require('path').join;
module.exports = function (result) {
// file that should be removed
var fd = fs.openSync(join(result.name, 'should-be-removed.file'), 'w');
fs.closeSync(fd);
// in tree source
var symlinkSource = join(__dirname, 'fixtures', 'symlinkme');
// testing target
var symlinkTarget = join(result.name, 'symlinkme-target');
// symlink that should be removed but the contents should be preserved.
// Skip on Windows because symlinks require elevated privileges (instead just
// create the file)
if (process.platform === 'win32') {
fs.writeFileSync(symlinkTarget);
} else {
fs.symlinkSync(symlinkSource, symlinkTarget, 'dir');
}
this.out(result.name);
};
| raszi/node-tmp | test/outband/unsafe.js | JavaScript | mit | 745 |
/* chromatic universe 2017 william k. johnson */
// Generated from /cci_src/imap2017/src/antlr-c++/src/grammars/action_expr.g4 by ANTLR 4.7
#pragma once
/* parser precinclude section */
#include <iostream>
#include <map>
#include <string>
#include <memory>
#include <sstream>
#include <utility>
#include "antlr4-runtime.h"
namespace action_expr {
class action_exprParser : public antlr4::Parser {
public:
enum {
T__0 = 1, T__1 = 2, T__2 = 3, MUL = 4, DIV = 5, ADD = 6, SUB = 7, ID = 8,
INT = 9, NEWLINE = 10, WS = 11
};
enum {
RuleStat = 0, RuleE = 1
};
action_exprParser(antlr4::TokenStream *input);
~action_exprParser();
virtual std::string getGrammarFileName() const override;
virtual const antlr4::atn::ATN& getATN() const override { return _atn; };
virtual const std::vector<std::string>& getTokenNames() const override { return _tokenNames; }; // deprecated: use vocabulary instead.
virtual const std::vector<std::string>& getRuleNames() const override;
virtual antlr4::dfa::Vocabulary& getVocabulary() const override;
/** "memory" for our calculator; variable/value pairs go here */
std::map<std::string ,unsigned> m_calc_dictionary;
int eval(int left, int op, int right) {
switch ( op ) {
case MUL : return left * right;
case DIV : return left / right;
case ADD : return left + right;
case SUB : return left - right;
}
return 0;
}
class StatContext;
class EContext;
class StatContext : public antlr4::ParserRuleContext {
public:
action_exprParser::EContext *eContext = nullptr;;
antlr4::Token *idToken = nullptr;;
StatContext(antlr4::ParserRuleContext *parent, size_t invokingState);
virtual size_t getRuleIndex() const override;
EContext *e();
antlr4::tree::TerminalNode *NEWLINE();
antlr4::tree::TerminalNode *ID();
virtual antlrcpp::Any accept(antlr4::tree::ParseTreeVisitor *visitor) override;
};
StatContext* stat();
class EContext : public antlr4::ParserRuleContext {
public:
int v;
action_exprParser::EContext *a = nullptr;;
antlr4::Token *intToken = nullptr;;
antlr4::Token *idToken = nullptr;;
action_exprParser::EContext *eContext = nullptr;;
antlr4::Token *op = nullptr;;
action_exprParser::EContext *b = nullptr;;
EContext(antlr4::ParserRuleContext *parent, size_t invokingState);
virtual size_t getRuleIndex() const override;
antlr4::tree::TerminalNode *INT();
antlr4::tree::TerminalNode *ID();
std::vector<EContext *> e();
EContext* e(size_t i);
virtual antlrcpp::Any accept(antlr4::tree::ParseTreeVisitor *visitor) override;
};
EContext* e();
EContext* e(int precedence);
virtual bool sempred(antlr4::RuleContext *_localctx, size_t ruleIndex, size_t predicateIndex) override;
bool eSempred(EContext *_localctx, size_t predicateIndex);
private:
static std::vector<antlr4::dfa::DFA> _decisionToDFA;
static antlr4::atn::PredictionContextCache _sharedContextCache;
static std::vector<std::string> _ruleNames;
static std::vector<std::string> _tokenNames;
static std::vector<std::string> _literalNames;
static std::vector<std::string> _symbolicNames;
static antlr4::dfa::Vocabulary _vocabulary;
static antlr4::atn::ATN _atn;
static std::vector<uint16_t> _serializedATN;
struct Initializer {
Initializer();
};
static Initializer _init;
};
} // namespace action_expr
| chromatic-universe/imap2017 | src/antlr-c++/include/action_exprParser.h | C | mit | 3,515 |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.1
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
//
// This code was auto-generated by AFNOR StoredProcedureSystem, version 1.0
//
using System;
using System.Collections.Generic;
using EspaceClient.FrontOffice.Domaine;
namespace EspaceClient.BackOffice.Silverlight.Business.Depots
{
/// <summary>
/// Dépôt des CategorieContacts.
/// </summary>
public partial interface IDepotCategorieContact
{
/// <summary>
/// Récupère toutes les données du dépôt.
/// </summary>
/// <param name="callback">Méthode à appeler lorsque l opération est terminée.</param>
void GetAll(Action<IEnumerable<CategorieContactDto>> callback, Action<Exception> error);
}
}
| apo-j/Projects_Working | EC/espace-client-dot-net/EspaceClient.BackOffice.Silverlight.Business/Depots/IDepotCategorieContact.Generated.cs | C# | mit | 1,069 |
#include "type.h"
////////////////////////////////////////////////////////////////////////////////
// Generic boxed data
////////////////////////////////////////////////////////////////////////////////
Box_ * box(void * content, void (*destruct_or)(void *), void * (*copier)(void *), void (*print_er)(void *))
{
Box_ * node = malloc(sizeof(Box_));
node -> content = content;
node -> destruct_or = destruct_or;
node -> copier = copier;
node -> print_er = print_er;
return node;
}
void * unbox(Box_ * node)
{
void * result = node -> content;
free(node);
return result;
}
Box_ * copy_(Box_ * node)
{
void * new_content = (node -> copier)(node -> content);
return box(new_content, node -> destruct_or, node -> copier, node -> print_er);
}
void destruct_(Box_ * node)
{
(node -> destruct_or)(node -> content);
free(node);
}
void print_(Box_ * node)
{
(node -> print_er)(node -> content);
}
////////////////////////////////////////////////////////////////////////////////
// Pair
////////////////////////////////////////////////////////////////////////////////
Pair * pair(Box_ * a, Box_ * b)
{
Pair * node = malloc(sizeof(Pair));
node -> Fst = a;
node -> Snd = b;
return node;
}
void * fst(Pair * node) {
return unbox(copy_(node -> Fst));
}
void * snd(Pair * node) {
return unbox(copy_(node -> Snd));
}
Pair * copy__pair(Pair * old)
{
return pair(copy_(old -> Fst), copy_(old -> Snd));
}
void free_pair(Pair * node)
{
destruct_(node -> Fst);
destruct_(node -> Snd);
free(node);
}
void print__pair(Pair * node)
{
printf("( ");
print_(node -> Fst);
printf(" , ");
print_(node -> Snd);
printf(" )");
}
Box_ * box_pair(Pair * node)
{
return box(node, (void (*)(void *))free_pair, (void * (*)(void *))copy__pair, (void (*)(void *))print__pair);
}
////////////////////////////////////////////////////////////////////////////////
// Either
////////////////////////////////////////////////////////////////////////////////
Either * left(Box_ * x)
{
Either * node = malloc(sizeof(Either));
node -> Left = x;
node -> Right = NULL;
return node;
}
Either * right(Box_ * x)
{
Either * node = malloc(sizeof(Either));
node -> Left = NULL;
node -> Right = x;
return node;
}
Either * copy__either(Either * node)
{
if (node -> Left) {
return left(copy_(node -> Left));
} else {
return right(copy_(node -> Right));
}
}
void free_either(Either * node)
{
if (node -> Left) {
destruct_(node -> Left);
} else {
destruct_(node -> Right);
}
}
void print__either(Either * node)
{
if (node -> Left) {
printf("Left ");
print_(node -> Left);
} else {
printf("Right ");
print_(node -> Right);
}
}
Box_ * box_either(Either * node)
{
return box(node, (void (*)(void *))free_either, (void * (*)(void *))copy__either, (void (*)(void *))print__either);
}
////////////////////////////////////////////////////////////////////////////////
// Maybe
////////////////////////////////////////////////////////////////////////////////
// typedef struct Maybe {
// Bool Nothing; // TRUE if Nothing, FALSE, if Just
// Box_ * Just;
// } Maybe;
Maybe * nothing()
{
Maybe * node = malloc(sizeof(Maybe));
node -> Nothing = TRUE;
node -> Just = NULL;
return node;
}
Maybe * just(Box_ * b)
{
Maybe * node = malloc(sizeof(Maybe));
node -> Nothing = FALSE;
node -> Just = b;
return node;
}
void * from_just(Maybe * node)
{
if (node -> Nothing) {
perror("from Nothing");
return NULL;
} else {
return unbox(copy_(node -> Just));
}
}
Maybe * copy__maybe(Maybe * node)
{
if (node -> Nothing) {
return nothing();
} else {
return just(copy_(node -> Just));
}
}
void print__maybe(Maybe * node)
{
if (node -> Nothing) {
printf("Nothing ");
} else {
printf("Just ");
print_(node -> Just);
}
}
void free_maybe(Maybe * node)
{
if (node -> Nothing) {
free(node);
} else {
destruct_(node -> Just);
free(node);
}
}
Box_ * box_maybe(Maybe * node)
{
return box(node, (void (*)(void *))free_maybe, (void * (*)(void *))copy__maybe, (void (*)(void *))print__maybe);
}
////////////////////////////////////////////////////////////////////////////////
// List_
////////////////////////////////////////////////////////////////////////////////
List_ * nil()
{
List_ * node = malloc(sizeof(List_));
node -> Nil = TRUE;
node -> Cons = NULL;
node -> data = NULL;
return node;
}
List_ * cons(Box_ * box, List_ * xs)
{
List_ * node = malloc(sizeof(List_));
node -> Nil = FALSE;
node -> data = box;
node -> Cons = xs;
return node;
}
// O(n)
List_ * snoc(List_ * xs, Box_ * box)
{
if (xs -> Nil) {
return cons(box, xs);
} else {
List_ * result = cons(xs -> data, snoc(xs -> Cons, box));
free(xs);
return result;
}
}
List_ * copy__list(List_ * xs)
{
if (xs -> Nil) {
return nil();
} else {
return cons(copy_(xs -> data), copy__list(xs -> Cons));
}
}
void * elemAt(List_ * xs, int n)
{
if (xs -> Nil) {
perror("indexing empty list");
return NULL;
} else {
if (n == 0) {
return head(xs);
} else if (n > 0) {
return elemAt(xs -> Cons, n - 1);
} else {
perror("invalid index number");
return NULL;
}
}
}
void * head(List_ * xs)
{
if (xs -> Nil) {
perror("head on empty list");
return NULL;
} else {
return unbox(copy_(xs -> data));
}
}
List_ * tail(List_ * xs)
{
if (xs -> Nil) {
perror("tail on empty list");
return NULL;
} else {
List_ * result = copy__list(xs -> Cons);
return result;
}
}
List_ * init(List_ * xs)
{
if (xs -> Nil) { // 0
perror("init on empty list");
return NULL;
} else if (xs -> Cons -> Nil) { // 1
return nil();
} else {
List_ * result = cons(copy_(xs -> data), init(xs -> Cons));
return result;
}
}
void * last(List_ * xs)
{
if (xs -> Nil) { // 0
perror("last on empty list");
return NULL;
} else if (xs -> Cons -> Nil) { // 1
void * result = unbox(copy_(xs -> data));
return result;
} else {
return last(xs -> Cons);
}
}
List_ * append_(List_ * xs, List_ * ys)
{
if (xs -> Nil) {
free(xs);
return ys;
} else {
List_ * result = cons(xs -> data, append_(xs -> Cons, ys));
free(xs);
return result;
}
}
List_ * reverse_(List_ * xs)
{
if (xs -> Nil) {
return xs;
} else {
List_ * result = snoc(reverse_(xs -> Cons), xs -> data);
free(xs);
return result;
}
}
List_ * map_(Box_ *(*f)(Box_ *), List_ * xs)
{
if (xs -> Nil) {
return xs;
} else {
List_ * result = map_(f, xs -> Cons);
Box_ * val = f(xs -> data);
free(xs);
return cons(val, result);
}
}
List_ * filter_(Bool (*f)(Box_ *), List_ * xs)
{
if (xs -> Nil) {
return xs;
} else {
List_ * result = filter_(f, xs -> Cons);
if (f(xs -> data)) {
Box_ * val = copy_(xs -> data);
destruct_(xs -> data);
free(xs);
return cons(val, result);
} else {
destruct_(xs -> data);
free(xs);
return result;
}
}
}
Bool null(List_ * xs)
{
return xs -> Nil;
}
int length(List_ * xs)
{
if (xs -> Nil) {
return 0;
} else {
return 1 + length(xs -> Cons);
}
}
void free_list(List_ * xs)
{
if (xs -> Nil) {
free(xs);
} else {
free_list(xs -> Cons);
destruct_(xs -> data);
free(xs);
}
}
void print__list_aux(List_ * xs)
{
if (xs -> Nil) {
// print_s nothing
} else if (xs -> Cons -> Nil) {
print_(xs -> data);
} else {
print_(xs -> data);
printf(", ");
print__list_aux(xs -> Cons);
}
}
void print__list(List_ * xs)
{
printf("[");
print__list_aux(xs);
printf("]");
}
Box_ * box_list(List_ * xs)
{
return box(xs, (void (*)(void *))free_list, (void * (*)(void *))copy__list, (void (*)(void *))print__list);
}
| banacorn/aussenhaut | legacy/type.c | C | mit | 8,542 |
<?php
namespace jakim\authserver\base;
interface FacebookUserIdentityInterface extends UserIdentityInterface
{
/**
* @param $user
* @return \jakim\authserver\base\BaseIdentityInterface
*/
public static function findIdentityByFacebookGraphUser($user);
} | jakim/yii2-authserver | src/base/FacebookUserIdentityInterface.php | PHP | mit | 278 |
<?php
/**
* Core Theme Object
* Core Version: @core_version@
*/
include_once('functions.php');
class MMM_Roots
{
var $_settings;
var $_options_pagename = 'mmm_roots';
var $_settings_key = 'mmm_roots';
var $_meta_key = 'mmm_roots_meta';
//var $_setting_prefix = 'mm_roots_';
var $_save_key = '';
var $_versionnum = "@core_version@";
var $menu_page;
var $shortcode_includes = ["row", "column"];
function MMM_Roots()
{
$this->_settings = get_option($this->_settings_key) ? get_option($this->_settings_key) : array();
add_action( 'admin_menu', array(&$this, 'create_menu_link') );
//Ajax Posts
add_action('wp_ajax_nopriv_do_ajax', array(&$this, '_save') );
add_action('wp_ajax_do_ajax', array(&$this, '_save') );
//Custom Taxonomies
add_action( 'init', array(&$this, 'custom_taxonomies'));
//Page / Post Meta
add_post_type_support( 'page', 'excerpt' ); //Pages should have this - it's silly not to!
//Custom Meta
add_action( 'admin_init', array(&$this, 'custom_metabox'));
add_action( 'save_post', array(&$this, '_save_post_meta'), 10, 2 );
//Custom CSS for taxonomy icons
add_action('admin_head', array(&$this, 'custom_dashboard_css'));
$this->load_shortcodes();
}
static function MMM_Roots_install() {
global $wpdb;
require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
//Get default values from the theme data file if there are none
//$this->_set_standart_values($themeSettings);
add_option($_settings_key . "_versionnum", $_versionnum);
}
function load_shortcodes()
{
foreach ($this->shortcode_includes as $shortcode) {
add_shortcode( $shortcode, 'MmmToolsNamespace\\' . $shortcode );
}
}
function custom_dashboard_css()
{
wp_enqueue_style('font-awesome', get_template_directory_uri() . '/assets/css/fontawesome.css', false, null);
wp_enqueue_style('mmm_roots_dashboard', get_template_directory_uri() . '/assets/css/dashboard.css', false, null);
}
function custom_metabox(){
global $taxonomies;
foreach ($taxonomies as $taxonomy)
{
add_meta_box("mm_post_meta", "Meta", array(&$this, "taxonomy_meta"), $taxonomy["slug"], "normal", "low", $taxonomy["options"]);
}
}
function custom_taxonomies()
{
global $taxonomies;
foreach ($taxonomies as $taxonomy)
{
if (isset($taxonomy["registration-args"]))
{
register_post_type( $taxonomy["slug"], $taxonomy["registration-args"] );
}
}
}
function taxonomy_meta($post, $data)
{
$options = $data["args"];
$values = get_post_meta($post->ID, $this->_meta_key, true);
\MmmToolsNamespace\load_admin_assets();
include_once('ui/meta_post_ui.php');
}
function create_menu_link()
{
$this->menu_page = add_options_page('Theme Options', 'Theme Options',
'manage_options',$this->_options_pagename, array(&$this, 'build_settings_page'));
}
function build_settings_page()
{
if (!$this->check_user_capability()) {
wp_die( __('You do not have sufficient permissions to access this page.') );
}
wp_enqueue_style('bootstrap', get_template_directory_uri() . '/assets/css/bootstrap.css', false, null);
wp_enqueue_script('bootstrap', get_template_directory_uri() . '/assets/js/plugins.js', false, null);
wp_enqueue_script('jquery', get_template_directory_uri() . '/assets/js/vendor/jquery-1.7.1.min.js', false, null);
\MmmToolsNamespace\load_admin_assets();
include_once('ui/admin_ui.php');
}
function check_user_capability()
{
if ( is_super_admin() || current_user_can('manage_options') ) return true;
return false;
}
function _save()
{
if ($this->check_user_capability())
{
switch($_REQUEST['fn']){
case 'settings':
$data_back = $_REQUEST['settings'];
$values = array();
$i = 0;
foreach ($data_back as $data)
{
if (array_key_exists($data['name'], $values))
{
$values[$data['name']] .= "," . $data['value'];
}
else
{
$values[$data['name']] = $data['value'];
}
}
$this->_save_settings_todb($values);
break;
}
}
switch($_REQUEST['fn']){
// case 'contact':
// $data_back = $_REQUEST['contact'];
// $data = array();
// $i = 0;
// foreach ($data_back as $field)
// {
// $data[$field['name']] = $field['value'];
// }
// if ($data['honey'] == '1' && $data['terms'] == '')
// {
// $emailTemplate = "%s says:<br /> %s<br /><br />- %s";
// $name = $data['name'];
// $contact = $data['contact'];
// $message = $data['message'];
// $emailBody = sprintf($emailTemplate, $name, $message, $contact);
// $toEmail = $this->get_setting('business_email');
// $subject = "Website Message";
// SendMail($toEmail, $subject, $toEmail, $emailBody);
// }
// break;
}
}
function _save_post_meta( $post_id, $post ){
global $pagenow;
global $taxonomies;
if ( 'post.php' != $pagenow ) return $post_id;
if ( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE )
return $post_id;
if ( ! isset( $_POST['mm_nonce'] ) || ! wp_verify_nonce( $_POST['mm_nonce'], 'mm_nonce' ) )
return $post_id;
$metafields = array();
$taxonomySlugs = array();
foreach ($taxonomies as $taxonomy) {
$taxonomySlugs[] = $taxonomy["slug"];
}
if (in_array($post->post_type, $taxonomySlugs))
{
$taxonomyKey = array_search($post->post_type, $taxonomySlugs);
$metafields = \MmmToolsNamespace\GetThemeDataFields($taxonomies[$taxonomyKey]["options"]);
$metadata = array();
foreach ($metafields as $field) {
$fieldID = $field["id"];
/*if ($metadata[$fieldID] != null)
{
$metadata[$fieldID] .= "," . $fieldID;
}
else
{
$metadata[$fieldID] = $fieldID;
}*/
$metadata[$fieldID] = $fieldID;
}
update_post_meta( $post_id, $this->_meta_key, $_REQUEST );
//TODO account for array data like multi select meta
//update_post_meta( $post_id, $this->_meta_key, array_map( 'strip_tags', $_REQUEST ) );
}
}
function get_option($setting)
{
return $this->_settings[$setting];
}
function _save_settings_todb($form_settings = '')
{
if ( $form_settings <> '' ) {
unset($form_settings[$this->_settings_key . '_saved']);
$this->_settings = $form_settings;
#set standart values in case we have empty fields
$this->_set_standart_values($form_settings);
}
update_option($this->_settings_key, $this->_settings);
}
function _set_standart_values($standart_values)
{
global $shortname;
foreach ($standart_values as $key => $value){
if ( !array_key_exists( $key, $this->_settings ) )
$this->_settings[$key] = '';
}
foreach ($this->_settings as $key => $value) {
if ( $value == '' ) $this->_settings[$key] = $standart_values[$key];
}
}
function get_setting($name, $defaultValue = "")
{
$output = $defaultValue;
if (isset($this->_settings[$name]))
{
$output = stripslashes($this->_settings[$name]);
}
return $output;
}
/*****
* get_post_meta($id, $key)
* $id - the post to get the theme meta from
* $key (optional) - the optional key if this is the only value you want or need
* $single (optional) - if the key is a single value or an array
* $ouput - returns either the single value key or the whole meta array
*/
function get_post_meta($id, $key=null, $single = true)
{
$output = "";
$post_meta = get_post_meta($id, $this->_meta_key, $single);
if ($key != null && isset($post_meta[$key]))
{
$output = $post_meta[$key];
}
return $output;
}
function get_post_variables($post)
{
$post_variables = array('{url}' => get_permalink($post),
'{title}' => $post->post_title,
'{image}' => getPostThumbnailUrl($post),
'{content}' => do_shortcode($post->post_content),
'{slug}' => $post->post_name);
return $post_variables;
}
}
register_activation_hook(__FILE__,array('MMM_Roots', 'MMM_Roots_install'));
add_action( 'init', 'MMM_Roots_Init', 5 );
function MMM_Roots_Init()
{
global $MMM_Roots;
$MMM_Roots = new MMM_Roots();
global $MMM_Data_Library;
if ($MMM_Data_Library == null)
{
$MMM_Data_Library = array();
}
array_push($MMM_Data_Library, $MMM_Roots);
} | MManifesto/sage | lib/theme/theme_core.php | PHP | mit | 8,398 |
#encoding: utf8
import sys
sys.path.append("../common")
from tcp_server import TCPServer
import ptrace
tcpServer=TCPServer()
tcpServer.listen()
tcpServer.run()
| lotaku/fzz | server/main.py | Python | mit | 165 |
package com.mmnaseri.utils.spring.data.tools;
import org.springframework.util.ReflectionUtils;
import java.lang.reflect.Method;
/**
* This filter will only accept methods that can be getters for properties (excluding the `is...`
* format usually used for {@literal boolean} types).
*
* @author Milad Naseri ([email protected])
* @since 1.0 (9/23/15)
*/
public class GetterMethodFilter implements ReflectionUtils.MethodFilter {
@Override
public boolean matches(Method method) {
return method.getName().matches("get[A-Z].*")
&& !void.class.equals(method.getReturnType())
&& method.getParameterTypes().length == 0;
}
}
| mmnaseri/spring-data-mock | spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/tools/GetterMethodFilter.java | Java | mit | 655 |
// Copyright (c) 2017-2021 Advanced Micro Devices, Inc. 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.
#include <stdio.h>
#include <gtest/gtest.h>
#include <vector>
#include <cmath>
#include <type_traits>
#include <hip/hip_runtime.h>
#define FQUALIFIERS __forceinline__ __host__ __device__
#include <rocrand/rocrand_kernel.h>
#include <rocrand/rocrand.h>
#include "test_common.hpp"
#include "test_rocrand_common.hpp"
template <class GeneratorState>
__global__
__launch_bounds__(32)
void rocrand_init_kernel(GeneratorState * states,
const size_t states_size,
unsigned long long seed,
unsigned long long offset)
{
const unsigned int state_id = hipBlockIdx_x * hipBlockDim_x + hipThreadIdx_x;
const unsigned int subsequence = state_id;
if(state_id < states_size)
{
GeneratorState state;
rocrand_init(seed, subsequence, offset, &state);
states[state_id] = state;
}
}
template <class GeneratorState>
__global__
__launch_bounds__(32)
void rocrand_kernel(unsigned int * output, const size_t size)
{
const unsigned int state_id = hipBlockIdx_x * hipBlockDim_x + hipThreadIdx_x;
const unsigned int global_size = hipGridDim_x * hipBlockDim_x;
GeneratorState state;
const unsigned int subsequence = state_id;
rocrand_init(0, subsequence, 0, &state);
unsigned int index = state_id;
while(index < size)
{
output[index] = rocrand(&state);
index += global_size;
}
}
template <class GeneratorState>
__global__
__launch_bounds__(32)
void rocrand_uniform_kernel(float * output, const size_t size)
{
const unsigned int state_id = hipBlockIdx_x * hipBlockDim_x + hipThreadIdx_x;
const unsigned int global_size = hipGridDim_x * hipBlockDim_x;
GeneratorState state;
const unsigned int subsequence = state_id;
rocrand_init(0, subsequence, 0, &state);
unsigned int index = state_id;
while(index < size)
{
if(state_id % 4 == 0)
output[index] = rocrand_uniform4(&state).x;
else if(state_id % 2 == 0)
output[index] = rocrand_uniform2(&state).x;
else
output[index] = rocrand_uniform(&state);
index += global_size;
}
}
template <class GeneratorState>
__global__
__launch_bounds__(32)
void rocrand_normal_kernel(float * output, const size_t size)
{
const unsigned int state_id = hipBlockIdx_x * hipBlockDim_x + hipThreadIdx_x;
const unsigned int global_size = hipGridDim_x * hipBlockDim_x;
GeneratorState state;
const unsigned int subsequence = state_id;
rocrand_init(0, subsequence, 0, &state);
unsigned int index = state_id;
while(index < size)
{
if(state_id % 4 == 0)
output[index] = rocrand_normal4(&state).x;
else if(state_id % 2 == 0)
output[index] = rocrand_normal2(&state).x;
else
output[index] = rocrand_normal(&state);
index += global_size;
}
}
template <class GeneratorState>
__global__
__launch_bounds__(32)
void rocrand_log_normal_kernel(float * output, const size_t size)
{
const unsigned int state_id = hipBlockIdx_x * hipBlockDim_x + hipThreadIdx_x;
const unsigned int global_size = hipGridDim_x * hipBlockDim_x;
GeneratorState state;
const unsigned int subsequence = state_id;
rocrand_init(0, subsequence, 0, &state);
unsigned int index = state_id;
while(index < size)
{
if(state_id % 4 == 0)
output[index] = rocrand_log_normal4(&state, 1.6f, 0.25f).x;
else if(state_id % 2 == 0)
output[index] = rocrand_log_normal2(&state, 1.6f, 0.25f).x;
else
output[index] = rocrand_log_normal(&state, 1.6f, 0.25f);
index += global_size;
}
}
template <class GeneratorState>
__global__
__launch_bounds__(64)
void rocrand_poisson_kernel(unsigned int * output, const size_t size, double lambda)
{
const unsigned int state_id = hipBlockIdx_x * hipBlockDim_x + hipThreadIdx_x;
const unsigned int global_size = hipGridDim_x * hipBlockDim_x;
GeneratorState state;
const unsigned int subsequence = state_id;
rocrand_init(456, subsequence, 234ULL, &state);
unsigned int index = state_id;
while(index < size)
{
output[index] = rocrand_poisson(&state, lambda);
index += global_size;
}
}
template <class GeneratorState>
__global__
__launch_bounds__(64)
void rocrand_discrete_kernel(unsigned int * output, const size_t size, rocrand_discrete_distribution discrete_distribution)
{
const unsigned int state_id = hipBlockIdx_x * hipBlockDim_x + hipThreadIdx_x;
const unsigned int global_size = hipGridDim_x * hipBlockDim_x;
GeneratorState state;
const unsigned int subsequence = state_id;
rocrand_init(456, subsequence, 234ULL, &state);
unsigned int index = state_id;
while(index < size)
{
output[index] = rocrand_discrete(&state, discrete_distribution);
index += global_size;
}
}
TEST(rocrand_kernel_philox4x32_10, rocrand_state_philox4x32_10_type)
{
typedef rocrand_state_philox4x32_10 state_type;
EXPECT_EQ(sizeof(state_type), 16 * sizeof(float));
EXPECT_EQ(sizeof(state_type[32]), 32 * sizeof(state_type));
EXPECT_TRUE(std::is_trivially_destructible<uint2>::value);
EXPECT_TRUE(std::is_trivially_destructible<uint4>::value);
EXPECT_TRUE(std::is_trivially_destructible<state_type>::value);
}
TEST(rocrand_kernel_philox4x32_10, DISABLED_rocrand_state_philox4x32_10_copyable)
{
typedef rocrand_state_philox4x32_10 state_type;
EXPECT_TRUE(std::is_trivially_copyable<uint2>::value);
EXPECT_TRUE(std::is_trivially_copyable<uint4>::value);
EXPECT_TRUE(std::is_trivially_copyable<state_type>::value);
}
TEST(rocrand_kernel_philox4x32_10, rocrand_init)
{
// Just get access to internal state
class rocrand_state_philox4x32_10_test : public rocrand_state_philox4x32_10
{
typedef rocrand_state_philox4x32_10::philox4x32_10_state internal_state_type;
public:
__host__ rocrand_state_philox4x32_10_test() {}
__host__ internal_state_type internal_state() const
{
return m_state;
}
};
typedef rocrand_state_philox4x32_10 state_type;
typedef rocrand_state_philox4x32_10_test state_type_test;
unsigned long long seed = 0xdeadbeefbeefdeadULL;
unsigned long long offset = 4 * ((UINT_MAX * 17ULL) + 17);
const size_t states_size = 256;
state_type * states;
HIP_CHECK(hipMallocHelper((void **)&states, states_size * sizeof(state_type)));
HIP_CHECK(hipDeviceSynchronize());
hipLaunchKernelGGL(
HIP_KERNEL_NAME(rocrand_init_kernel),
dim3(8), dim3(32), 0, 0,
states, states_size,
seed, offset
);
HIP_CHECK(hipGetLastError());
std::vector<state_type_test> states_host(states_size);
HIP_CHECK(
hipMemcpy(
states_host.data(), states,
states_size * sizeof(state_type),
hipMemcpyDeviceToHost
)
);
HIP_CHECK(hipDeviceSynchronize());
HIP_CHECK(hipFree(states));
unsigned int subsequence = 0;
for(auto& state : states_host)
{
auto s = state.internal_state();
EXPECT_EQ(s.key.x, 0xbeefdeadU);
EXPECT_EQ(s.key.y, 0xdeadbeefU);
EXPECT_EQ(s.counter.x, 0U);
EXPECT_EQ(s.counter.y, 17U);
EXPECT_EQ(s.counter.z, subsequence);
EXPECT_EQ(s.counter.w, 0U);
EXPECT_TRUE(
s.result.x != 0U
|| s.result.y != 0U
|| s.result.z != 0U
|| s.result.w
);
EXPECT_EQ(s.substate, 0U);
subsequence++;
}
}
TEST(rocrand_kernel_philox4x32_10, rocrand)
{
typedef rocrand_state_philox4x32_10 state_type;
const size_t output_size = 8192;
unsigned int * output;
HIP_CHECK(hipMallocHelper((void **)&output, output_size * sizeof(unsigned int)));
HIP_CHECK(hipDeviceSynchronize());
hipLaunchKernelGGL(
HIP_KERNEL_NAME(rocrand_kernel<state_type>),
dim3(8), dim3(32), 0, 0,
output, output_size
);
HIP_CHECK(hipGetLastError());
std::vector<unsigned int> output_host(output_size);
HIP_CHECK(
hipMemcpy(
output_host.data(), output,
output_size * sizeof(unsigned int),
hipMemcpyDeviceToHost
)
);
HIP_CHECK(hipDeviceSynchronize());
HIP_CHECK(hipFree(output));
double mean = 0;
for(auto v : output_host)
{
mean += static_cast<double>(v) / UINT_MAX;
}
mean = mean / output_size;
EXPECT_NEAR(mean, 0.5, 0.1);
}
TEST(rocrand_kernel_philox4x32_10, rocrand_uniform)
{
typedef rocrand_state_philox4x32_10 state_type;
const size_t output_size = 8192;
float * output;
HIP_CHECK(hipMallocHelper((void **)&output, output_size * sizeof(float)));
HIP_CHECK(hipDeviceSynchronize());
hipLaunchKernelGGL(
HIP_KERNEL_NAME(rocrand_uniform_kernel<state_type>),
dim3(8), dim3(32), 0, 0,
output, output_size
);
HIP_CHECK(hipGetLastError());
std::vector<float> output_host(output_size);
HIP_CHECK(
hipMemcpy(
output_host.data(), output,
output_size * sizeof(float),
hipMemcpyDeviceToHost
)
);
HIP_CHECK(hipDeviceSynchronize());
HIP_CHECK(hipFree(output));
double mean = 0;
for(auto v : output_host)
{
mean += static_cast<double>(v);
}
mean = mean / output_size;
EXPECT_NEAR(mean, 0.5, 0.1);
}
TEST(rocrand_kernel_philox4x32_10, rocrand_normal)
{
typedef rocrand_state_philox4x32_10 state_type;
const size_t output_size = 8192;
float * output;
HIP_CHECK(hipMallocHelper((void **)&output, output_size * sizeof(float)));
HIP_CHECK(hipDeviceSynchronize());
hipLaunchKernelGGL(
HIP_KERNEL_NAME(rocrand_normal_kernel<state_type>),
dim3(8), dim3(32), 0, 0,
output, output_size
);
HIP_CHECK(hipGetLastError());
std::vector<float> output_host(output_size);
HIP_CHECK(
hipMemcpy(
output_host.data(), output,
output_size * sizeof(float),
hipMemcpyDeviceToHost
)
);
HIP_CHECK(hipDeviceSynchronize());
HIP_CHECK(hipFree(output));
double mean = 0;
for(auto v : output_host)
{
mean += static_cast<double>(v);
}
mean = mean / output_size;
EXPECT_NEAR(mean, 0.0, 0.2);
double stddev = 0;
for(auto v : output_host)
{
stddev += std::pow(static_cast<double>(v) - mean, 2);
}
stddev = stddev / output_size;
EXPECT_NEAR(stddev, 1.0, 0.2);
}
TEST(rocrand_kernel_philox4x32_10, rocrand_log_normal)
{
typedef rocrand_state_philox4x32_10 state_type;
const size_t output_size = 8192;
float * output;
HIP_CHECK(hipMallocHelper((void **)&output, output_size * sizeof(float)));
HIP_CHECK(hipDeviceSynchronize());
hipLaunchKernelGGL(
HIP_KERNEL_NAME(rocrand_log_normal_kernel<state_type>),
dim3(8), dim3(32), 0, 0,
output, output_size
);
HIP_CHECK(hipGetLastError());
std::vector<float> output_host(output_size);
HIP_CHECK(
hipMemcpy(
output_host.data(), output,
output_size * sizeof(float),
hipMemcpyDeviceToHost
)
);
HIP_CHECK(hipDeviceSynchronize());
HIP_CHECK(hipFree(output));
double mean = 0;
for(auto v : output_host)
{
mean += static_cast<double>(v);
}
mean = mean / output_size;
double stddev = 0;
for(auto v : output_host)
{
stddev += std::pow(v - mean, 2);
}
stddev = std::sqrt(stddev / output_size);
double logmean = std::log(mean * mean / std::sqrt(stddev + mean * mean));
double logstd = std::sqrt(std::log(1.0f + stddev/(mean * mean)));
EXPECT_NEAR(1.6, logmean, 1.6 * 0.2);
EXPECT_NEAR(0.25, logstd, 0.25 * 0.2);
}
class rocrand_kernel_philox4x32_10_poisson : public ::testing::TestWithParam<double> { };
TEST_P(rocrand_kernel_philox4x32_10_poisson, rocrand_poisson)
{
typedef rocrand_state_philox4x32_10 state_type;
const double lambda = GetParam();
const size_t output_size = 8192;
unsigned int * output;
HIP_CHECK(hipMallocHelper((void **)&output, output_size * sizeof(unsigned int)));
HIP_CHECK(hipDeviceSynchronize());
hipLaunchKernelGGL(
HIP_KERNEL_NAME(rocrand_poisson_kernel<state_type>),
dim3(4), dim3(64), 0, 0,
output, output_size, lambda
);
HIP_CHECK(hipGetLastError());
std::vector<unsigned int> output_host(output_size);
HIP_CHECK(
hipMemcpy(
output_host.data(), output,
output_size * sizeof(unsigned int),
hipMemcpyDeviceToHost
)
);
HIP_CHECK(hipDeviceSynchronize());
HIP_CHECK(hipFree(output));
double mean = 0;
for(auto v : output_host)
{
mean += static_cast<double>(v);
}
mean = mean / output_size;
double variance = 0;
for(auto v : output_host)
{
variance += std::pow(v - mean, 2);
}
variance = variance / output_size;
EXPECT_NEAR(mean, lambda, std::max(1.0, lambda * 1e-1));
EXPECT_NEAR(variance, lambda, std::max(1.0, lambda * 1e-1));
}
TEST_P(rocrand_kernel_philox4x32_10_poisson, rocrand_discrete)
{
typedef rocrand_state_philox4x32_10 state_type;
const double lambda = GetParam();
const size_t output_size = 8192;
unsigned int * output;
HIP_CHECK(hipMallocHelper((void **)&output, output_size * sizeof(unsigned int)));
HIP_CHECK(hipDeviceSynchronize());
rocrand_discrete_distribution discrete_distribution;
ROCRAND_CHECK(rocrand_create_poisson_distribution(lambda, &discrete_distribution));
hipLaunchKernelGGL(
HIP_KERNEL_NAME(rocrand_discrete_kernel<state_type>),
dim3(4), dim3(64), 0, 0,
output, output_size, discrete_distribution
);
HIP_CHECK(hipGetLastError());
std::vector<unsigned int> output_host(output_size);
HIP_CHECK(
hipMemcpy(
output_host.data(), output,
output_size * sizeof(unsigned int),
hipMemcpyDeviceToHost
)
);
HIP_CHECK(hipDeviceSynchronize());
HIP_CHECK(hipFree(output));
ROCRAND_CHECK(rocrand_destroy_discrete_distribution(discrete_distribution));
double mean = 0;
for(auto v : output_host)
{
mean += static_cast<double>(v);
}
mean = mean / output_size;
double variance = 0;
for(auto v : output_host)
{
variance += std::pow(v - mean, 2);
}
variance = variance / output_size;
EXPECT_NEAR(mean, lambda, std::max(1.0, lambda * 1e-1));
EXPECT_NEAR(variance, lambda, std::max(1.0, lambda * 1e-1));
}
const double lambdas[] = { 1.0, 5.5, 20.0, 100.0, 1234.5, 5000.0 };
INSTANTIATE_TEST_SUITE_P(rocrand_kernel_philox4x32_10_poisson,
rocrand_kernel_philox4x32_10_poisson,
::testing::ValuesIn(lambdas));
| ROCmSoftwarePlatform/rocRAND | test/test_rocrand_kernel_philox4x32_10.cpp | C++ | mit | 16,188 |
<?php
/**
* Part of the Fuel framework.
*
* @package Fuel
* @version 1.7
* @author Fuel Development Team
* @license MIT License
* @copyright 2010 - 2013 Fuel Development Team
* @link http://fuelphp.com
*/
namespace Fuel\Core;
/**
* Cache_Handler_Serialized class tests
*
* @group Core
* @group Cache
*/
class Test_Cache_Handler_Serialized extends TestCase {
public function test_foo() {
}
}
| vienbk91/fuelphp17 | fuel/core/tests/cache/handler/serialized.php | PHP | mit | 429 |
import os, sys
os.chdir("../")
sys.setrecursionlimit(100000)
sys.path.append(os.path.abspath(""))
os.chdir("./Utility")
from Utility.Utils import getWordTag
def compare(taggedCorpus, goldenCorpus):
"""
To calculate the the performance on POS tagging
"""
outputTokens = open(taggedCorpus, "r").read().split()
standardTokens = open(goldenCorpus, "r").read().split()
if len(outputTokens) != len(standardTokens):
print "The numbers of tokens are not equal!"
return 0
numwords = 0
count = 0
for i in xrange(len(outputTokens)):
numwords += 1
word1, tag1 = getWordTag(outputTokens[i])
word2, tag2 = getWordTag(standardTokens[i])
if word1 != word2:
print "Data not equal in position", i
print outputTokens[i], standardTokens[i-1], standardTokens[i], standardTokens[i+1]
return 0
if tag1.lower() == tag2.lower():
count += 1
#else:
# print outputTokens[i-1], outputTokens[i], outputTokens[i+1], "<=>", standardTokens[i-1], standardTokens[i], standardTokens[i+1]
return count * 100 / float(len(outputTokens))
if __name__ == "__main__":
print compare(sys.argv[1:][0], sys.argv[1:][1]), "%"
pass
| ercgn/11411-proj | src/util/RDR_POS/Utility/Eval.py | Python | mit | 1,304 |
using System;
using NetRuntimeSystem = System;
using System.ComponentModel;
using NetOffice.Attributes;
namespace NetOffice.MSHTMLApi
{
/// <summary>
/// DispatchInterface DispHTMLTableCol
/// SupportByVersion MSHTML, 4
/// </summary>
[SupportByVersion("MSHTML", 4)]
[EntityType(EntityType.IsDispatchInterface), BaseType]
public class DispHTMLTableCol : COMObject
{
#pragma warning disable
#region Type Information
/// <summary>
/// Instance Type
/// </summary>
[EditorBrowsable(EditorBrowsableState.Advanced), Browsable(false), Category("NetOffice"), CoreOverridden]
public override Type InstanceType
{
get
{
return LateBindingApiWrapperType;
}
}
private static Type _type;
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public static Type LateBindingApiWrapperType
{
get
{
if (null == _type)
_type = typeof(DispHTMLTableCol);
return _type;
}
}
#endregion
#region Ctor
/// <param name="factory">current used factory core</param>
/// <param name="parentObject">object there has created the proxy</param>
/// <param name="proxyShare">proxy share instead if com proxy</param>
public DispHTMLTableCol(Core factory, ICOMObject parentObject, COMProxyShare proxyShare) : base(factory, parentObject, proxyShare)
{
}
///<param name="factory">current used factory core</param>
///<param name="parentObject">object there has created the proxy</param>
///<param name="comProxy">inner wrapped COM proxy</param>
public DispHTMLTableCol(Core factory, ICOMObject parentObject, object comProxy) : base(factory, parentObject, comProxy)
{
}
///<param name="parentObject">object there has created the proxy</param>
///<param name="comProxy">inner wrapped COM proxy</param>
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public DispHTMLTableCol(ICOMObject parentObject, object comProxy) : base(parentObject, comProxy)
{
}
///<param name="factory">current used factory core</param>
///<param name="parentObject">object there has created the proxy</param>
///<param name="comProxy">inner wrapped COM proxy</param>
///<param name="comProxyType">Type of inner wrapped COM proxy"</param>
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public DispHTMLTableCol(Core factory, ICOMObject parentObject, object comProxy, NetRuntimeSystem.Type comProxyType) : base(factory, parentObject, comProxy, comProxyType)
{
}
///<param name="parentObject">object there has created the proxy</param>
///<param name="comProxy">inner wrapped COM proxy</param>
///<param name="comProxyType">Type of inner wrapped COM proxy"</param>
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public DispHTMLTableCol(ICOMObject parentObject, object comProxy, NetRuntimeSystem.Type comProxyType) : base(parentObject, comProxy, comProxyType)
{
}
///<param name="replacedObject">object to replaced. replacedObject are not usable after this action</param>
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public DispHTMLTableCol(ICOMObject replacedObject) : base(replacedObject)
{
}
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public DispHTMLTableCol() : base()
{
}
/// <param name="progId">registered progID</param>
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public DispHTMLTableCol(string progId) : base(progId)
{
}
#endregion
#region Properties
/// <summary>
/// SupportByVersion MSHTML 4
/// Get/Set
/// </summary>
[SupportByVersion("MSHTML", 4)]
public string className
{
get
{
return Factory.ExecuteStringPropertyGet(this, "className");
}
set
{
Factory.ExecuteValuePropertySet(this, "className", value);
}
}
/// <summary>
/// SupportByVersion MSHTML 4
/// Get/Set
/// </summary>
[SupportByVersion("MSHTML", 4)]
public string id
{
get
{
return Factory.ExecuteStringPropertyGet(this, "id");
}
set
{
Factory.ExecuteValuePropertySet(this, "id", value);
}
}
/// <summary>
/// SupportByVersion MSHTML 4
/// Get
/// </summary>
[SupportByVersion("MSHTML", 4)]
public string tagName
{
get
{
return Factory.ExecuteStringPropertyGet(this, "tagName");
}
}
/// <summary>
/// SupportByVersion MSHTML 4
/// Get
/// </summary>
[SupportByVersion("MSHTML", 4)]
[BaseResult]
public NetOffice.MSHTMLApi.IHTMLElement parentElement
{
get
{
return Factory.ExecuteBaseReferencePropertyGet<NetOffice.MSHTMLApi.IHTMLElement>(this, "parentElement");
}
}
/// <summary>
/// SupportByVersion MSHTML 4
/// Get
/// </summary>
[SupportByVersion("MSHTML", 4)]
[BaseResult]
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public NetOffice.MSHTMLApi.IHTMLStyle style
{
get
{
return Factory.ExecuteBaseReferencePropertyGet<NetOffice.MSHTMLApi.IHTMLStyle>(this, "style");
}
}
/// <summary>
/// SupportByVersion MSHTML 4
/// Get/Set
/// </summary>
[SupportByVersion("MSHTML", 4)]
public object onhelp
{
get
{
return Factory.ExecuteVariantPropertyGet(this, "onhelp");
}
set
{
Factory.ExecuteVariantPropertySet(this, "onhelp", value);
}
}
/// <summary>
/// SupportByVersion MSHTML 4
/// Get/Set
/// </summary>
[SupportByVersion("MSHTML", 4)]
public object onclick
{
get
{
return Factory.ExecuteVariantPropertyGet(this, "onclick");
}
set
{
Factory.ExecuteVariantPropertySet(this, "onclick", value);
}
}
/// <summary>
/// SupportByVersion MSHTML 4
/// Get/Set
/// </summary>
[SupportByVersion("MSHTML", 4)]
public object ondblclick
{
get
{
return Factory.ExecuteVariantPropertyGet(this, "ondblclick");
}
set
{
Factory.ExecuteVariantPropertySet(this, "ondblclick", value);
}
}
/// <summary>
/// SupportByVersion MSHTML 4
/// Get/Set
/// </summary>
[SupportByVersion("MSHTML", 4)]
public object onkeydown
{
get
{
return Factory.ExecuteVariantPropertyGet(this, "onkeydown");
}
set
{
Factory.ExecuteVariantPropertySet(this, "onkeydown", value);
}
}
/// <summary>
/// SupportByVersion MSHTML 4
/// Get/Set
/// </summary>
[SupportByVersion("MSHTML", 4)]
public object onkeyup
{
get
{
return Factory.ExecuteVariantPropertyGet(this, "onkeyup");
}
set
{
Factory.ExecuteVariantPropertySet(this, "onkeyup", value);
}
}
/// <summary>
/// SupportByVersion MSHTML 4
/// Get/Set
/// </summary>
[SupportByVersion("MSHTML", 4)]
public object onkeypress
{
get
{
return Factory.ExecuteVariantPropertyGet(this, "onkeypress");
}
set
{
Factory.ExecuteVariantPropertySet(this, "onkeypress", value);
}
}
/// <summary>
/// SupportByVersion MSHTML 4
/// Get/Set
/// </summary>
[SupportByVersion("MSHTML", 4)]
public object onmouseout
{
get
{
return Factory.ExecuteVariantPropertyGet(this, "onmouseout");
}
set
{
Factory.ExecuteVariantPropertySet(this, "onmouseout", value);
}
}
/// <summary>
/// SupportByVersion MSHTML 4
/// Get/Set
/// </summary>
[SupportByVersion("MSHTML", 4)]
public object onmouseover
{
get
{
return Factory.ExecuteVariantPropertyGet(this, "onmouseover");
}
set
{
Factory.ExecuteVariantPropertySet(this, "onmouseover", value);
}
}
/// <summary>
/// SupportByVersion MSHTML 4
/// Get/Set
/// </summary>
[SupportByVersion("MSHTML", 4)]
public object onmousemove
{
get
{
return Factory.ExecuteVariantPropertyGet(this, "onmousemove");
}
set
{
Factory.ExecuteVariantPropertySet(this, "onmousemove", value);
}
}
/// <summary>
/// SupportByVersion MSHTML 4
/// Get/Set
/// </summary>
[SupportByVersion("MSHTML", 4)]
public object onmousedown
{
get
{
return Factory.ExecuteVariantPropertyGet(this, "onmousedown");
}
set
{
Factory.ExecuteVariantPropertySet(this, "onmousedown", value);
}
}
/// <summary>
/// SupportByVersion MSHTML 4
/// Get/Set
/// </summary>
[SupportByVersion("MSHTML", 4)]
public object onmouseup
{
get
{
return Factory.ExecuteVariantPropertyGet(this, "onmouseup");
}
set
{
Factory.ExecuteVariantPropertySet(this, "onmouseup", value);
}
}
/// <summary>
/// SupportByVersion MSHTML 4
/// Get
/// Unknown COM Proxy
/// </summary>
[SupportByVersion("MSHTML", 4), ProxyResult]
public object document
{
get
{
return Factory.ExecuteReferencePropertyGet(this, "document");
}
}
/// <summary>
/// SupportByVersion MSHTML 4
/// Get/Set
/// </summary>
[SupportByVersion("MSHTML", 4)]
public string title
{
get
{
return Factory.ExecuteStringPropertyGet(this, "title");
}
set
{
Factory.ExecuteValuePropertySet(this, "title", value);
}
}
/// <summary>
/// SupportByVersion MSHTML 4
/// Get/Set
/// </summary>
[SupportByVersion("MSHTML", 4)]
public string language
{
get
{
return Factory.ExecuteStringPropertyGet(this, "language");
}
set
{
Factory.ExecuteValuePropertySet(this, "language", value);
}
}
/// <summary>
/// SupportByVersion MSHTML 4
/// Get/Set
/// </summary>
[SupportByVersion("MSHTML", 4)]
public object onselectstart
{
get
{
return Factory.ExecuteVariantPropertyGet(this, "onselectstart");
}
set
{
Factory.ExecuteVariantPropertySet(this, "onselectstart", value);
}
}
/// <summary>
/// SupportByVersion MSHTML 4
/// Get
/// </summary>
[SupportByVersion("MSHTML", 4)]
public Int32 sourceIndex
{
get
{
return Factory.ExecuteInt32PropertyGet(this, "sourceIndex");
}
}
/// <summary>
/// SupportByVersion MSHTML 4
/// Get
/// </summary>
[SupportByVersion("MSHTML", 4)]
public object recordNumber
{
get
{
return Factory.ExecuteVariantPropertyGet(this, "recordNumber");
}
}
/// <summary>
/// SupportByVersion MSHTML 4
/// Get/Set
/// </summary>
[SupportByVersion("MSHTML", 4)]
public string lang
{
get
{
return Factory.ExecuteStringPropertyGet(this, "lang");
}
set
{
Factory.ExecuteValuePropertySet(this, "lang", value);
}
}
/// <summary>
/// SupportByVersion MSHTML 4
/// Get
/// </summary>
[SupportByVersion("MSHTML", 4)]
public Int32 offsetLeft
{
get
{
return Factory.ExecuteInt32PropertyGet(this, "offsetLeft");
}
}
/// <summary>
/// SupportByVersion MSHTML 4
/// Get
/// </summary>
[SupportByVersion("MSHTML", 4)]
public Int32 offsetTop
{
get
{
return Factory.ExecuteInt32PropertyGet(this, "offsetTop");
}
}
/// <summary>
/// SupportByVersion MSHTML 4
/// Get
/// </summary>
[SupportByVersion("MSHTML", 4)]
public Int32 offsetWidth
{
get
{
return Factory.ExecuteInt32PropertyGet(this, "offsetWidth");
}
}
/// <summary>
/// SupportByVersion MSHTML 4
/// Get
/// </summary>
[SupportByVersion("MSHTML", 4)]
public Int32 offsetHeight
{
get
{
return Factory.ExecuteInt32PropertyGet(this, "offsetHeight");
}
}
/// <summary>
/// SupportByVersion MSHTML 4
/// Get
/// </summary>
[SupportByVersion("MSHTML", 4)]
[BaseResult]
public NetOffice.MSHTMLApi.IHTMLElement offsetParent
{
get
{
return Factory.ExecuteBaseReferencePropertyGet<NetOffice.MSHTMLApi.IHTMLElement>(this, "offsetParent");
}
}
/// <summary>
/// SupportByVersion MSHTML 4
/// Get/Set
/// </summary>
[SupportByVersion("MSHTML", 4)]
public string innerHTML
{
get
{
return Factory.ExecuteStringPropertyGet(this, "innerHTML");
}
set
{
Factory.ExecuteValuePropertySet(this, "innerHTML", value);
}
}
/// <summary>
/// SupportByVersion MSHTML 4
/// Get/Set
/// </summary>
[SupportByVersion("MSHTML", 4)]
public string innerText
{
get
{
return Factory.ExecuteStringPropertyGet(this, "innerText");
}
set
{
Factory.ExecuteValuePropertySet(this, "innerText", value);
}
}
/// <summary>
/// SupportByVersion MSHTML 4
/// Get/Set
/// </summary>
[SupportByVersion("MSHTML", 4)]
public string outerHTML
{
get
{
return Factory.ExecuteStringPropertyGet(this, "outerHTML");
}
set
{
Factory.ExecuteValuePropertySet(this, "outerHTML", value);
}
}
/// <summary>
/// SupportByVersion MSHTML 4
/// Get/Set
/// </summary>
[SupportByVersion("MSHTML", 4)]
public string outerText
{
get
{
return Factory.ExecuteStringPropertyGet(this, "outerText");
}
set
{
Factory.ExecuteValuePropertySet(this, "outerText", value);
}
}
/// <summary>
/// SupportByVersion MSHTML 4
/// Get
/// </summary>
[SupportByVersion("MSHTML", 4)]
[BaseResult]
public NetOffice.MSHTMLApi.IHTMLElement parentTextEdit
{
get
{
return Factory.ExecuteBaseReferencePropertyGet<NetOffice.MSHTMLApi.IHTMLElement>(this, "parentTextEdit");
}
}
/// <summary>
/// SupportByVersion MSHTML 4
/// Get
/// </summary>
[SupportByVersion("MSHTML", 4)]
public bool isTextEdit
{
get
{
return Factory.ExecuteBoolPropertyGet(this, "isTextEdit");
}
}
/// <summary>
/// SupportByVersion MSHTML 4
/// Get
/// </summary>
[SupportByVersion("MSHTML", 4)]
public NetOffice.MSHTMLApi.IHTMLFiltersCollection filters
{
get
{
return Factory.ExecuteKnownReferencePropertyGet<NetOffice.MSHTMLApi.IHTMLFiltersCollection>(this, "filters", NetOffice.MSHTMLApi.IHTMLFiltersCollection.LateBindingApiWrapperType);
}
}
/// <summary>
/// SupportByVersion MSHTML 4
/// Get/Set
/// </summary>
[SupportByVersion("MSHTML", 4)]
public object ondragstart
{
get
{
return Factory.ExecuteVariantPropertyGet(this, "ondragstart");
}
set
{
Factory.ExecuteVariantPropertySet(this, "ondragstart", value);
}
}
/// <summary>
/// SupportByVersion MSHTML 4
/// Get/Set
/// </summary>
[SupportByVersion("MSHTML", 4)]
public object onbeforeupdate
{
get
{
return Factory.ExecuteVariantPropertyGet(this, "onbeforeupdate");
}
set
{
Factory.ExecuteVariantPropertySet(this, "onbeforeupdate", value);
}
}
/// <summary>
/// SupportByVersion MSHTML 4
/// Get/Set
/// </summary>
[SupportByVersion("MSHTML", 4)]
public object onafterupdate
{
get
{
return Factory.ExecuteVariantPropertyGet(this, "onafterupdate");
}
set
{
Factory.ExecuteVariantPropertySet(this, "onafterupdate", value);
}
}
/// <summary>
/// SupportByVersion MSHTML 4
/// Get/Set
/// </summary>
[SupportByVersion("MSHTML", 4)]
public object onerrorupdate
{
get
{
return Factory.ExecuteVariantPropertyGet(this, "onerrorupdate");
}
set
{
Factory.ExecuteVariantPropertySet(this, "onerrorupdate", value);
}
}
/// <summary>
/// SupportByVersion MSHTML 4
/// Get/Set
/// </summary>
[SupportByVersion("MSHTML", 4)]
public object onrowexit
{
get
{
return Factory.ExecuteVariantPropertyGet(this, "onrowexit");
}
set
{
Factory.ExecuteVariantPropertySet(this, "onrowexit", value);
}
}
/// <summary>
/// SupportByVersion MSHTML 4
/// Get/Set
/// </summary>
[SupportByVersion("MSHTML", 4)]
public object onrowenter
{
get
{
return Factory.ExecuteVariantPropertyGet(this, "onrowenter");
}
set
{
Factory.ExecuteVariantPropertySet(this, "onrowenter", value);
}
}
/// <summary>
/// SupportByVersion MSHTML 4
/// Get/Set
/// </summary>
[SupportByVersion("MSHTML", 4)]
public object ondatasetchanged
{
get
{
return Factory.ExecuteVariantPropertyGet(this, "ondatasetchanged");
}
set
{
Factory.ExecuteVariantPropertySet(this, "ondatasetchanged", value);
}
}
/// <summary>
/// SupportByVersion MSHTML 4
/// Get/Set
/// </summary>
[SupportByVersion("MSHTML", 4)]
public object ondataavailable
{
get
{
return Factory.ExecuteVariantPropertyGet(this, "ondataavailable");
}
set
{
Factory.ExecuteVariantPropertySet(this, "ondataavailable", value);
}
}
/// <summary>
/// SupportByVersion MSHTML 4
/// Get/Set
/// </summary>
[SupportByVersion("MSHTML", 4)]
public object ondatasetcomplete
{
get
{
return Factory.ExecuteVariantPropertyGet(this, "ondatasetcomplete");
}
set
{
Factory.ExecuteVariantPropertySet(this, "ondatasetcomplete", value);
}
}
/// <summary>
/// SupportByVersion MSHTML 4
/// Get/Set
/// </summary>
[SupportByVersion("MSHTML", 4)]
public object onfilterchange
{
get
{
return Factory.ExecuteVariantPropertyGet(this, "onfilterchange");
}
set
{
Factory.ExecuteVariantPropertySet(this, "onfilterchange", value);
}
}
/// <summary>
/// SupportByVersion MSHTML 4
/// Get
/// Unknown COM Proxy
/// </summary>
[SupportByVersion("MSHTML", 4), ProxyResult]
public object children
{
get
{
return Factory.ExecuteReferencePropertyGet(this, "children");
}
}
/// <summary>
/// SupportByVersion MSHTML 4
/// Get
/// Unknown COM Proxy
/// </summary>
[SupportByVersion("MSHTML", 4), ProxyResult]
public object all
{
get
{
return Factory.ExecuteReferencePropertyGet(this, "all");
}
}
/// <summary>
/// SupportByVersion MSHTML 4
/// Get
/// </summary>
[SupportByVersion("MSHTML", 4)]
public string scopeName
{
get
{
return Factory.ExecuteStringPropertyGet(this, "scopeName");
}
}
/// <summary>
/// SupportByVersion MSHTML 4
/// Get/Set
/// </summary>
[SupportByVersion("MSHTML", 4)]
public object onlosecapture
{
get
{
return Factory.ExecuteVariantPropertyGet(this, "onlosecapture");
}
set
{
Factory.ExecuteVariantPropertySet(this, "onlosecapture", value);
}
}
/// <summary>
/// SupportByVersion MSHTML 4
/// Get/Set
/// </summary>
[SupportByVersion("MSHTML", 4)]
public object onscroll
{
get
{
return Factory.ExecuteVariantPropertyGet(this, "onscroll");
}
set
{
Factory.ExecuteVariantPropertySet(this, "onscroll", value);
}
}
/// <summary>
/// SupportByVersion MSHTML 4
/// Get/Set
/// </summary>
[SupportByVersion("MSHTML", 4)]
public object ondrag
{
get
{
return Factory.ExecuteVariantPropertyGet(this, "ondrag");
}
set
{
Factory.ExecuteVariantPropertySet(this, "ondrag", value);
}
}
/// <summary>
/// SupportByVersion MSHTML 4
/// Get/Set
/// </summary>
[SupportByVersion("MSHTML", 4)]
public object ondragend
{
get
{
return Factory.ExecuteVariantPropertyGet(this, "ondragend");
}
set
{
Factory.ExecuteVariantPropertySet(this, "ondragend", value);
}
}
/// <summary>
/// SupportByVersion MSHTML 4
/// Get/Set
/// </summary>
[SupportByVersion("MSHTML", 4)]
public object ondragenter
{
get
{
return Factory.ExecuteVariantPropertyGet(this, "ondragenter");
}
set
{
Factory.ExecuteVariantPropertySet(this, "ondragenter", value);
}
}
/// <summary>
/// SupportByVersion MSHTML 4
/// Get/Set
/// </summary>
[SupportByVersion("MSHTML", 4)]
public object ondragover
{
get
{
return Factory.ExecuteVariantPropertyGet(this, "ondragover");
}
set
{
Factory.ExecuteVariantPropertySet(this, "ondragover", value);
}
}
/// <summary>
/// SupportByVersion MSHTML 4
/// Get/Set
/// </summary>
[SupportByVersion("MSHTML", 4)]
public object ondragleave
{
get
{
return Factory.ExecuteVariantPropertyGet(this, "ondragleave");
}
set
{
Factory.ExecuteVariantPropertySet(this, "ondragleave", value);
}
}
/// <summary>
/// SupportByVersion MSHTML 4
/// Get/Set
/// </summary>
[SupportByVersion("MSHTML", 4)]
public object ondrop
{
get
{
return Factory.ExecuteVariantPropertyGet(this, "ondrop");
}
set
{
Factory.ExecuteVariantPropertySet(this, "ondrop", value);
}
}
/// <summary>
/// SupportByVersion MSHTML 4
/// Get/Set
/// </summary>
[SupportByVersion("MSHTML", 4)]
public object onbeforecut
{
get
{
return Factory.ExecuteVariantPropertyGet(this, "onbeforecut");
}
set
{
Factory.ExecuteVariantPropertySet(this, "onbeforecut", value);
}
}
/// <summary>
/// SupportByVersion MSHTML 4
/// Get/Set
/// </summary>
[SupportByVersion("MSHTML", 4)]
public object oncut
{
get
{
return Factory.ExecuteVariantPropertyGet(this, "oncut");
}
set
{
Factory.ExecuteVariantPropertySet(this, "oncut", value);
}
}
/// <summary>
/// SupportByVersion MSHTML 4
/// Get/Set
/// </summary>
[SupportByVersion("MSHTML", 4)]
public object onbeforecopy
{
get
{
return Factory.ExecuteVariantPropertyGet(this, "onbeforecopy");
}
set
{
Factory.ExecuteVariantPropertySet(this, "onbeforecopy", value);
}
}
/// <summary>
/// SupportByVersion MSHTML 4
/// Get/Set
/// </summary>
[SupportByVersion("MSHTML", 4)]
public object oncopy
{
get
{
return Factory.ExecuteVariantPropertyGet(this, "oncopy");
}
set
{
Factory.ExecuteVariantPropertySet(this, "oncopy", value);
}
}
/// <summary>
/// SupportByVersion MSHTML 4
/// Get/Set
/// </summary>
[SupportByVersion("MSHTML", 4)]
public object onbeforepaste
{
get
{
return Factory.ExecuteVariantPropertyGet(this, "onbeforepaste");
}
set
{
Factory.ExecuteVariantPropertySet(this, "onbeforepaste", value);
}
}
/// <summary>
/// SupportByVersion MSHTML 4
/// Get/Set
/// </summary>
[SupportByVersion("MSHTML", 4)]
public object onpaste
{
get
{
return Factory.ExecuteVariantPropertyGet(this, "onpaste");
}
set
{
Factory.ExecuteVariantPropertySet(this, "onpaste", value);
}
}
/// <summary>
/// SupportByVersion MSHTML 4
/// Get
/// </summary>
[SupportByVersion("MSHTML", 4)]
[BaseResult]
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public NetOffice.MSHTMLApi.IHTMLCurrentStyle currentStyle
{
get
{
return Factory.ExecuteBaseReferencePropertyGet<NetOffice.MSHTMLApi.IHTMLCurrentStyle>(this, "currentStyle");
}
}
/// <summary>
/// SupportByVersion MSHTML 4
/// Get/Set
/// </summary>
[SupportByVersion("MSHTML", 4)]
public object onpropertychange
{
get
{
return Factory.ExecuteVariantPropertyGet(this, "onpropertychange");
}
set
{
Factory.ExecuteVariantPropertySet(this, "onpropertychange", value);
}
}
/// <summary>
/// SupportByVersion MSHTML 4
/// Get/Set
/// </summary>
[SupportByVersion("MSHTML", 4)]
public Int16 tabIndex
{
get
{
return Factory.ExecuteInt16PropertyGet(this, "tabIndex");
}
set
{
Factory.ExecuteValuePropertySet(this, "tabIndex", value);
}
}
/// <summary>
/// SupportByVersion MSHTML 4
/// Get/Set
/// </summary>
[SupportByVersion("MSHTML", 4)]
public string accessKey
{
get
{
return Factory.ExecuteStringPropertyGet(this, "accessKey");
}
set
{
Factory.ExecuteValuePropertySet(this, "accessKey", value);
}
}
/// <summary>
/// SupportByVersion MSHTML 4
/// Get/Set
/// </summary>
[SupportByVersion("MSHTML", 4)]
public object onblur
{
get
{
return Factory.ExecuteVariantPropertyGet(this, "onblur");
}
set
{
Factory.ExecuteVariantPropertySet(this, "onblur", value);
}
}
/// <summary>
/// SupportByVersion MSHTML 4
/// Get/Set
/// </summary>
[SupportByVersion("MSHTML", 4)]
public object onfocus
{
get
{
return Factory.ExecuteVariantPropertyGet(this, "onfocus");
}
set
{
Factory.ExecuteVariantPropertySet(this, "onfocus", value);
}
}
/// <summary>
/// SupportByVersion MSHTML 4
/// Get/Set
/// </summary>
[SupportByVersion("MSHTML", 4)]
public object onresize
{
get
{
return Factory.ExecuteVariantPropertyGet(this, "onresize");
}
set
{
Factory.ExecuteVariantPropertySet(this, "onresize", value);
}
}
/// <summary>
/// SupportByVersion MSHTML 4
/// Get
/// </summary>
[SupportByVersion("MSHTML", 4)]
public Int32 clientHeight
{
get
{
return Factory.ExecuteInt32PropertyGet(this, "clientHeight");
}
}
/// <summary>
/// SupportByVersion MSHTML 4
/// Get
/// </summary>
[SupportByVersion("MSHTML", 4)]
public Int32 clientWidth
{
get
{
return Factory.ExecuteInt32PropertyGet(this, "clientWidth");
}
}
/// <summary>
/// SupportByVersion MSHTML 4
/// Get
/// </summary>
[SupportByVersion("MSHTML", 4)]
public Int32 clientTop
{
get
{
return Factory.ExecuteInt32PropertyGet(this, "clientTop");
}
}
/// <summary>
/// SupportByVersion MSHTML 4
/// Get
/// </summary>
[SupportByVersion("MSHTML", 4)]
public Int32 clientLeft
{
get
{
return Factory.ExecuteInt32PropertyGet(this, "clientLeft");
}
}
/// <summary>
/// SupportByVersion MSHTML 4
/// Get
/// </summary>
[SupportByVersion("MSHTML", 4)]
public object readyState
{
get
{
return Factory.ExecuteVariantPropertyGet(this, "readyState");
}
}
/// <summary>
/// SupportByVersion MSHTML 4
/// Get/Set
/// </summary>
[SupportByVersion("MSHTML", 4)]
public object onreadystatechange
{
get
{
return Factory.ExecuteVariantPropertyGet(this, "onreadystatechange");
}
set
{
Factory.ExecuteVariantPropertySet(this, "onreadystatechange", value);
}
}
/// <summary>
/// SupportByVersion MSHTML 4
/// Get/Set
/// </summary>
[SupportByVersion("MSHTML", 4)]
public object onrowsdelete
{
get
{
return Factory.ExecuteVariantPropertyGet(this, "onrowsdelete");
}
set
{
Factory.ExecuteVariantPropertySet(this, "onrowsdelete", value);
}
}
/// <summary>
/// SupportByVersion MSHTML 4
/// Get/Set
/// </summary>
[SupportByVersion("MSHTML", 4)]
public object onrowsinserted
{
get
{
return Factory.ExecuteVariantPropertyGet(this, "onrowsinserted");
}
set
{
Factory.ExecuteVariantPropertySet(this, "onrowsinserted", value);
}
}
/// <summary>
/// SupportByVersion MSHTML 4
/// Get/Set
/// </summary>
[SupportByVersion("MSHTML", 4)]
public object oncellchange
{
get
{
return Factory.ExecuteVariantPropertyGet(this, "oncellchange");
}
set
{
Factory.ExecuteVariantPropertySet(this, "oncellchange", value);
}
}
/// <summary>
/// SupportByVersion MSHTML 4
/// Get/Set
/// </summary>
[SupportByVersion("MSHTML", 4)]
public string dir
{
get
{
return Factory.ExecuteStringPropertyGet(this, "dir");
}
set
{
Factory.ExecuteValuePropertySet(this, "dir", value);
}
}
/// <summary>
/// SupportByVersion MSHTML 4
/// Get
/// </summary>
[SupportByVersion("MSHTML", 4)]
public Int32 scrollHeight
{
get
{
return Factory.ExecuteInt32PropertyGet(this, "scrollHeight");
}
}
/// <summary>
/// SupportByVersion MSHTML 4
/// Get
/// </summary>
[SupportByVersion("MSHTML", 4)]
public Int32 scrollWidth
{
get
{
return Factory.ExecuteInt32PropertyGet(this, "scrollWidth");
}
}
/// <summary>
/// SupportByVersion MSHTML 4
/// Get/Set
/// </summary>
[SupportByVersion("MSHTML", 4)]
public Int32 scrollTop
{
get
{
return Factory.ExecuteInt32PropertyGet(this, "scrollTop");
}
set
{
Factory.ExecuteValuePropertySet(this, "scrollTop", value);
}
}
/// <summary>
/// SupportByVersion MSHTML 4
/// Get/Set
/// </summary>
[SupportByVersion("MSHTML", 4)]
public Int32 scrollLeft
{
get
{
return Factory.ExecuteInt32PropertyGet(this, "scrollLeft");
}
set
{
Factory.ExecuteValuePropertySet(this, "scrollLeft", value);
}
}
/// <summary>
/// SupportByVersion MSHTML 4
/// Get/Set
/// </summary>
[SupportByVersion("MSHTML", 4)]
public object oncontextmenu
{
get
{
return Factory.ExecuteVariantPropertyGet(this, "oncontextmenu");
}
set
{
Factory.ExecuteVariantPropertySet(this, "oncontextmenu", value);
}
}
/// <summary>
/// SupportByVersion MSHTML 4
/// Get
/// </summary>
[SupportByVersion("MSHTML", 4)]
public bool canHaveChildren
{
get
{
return Factory.ExecuteBoolPropertyGet(this, "canHaveChildren");
}
}
/// <summary>
/// SupportByVersion MSHTML 4
/// Get
/// </summary>
[SupportByVersion("MSHTML", 4)]
[BaseResult]
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public NetOffice.MSHTMLApi.IHTMLStyle runtimeStyle
{
get
{
return Factory.ExecuteBaseReferencePropertyGet<NetOffice.MSHTMLApi.IHTMLStyle>(this, "runtimeStyle");
}
}
/// <summary>
/// SupportByVersion MSHTML 4
/// Get
/// Unknown COM Proxy
/// </summary>
[SupportByVersion("MSHTML", 4), ProxyResult]
public object behaviorUrns
{
get
{
return Factory.ExecuteReferencePropertyGet(this, "behaviorUrns");
}
}
/// <summary>
/// SupportByVersion MSHTML 4
/// Get/Set
/// </summary>
[SupportByVersion("MSHTML", 4)]
public string tagUrn
{
get
{
return Factory.ExecuteStringPropertyGet(this, "tagUrn");
}
set
{
Factory.ExecuteValuePropertySet(this, "tagUrn", value);
}
}
/// <summary>
/// SupportByVersion MSHTML 4
/// Get/Set
/// </summary>
[SupportByVersion("MSHTML", 4)]
public object onbeforeeditfocus
{
get
{
return Factory.ExecuteVariantPropertyGet(this, "onbeforeeditfocus");
}
set
{
Factory.ExecuteVariantPropertySet(this, "onbeforeeditfocus", value);
}
}
/// <summary>
/// SupportByVersion MSHTML 4
/// Get
/// </summary>
[SupportByVersion("MSHTML", 4)]
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public Int32 readyStateValue
{
get
{
return Factory.ExecuteInt32PropertyGet(this, "readyStateValue");
}
}
/// <summary>
/// SupportByVersion MSHTML 4
/// Get
/// </summary>
[SupportByVersion("MSHTML", 4)]
public bool isMultiLine
{
get
{
return Factory.ExecuteBoolPropertyGet(this, "isMultiLine");
}
}
/// <summary>
/// SupportByVersion MSHTML 4
/// Get
/// </summary>
[SupportByVersion("MSHTML", 4)]
public bool canHaveHTML
{
get
{
return Factory.ExecuteBoolPropertyGet(this, "canHaveHTML");
}
}
/// <summary>
/// SupportByVersion MSHTML 4
/// Get/Set
/// </summary>
[SupportByVersion("MSHTML", 4)]
public object onlayoutcomplete
{
get
{
return Factory.ExecuteVariantPropertyGet(this, "onlayoutcomplete");
}
set
{
Factory.ExecuteVariantPropertySet(this, "onlayoutcomplete", value);
}
}
/// <summary>
/// SupportByVersion MSHTML 4
/// Get/Set
/// </summary>
[SupportByVersion("MSHTML", 4)]
public object onpage
{
get
{
return Factory.ExecuteVariantPropertyGet(this, "onpage");
}
set
{
Factory.ExecuteVariantPropertySet(this, "onpage", value);
}
}
/// <summary>
/// SupportByVersion MSHTML 4
/// Get/Set
/// </summary>
[SupportByVersion("MSHTML", 4)]
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public bool inflateBlock
{
get
{
return Factory.ExecuteBoolPropertyGet(this, "inflateBlock");
}
set
{
Factory.ExecuteValuePropertySet(this, "inflateBlock", value);
}
}
/// <summary>
/// SupportByVersion MSHTML 4
/// Get/Set
/// </summary>
[SupportByVersion("MSHTML", 4)]
public object onbeforedeactivate
{
get
{
return Factory.ExecuteVariantPropertyGet(this, "onbeforedeactivate");
}
set
{
Factory.ExecuteVariantPropertySet(this, "onbeforedeactivate", value);
}
}
/// <summary>
/// SupportByVersion MSHTML 4
/// Get/Set
/// </summary>
[SupportByVersion("MSHTML", 4)]
public string contentEditable
{
get
{
return Factory.ExecuteStringPropertyGet(this, "contentEditable");
}
set
{
Factory.ExecuteValuePropertySet(this, "contentEditable", value);
}
}
/// <summary>
/// SupportByVersion MSHTML 4
/// Get
/// </summary>
[SupportByVersion("MSHTML", 4)]
public bool isContentEditable
{
get
{
return Factory.ExecuteBoolPropertyGet(this, "isContentEditable");
}
}
/// <summary>
/// SupportByVersion MSHTML 4
/// Get/Set
/// </summary>
[SupportByVersion("MSHTML", 4)]
public bool hideFocus
{
get
{
return Factory.ExecuteBoolPropertyGet(this, "hideFocus");
}
set
{
Factory.ExecuteValuePropertySet(this, "hideFocus", value);
}
}
/// <summary>
/// SupportByVersion MSHTML 4
/// Get/Set
/// </summary>
[SupportByVersion("MSHTML", 4)]
public bool disabled
{
get
{
return Factory.ExecuteBoolPropertyGet(this, "disabled");
}
set
{
Factory.ExecuteValuePropertySet(this, "disabled", value);
}
}
/// <summary>
/// SupportByVersion MSHTML 4
/// Get
/// </summary>
[SupportByVersion("MSHTML", 4)]
public bool isDisabled
{
get
{
return Factory.ExecuteBoolPropertyGet(this, "isDisabled");
}
}
/// <summary>
/// SupportByVersion MSHTML 4
/// Get/Set
/// </summary>
[SupportByVersion("MSHTML", 4)]
public object onmove
{
get
{
return Factory.ExecuteVariantPropertyGet(this, "onmove");
}
set
{
Factory.ExecuteVariantPropertySet(this, "onmove", value);
}
}
/// <summary>
/// SupportByVersion MSHTML 4
/// Get/Set
/// </summary>
[SupportByVersion("MSHTML", 4)]
public object oncontrolselect
{
get
{
return Factory.ExecuteVariantPropertyGet(this, "oncontrolselect");
}
set
{
Factory.ExecuteVariantPropertySet(this, "oncontrolselect", value);
}
}
/// <summary>
/// SupportByVersion MSHTML 4
/// Get/Set
/// </summary>
[SupportByVersion("MSHTML", 4)]
public object onresizestart
{
get
{
return Factory.ExecuteVariantPropertyGet(this, "onresizestart");
}
set
{
Factory.ExecuteVariantPropertySet(this, "onresizestart", value);
}
}
/// <summary>
/// SupportByVersion MSHTML 4
/// Get/Set
/// </summary>
[SupportByVersion("MSHTML", 4)]
public object onresizeend
{
get
{
return Factory.ExecuteVariantPropertyGet(this, "onresizeend");
}
set
{
Factory.ExecuteVariantPropertySet(this, "onresizeend", value);
}
}
/// <summary>
/// SupportByVersion MSHTML 4
/// Get/Set
/// </summary>
[SupportByVersion("MSHTML", 4)]
public object onmovestart
{
get
{
return Factory.ExecuteVariantPropertyGet(this, "onmovestart");
}
set
{
Factory.ExecuteVariantPropertySet(this, "onmovestart", value);
}
}
/// <summary>
/// SupportByVersion MSHTML 4
/// Get/Set
/// </summary>
[SupportByVersion("MSHTML", 4)]
public object onmoveend
{
get
{
return Factory.ExecuteVariantPropertyGet(this, "onmoveend");
}
set
{
Factory.ExecuteVariantPropertySet(this, "onmoveend", value);
}
}
/// <summary>
/// SupportByVersion MSHTML 4
/// Get/Set
/// </summary>
[SupportByVersion("MSHTML", 4)]
public object onmouseenter
{
get
{
return Factory.ExecuteVariantPropertyGet(this, "onmouseenter");
}
set
{
Factory.ExecuteVariantPropertySet(this, "onmouseenter", value);
}
}
/// <summary>
/// SupportByVersion MSHTML 4
/// Get/Set
/// </summary>
[SupportByVersion("MSHTML", 4)]
public object onmouseleave
{
get
{
return Factory.ExecuteVariantPropertyGet(this, "onmouseleave");
}
set
{
Factory.ExecuteVariantPropertySet(this, "onmouseleave", value);
}
}
/// <summary>
/// SupportByVersion MSHTML 4
/// Get/Set
/// </summary>
[SupportByVersion("MSHTML", 4)]
public object onactivate
{
get
{
return Factory.ExecuteVariantPropertyGet(this, "onactivate");
}
set
{
Factory.ExecuteVariantPropertySet(this, "onactivate", value);
}
}
/// <summary>
/// SupportByVersion MSHTML 4
/// Get/Set
/// </summary>
[SupportByVersion("MSHTML", 4)]
public object ondeactivate
{
get
{
return Factory.ExecuteVariantPropertyGet(this, "ondeactivate");
}
set
{
Factory.ExecuteVariantPropertySet(this, "ondeactivate", value);
}
}
/// <summary>
/// SupportByVersion MSHTML 4
/// Get
/// </summary>
[SupportByVersion("MSHTML", 4)]
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public Int32 glyphMode
{
get
{
return Factory.ExecuteInt32PropertyGet(this, "glyphMode");
}
}
/// <summary>
/// SupportByVersion MSHTML 4
/// Get/Set
/// </summary>
[SupportByVersion("MSHTML", 4)]
public object onmousewheel
{
get
{
return Factory.ExecuteVariantPropertyGet(this, "onmousewheel");
}
set
{
Factory.ExecuteVariantPropertySet(this, "onmousewheel", value);
}
}
/// <summary>
/// SupportByVersion MSHTML 4
/// Get/Set
/// </summary>
[SupportByVersion("MSHTML", 4)]
public object onbeforeactivate
{
get
{
return Factory.ExecuteVariantPropertyGet(this, "onbeforeactivate");
}
set
{
Factory.ExecuteVariantPropertySet(this, "onbeforeactivate", value);
}
}
/// <summary>
/// SupportByVersion MSHTML 4
/// Get/Set
/// </summary>
[SupportByVersion("MSHTML", 4)]
public object onfocusin
{
get
{
return Factory.ExecuteVariantPropertyGet(this, "onfocusin");
}
set
{
Factory.ExecuteVariantPropertySet(this, "onfocusin", value);
}
}
/// <summary>
/// SupportByVersion MSHTML 4
/// Get/Set
/// </summary>
[SupportByVersion("MSHTML", 4)]
public object onfocusout
{
get
{
return Factory.ExecuteVariantPropertyGet(this, "onfocusout");
}
set
{
Factory.ExecuteVariantPropertySet(this, "onfocusout", value);
}
}
/// <summary>
/// SupportByVersion MSHTML 4
/// Get
/// </summary>
[SupportByVersion("MSHTML", 4)]
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public Int32 uniqueNumber
{
get
{
return Factory.ExecuteInt32PropertyGet(this, "uniqueNumber");
}
}
/// <summary>
/// SupportByVersion MSHTML 4
/// Get
/// </summary>
[SupportByVersion("MSHTML", 4)]
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public string uniqueID
{
get
{
return Factory.ExecuteStringPropertyGet(this, "uniqueID");
}
}
/// <summary>
/// SupportByVersion MSHTML 4
/// Get
/// </summary>
[SupportByVersion("MSHTML", 4)]
public Int32 nodeType
{
get
{
return Factory.ExecuteInt32PropertyGet(this, "nodeType");
}
}
/// <summary>
/// SupportByVersion MSHTML 4
/// Get
/// </summary>
[SupportByVersion("MSHTML", 4)]
[BaseResult]
public NetOffice.MSHTMLApi.IHTMLDOMNode parentNode
{
get
{
return Factory.ExecuteBaseReferencePropertyGet<NetOffice.MSHTMLApi.IHTMLDOMNode>(this, "parentNode");
}
}
/// <summary>
/// SupportByVersion MSHTML 4
/// Get
/// Unknown COM Proxy
/// </summary>
[SupportByVersion("MSHTML", 4), ProxyResult]
public object childNodes
{
get
{
return Factory.ExecuteReferencePropertyGet(this, "childNodes");
}
}
/// <summary>
/// SupportByVersion MSHTML 4
/// Get
/// Unknown COM Proxy
/// </summary>
[SupportByVersion("MSHTML", 4), ProxyResult]
public object attributes
{
get
{
return Factory.ExecuteReferencePropertyGet(this, "attributes");
}
}
/// <summary>
/// SupportByVersion MSHTML 4
/// Get
/// </summary>
[SupportByVersion("MSHTML", 4)]
public string nodeName
{
get
{
return Factory.ExecuteStringPropertyGet(this, "nodeName");
}
}
/// <summary>
/// SupportByVersion MSHTML 4
/// Get/Set
/// </summary>
[SupportByVersion("MSHTML", 4)]
public object nodeValue
{
get
{
return Factory.ExecuteVariantPropertyGet(this, "nodeValue");
}
set
{
Factory.ExecuteVariantPropertySet(this, "nodeValue", value);
}
}
/// <summary>
/// SupportByVersion MSHTML 4
/// Get
/// </summary>
[SupportByVersion("MSHTML", 4)]
[BaseResult]
public NetOffice.MSHTMLApi.IHTMLDOMNode firstChild
{
get
{
return Factory.ExecuteBaseReferencePropertyGet<NetOffice.MSHTMLApi.IHTMLDOMNode>(this, "firstChild");
}
}
/// <summary>
/// SupportByVersion MSHTML 4
/// Get
/// </summary>
[SupportByVersion("MSHTML", 4)]
[BaseResult]
public NetOffice.MSHTMLApi.IHTMLDOMNode lastChild
{
get
{
return Factory.ExecuteBaseReferencePropertyGet<NetOffice.MSHTMLApi.IHTMLDOMNode>(this, "lastChild");
}
}
/// <summary>
/// SupportByVersion MSHTML 4
/// Get
/// </summary>
[SupportByVersion("MSHTML", 4)]
[BaseResult]
public NetOffice.MSHTMLApi.IHTMLDOMNode previousSibling
{
get
{
return Factory.ExecuteBaseReferencePropertyGet<NetOffice.MSHTMLApi.IHTMLDOMNode>(this, "previousSibling");
}
}
/// <summary>
/// SupportByVersion MSHTML 4
/// Get
/// </summary>
[SupportByVersion("MSHTML", 4)]
[BaseResult]
public NetOffice.MSHTMLApi.IHTMLDOMNode nextSibling
{
get
{
return Factory.ExecuteBaseReferencePropertyGet<NetOffice.MSHTMLApi.IHTMLDOMNode>(this, "nextSibling");
}
}
/// <summary>
/// SupportByVersion MSHTML 4
/// Get
/// Unknown COM Proxy
/// </summary>
[SupportByVersion("MSHTML", 4), ProxyResult]
public object ownerDocument
{
get
{
return Factory.ExecuteReferencePropertyGet(this, "ownerDocument");
}
}
/// <summary>
/// SupportByVersion MSHTML 4
/// Get/Set
/// </summary>
[SupportByVersion("MSHTML", 4)]
public string role
{
get
{
return Factory.ExecuteStringPropertyGet(this, "role");
}
set
{
Factory.ExecuteValuePropertySet(this, "role", value);
}
}
/// <summary>
/// SupportByVersion MSHTML 4
/// Get/Set
/// </summary>
[SupportByVersion("MSHTML", 4)]
public string ariaBusy
{
get
{
return Factory.ExecuteStringPropertyGet(this, "ariaBusy");
}
set
{
Factory.ExecuteValuePropertySet(this, "ariaBusy", value);
}
}
/// <summary>
/// SupportByVersion MSHTML 4
/// Get/Set
/// </summary>
[SupportByVersion("MSHTML", 4)]
public string ariaChecked
{
get
{
return Factory.ExecuteStringPropertyGet(this, "ariaChecked");
}
set
{
Factory.ExecuteValuePropertySet(this, "ariaChecked", value);
}
}
/// <summary>
/// SupportByVersion MSHTML 4
/// Get/Set
/// </summary>
[SupportByVersion("MSHTML", 4)]
public string ariaDisabled
{
get
{
return Factory.ExecuteStringPropertyGet(this, "ariaDisabled");
}
set
{
Factory.ExecuteValuePropertySet(this, "ariaDisabled", value);
}
}
/// <summary>
/// SupportByVersion MSHTML 4
/// Get/Set
/// </summary>
[SupportByVersion("MSHTML", 4)]
public string ariaExpanded
{
get
{
return Factory.ExecuteStringPropertyGet(this, "ariaExpanded");
}
set
{
Factory.ExecuteValuePropertySet(this, "ariaExpanded", value);
}
}
/// <summary>
/// SupportByVersion MSHTML 4
/// Get/Set
/// </summary>
[SupportByVersion("MSHTML", 4)]
public string ariaHaspopup
{
get
{
return Factory.ExecuteStringPropertyGet(this, "ariaHaspopup");
}
set
{
Factory.ExecuteValuePropertySet(this, "ariaHaspopup", value);
}
}
/// <summary>
/// SupportByVersion MSHTML 4
/// Get/Set
/// </summary>
[SupportByVersion("MSHTML", 4)]
public string ariaHidden
{
get
{
return Factory.ExecuteStringPropertyGet(this, "ariaHidden");
}
set
{
Factory.ExecuteValuePropertySet(this, "ariaHidden", value);
}
}
/// <summary>
/// SupportByVersion MSHTML 4
/// Get/Set
/// </summary>
[SupportByVersion("MSHTML", 4)]
public string ariaInvalid
{
get
{
return Factory.ExecuteStringPropertyGet(this, "ariaInvalid");
}
set
{
Factory.ExecuteValuePropertySet(this, "ariaInvalid", value);
}
}
/// <summary>
/// SupportByVersion MSHTML 4
/// Get/Set
/// </summary>
[SupportByVersion("MSHTML", 4)]
public string ariaMultiselectable
{
get
{
return Factory.ExecuteStringPropertyGet(this, "ariaMultiselectable");
}
set
{
Factory.ExecuteValuePropertySet(this, "ariaMultiselectable", value);
}
}
/// <summary>
/// SupportByVersion MSHTML 4
/// Get/Set
/// </summary>
[SupportByVersion("MSHTML", 4)]
public string ariaPressed
{
get
{
return Factory.ExecuteStringPropertyGet(this, "ariaPressed");
}
set
{
Factory.ExecuteValuePropertySet(this, "ariaPressed", value);
}
}
/// <summary>
/// SupportByVersion MSHTML 4
/// Get/Set
/// </summary>
[SupportByVersion("MSHTML", 4)]
public string ariaReadonly
{
get
{
return Factory.ExecuteStringPropertyGet(this, "ariaReadonly");
}
set
{
Factory.ExecuteValuePropertySet(this, "ariaReadonly", value);
}
}
/// <summary>
/// SupportByVersion MSHTML 4
/// Get/Set
/// </summary>
[SupportByVersion("MSHTML", 4)]
public string ariaRequired
{
get
{
return Factory.ExecuteStringPropertyGet(this, "ariaRequired");
}
set
{
Factory.ExecuteValuePropertySet(this, "ariaRequired", value);
}
}
/// <summary>
/// SupportByVersion MSHTML 4
/// Get/Set
/// </summary>
[SupportByVersion("MSHTML", 4)]
public string ariaSecret
{
get
{
return Factory.ExecuteStringPropertyGet(this, "ariaSecret");
}
set
{
Factory.ExecuteValuePropertySet(this, "ariaSecret", value);
}
}
/// <summary>
/// SupportByVersion MSHTML 4
/// Get/Set
/// </summary>
[SupportByVersion("MSHTML", 4)]
public string ariaSelected
{
get
{
return Factory.ExecuteStringPropertyGet(this, "ariaSelected");
}
set
{
Factory.ExecuteValuePropertySet(this, "ariaSelected", value);
}
}
/// <summary>
/// SupportByVersion MSHTML 4
/// Get
/// </summary>
[SupportByVersion("MSHTML", 4)]
public NetOffice.MSHTMLApi.IHTMLAttributeCollection3 ie8_attributes
{
get
{
return Factory.ExecuteKnownReferencePropertyGet<NetOffice.MSHTMLApi.IHTMLAttributeCollection3>(this, "ie8_attributes", NetOffice.MSHTMLApi.IHTMLAttributeCollection3.LateBindingApiWrapperType);
}
}
/// <summary>
/// SupportByVersion MSHTML 4
/// Get/Set
/// </summary>
[SupportByVersion("MSHTML", 4)]
public string ariaValuenow
{
get
{
return Factory.ExecuteStringPropertyGet(this, "ariaValuenow");
}
set
{
Factory.ExecuteValuePropertySet(this, "ariaValuenow", value);
}
}
/// <summary>
/// SupportByVersion MSHTML 4
/// Get/Set
/// </summary>
[SupportByVersion("MSHTML", 4)]
public Int16 ariaPosinset
{
get
{
return Factory.ExecuteInt16PropertyGet(this, "ariaPosinset");
}
set
{
Factory.ExecuteValuePropertySet(this, "ariaPosinset", value);
}
}
/// <summary>
/// SupportByVersion MSHTML 4
/// Get/Set
/// </summary>
[SupportByVersion("MSHTML", 4)]
public Int16 ariaSetsize
{
get
{
return Factory.ExecuteInt16PropertyGet(this, "ariaSetsize");
}
set
{
Factory.ExecuteValuePropertySet(this, "ariaSetsize", value);
}
}
/// <summary>
/// SupportByVersion MSHTML 4
/// Get/Set
/// </summary>
[SupportByVersion("MSHTML", 4)]
public Int16 ariaLevel
{
get
{
return Factory.ExecuteInt16PropertyGet(this, "ariaLevel");
}
set
{
Factory.ExecuteValuePropertySet(this, "ariaLevel", value);
}
}
/// <summary>
/// SupportByVersion MSHTML 4
/// Get/Set
/// </summary>
[SupportByVersion("MSHTML", 4)]
public string ariaValuemin
{
get
{
return Factory.ExecuteStringPropertyGet(this, "ariaValuemin");
}
set
{
Factory.ExecuteValuePropertySet(this, "ariaValuemin", value);
}
}
/// <summary>
/// SupportByVersion MSHTML 4
/// Get/Set
/// </summary>
[SupportByVersion("MSHTML", 4)]
public string ariaValuemax
{
get
{
return Factory.ExecuteStringPropertyGet(this, "ariaValuemax");
}
set
{
Factory.ExecuteValuePropertySet(this, "ariaValuemax", value);
}
}
/// <summary>
/// SupportByVersion MSHTML 4
/// Get/Set
/// </summary>
[SupportByVersion("MSHTML", 4)]
public string ariaControls
{
get
{
return Factory.ExecuteStringPropertyGet(this, "ariaControls");
}
set
{
Factory.ExecuteValuePropertySet(this, "ariaControls", value);
}
}
/// <summary>
/// SupportByVersion MSHTML 4
/// Get/Set
/// </summary>
[SupportByVersion("MSHTML", 4)]
public string ariaDescribedby
{
get
{
return Factory.ExecuteStringPropertyGet(this, "ariaDescribedby");
}
set
{
Factory.ExecuteValuePropertySet(this, "ariaDescribedby", value);
}
}
/// <summary>
/// SupportByVersion MSHTML 4
/// Get/Set
/// </summary>
[SupportByVersion("MSHTML", 4)]
public string ariaFlowto
{
get
{
return Factory.ExecuteStringPropertyGet(this, "ariaFlowto");
}
set
{
Factory.ExecuteValuePropertySet(this, "ariaFlowto", value);
}
}
/// <summary>
/// SupportByVersion MSHTML 4
/// Get/Set
/// </summary>
[SupportByVersion("MSHTML", 4)]
public string ariaLabelledby
{
get
{
return Factory.ExecuteStringPropertyGet(this, "ariaLabelledby");
}
set
{
Factory.ExecuteValuePropertySet(this, "ariaLabelledby", value);
}
}
/// <summary>
/// SupportByVersion MSHTML 4
/// Get/Set
/// </summary>
[SupportByVersion("MSHTML", 4)]
public string ariaActivedescendant
{
get
{
return Factory.ExecuteStringPropertyGet(this, "ariaActivedescendant");
}
set
{
Factory.ExecuteValuePropertySet(this, "ariaActivedescendant", value);
}
}
/// <summary>
/// SupportByVersion MSHTML 4
/// Get/Set
/// </summary>
[SupportByVersion("MSHTML", 4)]
public string ariaOwns
{
get
{
return Factory.ExecuteStringPropertyGet(this, "ariaOwns");
}
set
{
Factory.ExecuteValuePropertySet(this, "ariaOwns", value);
}
}
/// <summary>
/// SupportByVersion MSHTML 4
/// Get/Set
/// </summary>
[SupportByVersion("MSHTML", 4)]
public string ariaLive
{
get
{
return Factory.ExecuteStringPropertyGet(this, "ariaLive");
}
set
{
Factory.ExecuteValuePropertySet(this, "ariaLive", value);
}
}
/// <summary>
/// SupportByVersion MSHTML 4
/// Get/Set
/// </summary>
[SupportByVersion("MSHTML", 4)]
public string ariaRelevant
{
get
{
return Factory.ExecuteStringPropertyGet(this, "ariaRelevant");
}
set
{
Factory.ExecuteValuePropertySet(this, "ariaRelevant", value);
}
}
/// <summary>
/// SupportByVersion MSHTML 4
/// Get
/// Unknown COM Proxy
/// </summary>
[SupportByVersion("MSHTML", 4), ProxyResult]
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public object constructor
{
get
{
return Factory.ExecuteReferencePropertyGet(this, "constructor");
}
}
/// <summary>
/// SupportByVersion MSHTML 4
/// Get/Set
/// </summary>
[SupportByVersion("MSHTML", 4)]
public Int32 span
{
get
{
return Factory.ExecuteInt32PropertyGet(this, "span");
}
set
{
Factory.ExecuteValuePropertySet(this, "span", value);
}
}
/// <summary>
/// SupportByVersion MSHTML 4
/// Get/Set
/// </summary>
[SupportByVersion("MSHTML", 4)]
public object width
{
get
{
return Factory.ExecuteVariantPropertyGet(this, "width");
}
set
{
Factory.ExecuteVariantPropertySet(this, "width", value);
}
}
/// <summary>
/// SupportByVersion MSHTML 4
/// Get/Set
/// </summary>
[SupportByVersion("MSHTML", 4)]
public string align
{
get
{
return Factory.ExecuteStringPropertyGet(this, "align");
}
set
{
Factory.ExecuteValuePropertySet(this, "align", value);
}
}
/// <summary>
/// SupportByVersion MSHTML 4
/// Get/Set
/// </summary>
[SupportByVersion("MSHTML", 4)]
public string vAlign
{
get
{
return Factory.ExecuteStringPropertyGet(this, "vAlign");
}
set
{
Factory.ExecuteValuePropertySet(this, "vAlign", value);
}
}
/// <summary>
/// SupportByVersion MSHTML 4
/// Get/Set
/// </summary>
[SupportByVersion("MSHTML", 4)]
public string ch
{
get
{
return Factory.ExecuteStringPropertyGet(this, "ch");
}
set
{
Factory.ExecuteValuePropertySet(this, "ch", value);
}
}
/// <summary>
/// SupportByVersion MSHTML 4
/// Get/Set
/// </summary>
[SupportByVersion("MSHTML", 4)]
public string chOff
{
get
{
return Factory.ExecuteStringPropertyGet(this, "chOff");
}
set
{
Factory.ExecuteValuePropertySet(this, "chOff", value);
}
}
#endregion
#region Methods
/// <summary>
/// SupportByVersion MSHTML 4
/// </summary>
/// <param name="strAttributeName">string strAttributeName</param>
/// <param name="attributeValue">object attributeValue</param>
/// <param name="lFlags">optional Int32 lFlags = 1</param>
[SupportByVersion("MSHTML", 4)]
public void setAttribute(string strAttributeName, object attributeValue, object lFlags)
{
Factory.ExecuteMethod(this, "setAttribute", strAttributeName, attributeValue, lFlags);
}
/// <summary>
/// SupportByVersion MSHTML 4
/// </summary>
/// <param name="strAttributeName">string strAttributeName</param>
/// <param name="attributeValue">object attributeValue</param>
[CustomMethod]
[SupportByVersion("MSHTML", 4)]
public void setAttribute(string strAttributeName, object attributeValue)
{
Factory.ExecuteMethod(this, "setAttribute", strAttributeName, attributeValue);
}
/// <summary>
/// SupportByVersion MSHTML 4
/// </summary>
/// <param name="strAttributeName">string strAttributeName</param>
/// <param name="lFlags">optional Int32 lFlags = 0</param>
[SupportByVersion("MSHTML", 4)]
public object getAttribute(string strAttributeName, object lFlags)
{
return Factory.ExecuteVariantMethodGet(this, "getAttribute", strAttributeName, lFlags);
}
/// <summary>
/// SupportByVersion MSHTML 4
/// </summary>
/// <param name="strAttributeName">string strAttributeName</param>
[CustomMethod]
[SupportByVersion("MSHTML", 4)]
public object getAttribute(string strAttributeName)
{
return Factory.ExecuteVariantMethodGet(this, "getAttribute", strAttributeName);
}
/// <summary>
/// SupportByVersion MSHTML 4
/// </summary>
/// <param name="strAttributeName">string strAttributeName</param>
/// <param name="lFlags">optional Int32 lFlags = 1</param>
[SupportByVersion("MSHTML", 4)]
public bool removeAttribute(string strAttributeName, object lFlags)
{
return Factory.ExecuteBoolMethodGet(this, "removeAttribute", strAttributeName, lFlags);
}
/// <summary>
/// SupportByVersion MSHTML 4
/// </summary>
/// <param name="strAttributeName">string strAttributeName</param>
[CustomMethod]
[SupportByVersion("MSHTML", 4)]
public bool removeAttribute(string strAttributeName)
{
return Factory.ExecuteBoolMethodGet(this, "removeAttribute", strAttributeName);
}
/// <summary>
/// SupportByVersion MSHTML 4
/// </summary>
/// <param name="varargStart">optional object varargStart</param>
[SupportByVersion("MSHTML", 4)]
public void scrollIntoView(object varargStart)
{
Factory.ExecuteMethod(this, "scrollIntoView", varargStart);
}
/// <summary>
/// SupportByVersion MSHTML 4
/// </summary>
[CustomMethod]
[SupportByVersion("MSHTML", 4)]
public void scrollIntoView()
{
Factory.ExecuteMethod(this, "scrollIntoView");
}
/// <summary>
/// SupportByVersion MSHTML 4
/// </summary>
/// <param name="pChild">NetOffice.MSHTMLApi.IHTMLElement pChild</param>
[SupportByVersion("MSHTML", 4)]
public bool contains(NetOffice.MSHTMLApi.IHTMLElement pChild)
{
return Factory.ExecuteBoolMethodGet(this, "contains", pChild);
}
/// <summary>
/// SupportByVersion MSHTML 4
/// </summary>
/// <param name="where">string where</param>
/// <param name="html">string html</param>
[SupportByVersion("MSHTML", 4)]
public void insertAdjacentHTML(string where, string html)
{
Factory.ExecuteMethod(this, "insertAdjacentHTML", where, html);
}
/// <summary>
/// SupportByVersion MSHTML 4
/// </summary>
/// <param name="where">string where</param>
/// <param name="text">string text</param>
[SupportByVersion("MSHTML", 4)]
public void insertAdjacentText(string where, string text)
{
Factory.ExecuteMethod(this, "insertAdjacentText", where, text);
}
/// <summary>
/// SupportByVersion MSHTML 4
/// </summary>
[SupportByVersion("MSHTML", 4)]
public void click()
{
Factory.ExecuteMethod(this, "click");
}
/// <summary>
/// SupportByVersion MSHTML 4
/// </summary>
[SupportByVersion("MSHTML", 4)]
public string toString()
{
return Factory.ExecuteStringMethodGet(this, "toString");
}
/// <summary>
/// SupportByVersion MSHTML 4
/// </summary>
/// <param name="containerCapture">optional bool containerCapture = true</param>
[SupportByVersion("MSHTML", 4)]
public void setCapture(object containerCapture)
{
Factory.ExecuteMethod(this, "setCapture", containerCapture);
}
/// <summary>
/// SupportByVersion MSHTML 4
/// </summary>
[CustomMethod]
[SupportByVersion("MSHTML", 4)]
public void setCapture()
{
Factory.ExecuteMethod(this, "setCapture");
}
/// <summary>
/// SupportByVersion MSHTML 4
/// </summary>
[SupportByVersion("MSHTML", 4)]
public void releaseCapture()
{
Factory.ExecuteMethod(this, "releaseCapture");
}
/// <summary>
/// SupportByVersion MSHTML 4
/// </summary>
/// <param name="x">Int32 x</param>
/// <param name="y">Int32 y</param>
[SupportByVersion("MSHTML", 4)]
public string componentFromPoint(Int32 x, Int32 y)
{
return Factory.ExecuteStringMethodGet(this, "componentFromPoint", x, y);
}
/// <summary>
/// SupportByVersion MSHTML 4
/// </summary>
/// <param name="component">optional object component</param>
[SupportByVersion("MSHTML", 4)]
public void doScroll(object component)
{
Factory.ExecuteMethod(this, "doScroll", component);
}
/// <summary>
/// SupportByVersion MSHTML 4
/// </summary>
[CustomMethod]
[SupportByVersion("MSHTML", 4)]
public void doScroll()
{
Factory.ExecuteMethod(this, "doScroll");
}
/// <summary>
/// SupportByVersion MSHTML 4
/// </summary>
[SupportByVersion("MSHTML", 4)]
public NetOffice.MSHTMLApi.IHTMLRectCollection getClientRects()
{
return Factory.ExecuteKnownReferenceMethodGet<NetOffice.MSHTMLApi.IHTMLRectCollection>(this, "getClientRects", NetOffice.MSHTMLApi.IHTMLRectCollection.LateBindingApiWrapperType);
}
/// <summary>
/// SupportByVersion MSHTML 4
/// </summary>
[SupportByVersion("MSHTML", 4)]
public NetOffice.MSHTMLApi.IHTMLRect getBoundingClientRect()
{
return Factory.ExecuteKnownReferenceMethodGet<NetOffice.MSHTMLApi.IHTMLRect>(this, "getBoundingClientRect", NetOffice.MSHTMLApi.IHTMLRect.LateBindingApiWrapperType);
}
/// <summary>
/// SupportByVersion MSHTML 4
/// </summary>
/// <param name="propname">string propname</param>
/// <param name="expression">string expression</param>
/// <param name="language">optional string language = </param>
[SupportByVersion("MSHTML", 4)]
public void setExpression(string propname, string expression, object language)
{
Factory.ExecuteMethod(this, "setExpression", propname, expression, language);
}
/// <summary>
/// SupportByVersion MSHTML 4
/// </summary>
/// <param name="propname">string propname</param>
/// <param name="expression">string expression</param>
[CustomMethod]
[SupportByVersion("MSHTML", 4)]
public void setExpression(string propname, string expression)
{
Factory.ExecuteMethod(this, "setExpression", propname, expression);
}
/// <summary>
/// SupportByVersion MSHTML 4
/// </summary>
/// <param name="propname">string propname</param>
[SupportByVersion("MSHTML", 4)]
public object getExpression(string propname)
{
return Factory.ExecuteVariantMethodGet(this, "getExpression", propname);
}
/// <summary>
/// SupportByVersion MSHTML 4
/// </summary>
/// <param name="propname">string propname</param>
[SupportByVersion("MSHTML", 4)]
public bool removeExpression(string propname)
{
return Factory.ExecuteBoolMethodGet(this, "removeExpression", propname);
}
/// <summary>
/// SupportByVersion MSHTML 4
/// </summary>
[SupportByVersion("MSHTML", 4)]
public void focus()
{
Factory.ExecuteMethod(this, "focus");
}
/// <summary>
/// SupportByVersion MSHTML 4
/// </summary>
[SupportByVersion("MSHTML", 4)]
public void blur()
{
Factory.ExecuteMethod(this, "blur");
}
/// <summary>
/// SupportByVersion MSHTML 4
/// </summary>
/// <param name="pUnk">object pUnk</param>
[SupportByVersion("MSHTML", 4)]
public void addFilter(object pUnk)
{
Factory.ExecuteMethod(this, "addFilter", pUnk);
}
/// <summary>
/// SupportByVersion MSHTML 4
/// </summary>
/// <param name="pUnk">object pUnk</param>
[SupportByVersion("MSHTML", 4)]
public void removeFilter(object pUnk)
{
Factory.ExecuteMethod(this, "removeFilter", pUnk);
}
/// <summary>
/// SupportByVersion MSHTML 4
/// </summary>
/// <param name="_event">string event</param>
/// <param name="pdisp">object pdisp</param>
[SupportByVersion("MSHTML", 4)]
public bool attachEvent(string _event, object pdisp)
{
return Factory.ExecuteBoolMethodGet(this, "attachEvent", _event, pdisp);
}
/// <summary>
/// SupportByVersion MSHTML 4
/// </summary>
/// <param name="_event">string event</param>
/// <param name="pdisp">object pdisp</param>
[SupportByVersion("MSHTML", 4)]
public void detachEvent(string _event, object pdisp)
{
Factory.ExecuteMethod(this, "detachEvent", _event, pdisp);
}
/// <summary>
/// SupportByVersion MSHTML 4
/// </summary>
[SupportByVersion("MSHTML", 4)]
public object createControlRange()
{
return Factory.ExecuteVariantMethodGet(this, "createControlRange");
}
/// <summary>
/// SupportByVersion MSHTML 4
/// </summary>
[SupportByVersion("MSHTML", 4)]
public void clearAttributes()
{
Factory.ExecuteMethod(this, "clearAttributes");
}
/// <summary>
/// SupportByVersion MSHTML 4
/// </summary>
/// <param name="where">string where</param>
/// <param name="insertedElement">NetOffice.MSHTMLApi.IHTMLElement insertedElement</param>
[SupportByVersion("MSHTML", 4)]
[BaseResult]
public NetOffice.MSHTMLApi.IHTMLElement insertAdjacentElement(string where, NetOffice.MSHTMLApi.IHTMLElement insertedElement)
{
return Factory.ExecuteBaseReferenceMethodGet<NetOffice.MSHTMLApi.IHTMLElement>(this, "insertAdjacentElement", where, insertedElement);
}
/// <summary>
/// SupportByVersion MSHTML 4
/// </summary>
/// <param name="apply">NetOffice.MSHTMLApi.IHTMLElement apply</param>
/// <param name="where">string where</param>
[SupportByVersion("MSHTML", 4)]
[BaseResult]
public NetOffice.MSHTMLApi.IHTMLElement applyElement(NetOffice.MSHTMLApi.IHTMLElement apply, string where)
{
return Factory.ExecuteBaseReferenceMethodGet<NetOffice.MSHTMLApi.IHTMLElement>(this, "applyElement", apply, where);
}
/// <summary>
/// SupportByVersion MSHTML 4
/// </summary>
/// <param name="where">string where</param>
[SupportByVersion("MSHTML", 4)]
public string getAdjacentText(string where)
{
return Factory.ExecuteStringMethodGet(this, "getAdjacentText", where);
}
/// <summary>
/// SupportByVersion MSHTML 4
/// </summary>
/// <param name="where">string where</param>
/// <param name="newText">string newText</param>
[SupportByVersion("MSHTML", 4)]
public string replaceAdjacentText(string where, string newText)
{
return Factory.ExecuteStringMethodGet(this, "replaceAdjacentText", where, newText);
}
/// <summary>
/// SupportByVersion MSHTML 4
/// </summary>
/// <param name="bstrUrl">string bstrUrl</param>
/// <param name="pvarFactory">optional object pvarFactory</param>
[SupportByVersion("MSHTML", 4)]
public Int32 addBehavior(string bstrUrl, object pvarFactory)
{
return Factory.ExecuteInt32MethodGet(this, "addBehavior", bstrUrl, pvarFactory);
}
/// <summary>
/// SupportByVersion MSHTML 4
/// </summary>
/// <param name="bstrUrl">string bstrUrl</param>
[CustomMethod]
[SupportByVersion("MSHTML", 4)]
public Int32 addBehavior(string bstrUrl)
{
return Factory.ExecuteInt32MethodGet(this, "addBehavior", bstrUrl);
}
/// <summary>
/// SupportByVersion MSHTML 4
/// </summary>
/// <param name="cookie">Int32 cookie</param>
[SupportByVersion("MSHTML", 4)]
public bool removeBehavior(Int32 cookie)
{
return Factory.ExecuteBoolMethodGet(this, "removeBehavior", cookie);
}
/// <summary>
/// SupportByVersion MSHTML 4
/// </summary>
/// <param name="v">string v</param>
[SupportByVersion("MSHTML", 4)]
[BaseResult]
public NetOffice.MSHTMLApi.IHTMLElementCollection getElementsByTagName(string v)
{
return Factory.ExecuteBaseReferenceMethodGet<NetOffice.MSHTMLApi.IHTMLElementCollection>(this, "getElementsByTagName", v);
}
/// <summary>
/// SupportByVersion MSHTML 4
/// </summary>
/// <param name="mergeThis">NetOffice.MSHTMLApi.IHTMLElement mergeThis</param>
/// <param name="pvarFlags">optional object pvarFlags</param>
[SupportByVersion("MSHTML", 4)]
public void mergeAttributes(NetOffice.MSHTMLApi.IHTMLElement mergeThis, object pvarFlags)
{
Factory.ExecuteMethod(this, "mergeAttributes", mergeThis, pvarFlags);
}
/// <summary>
/// SupportByVersion MSHTML 4
/// </summary>
/// <param name="mergeThis">NetOffice.MSHTMLApi.IHTMLElement mergeThis</param>
[CustomMethod]
[SupportByVersion("MSHTML", 4)]
public void mergeAttributes(NetOffice.MSHTMLApi.IHTMLElement mergeThis)
{
Factory.ExecuteMethod(this, "mergeAttributes", mergeThis);
}
/// <summary>
/// SupportByVersion MSHTML 4
/// </summary>
[SupportByVersion("MSHTML", 4)]
public void setActive()
{
Factory.ExecuteMethod(this, "setActive");
}
/// <summary>
/// SupportByVersion MSHTML 4
/// </summary>
/// <param name="bstrEventName">string bstrEventName</param>
/// <param name="pvarEventObject">optional object pvarEventObject</param>
[SupportByVersion("MSHTML", 4)]
public bool FireEvent(string bstrEventName, object pvarEventObject)
{
return Factory.ExecuteBoolMethodGet(this, "FireEvent", bstrEventName, pvarEventObject);
}
/// <summary>
/// SupportByVersion MSHTML 4
/// </summary>
/// <param name="bstrEventName">string bstrEventName</param>
[CustomMethod]
[SupportByVersion("MSHTML", 4)]
public bool FireEvent(string bstrEventName)
{
return Factory.ExecuteBoolMethodGet(this, "FireEvent", bstrEventName);
}
/// <summary>
/// SupportByVersion MSHTML 4
/// </summary>
[SupportByVersion("MSHTML", 4)]
public bool dragDrop()
{
return Factory.ExecuteBoolMethodGet(this, "dragDrop");
}
/// <summary>
/// SupportByVersion MSHTML 4
/// </summary>
[SupportByVersion("MSHTML", 4)]
public void normalize()
{
Factory.ExecuteMethod(this, "normalize");
}
/// <summary>
/// SupportByVersion MSHTML 4
/// </summary>
/// <param name="bstrName">string bstrName</param>
[SupportByVersion("MSHTML", 4)]
[BaseResult]
public NetOffice.MSHTMLApi.IHTMLDOMAttribute getAttributeNode(string bstrName)
{
return Factory.ExecuteBaseReferenceMethodGet<NetOffice.MSHTMLApi.IHTMLDOMAttribute>(this, "getAttributeNode", bstrName);
}
/// <summary>
/// SupportByVersion MSHTML 4
/// </summary>
/// <param name="pattr">NetOffice.MSHTMLApi.IHTMLDOMAttribute pattr</param>
[SupportByVersion("MSHTML", 4)]
[BaseResult]
public NetOffice.MSHTMLApi.IHTMLDOMAttribute setAttributeNode(NetOffice.MSHTMLApi.IHTMLDOMAttribute pattr)
{
return Factory.ExecuteBaseReferenceMethodGet<NetOffice.MSHTMLApi.IHTMLDOMAttribute>(this, "setAttributeNode", pattr);
}
/// <summary>
/// SupportByVersion MSHTML 4
/// </summary>
/// <param name="pattr">NetOffice.MSHTMLApi.IHTMLDOMAttribute pattr</param>
[SupportByVersion("MSHTML", 4)]
[BaseResult]
public NetOffice.MSHTMLApi.IHTMLDOMAttribute removeAttributeNode(NetOffice.MSHTMLApi.IHTMLDOMAttribute pattr)
{
return Factory.ExecuteBaseReferenceMethodGet<NetOffice.MSHTMLApi.IHTMLDOMAttribute>(this, "removeAttributeNode", pattr);
}
/// <summary>
/// SupportByVersion MSHTML 4
/// </summary>
[SupportByVersion("MSHTML", 4)]
public bool hasChildNodes()
{
return Factory.ExecuteBoolMethodGet(this, "hasChildNodes");
}
/// <summary>
/// SupportByVersion MSHTML 4
/// </summary>
/// <param name="newChild">NetOffice.MSHTMLApi.IHTMLDOMNode newChild</param>
/// <param name="refChild">optional object refChild</param>
[SupportByVersion("MSHTML", 4)]
[BaseResult]
public NetOffice.MSHTMLApi.IHTMLDOMNode insertBefore(NetOffice.MSHTMLApi.IHTMLDOMNode newChild, object refChild)
{
return Factory.ExecuteBaseReferenceMethodGet<NetOffice.MSHTMLApi.IHTMLDOMNode>(this, "insertBefore", newChild, refChild);
}
/// <summary>
/// SupportByVersion MSHTML 4
/// </summary>
/// <param name="newChild">NetOffice.MSHTMLApi.IHTMLDOMNode newChild</param>
[CustomMethod]
[BaseResult]
[SupportByVersion("MSHTML", 4)]
public NetOffice.MSHTMLApi.IHTMLDOMNode insertBefore(NetOffice.MSHTMLApi.IHTMLDOMNode newChild)
{
return Factory.ExecuteBaseReferenceMethodGet<NetOffice.MSHTMLApi.IHTMLDOMNode>(this, "insertBefore", newChild);
}
/// <summary>
/// SupportByVersion MSHTML 4
/// </summary>
/// <param name="oldChild">NetOffice.MSHTMLApi.IHTMLDOMNode oldChild</param>
[SupportByVersion("MSHTML", 4)]
[BaseResult]
public NetOffice.MSHTMLApi.IHTMLDOMNode removeChild(NetOffice.MSHTMLApi.IHTMLDOMNode oldChild)
{
return Factory.ExecuteBaseReferenceMethodGet<NetOffice.MSHTMLApi.IHTMLDOMNode>(this, "removeChild", oldChild);
}
/// <summary>
/// SupportByVersion MSHTML 4
/// </summary>
/// <param name="newChild">NetOffice.MSHTMLApi.IHTMLDOMNode newChild</param>
/// <param name="oldChild">NetOffice.MSHTMLApi.IHTMLDOMNode oldChild</param>
[SupportByVersion("MSHTML", 4)]
[BaseResult]
public NetOffice.MSHTMLApi.IHTMLDOMNode replaceChild(NetOffice.MSHTMLApi.IHTMLDOMNode newChild, NetOffice.MSHTMLApi.IHTMLDOMNode oldChild)
{
return Factory.ExecuteBaseReferenceMethodGet<NetOffice.MSHTMLApi.IHTMLDOMNode>(this, "replaceChild", newChild, oldChild);
}
/// <summary>
/// SupportByVersion MSHTML 4
/// </summary>
/// <param name="fDeep">bool fDeep</param>
[SupportByVersion("MSHTML", 4)]
[BaseResult]
public NetOffice.MSHTMLApi.IHTMLDOMNode cloneNode(bool fDeep)
{
return Factory.ExecuteBaseReferenceMethodGet<NetOffice.MSHTMLApi.IHTMLDOMNode>(this, "cloneNode", fDeep);
}
/// <summary>
/// SupportByVersion MSHTML 4
/// </summary>
/// <param name="fDeep">optional bool fDeep = false</param>
[SupportByVersion("MSHTML", 4)]
[BaseResult]
public NetOffice.MSHTMLApi.IHTMLDOMNode removeNode(object fDeep)
{
return Factory.ExecuteBaseReferenceMethodGet<NetOffice.MSHTMLApi.IHTMLDOMNode>(this, "removeNode", fDeep);
}
/// <summary>
/// SupportByVersion MSHTML 4
/// </summary>
[CustomMethod]
[BaseResult]
[SupportByVersion("MSHTML", 4)]
public NetOffice.MSHTMLApi.IHTMLDOMNode removeNode()
{
return Factory.ExecuteBaseReferenceMethodGet<NetOffice.MSHTMLApi.IHTMLDOMNode>(this, "removeNode");
}
/// <summary>
/// SupportByVersion MSHTML 4
/// </summary>
/// <param name="otherNode">NetOffice.MSHTMLApi.IHTMLDOMNode otherNode</param>
[SupportByVersion("MSHTML", 4)]
[BaseResult]
public NetOffice.MSHTMLApi.IHTMLDOMNode swapNode(NetOffice.MSHTMLApi.IHTMLDOMNode otherNode)
{
return Factory.ExecuteBaseReferenceMethodGet<NetOffice.MSHTMLApi.IHTMLDOMNode>(this, "swapNode", otherNode);
}
/// <summary>
/// SupportByVersion MSHTML 4
/// </summary>
/// <param name="replacement">NetOffice.MSHTMLApi.IHTMLDOMNode replacement</param>
[SupportByVersion("MSHTML", 4)]
[BaseResult]
public NetOffice.MSHTMLApi.IHTMLDOMNode replaceNode(NetOffice.MSHTMLApi.IHTMLDOMNode replacement)
{
return Factory.ExecuteBaseReferenceMethodGet<NetOffice.MSHTMLApi.IHTMLDOMNode>(this, "replaceNode", replacement);
}
/// <summary>
/// SupportByVersion MSHTML 4
/// </summary>
/// <param name="newChild">NetOffice.MSHTMLApi.IHTMLDOMNode newChild</param>
[SupportByVersion("MSHTML", 4)]
[BaseResult]
public NetOffice.MSHTMLApi.IHTMLDOMNode appendChild(NetOffice.MSHTMLApi.IHTMLDOMNode newChild)
{
return Factory.ExecuteBaseReferenceMethodGet<NetOffice.MSHTMLApi.IHTMLDOMNode>(this, "appendChild", newChild);
}
/// <summary>
/// SupportByVersion MSHTML 4
/// </summary>
/// <param name="bstrName">string bstrName</param>
[SupportByVersion("MSHTML", 4)]
[BaseResult]
public NetOffice.MSHTMLApi.IHTMLDOMAttribute2 ie8_getAttributeNode(string bstrName)
{
return Factory.ExecuteBaseReferenceMethodGet<NetOffice.MSHTMLApi.IHTMLDOMAttribute2>(this, "ie8_getAttributeNode", bstrName);
}
/// <summary>
/// SupportByVersion MSHTML 4
/// </summary>
/// <param name="pattr">NetOffice.MSHTMLApi.IHTMLDOMAttribute2 pattr</param>
[SupportByVersion("MSHTML", 4)]
[BaseResult]
public NetOffice.MSHTMLApi.IHTMLDOMAttribute2 ie8_setAttributeNode(NetOffice.MSHTMLApi.IHTMLDOMAttribute2 pattr)
{
return Factory.ExecuteBaseReferenceMethodGet<NetOffice.MSHTMLApi.IHTMLDOMAttribute2>(this, "ie8_setAttributeNode", pattr);
}
/// <summary>
/// SupportByVersion MSHTML 4
/// </summary>
/// <param name="pattr">NetOffice.MSHTMLApi.IHTMLDOMAttribute2 pattr</param>
[SupportByVersion("MSHTML", 4)]
[BaseResult]
public NetOffice.MSHTMLApi.IHTMLDOMAttribute2 ie8_removeAttributeNode(NetOffice.MSHTMLApi.IHTMLDOMAttribute2 pattr)
{
return Factory.ExecuteBaseReferenceMethodGet<NetOffice.MSHTMLApi.IHTMLDOMAttribute2>(this, "ie8_removeAttributeNode", pattr);
}
/// <summary>
/// SupportByVersion MSHTML 4
/// </summary>
/// <param name="name">string name</param>
[SupportByVersion("MSHTML", 4)]
public bool hasAttribute(string name)
{
return Factory.ExecuteBoolMethodGet(this, "hasAttribute", name);
}
/// <summary>
/// SupportByVersion MSHTML 4
/// </summary>
/// <param name="strAttributeName">string strAttributeName</param>
[SupportByVersion("MSHTML", 4)]
public object ie8_getAttribute(string strAttributeName)
{
return Factory.ExecuteVariantMethodGet(this, "ie8_getAttribute", strAttributeName);
}
/// <summary>
/// SupportByVersion MSHTML 4
/// </summary>
/// <param name="strAttributeName">string strAttributeName</param>
/// <param name="attributeValue">object attributeValue</param>
[SupportByVersion("MSHTML", 4)]
public void ie8_setAttribute(string strAttributeName, object attributeValue)
{
Factory.ExecuteMethod(this, "ie8_setAttribute", strAttributeName, attributeValue);
}
/// <summary>
/// SupportByVersion MSHTML 4
/// </summary>
/// <param name="strAttributeName">string strAttributeName</param>
[SupportByVersion("MSHTML", 4)]
public bool ie8_removeAttribute(string strAttributeName)
{
return Factory.ExecuteBoolMethodGet(this, "ie8_removeAttribute", strAttributeName);
}
/// <summary>
/// SupportByVersion MSHTML 4
/// </summary>
[SupportByVersion("MSHTML", 4)]
public bool hasAttributes()
{
return Factory.ExecuteBoolMethodGet(this, "hasAttributes");
}
#endregion
#pragma warning restore
}
}
| NetOfficeFw/NetOffice | Source/MSHTML/DispatchInterfaces/DispHTMLTableCol.cs | C# | mit | 76,599 |
CREATE TABLE IF NOT EXISTS "migration" (
"id" integer NOT NULL PRIMARY KEY AUTOINCREMENT,
"version" text UNIQUE NOT NULL,
"executed" integer NOT NULL
); | wmenge/php-migration-lib | tests/WM/Lib/Tests/Integration/files/migration-table-sqlite.sql | SQL | mit | 158 |
using System;
using System.Collections.Generic;
using System.Net;
using Htc.Vita.Core.Log;
using Htc.Vita.Core.Util;
namespace Htc.Vita.Core.Net
{
internal partial class HttpFileDownloader
{
internal class HttpStatusErrorException : Exception
{
public HttpStatusCode HttpStatusCode { get; set; }
public HttpStatusErrorException() : base() { }
public HttpStatusErrorException(HttpStatusCode httpStatusCode) : base()
{
HttpStatusCode = httpStatusCode;
}
public HttpStatusErrorException(HttpStatusCode httpStatusCode, string message) : base(message)
{
HttpStatusCode = httpStatusCode;
}
}
internal class MultipleHostHelper
{
private List<string> _hostList;
private int _index = -1;
private int _retryCount;
private int _maxRetryCount;
public MultipleHostHelper(
List<string> hostList,
int maxRetryCount)
{
_hostList = hostList;
_maxRetryCount = maxRetryCount;
}
public string GetNextUrl(string originalUrl)
{
_index++;
if (_retryCount >= _maxRetryCount) return "";
if (_index >= _hostList.Count)
{
_index = -1;
_retryCount++;
return GetNextUrl(originalUrl);
}
try
{
var uriStringFromNetMethodTargetField = _hostList[_index];
var uriDownload = new UriBuilder(uriStringFromNetMethodTargetField);
UriBuilder uri;
if (!originalUrl.StartsWith("http://", StringComparison.OrdinalIgnoreCase) &&
!originalUrl.StartsWith("https://", StringComparison.OrdinalIgnoreCase))
{
uri = new UriBuilder($"http://a.b.c/{originalUrl.TrimStart('/')}");
}
else
{
uri = new UriBuilder(originalUrl);
}
uriDownload.Path = uriDownload.Path.Equals("/")
? uri.Path
: $"{uriDownload.Path.TrimEnd('/')}{uri.Path}";
var query = HttpUtilityLite.ParseQueryString(uri.Query);
uriDownload.Query = query.ToString();
return uriDownload.ToString();
}
catch (Exception exc)
{
Logger.GetInstance(typeof(MultipleHostHelper)).Error($"Exception: {exc}");
return GetNextUrl(originalUrl);
}
}
}
internal class SynchronousProgress<T> : IProgress<T>
{
private readonly Action<T> _callback;
public SynchronousProgress(Action<T> callback)
{
_callback = callback;
}
void IProgress<T>.Report(T data) => _callback(data);
}
}
}
| ViveportSoftware/vita_core_csharp | source/Htc.Vita.Core/Net/HttpFileDownloader.DataType.cs | C# | mit | 3,222 |
//! TODO Documentation
use std::marker::PhantomData;
use crate::libc::c_int;
use wlroots_sys::{wl_output_transform, wl_resource, wlr_surface_state};
use crate::{render::PixmanRegion, surface::Surface};
#[derive(Debug)]
#[repr(u32)]
/// Represents a change in the pending state.
///
/// When a particular bit is set, it means the field corresponding to it
/// will be updated for the current state on the next commit.
///
/// # Pending vs Current state
/// When this is set on the pending state, it means this field will be updated
/// on the next commit.
///
/// When it is set on the current state, it indicates what fields have changed
/// since the last commit.
pub enum InvalidState {
Buffer = 1,
SurfaceDamage = 2,
BufferDamage = 4,
OpaqueRegion = 8,
InputRegion = 16,
Transform = 32,
Scale = 64,
SubsurfacePosition = 128,
FrameCallbackList = 256
}
/// Surface state as reported by wlroots.
#[derive(Debug)]
pub struct State<'surface> {
state: wlr_surface_state,
phantom: PhantomData<&'surface Surface>
}
impl<'surface> State<'surface> {
/// Create a new subsurface from the given surface.
///
/// # Safety
/// Since we rely on the surface providing a valid surface state,
/// this function is marked unsafe.
pub(crate) unsafe fn new(state: wlr_surface_state) -> State<'surface> {
State {
state,
phantom: PhantomData
}
}
/// Gets the state of the sub surface.
///
/// # Panics
/// If the invalid state is in an undefined state, this will panic.
pub fn committed(&self) -> InvalidState {
use self::InvalidState::*;
unsafe {
match self.state.committed {
1 => Buffer,
2 => SurfaceDamage,
4 => BufferDamage,
8 => OpaqueRegion,
16 => InputRegion,
32 => Transform,
64 => Scale,
128 => SubsurfacePosition,
256 => FrameCallbackList,
invalid => {
wlr_log!(WLR_ERROR, "Invalid invalid state {}", invalid);
panic!("Invalid invalid state in wlr_surface_state")
}
}
}
}
/// Get the position of the surface relative to the previous position.
///
/// Return value is in (dx, dy) format.
pub fn position(&self) -> (i32, i32) {
unsafe { (self.state.dx, self.state.dy) }
}
/// Get the size of the sub surface.
///
/// Return value is in (width, height) format.
pub fn size(&self) -> (c_int, c_int) {
unsafe { (self.state.width, self.state.height) }
}
/// Get the size of the buffer.
///
/// Return value is iw (width, height) format.
pub fn buffer_size(&self) -> (c_int, c_int) {
unsafe { (self.state.buffer_width, self.state.buffer_height) }
}
/// Get the scale applied to the surface.
pub fn scale(&self) -> i32 {
unsafe { self.state.scale }
}
/// Get the output transform applied to the surface.
pub fn transform(&self) -> wl_output_transform {
unsafe { self.state.transform }
}
/// Gets the buffer of the surface.
pub unsafe fn buffer(&self) -> *mut wl_resource {
self.state.buffer_resource
}
pub unsafe fn surface_damage(&self) -> PixmanRegion {
PixmanRegion {
region: self.state.surface_damage
}
}
pub unsafe fn buffer_damage(&self) -> PixmanRegion {
PixmanRegion {
region: self.state.buffer_damage
}
}
pub unsafe fn opaque(&self) -> PixmanRegion {
PixmanRegion {
region: self.state.opaque
}
}
pub unsafe fn input(&self) -> PixmanRegion {
PixmanRegion {
region: self.state.input
}
}
}
| way-cooler/wlroots-rs | src/types/surface/surface_state.rs | Rust | mit | 3,883 |
import * as path from 'path';
import { getSystemPath, join, normalize, Path, virtualFs } from '@angular-devkit/core';
import * as denodeify from 'denodeify';
import { pathExists, remove, stat } from 'fs-extra';
import * as glob from 'glob';
import * as minimatch from 'minimatch';
import { concat, of } from 'rxjs';
import { concatMap, last } from 'rxjs/operators';
import { Compiler } from 'webpack';
import { AfterEmitCleanOptions, BeforeBuildCleanOptions, CleanOptions } from '../../../models';
import { InternalError, InvalidConfigError } from '../../../models/errors';
import { isGlob, isInFolder, isSamePaths, Logger, LogLevelString, normalizeRelativePath } from '../../../utils';
const globPromise = denodeify(glob) as (pattern: string, options?: glob.IOptions) => Promise<string[]>;
export interface CleanWebpackPluginOptions extends CleanOptions {
workspaceRoot: string;
outputPath?: string;
cacheDirectries?: string[];
forceCleanToDisk?: boolean;
host?: virtualFs.Host;
logLevel?: LogLevelString;
}
export class CleanWebpackPlugin {
private readonly _logger: Logger;
private readonly _persistedOutputFileSystemNames = ['NodeOutputFileSystem'];
private _beforeRunCleaned = false;
private _afterEmitCleaned = false;
private _isPersistedOutputFileSystem = true;
get name(): string {
return 'clean-webpack-plugin';
}
constructor(private readonly _options: CleanWebpackPluginOptions) {
this._logger = new Logger({
name: `[${this.name}]`,
logLevel: this._options.logLevel || 'info'
});
}
// tslint:disable-next-line:max-func-body-length
apply(compiler: Compiler): void {
let outputPath = this._options.outputPath;
if (!outputPath && compiler.options.output && compiler.options.output.path) {
outputPath = compiler.options.output.path;
}
const workspaceRoot = this._options.workspaceRoot;
if (!this._persistedOutputFileSystemNames.includes(compiler.outputFileSystem.constructor.name)) {
this._isPersistedOutputFileSystem = false;
}
// tslint:disable-next-line:no-any
compiler.hooks.beforeRun.tapAsync(this.name, (_: any, cb: (err?: Error) => void) => {
const startTime = Date.now();
if (this._beforeRunCleaned || !this._options.beforeBuild) {
cb();
return;
}
const beforeBuildOptions = this._options.beforeBuild;
if (!beforeBuildOptions.cleanOutDir &&
!beforeBuildOptions.cleanCache &&
(beforeBuildOptions.cleanCache &&
(!this._options.cacheDirectries || !this._options.cacheDirectries.length)) &&
(!beforeBuildOptions.paths || (beforeBuildOptions.paths && !beforeBuildOptions.paths.length))) {
this._beforeRunCleaned = true;
cb();
return;
}
if (!outputPath || outputPath === '/' || !path.isAbsolute(outputPath)) {
throw new InternalError(
`[${this.name}] Absolute output path must be specified at webpack config -> output -> path.`);
}
this._logger.debug('The before build cleaning started');
if (!this._isPersistedOutputFileSystem && !this._options.forceCleanToDisk && !this._options.host) {
this._logger.debug(
`No persisted output file system: '${compiler.outputFileSystem.constructor.name}', skipping`);
this._beforeRunCleaned = true;
cb();
return;
}
this.cleanTask(beforeBuildOptions, true, outputPath, workspaceRoot)
.then(() => {
this._beforeRunCleaned = true;
const duration = Date.now() - startTime;
this._logger.debug(`The before build cleaning completed in [${duration}ms]`);
cb();
return;
})
.catch(cb);
});
// tslint:disable-next-line:no-any
compiler.hooks.afterEmit.tapAsync(this.name, (_: any, cb: (err?: Error) => void) => {
const startTime = Date.now();
if (this._afterEmitCleaned || !this._options.afterEmit) {
cb();
return;
}
const afterEmitOptions = this._options.afterEmit;
if (!afterEmitOptions.paths || (afterEmitOptions.paths && !afterEmitOptions.paths.length)) {
this._afterEmitCleaned = true;
cb();
return;
}
if (!this._isPersistedOutputFileSystem && !this._options.forceCleanToDisk && !this._options.host) {
this._logger.debug(
`No persisted output file system: '${compiler.outputFileSystem.constructor.name}', skipping`);
this._afterEmitCleaned = true;
cb();
return;
}
if (!outputPath || outputPath === '/' || !path.isAbsolute(outputPath)) {
throw new InternalError(
`[${this.name}] Absolute output path must be specified at webpack config -> output -> path.`);
}
this._logger.debug('The after emit cleaning started');
this.cleanTask(afterEmitOptions, false, outputPath, workspaceRoot)
.then(() => {
const duration = Date.now() - startTime;
this._logger.debug(`The after emit cleaning completed in [${duration}ms]`);
this._afterEmitCleaned = true;
cb();
return;
})
.catch((err: Error) => {
cb(err);
return;
});
});
}
// tslint:disable:max-func-body-length
private async cleanTask(cleanOptions: BeforeBuildCleanOptions | AfterEmitCleanOptions,
isBeforeBuildClean: boolean,
outputPath: string,
workspaceRoot: string): Promise<void> {
const rawPathsToClean: string[] = [];
if (!outputPath) {
throw new InternalError("The 'outputPath' options is required.");
}
if (!path.isAbsolute(outputPath) || outputPath === '/' || isGlob(outputPath)) {
throw new InternalError("The absolute path is required for 'outputPath' options.");
}
if (isSamePaths(path.parse(outputPath).root, outputPath)) {
throw new InternalError(
`The output path must not be the root directory, outputPath: ${outputPath}.`);
}
if (isSamePaths(workspaceRoot, outputPath)) {
throw new InternalError(
`The output path must not be the workspace root directory, outputPath: ${outputPath}.`);
}
if (isInFolder(outputPath, workspaceRoot)) {
throw new InternalError(
`The workspace root directory must not be inside the output path, outputPath: ${outputPath}.`);
}
if (isBeforeBuildClean && (cleanOptions as BeforeBuildCleanOptions).cleanOutDir) {
if (!isInFolder(workspaceRoot, outputPath) && this._options.allowOutsideWorkspaceRoot === false) {
throw new InternalError(
`Cleaning outside of the workspace root directory is disabled, outputPath: ${outputPath}.` +
" To enable cleaning, please set 'allowOutsideWorkspaceRoot = true' in clean option.");
}
rawPathsToClean.push(outputPath);
rawPathsToClean.push('**/*');
}
if (cleanOptions.paths && cleanOptions.paths.length) {
cleanOptions.paths.forEach(p => {
rawPathsToClean.push(p);
});
}
if (this._options.cacheDirectries && this._options.cacheDirectries.length) {
this._options.cacheDirectries.forEach(p => {
rawPathsToClean.push(p);
});
}
const outputPathFragements: Path[] = [];
const outputDirFragements: Path[] = [];
let outputPathFragementsInitialized = false;
// calculate excludes
const patternsToExclude: string[] = [];
const pathsToExclude: string[] = [];
const existedFilesToExclude: string[] = [];
const existedDirsToExclude: string[] = [];
if (cleanOptions.excludes) {
cleanOptions.excludes.forEach(excludePath => {
if (isGlob(excludePath)) {
if (!patternsToExclude.includes(excludePath)) {
patternsToExclude.push(excludePath);
}
} else {
const absPath = path.isAbsolute(excludePath)
? path.resolve(excludePath)
: path.resolve(outputPath, excludePath);
if (!pathsToExclude.includes(absPath)) {
pathsToExclude.push(absPath);
}
}
});
} else {
pathsToExclude.push(path.resolve(outputPath, '.gitkeep'));
}
if (pathsToExclude.length > 0) {
await Promise.all(pathsToExclude.map(async (excludePath: string) => {
if (this._isPersistedOutputFileSystem || this._options.forceCleanToDisk) {
const isExists = await pathExists(excludePath);
if (isExists) {
const statInfo = await stat(excludePath);
if (statInfo.isDirectory()) {
if (!existedDirsToExclude.includes(excludePath)) {
existedDirsToExclude.push(excludePath);
}
} else {
if (!existedFilesToExclude.includes(excludePath)) {
existedFilesToExclude.push(excludePath);
}
}
}
} else if (this._options.host) {
const host = this._options.host;
const resolvedPath = normalize(excludePath);
await host.exists(resolvedPath).pipe(
concatMap(exists => {
if (exists) {
return host.isDirectory(resolvedPath).pipe(concatMap(isDir => {
if (isDir) {
if (!existedDirsToExclude.includes(excludePath)) {
existedDirsToExclude.push(excludePath);
}
} else {
if (!existedFilesToExclude.includes(excludePath)) {
existedFilesToExclude.push(excludePath);
}
}
return of(null);
}));
} else {
return of(null);
}
}),
).toPromise();
}
}));
}
if (patternsToExclude.length > 0) {
if ((this._isPersistedOutputFileSystem || this._options.forceCleanToDisk)) {
await Promise.all(patternsToExclude.map(async (excludePattern: string) => {
const foundExcludePaths =
await globPromise(excludePattern, { cwd: outputPath, dot: true, absolute: true });
for (const p of foundExcludePaths) {
const absPath = path.isAbsolute(p) ? path.resolve(p) : path.resolve(outputPath, p);
const statInfo = await stat(absPath);
if (statInfo.isDirectory()) {
if (!existedDirsToExclude.includes(absPath)) {
existedDirsToExclude.push(absPath);
}
} else {
if (!existedFilesToExclude.includes(absPath)) {
existedFilesToExclude.push(absPath);
}
}
}
}));
} else if (this._options.host) {
const host = this._options.host;
if (!outputPathFragementsInitialized) {
await this.calculateOutputPathRecursive(host, outputPathFragements, outputDirFragements, normalize(outputPath));
outputPathFragementsInitialized = true;
}
if (outputPathFragements.length > 0) {
for (const p of outputPathFragements) {
const sysPath = getSystemPath(p);
const absPath = path.isAbsolute(sysPath)
? path.resolve(sysPath)
: path.resolve(outputPath, sysPath);
const relToOutDir = normalizeRelativePath(path.relative(outputPath, absPath));
if (relToOutDir) {
let il = patternsToExclude.length;
let found = false;
while (il--) {
const ignoreGlob = patternsToExclude[il];
if (minimatch(relToOutDir, ignoreGlob, { dot: true, matchBase: true })) {
found = true;
break;
}
}
if (found) {
if (outputDirFragements.includes(p)) {
if (!existedDirsToExclude.includes(absPath)) {
existedDirsToExclude.push(absPath);
}
} else {
if (!existedFilesToExclude.includes(absPath)) {
existedFilesToExclude.push(absPath);
}
}
}
}
}
}
}
}
const pathsToClean: string[] = [];
await Promise.all(rawPathsToClean.map(async (cleanPattern: string) => {
if (!isGlob(cleanPattern)) {
const absolutePath = path.isAbsolute(cleanPattern)
? path.resolve(cleanPattern)
: path.resolve(outputPath, cleanPattern);
if (!pathsToClean.includes(absolutePath)) {
pathsToClean.push(absolutePath);
}
} else {
if (this._isPersistedOutputFileSystem || this._options.forceCleanToDisk) {
const foundPaths =
await globPromise(cleanPattern, { cwd: outputPath, dot: true });
foundPaths.forEach(p => {
const absolutePath = path.isAbsolute(p)
? path.resolve(p)
: path.resolve(outputPath, p);
if (!pathsToClean.includes(absolutePath)) {
pathsToClean.push(absolutePath);
}
});
} else if (this._options.host) {
const host = this._options.host;
if (!outputPathFragementsInitialized) {
await this.calculateOutputPathRecursive(host, outputPathFragements, outputDirFragements, normalize(outputPath));
outputPathFragementsInitialized = true;
}
if (outputPathFragements.length > 0) {
outputPathFragements.forEach(p => {
const sysPath = getSystemPath(p);
const absPath = path.isAbsolute(sysPath)
? path.resolve(sysPath)
: path.resolve(outputPath, sysPath);
const relToOutDir = normalizeRelativePath(path.relative(outputPath, absPath));
if (relToOutDir) {
if (minimatch(relToOutDir, cleanPattern, { dot: true, matchBase: true })) {
if (!pathsToClean.includes(absPath)) {
pathsToClean.push(absPath);
}
}
}
});
}
}
}
}));
const cachePaths = this._options.cacheDirectries || [];
for (const pathToClean of pathsToClean) {
if (existedFilesToExclude.includes(pathToClean) ||
existedDirsToExclude.includes(pathToClean) ||
pathsToExclude.includes(pathToClean) ||
existedDirsToExclude.find(e => isInFolder(e, pathToClean))) {
continue;
}
const relToOutDir = normalizeRelativePath(path.relative(outputPath, pathToClean));
if (relToOutDir) {
let il = patternsToExclude.length;
let foundExclude = false;
while (il--) {
const ignoreGlob = patternsToExclude[il];
if (minimatch(relToOutDir, ignoreGlob, { dot: true, matchBase: true })) {
foundExclude = true;
break;
}
}
if (foundExclude) {
continue;
}
}
if (path.extname(pathToClean) === '' &&
(existedFilesToExclude.find(e => isInFolder(pathToClean, e)) ||
existedDirsToExclude.find(e => isInFolder(pathToClean, e)))) {
continue;
}
// validation
if (!isSamePaths(pathToClean, outputPath)) {
if (isSamePaths(path.parse(pathToClean).root, pathToClean)) {
throw new InvalidConfigError(
`Cleaning the root directory is not permitted, path: ${pathToClean}.`);
}
if (workspaceRoot && isInFolder(pathToClean, workspaceRoot)) {
throw new InvalidConfigError(
`The workspace root path must not be inside the path to be deleted, path: ${pathToClean
}, context: ${
workspaceRoot}.`);
}
if (workspaceRoot && isSamePaths(pathToClean, workspaceRoot)) {
throw new InvalidConfigError(
`The path to be deleted must not be the same as workspace root path, path: ${outputPath
}, context: ${
workspaceRoot}.`);
}
if (!isInFolder(workspaceRoot, pathToClean) && this._options.allowOutsideWorkspaceRoot === false) {
throw new InternalError(
`Cleaning outside of the workspace root directory is disabled, outputPath: ${pathToClean
}.` +
" To enable cleaning, please set 'allowOutsideWorkspaceRoot = true' in clean option.");
}
if ((!isInFolder(outputPath, pathToClean) || isSamePaths(outputPath, pathToClean)) &&
!this._options.allowOutsideOutDir && !cachePaths.includes(pathToClean)) {
throw new InvalidConfigError(
`Cleaning outside of output directory is disabled, path to clean: ${pathToClean
}.` +
" To enable cleaning, please set 'allowOutsideOutDir = true' in clean option.");
}
}
const relToWorkspace = normalizeRelativePath(path.relative(workspaceRoot, pathToClean));
let retryDelete = false;
if (this._options.host) {
const host = this._options.host;
const resolvedPath = normalize(pathToClean);
try {
await host.exists(resolvedPath).pipe(
concatMap(exists => {
if (exists) {
this._logger.debug(`Deleting ${relToWorkspace}`);
return concat(host.delete(resolvedPath), of(null)).pipe(last());
} else {
return of(null);
}
}),
).toPromise();
} catch (deleteError) {
if (this._isPersistedOutputFileSystem || this._options.forceCleanToDisk) {
retryDelete = true;
} else {
throw deleteError;
}
}
}
if ((!this._options.host || retryDelete) && (this._isPersistedOutputFileSystem || this._options.forceCleanToDisk)) {
const exists = await pathExists(pathToClean);
if (exists) {
if (!retryDelete) {
this._logger.debug(`Deleting ${relToWorkspace}`);
}
let retryDeleteCount = 0;
do {
try {
await remove(pathToClean);
retryDelete = false;
} catch (deleteError) {
retryDelete = true;
++retryDeleteCount;
if (retryDeleteCount >= 3) {
throw deleteError;
}
}
} while (retryDelete && retryDeleteCount < 3);
}
}
}
}
private async calculateOutputPathRecursive(host: virtualFs.Host,
pathFragements: Path[], dirFragements: Path[], basePath: Path): Promise<void> {
const paths = await host.list(basePath).toPromise();
for (const p of paths) {
const resolvedPath = join(basePath, p);
pathFragements.push(resolvedPath);
const isDir = await host.isDirectory(resolvedPath).toPromise();
if (isDir) {
dirFragements.push(resolvedPath);
await this.calculateOutputPathRecursive(host, pathFragements, dirFragements, resolvedPath);
}
}
}
}
| BizAppFramework/angular-build | src/plugins/clean-webpack-plugin/src/index.ts | TypeScript | mit | 23,114 |
<?php
/**
* Slim Composer Installer
*
* @link https://github.com/mc388/slim-composer-installer
* @copyright Copyright (c) Marvin Caspar
* @license https://github.com/mc388/slim-composer-installer/blob/master/LICENSE (MIT License)
*/
namespace Mc388\SlimComposerInstaller;
/**
* Class Autoloader
* @package Mc388\SlimComposerInstaller
*/
class Autoloader
{
const CONFIG_FILE_PATH = 'config/';
const CONFIG_FILE_NAME = 'modules.json';
/**
* @return array
*/
public function getModules()
{
$installedModules = [];
$moduleNames = [];
$configPath = $_SERVER['DOCUMENT_ROOT'] . '/../' . self::CONFIG_FILE_PATH . self::CONFIG_FILE_NAME;
if (file_exists($configPath)) {
$configFileContent = file_get_contents($configPath);
$installedModules = json_decode($configFileContent, true);
}
foreach ($installedModules as $name => $namespace) {
array_push($moduleNames, $name);
}
return $installedModules;
}
}
| mc388/slim-composer-installer | src/Autoloader.php | PHP | mit | 1,049 |
#region Licence...
//-----------------------------------------------------------------------------
// Date: 10/11/04 Time: 3:00p
// Module: CSScriptLib.cs
// Classes: CSScript
// AppInfo
//
// This module contains the definition of the CSScript class. Which implements
// compiling C# script engine (CSExecutor). Can be used for hosting C# script engine
// from any CLR application
//
// Written by Oleg Shilo ([email protected])
// Copyright (c) 2004-2012. All rights reserved.
//
// Redistribution and use of this code WITHOUT MODIFICATIONS are permitted provided that
// the following conditions are met:
// 1. Redistributions must retain the above copyright notice, this list of conditions
// and the following disclaimer.
// 2. Neither the name of an author nor the names of the contributors may be used
// to endorse or promote products derived from this software without specific
// prior written permission.
//
// Redistribution and use of this code WITH MODIFICATIONS are permitted provided that all
// above conditions are met and software is not used or sold for profit.
//
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
// TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Caution: Bugs are expected!
//----------------------------------------------
#endregion Licence...
using System;
using System.IO;
using System.Text;
//using System.Windows.Forms;
using System.Reflection;
using System.Diagnostics;
using System.Collections;
#if !net1
using System.Collections.Generic;
using System.Linq;
#endif
using csscript;
using System.Threading;
using System.CodeDom.Compiler;
using System.Security;
using System.Security.Permissions;
namespace CSScriptLibrary
{
#if !net1
/// <summary>
/// Simple helper class for extending functionality of <see cref="T:System.AppDomain"/>.
/// <para>
/// This class mainly consist of the extension methods for <see cref="T:System.AppDomain"/> and it is to be used for executing the arbitrary
/// code routines in the separate (temporary) <see cref="T:System.AppDomain"/> with the optional unloading.
/// </para>This class is particularly useful for executing the CS-Script script in the separate <see cref="T:System.AppDomain"/> as this is the
/// only way to unload the script assembly after the execution (known .NET limitation).
/// <para>
/// <example>The following are the examples of the execution CS-Script scripts and unloading them after the execution:
///<code>
/// AppDomain.CurrentDomain
/// .Clone()
/// .Execute(Job)
/// .Unload();
/// ...
///
/// void Job()
/// {
/// var script = CSScript.LoadMethod("some C# script code")
/// .GetStaticMethod();
/// script();
/// };
/// </code>
/// <code>
/// AppDomain remote = AppDomain.CurrentDomain.Clone();
///
/// remote.Execute(() =>
/// {
/// var Sum = CSScript.BuildEval(@"func(float a, float b) {
/// return a + b;
/// }");
///
/// var Average = CSScript.BuildEval(@"func(float a, float b) {
/// return (a + b)/2;
/// }");
///
/// Console.WriteLine("Sum = {0}\nAverage={1}", Sum(1f, 2f), Average(1f, 2f));
/// });
///
/// remote.Unload();
/// </code>
/// </example>
/// </para>
/// <remarks>
/// The functionality of this class is very similar to the <see cref="T:CSScriptLibrary.AsmHelper"/>, which also allows executing and unloading the script(s).
/// However <see cref="T:CSScriptLibrary.AppDomainHelper"/> is designed as a generic class and as such it is more suitable for executing a "job" routines instead of individual scripts.
/// <para>
/// This creates some attractive opportunities for grouping scripting routines in a single <see cref="T:CSScriptLibrary.AsmHelper"/>, which allows simple calling conventions (e.g. <c>CSScript.Load()</c>
/// instead of <c>CSScript.Compile()</c>) lighter type system (e.g. no need for MarshalByRefObject inheritance).
/// </para>
/// </remarks>
/// </summary>
public static class AppDomainHelper
{
private class RemoteExecutor : MarshalByRefObject
{
public void Execute(Action action)
{
action();
}
}
/// <summary>
/// Executes the <see cref="T:System.Action"/> delegate in the specified <see cref="T:System.AppDomain"/>.
/// <example>The following are the examples of the execution CS-Script scripts and unloading them after the execution:
///<code>
/// var remoteDomain = AppDomain.CurrentDomain.Clone();
/// remoteDomain.Execute(Job)
/// remoteDomain.Unload();
/// ...
///
/// void Job()
/// {
/// var script = CSScript.LoadMethod("some C# script code")
/// .GetStaticMethod();
/// script();
/// };
/// </code>
/// </example>
/// </summary>
/// <param name="domain">The <see cref="T:System.AppDomain"/> the delegate should be executed in.</param>
/// <param name="action">The delegate.</param>
/// <returns>Reference to the <see cref="T:System.AppDomain"/>. It is the same object, which is passed as the <paramref name="domain"/>.</returns>
public static AppDomain Execute(this AppDomain domain, Action action)
{
var remote = (RemoteExecutor)domain.CreateInstanceFromAndUnwrap(Assembly.GetExecutingAssembly().Location, typeof(RemoteExecutor).ToString());
remote.Execute(action);
return domain;
}
/// <summary>
/// <para>Executes the delegate in the temporary <see cref="T:System.AppDomain"/> with the following unloading of this domain.
/// </para>
/// <example>The following code the complete equivalent implementation of the <c>ExecuteAndUnload</c>:
///<code>
/// AppDomain.CurrentDomain
/// .Clone()
/// .Execute(action)
/// .Unload();
/// </code>
/// </example>
/// </summary>
/// <param name="action">The delegate to be executed.</param>
public static void ExecuteAndUnload(Action action)
{
AppDomain.CurrentDomain
.Clone()
.Execute(action)
.Unload();
}
/// <summary>
/// Unloads the specified <see cref="T:System.AppDomain"/>.
/// </summary>
/// <param name="domain">The <see cref="T:System.AppDomain"/> to be unloaded.</param>
public static void Unload(this AppDomain domain)
{
AppDomain.Unload(domain);
}
/// <summary>
/// Clones the specified <see cref="T:System.AppDomain"/>. The mandatory "creation" properties of the <paramref name="domain"/> are used to create the new instance of <see cref="T:System.AppDomain"/>.
/// <para>The "friendly name" of the cloned <see cref="T:System.AppDomain"/> is a string representation of the random <c>GUID</c>.</para>
/// </summary>
/// <param name="domain">The <see cref="T:System.AppDomain"/> to be cloned.</param>
/// <returns>The newly created <see cref="T:System.AppDomain"/>.</returns>
public static AppDomain Clone(this AppDomain domain)
{
return domain.Clone(Guid.NewGuid().ToString());
}
/// <summary>
/// Clones the specified <see cref="T:System.AppDomain"/>. The mandatory "creation" properties of the <paramref name="domain"/> are used to create the new instance of <see cref="T:System.AppDomain"/>.
/// <para>The <paramref name="name"/> parameter is used as the "friendly name" for the cloned <see cref="T:System.AppDomain"/>.</para>
/// </summary>
/// <param name="domain">The <see cref="T:System.AppDomain"/> to be cloned.</param>
/// <param name="name">The "friendly name" of the new <see cref="T:System.AppDomain"/> to be created.</param>
/// <returns>The newly created <see cref="T:System.AppDomain"/>.</returns>
public static AppDomain Clone(this AppDomain domain, string name)
{
AppDomainSetup setup = new AppDomainSetup();
setup.ApplicationBase = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
setup.PrivateBinPath = AppDomain.CurrentDomain.BaseDirectory;
setup.ShadowCopyFiles = "true";
setup.ShadowCopyDirectories = setup.ApplicationBase;
return AppDomain.CreateDomain(name, null, setup);
}
}
#endif
/// <summary>
/// Simple security helper class. This class is nothing else but a syntactic sugar.
/// <para>
/// <example>The following is an example of execution under .NET sandbox:
/// <code>
/// Sandbox.With(SecurityPermissionFlag.Execution)
/// .Execute(() =>
/// {
/// //call sandboxed actions
/// });
/// </code>
/// </example>
/// </para>
/// </summary>
public static class Sandbox
{
/// <summary>
/// Generic void/void delegate
/// </summary>
public delegate void Action();
#if net1
#endif
/// <summary>
/// Extension method. Executes <see cref="T:System.Action"/> with the specified array of permissions
/// </summary>
/// <param name="permissions">The permissions set to be used for the execution.</param>
/// <param name="action">The action to be executed.</param>
#if net1
public static void Execute(PermissionSet permissions, Action action)
#else
public static void Execute(this PermissionSet permissions, Action action)
#endif
{
permissions.PermitOnly();
try
{
action();
}
finally
{
CodeAccessPermission.RevertPermitOnly();
}
}
/// <summary>
/// Returns the specified permissions as <see cref="T:System.Security.PermissionSet"/> to be used with <see cref="T:CSScriptLibrary.Sandbox.Execute"/>.
/// </summary>
/// <param name="permissions">The permissions.</param>
/// <returns><see cref="T:System.Security.PermissionSet"/> instance.</returns>
public static PermissionSet With(params IPermission[] permissions)
{
PermissionSet permissionSet = new PermissionSet(PermissionState.None);
foreach (IPermission permission in permissions)
permissionSet.AddPermission(permission);
return permissionSet;
}
/// <summary>
/// Returns the specified permissions as <see cref="T:System.Security.PermissionSet"/> to be used with <see cref="T:csscript.Sandbox.Execute"/>.
/// </summary>
/// <param name="permissionsFlag">The permissions flag. Can be combination of multiple values.</param>
/// <returns><see cref="T:System.Security.PermissionSet"/> instance.</returns>
public static PermissionSet With(SecurityPermissionFlag permissionsFlag)
{
PermissionSet permissionSet = new PermissionSet(PermissionState.None);
permissionSet.AddPermission(new SecurityPermission(permissionsFlag));
return permissionSet;
}
}
/// <summary>
/// Delegate to handle output from script
/// </summary>
public delegate void PrintDelegate(string msg);
/// <summary>
/// Class which is implements CS-Script class library interface.
/// </summary>
public class CSScript
{
static string dummy = "";
/// <summary>
/// Default constructor
/// </summary>
public CSScript()
{
rethrow = false;
}
/// <summary>
/// Determines whether the specified assembly is a script assembly (compiled script) and returns full path of the script file
/// used to compile the assembly. The analysis is based on the fact that script assembly (in hosing scenarios) is always
/// stamped with <see cref="T:System.Reflection.AssemblyDescriptionAttribute"/>, which contains name of the script file the
/// assembly was compiled from.
/// <para>The format of the description </para>
/// </summary>
/// <param name="assembly">The assembly.</param>
/// <returns>
/// Script file path if the specified assembly is a script assembly otherwise <c>null</c>.
/// </returns>
static public string GetScriptName(Assembly assembly)
{
//Note assembly can contain only single AssemblyDescriptionAttribute
foreach (AssemblyDescriptionAttribute attribute in assembly.GetCustomAttributes(typeof(AssemblyDescriptionAttribute), true))
return attribute.Description;
return null;
}
/// <summary>
/// Force caught exceptions to be re-thrown.
/// </summary>
static public bool Rethrow
{
get { return rethrow; }
set { rethrow = value; }
}
/// <summary>
/// Enables automatic resolving of unsuccessful assembly probing on the base of the Settings.SearchDirs.
/// Default value is true.
///
/// CLR does assembly probing only in GAC and in the local (with respect to the application) directories. CS-Script
/// however allows you to specify extra directory(es) for assembly probing by setting enabling CS-Script assembly resolving
/// through setting the AssemblyResolvingEnabled to true and changing the Settings.SearchDirs appropriately.
/// </summary>
static public bool AssemblyResolvingEnabled
{
get { return assemblyResolvingEnabled; }
set
{
if (value)
{
AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(OnAssemblyResolve);
callingResolveEnabledAssembly = Assembly.GetCallingAssembly();
}
else
AppDomain.CurrentDomain.AssemblyResolve -= new ResolveEventHandler(OnAssemblyResolve);
assemblyResolvingEnabled = value;
}
}
static bool assemblyResolvingEnabled = true;
/// <summary>
/// Gets or sets the assembly sharing mode. If set to true all assemblies (including the host assembly itself)
/// currently loaded to the host application AppDomain are automatically available/accessible from the script code.
/// Default value is true.
///
/// Sharing the same assembly set between the host application and the script require AssemblyResolvingEnabled to
/// be enabled. Whenever SharesHostRefAssemblies is changed to true it automatically sets AssemblyResolvingEnabled to
/// true as well.
/// </summary>
static public bool ShareHostRefAssemblies
{
get { return shareHostRefAssemblies; }
set
{
if (shareHostRefAssemblies != value)
{
shareHostRefAssemblies = value;
if (shareHostRefAssemblies)
AssemblyResolvingEnabled = true;
}
}
}
static private bool shareHostRefAssemblies = true;
static Assembly callingResolveEnabledAssembly;
private static Assembly OnAssemblyResolve(object sender, ResolveEventArgs args)
{
Assembly retval = null;
if (args.Name == "GetExecutingAssembly()")
retval = callingResolveEnabledAssembly;//Assembly.GetExecutingAssembly();
else if (args.Name == "GetEntryAssembly()")
retval = Assembly.GetEntryAssembly();
else
{
ExecuteOptions options = InitExecuteOptions(new ExecuteOptions(), CSScript.GlobalSettings, null, ref dummy);
foreach (string dir in options.searchDirs)
{
if ((retval = AssemblyResolver.ResolveAssembly(args.Name, dir)) != null)
break;
}
}
return retval;
}
/// <summary>
/// Settings object containing runtime settings, which controls script compilation/execution.
/// This is Settings class essentially is a deserialized content of the CS-Script configuration file (css_config.xml).
/// </summary>
public static Settings GlobalSettings = Settings.Load(Environment.ExpandEnvironmentVariables(@"%CSSCRIPT_DIR%\css_config.xml"));
#if !net1
/// <summary>
/// Collection of all compiling results. Every time the script is compiled the compiling result is added to this collection regardless of
/// the success or failure of the actual compilation.
/// </summary>
public static Dictionary<FileInfo, CompilerResults> CompilingHistory = new Dictionary<FileInfo, CompilerResults>();
private static bool keepCompilingHistory = false;
/// <summary>
/// Gets or sets a value indicating whether compiling history should be kept. The compilation results are stored in <see cref="CompilingHistory"></see>.
/// </summary>
/// <value>
/// <c>true</c> if compiling history should be kept; otherwise, <c>false</c>.
/// </value>
public static bool KeepCompilingHistory
{
get { return keepCompilingHistory; }
set { keepCompilingHistory = value; }
}
#endif
/// <summary>
/// Invokes global (static) CSExecutor (C# script engine)
/// </summary>
/// <param name="print">Print delegate to be used (if not null) to handle script engine output (eg. compilation errors).</param>
/// <param name="args">Script arguments.</param>
static public void Execute(CSScriptLibrary.PrintDelegate print, string[] args)
{
lock (CSExecutor.options)
{
ExecuteOptions oldOptions = CSExecutor.options;
try
{
csscript.AppInfo.appName = Path.GetFileName(Assembly.GetExecutingAssembly().Location);
csscript.CSExecutor exec = new csscript.CSExecutor();
exec.Rethrow = Rethrow;
InitExecuteOptions(CSExecutor.options, CSScript.GlobalSettings, null, ref dummy);
exec.Execute(args, new csscript.PrintDelegate(print != null ? print : new CSScriptLibrary.PrintDelegate(DefaultPrint)), null);
}
finally
{
CSExecutor.options = oldOptions;
}
}
}
/// <summary>
/// Invokes CSExecutor (C# script engine)
/// </summary>
/// <param name="print">Print delegate to be used (if not null) to handle script engine output (eg. compilation errors).</param>
/// <param name="args">Script arguments.</param>
/// <param name="rethrow">Flag, which indicated if script exceptions should be rethrowed by the script engine without any handling.</param>
public void Execute(CSScriptLibrary.PrintDelegate print, string[] args, bool rethrow)
{
lock (CSExecutor.options)
{
ExecuteOptions oldOptions = CSExecutor.options;
try
{
AppInfo.appName = Path.GetFileName(Assembly.GetExecutingAssembly().Location);
CSExecutor exec = new CSExecutor();
exec.Rethrow = rethrow;
InitExecuteOptions(CSExecutor.options, CSScript.GlobalSettings, null, ref dummy);
exec.Execute(args, new csscript.PrintDelegate(print != null ? print : new CSScriptLibrary.PrintDelegate(DefaultPrint)), null);
}
finally
{
CSExecutor.options = oldOptions;
}
}
}
/// <summary>
/// Compiles script code into assembly with CSExecutor
/// </summary>
/// <param name="scriptText">The script code to be compiled.</param>
/// <param name="refAssemblies">The string array containing file nemes to the additional assemblies referenced by the script. </param>
/// <returns>Compiled assembly file name.</returns>
static public string CompileCode(string scriptText, params string[] refAssemblies)
{
return CompileCode(scriptText, null, false, refAssemblies);
}
/// <summary>
/// Compiles script code into assembly with CSExecutor
/// </summary>
/// <param name="scriptText">The script code to be compiled.</param>
/// <param name="assemblyFile">The name of compiled assembly. If set to null a temporary file name will be used.</param>
/// <param name="debugBuild">'true' if debug information should be included in assembly; otherwise, 'false'.</param>
/// <param name="refAssemblies">The string array containing file nemes to the additional assemblies referenced by the script. </param>
/// <returns>Compiled assembly file name.</returns>
static public string CompileCode(string scriptText, string assemblyFile, bool debugBuild, params string[] refAssemblies)
{
string tempFile = CSExecutor.GetScriptTempFile();
try
{
using (StreamWriter sw = new StreamWriter(tempFile))
{
sw.Write(scriptText);
}
return Compile(tempFile, assemblyFile, debugBuild, refAssemblies);
}
finally
{
if (!debugBuild)
File.Delete(tempFile);
else
{
if (tempFiles == null)
{
tempFiles = new ArrayList();
//Note: ApplicationExit will not be called if this library is hosted by a console application.
//Thus CS-Script periodical cleanup will take care of the temp files
//Application.ApplicationExit += new EventHandler(OnApplicationExit); //will not be available on .NET CE
AppDomain.CurrentDomain.DomainUnload += new EventHandler(CurrentDomain_DomainUnload);
}
tempFiles.Add(tempFile);
}
}
}
/// <summary>
/// Returns the name of the temporary file in the CSSCRIPT subfolder of Path.GetTempPath().
/// </summary>
/// <returns>Temporary file name.</returns>
static public string GetScriptTempFile()
{
return CSExecutor.GetScriptTempFile();
}
/// <summary>
/// Returns the name of the CSScript temporary folder.
/// </summary>
/// <returns>Temporary folder name.</returns>
static public string GetScriptTempDir()
{
return CSExecutor.GetScriptTempDir();
}
/// <summary>
/// Compiles script file into assembly with CSExecutor
/// </summary>
/// <param name="scriptFile">The name of script file to be compiled.</param>
/// <param name="assemblyFile">The name of compiled assembly. If set to null a temporary file name will be used.</param>
/// <param name="debugBuild">'true' if debug information should be included in assembly; otherwise, 'false'.</param>
/// <param name="refAssemblies">The string array containing file names to the additional assemblies referenced by the script. </param>
/// <returns>Compiled assembly file name.</returns>
static public string Compile(string scriptFile, string assemblyFile, bool debugBuild, params string[] refAssemblies)
{
return CompileWithConfig(scriptFile, assemblyFile, debugBuild, CSScript.GlobalSettings, null, refAssemblies);
}
/// <summary>
/// Compiles script file into assembly (temporary file) with CSExecutor.
/// This method is an equivalent of the CSScript.Compile(scriptFile, null, false);
/// </summary>
/// <param name="scriptFile">The name of script file to be compiled.</param>
/// <param name="refAssemblies">The string array containing file names to the additional assemblies referenced by the script. </param>
/// <returns>Compiled assembly file name.</returns>
static public string Compile(string scriptFile, params string[] refAssemblies)
{
return Compile(scriptFile, null, false, refAssemblies);
}
/// <summary>
/// Compiles script file into assembly with CSExecutor. Uses specified config file to load script engine settings.
/// </summary>
/// <param name="scriptFile">The name of script file to be compiled.</param>
/// <param name="assemblyFile">The name of compiled assembly. If set to null a temporary file name will be used.</param>
/// <param name="debugBuild">'true' if debug information should be included in assembly; otherwise, 'false'.</param>
/// <param name="cssConfigFile">The name of CS-Script configuration file. If null the default config file will be used (appDir/css_config.xml).</param>
/// <returns>Compiled assembly file name.</returns>
static public string CompileWithConfig(string scriptFile, string assemblyFile, bool debugBuild, string cssConfigFile)
{
return CompileWithConfig(scriptFile, assemblyFile, debugBuild, cssConfigFile, null, null);
}
/// <summary>
/// Compiles script file into assembly with CSExecutor. Uses specified config file to load script engine settings and compiler specific options.
/// </summary>
/// <param name="scriptFile">The name of script file to be compiled.</param>
/// <param name="assemblyFile">The name of compiled assembly. If set to null a temporary file name will be used.</param>
/// <param name="debugBuild">'true' if debug information should be included in assembly; otherwise, 'false'.</param>
/// <param name="cssConfigFile">The name of CS-Script configuration file. If null the default config file will be used (appDir/css_config.xml).</param>
/// <param name="compilerOptions">The string value to be passed directly to the language compiler. </param>
/// <param name="refAssemblies">The string array containing file names to the additional assemblies referenced by the script. </param>
/// <returns>Compiled assembly file name.</returns>
static public string CompileWithConfig(string scriptFile, string assemblyFile, bool debugBuild, string cssConfigFile, string compilerOptions, params string[] refAssemblies)
{
Settings settings = Settings.Load(cssConfigFile != null ? cssConfigFile : Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "css_config.xml"));
if (settings == null)
throw new ApplicationException("The configuration file \"" + cssConfigFile + "\" cannot be loaded");
return CompileWithConfig(scriptFile, assemblyFile, debugBuild, settings, compilerOptions, refAssemblies);
}
private static string GetCompilerLockName(string scriptFile, Settings scriptSettings)
{
if (scriptSettings.OptimisticConcurrencyModel)
{
return Process.GetCurrentProcess().Id.ToString(); //less aggressive lock
}
else
{
return string.Format("{0}.{1}", Process.GetCurrentProcess().Id, scriptFile.GetHashCode());
}
}
/// <summary>
/// Compiles script file into assembly with CSExecutor. Uses script engine settings object and compiler specific options.
/// </summary>
/// <param name="scriptFile">The name of script file to be compiled.</param>
/// <param name="assemblyFile">The name of compiled assembly. If set to null a temporary file name will be used.</param>
/// <param name="debugBuild">'true' if debug information should be included in assembly; otherwise, 'false'.</param>
/// <param name="scriptSettings">The script engine Settings object.</param>
/// <param name="compilerOptions">The string value to be passed directly to the language compiler. </param>
/// <param name="refAssemblies">The string array containing file names to the additional assemblies referenced by the script. </param>
/// <returns>Compiled assembly file name.</returns>
static public string CompileWithConfig(string scriptFile, string assemblyFile, bool debugBuild, Settings scriptSettings, string compilerOptions, params string[] refAssemblies)
{
using (Mutex fileLock = new Mutex(false, GetCompilerLockName(assemblyFile, scriptSettings)))
{
lock (CSExecutor.options)
{
ExecuteOptions oldOptions = CSExecutor.options;
try
{
int start = Environment.TickCount;
fileLock.WaitOne(5000, false); //let other thread/process (if any) to finish loading/compiling the same file; 5 seconds should be enough, if you need more use more sophisticated synchronization
//Trace.WriteLine(">>> Waited " + (Environment.TickCount - start));
CSExecutor exec = new csscript.CSExecutor();
exec.Rethrow = true;
InitExecuteOptions(CSExecutor.options, scriptSettings, compilerOptions, ref scriptFile);
CSExecutor.options.DBG = debugBuild;
ExecuteOptions.options.useSmartCaching = CacheEnabled;
if (refAssemblies != null && refAssemblies.Length != 0)
{
string dir;
foreach (string file in refAssemblies)
{
dir = Path.GetDirectoryName(file);
CSExecutor.options.AddSearchDir(dir); //settings used by Compiler
CSScript.GlobalSettings.AddSearchDir(dir); //settings used by AsmHelper
}
CSExecutor.options.refAssemblies = refAssemblies;
}
if (CacheEnabled)
{
if (assemblyFile != null)
{
if (!ScriptAsmOutOfDate(scriptFile, assemblyFile))
return assemblyFile;
}
else
{
Assembly asm = GetCachedScriptAssembly(scriptFile);
if (asm != null)
return asm.Location;
}
}
#if !net1
string retval = exec.Compile(scriptFile, assemblyFile, debugBuild);
if (KeepCompilingHistory)
CompilingHistory.Add(new FileInfo(scriptFile), exec.LastCompileResult);
return retval;
#else
return exec.Compile(scriptFile, assemblyFile, debugBuild);
#endif
}
finally
{
CSExecutor.options = oldOptions;
try { fileLock.ReleaseMutex(); }
catch { }
}
}
}
}
private static ExecuteOptions InitExecuteOptions(ExecuteOptions options, Settings scriptSettings, string compilerOptions, ref string scriptFile)
{
Settings settings = (scriptSettings == null ? CSScript.GlobalSettings : scriptSettings);
options.altCompiler = settings.ExpandUseAlternativeCompiler();
options.compilerOptions = compilerOptions != null ? compilerOptions : "";
options.apartmentState = settings.DefaultApartmentState;
options.reportDetailedErrorInfo = settings.ReportDetailedErrorInfo;
options.cleanupShellCommand = settings.CleanupShellCommand;
options.inMemoryAsm = settings.InMemoryAsssembly;
options.TargetFramework = settings.TargetFramework;
options.doCleanupAfterNumberOfRuns = settings.DoCleanupAfterNumberOfRuns;
options.useCompiled = CSScript.CacheEnabled;
options.useSurrogateHostingProcess = false; //regardless of the input useSurrogateHostingProcess is not appropriate for teh hosting scenarios, so set it to 'false'
ArrayList dirs = new ArrayList();
options.shareHostRefAssemblies = ShareHostRefAssemblies;
if (options.shareHostRefAssemblies)
{
foreach (Assembly asm in AppDomain.CurrentDomain.GetAssemblies())
try
{
if (asm is System.Reflection.Emit.AssemblyBuilder)
continue;
if (asm.FullName.StartsWith("Anonymously Hosted DynamicMethods") || !File.Exists(asm.Location))
continue;
dirs.Add(Path.GetDirectoryName(asm.Location));
}
catch
{
//Under ASP.NET some assemblies do not have location (e.g. dynamically built/emitted assemblies)
//in such case NotSupportedException will be raised
//In fact ignore all exceptions as we should continue if for whatever reason assembly the location cannot be obtained
}
}
string libDir = Environment.ExpandEnvironmentVariables("%CSSCRIPT_DIR%" + Path.DirectorySeparatorChar + "lib");
if (!libDir.StartsWith("%"))
dirs.Add(libDir);
if (settings != null)
dirs.AddRange(Environment.ExpandEnvironmentVariables(settings.SearchDirs).Split(",;".ToCharArray(), StringSplitOptions.RemoveEmptyEntries));
if (scriptFile != "")
{
scriptFile = FileParser.ResolveFile(scriptFile, (string[])dirs.ToArray(typeof(string))); //to handle the case when the script file is specified by file name only
dirs.Add(Path.GetDirectoryName(scriptFile));
}
options.searchDirs = RemovePathDuplicates((string[])dirs.ToArray(typeof(string)));
options.scriptFileName = scriptFile;
return options;
}
/// <summary>
/// Surrounds the method implementation code into a class and compiles it code into assembly with CSExecutor and loads it in current AppDomain.
/// The most convenient way of using dynamic methods is to declare them as static methods. In this case they can be invoked with wild card character as a class name (e.g. asmHelper.Invoke("*.SayHello")). Otherwise you will need to instantiate class "DyamicClass.Script" in order to call dynamic method.
///
/// You can have multiple methods implementations in the single methodCode. Also you can specify namespaces at the begining of the code:
///
/// CSScript.LoadMethod(
/// @"using System.Windows.Forms;
///
/// public static void SayHello(string gritting)
/// {
/// MessageBoxSayHello(gritting);
/// ConsoleSayHello(gritting);
/// }
/// public static void MessageBoxSayHello(string gritting)
/// {
/// MessageBox.Show(gritting);
/// }
/// public static void ConsoleSayHello(string gritting)
/// {
/// Console.WriteLine(gritting);
/// }");
/// </summary>
/// <param name="methodCode">The C# code, containing method implementation.</param>
/// <param name="refAssemblies">The string array containing file names to the additional assemblies referenced by the script. </param>
/// <returns>Compiled assembly.</returns>
static public Assembly LoadMethod(string methodCode, params string[] refAssemblies)
{
return LoadMethod(methodCode, null, false, refAssemblies);
}
static string evalNamespaces;
/// <summary>
/// Sets the <c>;</c>-delimited string containing namespaces to be used by the C# expressions being compiled with
/// <see cref="T:CSScriptLibrary.CSScript.EvalBuild"/> and <see cref="T:CSScriptLibrary.CSScript.Eval"/>.
/// <para>The default value is <c>"System;System.IO;System.Diagnostics;System.Collections.Generic;System.Threading"</c></para>
/// </summary>
/// <para>The following is a typical example of <c>BuildEval</c> usage:</para>
/// <code>
/// CSScript.EvalNamespaces = "System;System.Diagnostics";
///
/// var Trace = CSScript.BuildEval(@"trace (object message)
/// {
/// Trace.WriteLine(""EVAL:"" + message);
/// }");
///
/// var Average = CSScript.BuildEval("avrg (int a, int b) { return (a+b)/2.0; }");
///
/// Trace(Average(7, 8));
/// </code>
/// <value>
/// The <c>Eval</c> namespaces.
/// </value>
public static string EvalNamespaces
{
private get
{
if (evalNamespaces == null)
evalNamespaces = SplitNamespaces("System;System.IO;System.Diagnostics;System.Collections.Generic;System.Threading");
return evalNamespaces;
}
set
{
evalNamespaces = SplitNamespaces(value);
}
}
private static string SplitNamespaces(string text)
{
StringBuilder sb = new StringBuilder();
foreach (string @namespace in text.Split(new char[] { ';' }))
{
sb.Append("using ");
sb.Append(@namespace);
sb.Append(";\n");
}
return sb.ToString();
}
#if !net1
/// <summary>
/// Evaluates string as a method code and returns the <see cref="T:CSScriptLibrary.MethodDelegate"/>.
/// <para><c>BuildEval</c> is a specific case of <see cref="T:CSScriptLibrary.CSScript.LoadMethod"/>, which
/// offers a simpler and more convenient syntactical model. It has number of limitations comparing to
/// the <see cref="T:CSScriptLibrary.CSScript.LoadMethod"/>.
/// <list type="bullet">
/// <item ><description><c>methodCode</c> should contain nothing else but only a single method definition</description></item>
/// <item ><description>The method signature should not contain any return type.</description></item>
/// <item ><description>All namespaces used by the method code should be either specified explicitly in code or listed in the value of <see cref="T:CSSCriptLibrary.CSScript.EvalNamespaces"/>.</description></item>
/// <item ><description>The method code can only interact with the types of the currently loaded in the <c>AppDomain.CurrentDomain</c> assemblies.</description></item>
/// </list>
/// This is the when the flexibility is partially sacrificed for the sake of convenience.
/// <para>The following is a typical example of <c>BuildEval</c> usage:</para>
/// <code>
/// CSScript.EvalNamespaces = "System;System.Diagnostics";
///
/// var Trace = CSScript.BuildEval(@"trace (object message)
/// {
/// Trace.WriteLine(""EVAL:"" + message);
/// }");
///
/// var Average = CSScript.BuildEval("avrg (int a, int b) { return (a+b)/2.0; }");
///
/// Trace(Average(7, 8));
/// </code>
/// <remarks>Note that CS-Script <c>BuildEval</c> should not be treated as <c>eval</c> in dynamic languages even despite some resemblance. After all C# is a static language.
/// <para>CS-Script <c>BuildEval</c> yields the method delegate, which can access all public types of the AppDomain but it cannot interact with the types instances unless
/// they are directly passed to the delegate or can be accessed through the Type static members.</para>
/// </remarks>
///
///
/// </para>
/// </summary>
/// <param name="methodCode">The method code.</param>
/// <returns>Delegate with the "evaluated" routine. It can be invoked as any .NET delegate.</returns>
static public MethodDelegate BuildEval(string methodCode)
{
string[] refAssemblies;
string code = GenerateEvalSourceCode(methodCode, out refAssemblies, false);
Assembly asm = LoadMethod(code, null, true, refAssemblies);
return asm.GetStaticMethod();
}
/// <summary>
/// Evaluates string as a method code and executes it with the specified method parameters.
/// <para>
/// <c>Eval</c> is very similar to <see cref="T:CSScriptLibrary.CSScript.BuildEval"/> and it shares the some of its limitations.
/// <list type="bullet">
/// <item ><description><c>methodCode</c> should contain nothing else but only a single method definition</description></item>
/// <item ><description>The method signature should not contain any return type.</description></item>
/// <item ><description>All namespaces used by the method code should be either specified explicitly in code or listed in the value of <see cref="T:CSSCriptLibrary.CSScript.EvalNamespaces"/>.</description></item>
/// </list>
/// However <c>Eval</c> offers an important advantage comparing to the <c>BuildEval</c> - after the execution it unloads all dynamically emitted routines
/// preventing any potential memory leaks. Though because of this the "evaluated" routines are not reusable thus you need to do the full eval every time
/// you wan to invoke the routine. And of course this can affect performance dramatically and that is why usage of <c>Eval</c> should be considered very carefully.
///
/// <para>Note that the calling convention is that all parameters of the method to be "evaluated" must be
/// followed by the string of code defining this method. </para>
/// <para>The following is a typical example of <c>Eval</c> usage:</para>
/// <code>
///
/// var result = CSScript.Eval(1, 3,
/// @"sum (int a, int b) {
/// return a+b;
/// }");
///
/// </code>
///
/// <remarks>Note that CS-Script <c>Eval</c> should not be treated as <c>eval</c> in dynamic languages even despite some resemblance.
/// After all C# is a static language.
/// <para>CS-Script <c>Eval</c> can access all public types of the AppDomain but it cannot interact with the types instances unless
/// they are directly passed to the delegate or can be accessed through the Type static members.</para>
/// </remarks>
///
///
/// </para>
/// </summary>
/// <param name="args">Collection of the method parameters followed by the method code.</param>
/// <returns>The return value of the method being "evaluated"</returns>
static public object Eval(params object[] args)
{
if (args.Length == 0)
throw new Exception("You did not specify the code to 'Eval'");
object lastArg = args.Last();
if (lastArg == null || !(lastArg is string))
throw new Exception("You did not specify the code to 'Eval'");
string methodCode = ((string)lastArg).Trim();
string methodName = methodCode.Split(new char[] { '(', ' ' }, StringSplitOptions.RemoveEmptyEntries).FirstOrDefault();
if (methodName == null)
throw new Exception("The code to 'Eval' is not valid. The expected code patterns is as 'func(type arg1,..., type argN){ return <result>; }'");
object[] newArgs = new object[args.Length - 1];
Array.Copy(args, newArgs, newArgs.Length);
string[] refAssemblies;
string code = GenerateEvalSourceCode(methodCode, out refAssemblies, true);
using (var helper = new AsmHelper(CSScript.CompileCode(code, null, true, refAssemblies), null, true))
{
return helper.Invoke("*." + methodName, newArgs);
}
}
static private string GenerateEvalSourceCode(string methodCode, out string[] refAssemblies, bool injectClassDef)
{
string code = evalNamespaces;
if (injectClassDef)
{
//code += "[assembly: System.Runtime.CompilerServices.InternalsVisibleTo( \"Testpad\" )]\n";
code += "public static class EvalClass {\n";
}
code += "public static object ";
if (methodCode.EndsWith("}"))
code += methodCode.Substring(0, methodCode.Length - 1) + "\n return null;\n}"; //ensure "return null; is injected just before the last bracket"
else
code += methodCode;
if (injectClassDef)
code += "}";
refAssemblies = AppDomain.CurrentDomain
.GetAssemblies()
.Select(a =>
{
try
{
if (!(a is System.Reflection.Emit.AssemblyBuilder))
return a.Location;
}
catch
{
}
return "";
})
.Where(a => a != "")
.ToArray();
return code;
}
#endif
private static object LoadAutoCodeSynch = new object();
/// <summary>
/// Surrounds the method implementation code into a class and compiles it code into
/// assembly with CSExecutor and loads it in current AppDomain. The most convenient way of
/// using dynamic methods is to declare them as static methods. In this case they can be
/// invoked with wild card character as a class name (e.g. asmHelper.Invoke("*.SayHello")).
/// Otherwise you will need to instantiate class "DyamicClass.Script" in order to call dynamic method.
///
///
/// You can have multiple methods implementations in the single methodCode. Also you can specify namespaces at the beginning of the code:
///
/// CSScript.LoadMethod(
/// @"using System.Windows.Forms;
///
/// public static void SayHello(string gritting)
/// {
/// MessageBoxSayHello(gritting);
/// ConsoleSayHello(gritting);
/// }
/// public static void MessageBoxSayHello(string gritting)
/// {
/// MessageBox.Show(gritting);
/// }
/// public static void ConsoleSayHello(string gritting)
/// {
/// Console.WriteLine(gritting);
/// }");
/// </summary>
/// <param name="methodCode">The C# code, containing method implementation.</param>
/// <param name="assemblyFile">The name of compiled assembly. If set to null a temporary file name will be used.</param>
/// <param name="debugBuild">'true' if debug information should be included in assembly; otherwise, 'false'.</param>
/// <param name="refAssemblies">The string array containing file names to the additional assemblies referenced by the script. </param>
/// <returns>Compiled assembly.</returns>
static public Assembly LoadMethod(string methodCode, string assemblyFile, bool debugBuild, params string[] refAssemblies)
{
lock (LoadAutoCodeSynch)
{
StringBuilder code = new StringBuilder(4096);
code.Append("//Auto-generated file\r\n"); //cannot use AppendLine as it is not available in StringBuilder v1.1
code.Append("using System;\r\n");
bool headerProcessed = false;
string line;
using (StringReader sr = new StringReader(methodCode))
while ((line = sr.ReadLine()) != null)
{
if (!headerProcessed && !line.TrimStart().StartsWith("using ")) //not using...; statement of the file header
if (!line.StartsWith("//") && line.Trim() != "") //not comments or empty line
{
headerProcessed = true;
//code.Append("[assembly: System.Runtime.CompilerServices.InternalsVisibleTo( \"Testpad\" )]\r\n"); //zos
//code.Append("[assembly: System.Runtime.CompilerServices.InternalsVisibleTo( \"Rubenhak.Utils.Gen\" )]\r\n"); //zos
//code.Append("[assembly: System.Runtime.CompilerServices.InternalsVisibleTo( \"" + Assembly.GetExecutingAssembly().GetName().Name + "\" )]\r\n"); //zos
code.Append("namespace Scripting\r\n");
code.Append("{\r\n");
code.Append(" public class DynamicClass\r\n");
code.Append(" {\r\n");
}
code.Append(line);
code.Append("\r\n");
}
code.Append(" }\r\n");
code.Append("}\r\n");
return LoadCode(code.ToString(), assemblyFile, debugBuild, refAssemblies);
}
}
/// <summary>
/// Compiles script code into assembly with CSExecutor and loads it in current AppDomain.
/// </summary>
/// <param name="scriptText">The script code to be compiled.</param>
/// <param name="refAssemblies">The string array containing file names to the additional assemblies referenced by the script. </param>
/// <returns>Compiled assembly.</returns>
static public Assembly LoadCode(string scriptText, params string[] refAssemblies)
{
return LoadCode(scriptText, null, false, refAssemblies);
}
/// <summary>
/// Compiles script code into assembly with CSExecutor and loads it in current AppDomain.
/// </summary>
/// <param name="scriptText">The script code to be compiled.</param>
/// <param name="assemblyFile">The name of compiled assembly. If set to null a temporary file name will be used.</param>
/// <param name="debugBuild">'true' if debug information should be included in assembly; otherwise, 'false'.</param>
/// <param name="refAssemblies">The string array containing file names to the additional assemblies referenced by the script. </param>
/// <returns>Compiled assembly.</returns>
static public Assembly LoadCode(string scriptText, string assemblyFile, bool debugBuild, params string[] refAssemblies)
{
return LoadCode(scriptText, "", assemblyFile, debugBuild, refAssemblies);
}
#if !net1
static Dictionary<UInt32, string> dynamicScriptsAssemblies = new Dictionary<UInt32, string>();
#else
static Hashtable dynamicScriptsAssemblies = new Hashtable();
#endif
/// <summary>
/// Compiles script code into assembly with CSExecutor and loads it in current AppDomain.
/// </summary>
/// <param name="scriptText">The script code to be compiled.</param>
/// <param name="tempFileExtension">The file extension of the temporary file to hold script code during compilation. This parameter may be
/// needed if custom CS-Script compilers rely on file extension to identify the script syntax.</param>
/// <param name="assemblyFile">The name of compiled assembly. If set to null a temporary file name will be used.</param>
/// <param name="debugBuild">'true' if debug information should be included in assembly; otherwise, 'false'.</param>
/// <param name="refAssemblies">The string array containing file nemes to the additional assemblies referenced by the script. </param>
/// <returns>Compiled assembly.</returns>
static public Assembly LoadCode(string scriptText, string tempFileExtension, string assemblyFile, bool debugBuild, params string[] refAssemblies)
{
UInt32 scriptTextCRC = 0;
if (CacheEnabled)
{
scriptTextCRC = Crc32.Compute(Encoding.Unicode.GetBytes(scriptText));
if (dynamicScriptsAssemblies.ContainsKey(scriptTextCRC))
try
{
#if !net1
return Assembly.LoadFrom(dynamicScriptsAssemblies[scriptTextCRC]);
#else
return Assembly.LoadFrom(dynamicScriptsAssemblies[scriptTextCRC].ToString());
#endif
}
catch
{
Trace.WriteLine("Cannot use cache...");
}
}
string tempFile = CSExecutor.GetScriptTempFile();
if (tempFileExtension != null && tempFileExtension != "")
tempFile = Path.ChangeExtension(tempFile, tempFileExtension);
try
{
using (StreamWriter sw = new StreamWriter(tempFile))
{
sw.Write(scriptText);
}
Assembly asm = Load(tempFile, assemblyFile, debugBuild, refAssemblies);
if (CacheEnabled)
if (dynamicScriptsAssemblies.ContainsKey(scriptTextCRC))
dynamicScriptsAssemblies[scriptTextCRC] = asm.Location;
else
dynamicScriptsAssemblies.Add(scriptTextCRC, asm.Location);
return asm;
}
finally
{
if (!debugBuild)
File.Delete(tempFile);
else
{
if (tempFiles == null)
{
tempFiles = new ArrayList();
//Note: ApplicationExit will not be called if this library is hosted by a console application.
//Thus CS-Script periodical cleanup will take care of the temp files
//Application.ApplicationExit += new EventHandler(OnApplicationExit); //will not be available on .NET CE
AppDomain.CurrentDomain.DomainUnload += new EventHandler(CurrentDomain_DomainUnload);
}
tempFiles.Add(tempFile);
}
}
}
private static void CurrentDomain_DomainUnload(object sender, EventArgs e)
{
OnApplicationExit(sender, e);
}
static ArrayList tempFiles;
private static void OnApplicationExit(object sender, EventArgs e)
{
if (tempFiles != null)
foreach (string file in tempFiles)
try
{
File.Delete(file);
}
catch { }
}
/// <summary>
/// Compiles script file into assembly with CSExecutor and loads it in current AppDomain
/// </summary>
/// <param name="scriptFile">The name of script file to be compiled.</param>
/// <param name="assemblyFile">The name of compiled assembly. If set to null a temporary file name will be used.</param>
/// <param name="debugBuild">'true' if debug information should be included in assembly; otherwise, 'false'.</param>
/// /// <param name="refAssemblies">The string array containing file names to the additional assemblies referenced by the script. </param>
/// <returns>Compiled/Loaded assembly.</returns>
static public Assembly Load(string scriptFile, string assemblyFile, bool debugBuild, params string[] refAssemblies)
{
using (Mutex fileLock = new Mutex(false, GetCompilerLockName(assemblyFile, CSScript.GlobalSettings)))
{
ExecuteOptions oldOptions = CSExecutor.options;
try
{
int start = Environment.TickCount;
fileLock.WaitOne(5000, false); //let other thread/process (if any) to finish loading/compiling the same file; 2 seconds should be enough, if you need more use more sophisticated synchronization
Trace.WriteLine(">>> Waited " + (Environment.TickCount - start));
CSExecutor exec = new CSExecutor();
exec.Rethrow = true;
InitExecuteOptions(CSExecutor.options, CSScript.GlobalSettings, "", ref scriptFile);
CSExecutor.options.DBG = debugBuild;
ExecuteOptions.options.useSmartCaching = CacheEnabled;
if (refAssemblies != null && refAssemblies.Length != 0)
{
string dir;
foreach (string file in refAssemblies)
{
dir = Path.GetDirectoryName(file);
CSExecutor.options.AddSearchDir(dir); //settings used by Compiler
CSScript.GlobalSettings.AddSearchDir(dir); //settings used by AsmHelper
}
CSExecutor.options.refAssemblies = refAssemblies;
}
Assembly retval = null;
if (CacheEnabled)
retval = GetCachedScriptAssembly(scriptFile);
if (retval == null)
{
string outputFile = exec.Compile(scriptFile, assemblyFile, debugBuild);
#if !net1
if (KeepCompilingHistory)
CompilingHistory.Add(new FileInfo(scriptFile), exec.LastCompileResult);
#endif
if (!ExecuteOptions.options.inMemoryAsm)
{
retval = Assembly.LoadFrom(outputFile);
}
else
{
//Load(byte[]) does not lock the assembly file as LoadFrom(filename) does
using (FileStream fs = new FileStream(outputFile, FileMode.Open))
{
byte[] data = new byte[fs.Length];
fs.Read(data, 0, data.Length);
string dbg = Path.ChangeExtension(outputFile, ".pdb");
if (File.Exists(dbg))
{
using (FileStream fsDbg = new FileStream(dbg, FileMode.Open))
{
byte[] dbgData = new byte[fsDbg.Length];
fsDbg.Read(dbgData, 0, dbgData.Length);
retval = Assembly.Load(data, dbgData);
}
}
else
retval = Assembly.Load(data);
}
}
if (retval != null)
scriptCache.Add(new LoadedScript(scriptFile, retval));
}
return retval;
}
finally
{
CSExecutor.options = oldOptions;
}
}
}
/// <summary>
/// Compiles script file into assembly (temporary file) with CSExecutor and loads it in current AppDomain.
/// This method is an equivalent of the CSScript.Load(scriptFile, null, false);
/// </summary>
/// <param name="scriptFile">The name of script file to be compiled.</param>
/// <returns>Compiled/Loaded assembly.</returns>
static public Assembly Load(string scriptFile)
{
return Load(scriptFile, null, false, null);
}
/// <summary>
/// Compiles script file into assembly (temporary file) with CSExecutor and loads it in current AppDomain.
/// This method is an equivalent of the CSScript.Load(scriptFile, null, false);
/// </summary>
/// <param name="scriptFile">The name of script file to be compiled.</param>
/// <param name="refAssemblies">The string array containing file nemes to the additional assemblies referenced by the script. </param>
/// <returns>Compiled/Loaded assembly.</returns>
static public Assembly Load(string scriptFile, params string[] refAssemblies)
{
return Load(scriptFile, null, false, refAssemblies);
}
/// <summary>
/// Default implementation of displaying application messages.
/// </summary>
private static void DefaultPrint(string msg)
{
//do nothing
}
static bool rethrow;
/// <summary>
/// LoadedScript is a class, which holds information about the script file location and it's compiled and loaded assmbly (current AppDomain).
/// </summary>
public class LoadedScript
{
/// <summary>
/// Creates instance of LoadedScript
/// </summary>
/// <param name="script">Script file location.</param>
/// <param name="asm">Compiled script assembly loaded into current AppDomain.</param>
public LoadedScript(string script, Assembly asm)
{
this.script = Path.GetFullPath(script);
this.asm = asm;
}
/// <summary>
/// Script file location.
/// </summary>
public string script;
/// <summary>
/// Compiled script assembly loaded into current AppDomain.
/// </summary>
public Assembly asm;
}
/// <summary>
/// Controls if ScriptCache should be used when script file loading is requested (CSScript.Load(...)). If set to true and the script file was previously compiled and already loaded
/// the script engine will use that compiled script from the cache instead of compiling it again.
/// Note the script cache is always maintained by the script engine. The CacheEnabled property only indicates if the cached script should be used or not when CSScript.Load(...) method is called.
/// </summary>
public static bool CacheEnabled = true;
/// <summary>
/// Cache of all loaded script files for the current process.
/// </summary>
public static LoadedScript[] ScriptCache
{
get
{
#if net1
return (LoadedScript[])scriptCache.ToArray(typeof(LoadedScript));
#else
return scriptCache.ToArray();
#endif
}
}
#if net1
static ArrayList scriptCache = new ArrayList();
#else
static List<LoadedScript> scriptCache = new List<LoadedScript>();
#endif
/// <summary>
/// Returns cached script assembly matching the scrpt file name.
/// </summary>
/// <param name="file">Pull path of the script file.</param>
/// <returns>Assembly loaded int the current AppDomain.
/// Returns null if the loaded script cannot be found.
/// </returns>
public static Assembly GetCachedScriptAssembly(string file)
{
string path = Path.GetFullPath(file);
foreach (LoadedScript item in ScriptCache)
if (item.script == path && !ScriptAsmOutOfDate(path, item.asm.Location))
return item.asm;
string cacheFile = Path.Combine(csscript.CSSEnvironment.GetCacheDirectory(path), Path.GetFileName(path) + ".compiled");
if (File.Exists(cacheFile) && !ScriptAsmOutOfDate(path, cacheFile))
return Assembly.LoadFrom(cacheFile);
return null;
}
internal static bool ScriptAsmOutOfDate(string scriptFileName, string assemblyFileName)
{
if (File.GetLastWriteTimeUtc(scriptFileName) != File.GetLastWriteTimeUtc(assemblyFileName))
return true;
return MetaDataItems.IsOutOfDate(scriptFileName, assemblyFileName);
}
internal static string[] RemovePathDuplicates(string[] list)
{
lock (typeof(CSScript))
{
return Utils.RemovePathDuplicates(list);
}
}
}
}
namespace csscript
{
/// <summary>
/// This class implements access to the CS-Script global configuration settings.
/// </summary>
public class CSSEnvironment
{
/// <summary>
/// Generates the name of the cache directory for the specified script file.
/// </summary>
/// <param name="file">Script file name.</param>
/// <returns>Cache directory name.</returns>
public static string GetCacheDirectory(string file)
{
return CSExecutor.GetCacheDirectory(file);
}
/// <summary>
/// Saves code to the script file in the dedicated CS-Script <c>temporary files</c> location. You do not have to delete the script file after the execution.
/// It will be deleted as part of the periodical automatic CS-Script maintenance.
/// </summary>
/// <param name="content">The script file content.</param>
/// <returns>Name of the created temporary script file.</returns>
public static string SaveAsTempScript(string content)
{
string tempFile = CSExecutor.GetScriptTempFile();
using (StreamWriter sw = new StreamWriter(tempFile))
{
sw.Write(content);
}
return tempFile;
}
/// <summary>
/// Generates the script file path in the dedicated CS-Script <c>temporary files</c> location. You do not have to delete such file after the execution.
/// It will be deleted as part of the periodical automatic CS-Script maintenance.
/// </summary>
/// <returns>Name of the temporary script file.</returns>
public static string GetTempScriptName()
{
return CSExecutor.GetScriptTempFile();
}
/// <summary>
/// Sets the location for the CS-Script temporary files directory.
/// </summary>
/// <param name="path">The path for the temporary directory.</param>
static public void SetScriptTempDir(string path)
{
CSExecutor.SetScriptTempDir(path);
}
/// <summary>
/// The full name of the script file being executed.
/// </summary>
public static string ScriptFile
{
get
{
scriptFile = FindExecuteOptionsField(Assembly.GetExecutingAssembly(), "scriptFileName");
if (scriptFile == null)
scriptFile = FindExecuteOptionsField(Assembly.GetEntryAssembly(), "scriptFileName");
return scriptFile;
}
}
static private string scriptFile = null;
/// <summary>
/// The full name of the primary script file being executed. Usually it is the same file as ScriptFile.
/// However these fields are different if analysed from the pre/post-script.
/// </summary>
public static string PrimaryScriptFile
{
get
{
if (scriptFileNamePrimary == null)
{
scriptFileNamePrimary = FindExecuteOptionsField(Assembly.GetExecutingAssembly(), "scriptFileNamePrimary");
if (scriptFileNamePrimary == null || scriptFileNamePrimary == "")
scriptFileNamePrimary = FindExecuteOptionsField(Assembly.GetEntryAssembly(), "scriptFileNamePrimary");
}
return scriptFileNamePrimary;
}
}
static private string scriptFileNamePrimary = null;
static private string FindExecuteOptionsField(Assembly asm, string field)
{
Type t = asm.GetModules()[0].GetType("csscript.ExecuteOptions");
if (t != null)
{
foreach (FieldInfo fi in t.GetFields(BindingFlags.Static | BindingFlags.Public))
{
if (fi.Name == "options")
{
//need to use reflection as we might be running either cscs.exe or the script host application
//thus there is no warranty which assembly contains correct "options" object
object otionsObject = fi.GetValue(null);
if (otionsObject != null)
{
object scriptFileObject = otionsObject.GetType().GetField(field).GetValue(otionsObject);
if (scriptFileObject != null)
return scriptFileObject.ToString();
}
break;
}
}
}
return null;
}
private CSSEnvironment()
{
}
}
delegate void PrintDelegate(string msg);
/// <summary>
/// Repository for application specific data
/// </summary>
internal class AppInfo
{
public static string appName = "CSScriptLibrary";
public static bool appConsole = false;
public static string appLogo
{
get { return "C# Script execution engine. Version " + System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString() + ".\nCopyright (C) 2004 Oleg Shilo.\n"; }
}
public static string appLogoShort
{
get { return "C# Script execution engine. Version " + System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString() + ".\n"; }
}
//#pragma warning disable 414
public static string appParams = "[/nl]:";
//#pragma warning restore 414
public static string appParamsHelp = "nl - No logo mode: No banner will be shown at execution time.\n";
}
} | GlobalcachingEU/GAPP | CSScriptLibrary/CSScriptLib.cs | C# | mit | 73,213 |
No Workshop de 2016, o minicurso de Introdução ao R foi ministrado pelo mestrando Rodrigo Amadeu, também membro do laboratório de Genética Estatística de ESALQ.
Acesse [aqui](https://rramadeu.github.io/) o material feito por ele! | Cristianetaniguti/Workshop_genetica_2015 | _posts/2016-07-20-Workshop (2016) Introdução ao R.md | Markdown | mit | 236 |
<?php
require './include/common.inc.php';
require WEB_ROOT.'./include/chkuser.inc.php';
$table = 'manager';
$showname = 'person';
if(isset($_POST['update'])){
$newpwd=I('post.pwd_new','','md5');//md5($_POST['pwd_new']);
$oldpwd=I('post.pwd_old','','md5');//md5($_POST['pwd_old']);
$map = array(
'username' => $_SESSION['Admin_UserName'],
'password' => $oldpwd,
);
$result = M($table)->where($map)->find();
if(!$result){
Redirect::JsError("信息提示:原密码错误!");
}else{
$result = M($table)->where($map)->setField('password',$newpwd);
AddLog("编辑普通管理员密码",$_SESSION['Admin_UserName']);
Redirect::JsSuccess("操作成功!","person.php");
}
exit();
}
?>
<!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">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>密码修改</title>
<link href="images/common.css" rel="stylesheet" type="text/css" />
<link href="images/style.css" rel="stylesheet" type="text/css" />
<script src="js/jquery-1.8.3.min.js" language="javascript"></script>
<script src="js/js.js" language="javascript"></script>
<script src="js/placeholdem.min.js"></script>
<script language="javascript" src="js/checkform.js"></script>
</head>
<body>
<div class="content clr">
<div class="weizhi">
<p>位置:
<a href="mains.php">首页</a>
<span>></span>
<a href="person.php">密码修改</a>
</p>
</div>
<div class="right clr">
<div class="zhengwen clr">
<div class="xuanhuan clr">
<a href="javascript:void()" class="zai" style="margin-left:30px;">密码修改</a>
</div>
<div class="miaoshu clr">
<div id="tab1" class="tabson">
<div class="formtext">Hi,<b><?php echo $_SESSION['Admin_UserName']?></b>,欢迎您使用信息发布功能!</div>
<ul class="forminfo">
<form name="frm" method="post" action="" onSubmit="return checkperson(this);">
<li class="fade"><label>原密码<b>*</b></label><input name="pwd_old" type="text" class="shurukuang" value=""/></li>
<li class="fade"><label>新密码<b>*</b></label><input name="pwd_new" type="text" class="shurukuang" value=""/></li>
<li class="fade"><label> </label><input name="update" type="submit" class="btn" value="提 交"/></li>
</form>
</ul>
</div>
</div>
</div>
</div>
</div>
</body>
</html> | nicerway/tongyong | public/web_manage/person.php | PHP | mit | 2,698 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Mn.NewsCms.Web.Models
{
public class TitleValue
{
public TitleValue()
{
}
public TitleValue(string title, int value)
: this()
{
this.Title = title;
this.Value = value;
}
public string Title { get; set; }
public int Value { get; set; }
}
public class TitleValue<T>
{
public TitleValue()
{
}
public TitleValue(string title, T value)
: this()
{
this.Title = title;
this.Value = value;
}
public string Title { get; set; }
public T Value { get; set; }
}
} | navaei/NewsCMS | Web/Models/Shared/TitleValue.cs | C# | mit | 776 |
---
tags: media quote
layout: post
title: "Great western movie line"
---
I was flipping channels Saturday afternoon and came on <a href="http://us.imdb.com/Title?0064116">Once Upon a Time in the West</a>. It's a long movie I've never seen (but would like to) and I popped in somewhere in the middle, so I only watched a couple minutes. In the scene I did see, Henry Fonda kicks out a crutch from a guy he's disgustedly talking at and then sneers down at him: "I could squash you like a wormy apple." This line sweetly teases to oh-so-many clichéd lines of this nature you ever heard. Nice!
| cwinters/cwinters.github.io | _posts/2002-08-26-great_western_movie_line.md | Markdown | mit | 602 |
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("Archimedes.Geometry.Rendering")]
[assembly: AssemblyDescription("Provides the ability to render the primitives from Archimedes.Geometry library.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("ElderByte")]
[assembly: AssemblyProduct("Archimedes.Geometry.Rendering")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("Archimedes")]
[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("a3f6ad6b-b36a-4546-9627-38a6553bd29b")]
// 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.6.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| ElderByte-/Archimedes.Geometry | Archimedes.Geometry.Rendering/Properties/AssemblyInfo.cs | C# | mit | 1,532 |
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true,
});
exports.User = User;
exports.Fixture = Fixture;
var React = require('react');
var PropTypes = require('prop-types');
function User(props) {
return React.createElement('span', null, 'User ', props.index);
}
User.propTypes = {
index: PropTypes.number.isRequired,
};
function Fixture() {
return React.createElement(
'div',
null,
React.createElement(
'ul',
null,
React.createElement('li', null, React.createElement(User, { index: 1 })),
React.createElement('li', null, React.createElement(User, { index: 2 }))
)
);
}
| blainekasten/enzyme-matchers | packages/jasmine-enzyme/spec/fixtures/toContainReact.fixture.js | JavaScript | mit | 645 |
---
layout: post
title: AINARA FOLLANDO JUNTO A SILVIA GRISSO.
titleinfo: pornvd
desc: Watch AINARA FOLLANDO JUNTO A SILVIA GRISSO.. Pornhub is the ultimate xxx porn and sex site.
---
<iframe src="http://www.pornhub.com/embed/405611982" frameborder="0" width="630" height="338" scrolling="no"></iframe>
<h2>AINARA FOLLANDO JUNTO A SILVIA GRISSO.</h2>
<h3>Watch AINARA FOLLANDO JUNTO A SILVIA GRISSO.. Pornhub is the ultimate xxx porn and sex site.</h3>
| pornvd/pornvd.github.io | _posts/2016-01-24-AINARA-FOLLANDO-JUNTO-A-SILVIA-GRISSO..md | Markdown | mit | 470 |
module DataAggregation::Accumulator
module Message
def self.included(cls)
cls.class_exec do
include Messaging::Message
attribute :source_stream_version, Integer, default: -1
attribute :source_global_position, Integer
virtual :advance
end
end
def applied?(version)
version <= source_stream_version
end
end
end
| obsidian-btc/data-aggregation-accumulator | lib/data_aggregation/accumulator/message.rb | Ruby | mit | 382 |
<?php
namespace Ionize\Providers;
use App\User;
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\ServiceProvider;
class AuthService extends ServiceProvider
{
/**
* Register any application services.
*
* @return void
*/
public function register()
{
//
}
/**
* Boot the authentication services for the application.
*
* @return void
*/
public function boot()
{
// Here you may define how you wish users to be authenticated for your Lumen
// application. The callback which receives the incoming request instance
// should return either a User instance or null. You're free to obtain
// the User instance via an API token or any other method necessary.
$this->app['auth']->viaRequest('api', function ($request) {
if ($request->input('token')) {
return User::where('token', $request->input('token'))->first();
}
});
}
}
/* End of file: AuthService.php */
/* Location: Ionize\Providers */
| adaliszk/ionize-core | ionize/Providers/AuthService.php | PHP | mit | 1,067 |
package com.android.test;
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
public class MainActivity extends ActionBarActivity {
Button buttonWifi;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonWifi = (Button)findViewById(R.id.button_wifi);
buttonWifi.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new Intent(MainActivity.this,CheckWifi.class);
startActivity(i);
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
| IIT-RTC-Lab/app-access-points | Test/app/src/main/java/com/android/test/MainActivity.java | Java | mit | 1,554 |
goods3:{
list: [
{
modificator: '',
achivement: {
text: '<i class="icon-star"></i>Хит продаж',
type: 'best-buy'
},
image: '%=staticPrefix=%img/assets/catalog/1.jpg',
rubrika: 'Внешние аккумуляторы',
name: 'Пуско-зарядное устройство WUHAI',
charct: {
'Материал': 'Пластик',
'Время зарядки': '1,5-5 ч.',
'Цвет': 'Белый и черный',
'Напряж. и ток': '5В 1А',
'Гарантия': '1 год'
},
price: '5 990 <span class="rub">⃏</span>'
},
{
modificator: '',
achivement: {
text: '<i class="icon-sale"></i>Скидка',
type: 'sale'
},
image: '%=staticPrefix=%img/assets/catalog/2.jpg',
rubrika: 'Авто-сканеры',
name: 'AUTOPHIX OM 123',
charct: {
'Материал': 'Пластик',
'Время зарядки': '1,5-5 ч.',
'Цвет': 'Белый и черный',
'Напряж. и ток': '5В 1А',
'Гарантия': '1 год'
},
price: '2 900 <span class="rub">⃏</span>',
oldprice: '3 900 <span class="rub">⃏</span>'
},
{
modificator: '',
achivement: {
text: '<i class="icon-new"></i>Новинка',
type: 'new'
},
image: '%=staticPrefix=%img/assets/catalog/3.jpg',
rubrika: 'Внешние аккумуляторы',
name: 'Портативный внешний аккумулятор 8000 mAh',
charct: {
'Материал': 'Пластик',
'Время зарядки': '1,5-5 ч.',
'Цвет': 'Белый и черный',
'Напряж. и ток': '5В 1А',
'Гарантия': '1 год'
},
price: '1 690 <span class="rub">⃏</span>'
},
{
modificator: '',
image: '%=staticPrefix=%img/assets/catalog/4.jpg',
rubrika: 'Беспроводные зарядки',
name: 'Беспроводная автозарядка Magic BOX',
charct: {
'Материал': 'Пластик',
'Время зарядки': '1,5-5 ч.',
'Цвет': 'Белый и черный',
'Напряж. и ток': '5В 1А',
'Гарантия': '1 год'
},
price: '3 200 <span class="rub">⃏</span>'
},
{
modificator: '',
achivement: {
text: '<i class="icon-star"></i>Хит продаж',
type: 'best-buy'
},
image: '%=staticPrefix=%img/assets/catalog/1.jpg',
rubrika: 'Внешние аккумуляторы',
name: 'Пуско-зарядное устройство WUHAI',
charct: {
'Материал': 'Пластик',
'Время зарядки': '1,5-5 ч.',
'Цвет': 'Белый и черный',
'Напряж. и ток': '5В 1А',
'Гарантия': '1 год'
},
price: '5 990 <span class="rub">⃏</span>'
},
{
modificator: '',
achivement: {
text: '<i class="icon-sale"></i>Скидка',
type: 'sale'
},
image: '%=staticPrefix=%img/assets/catalog/2.jpg',
rubrika: 'Авто-сканеры',
name: 'AUTOPHIX OM 123',
charct: {
'Материал': 'Пластик',
'Время зарядки': '1,5-5 ч.',
'Цвет': 'Белый и черный',
'Напряж. и ток': '5В 1А',
'Гарантия': '1 год'
},
price: '2 900 <span class="rub">⃏</span>',
oldprice: '3 900 <span class="rub">⃏</span>'
},
{
modificator: '',
achivement: {
text: '<i class="icon-new"></i>Новинка',
type: 'new'
},
image: '%=staticPrefix=%img/assets/catalog/3.jpg',
rubrika: 'Внешние аккумуляторы',
name: 'Портативный внешний аккумулятор 8000 mAh',
charct: {
'Материал': 'Пластик',
'Время зарядки': '1,5-5 ч.',
'Цвет': 'Белый и черный',
'Напряж. и ток': '5В 1А',
'Гарантия': '1 год'
},
price: '1 690 <span class="rub">⃏</span>'
},
{
modificator: '',
image: '%=staticPrefix=%img/assets/catalog/4.jpg',
rubrika: 'Беспроводные зарядки',
name: 'Беспроводная автозарядка Magic BOX',
charct: {
'Материал': 'Пластик',
'Время зарядки': '1,5-5 ч.',
'Цвет': 'Белый и черный',
'Напряж. и ток': '5В 1А',
'Гарантия': '1 год'
},
price: '3 200 <span class="rub">⃏</span>'
},
{
modificator: '',
achivement: {
text: '<i class="icon-star"></i>Хит продаж',
type: 'best-buy'
},
image: '%=staticPrefix=%img/assets/catalog/1.jpg',
rubrika: 'Внешние аккумуляторы',
name: 'Пуско-зарядное устройство WUHAI',
charct: {
'Материал': 'Пластик',
'Время зарядки': '1,5-5 ч.',
'Цвет': 'Белый и черный',
'Напряж. и ток': '5В 1А',
'Гарантия': '1 год'
},
price: '5 990 <span class="rub">⃏</span>'
},
{
modificator: '',
achivement: {
text: '<i class="icon-sale"></i>Скидка',
type: 'sale'
},
image: '%=staticPrefix=%img/assets/catalog/2.jpg',
rubrika: 'Авто-сканеры',
name: 'AUTOPHIX OM 123',
charct: {
'Материал': 'Пластик',
'Время зарядки': '1,5-5 ч.',
'Цвет': 'Белый и черный',
'Напряж. и ток': '5В 1А',
'Гарантия': '1 год'
},
price: '2 900 <span class="rub">⃏</span>',
oldprice: '3 900 <span class="rub">⃏</span>'
},
{
modificator: '',
achivement: {
text: '<i class="icon-new"></i>Новинка',
type: 'new'
},
image: '%=staticPrefix=%img/assets/catalog/3.jpg',
rubrika: 'Внешние аккумуляторы',
name: 'Портативный внешний аккумулятор 8000 mAh',
charct: {
'Материал': 'Пластик',
'Время зарядки': '1,5-5 ч.',
'Цвет': 'Белый и черный',
'Напряж. и ток': '5В 1А',
'Гарантия': '1 год'
},
price: '1 690 <span class="rub">⃏</span>'
},
{
modificator: '',
image: '%=staticPrefix=%img/assets/catalog/4.jpg',
rubrika: 'Беспроводные зарядки',
name: 'Беспроводная автозарядка Magic BOX',
charct: {
'Материал': 'Пластик',
'Время зарядки': '1,5-5 ч.',
'Цвет': 'Белый и черный',
'Напряж. и ток': '5В 1А',
'Гарантия': '1 год'
},
price: '3 200 <span class="rub">⃏</span>'
}
]
}
| mik639/shopgadgets | markup/modules/goods/goods3/data/data.js | JavaScript | mit | 8,791 |
package tarantool
import (
"io"
)
// AnonSlave connects to Tarantool >= 2.3.1 instance and subscribes for changes as anonymous replica.
// Tarantool instance acting as a master sees AnonSlave like anonymous replica.
// AnonSlave can't be used concurrently, route responses from returned channel instead.
type AnonSlave struct {
Slave
}
// NewAnonSlave returns new AnonSlave instance.
// URI is parsed by url package and therefore should contains any scheme supported by net.Dial.
func NewAnonSlave(uri string, opts ...Options) (as *AnonSlave, err error) {
s, err := NewSlave(uri, opts...)
if err != nil {
return nil, err
}
// check tarantool version. Anonymous replica support was added in Tarantool 2.3.1
if s.Version() < version2_3_1 {
return nil, ErrOldVersionAnon
}
return &AnonSlave{*s}, nil
}
// JoinWithSnap fetch snapshots from Master instance.
// Snapshot logs is available through the given out channel or returned PacketIterator.
// (In truth, Slave itself is returned in PacketIterator wrapper)
func (s *AnonSlave) JoinWithSnap(out ...chan *Packet) (it PacketIterator, err error) {
if err = s.fetchSnapshot(); err != nil {
return nil, err
}
// set iterator for the Next method
s.next = s.nextSnap
if s.isEmptyChan(out...) {
// no chan means synchronous snapshot scanning
return s, nil
}
defer close(out[0])
for s.HasNext() {
out[0] <- s.Packet()
}
return nil, s.Err()
}
// Join fetches snapshots using Master instance.
func (s *AnonSlave) Join() (err error) {
_, err = s.JoinWithSnap()
if err != nil {
return err
}
for s.HasNext() {
}
return s.Err()
}
// Subscribe for DML requests (insert, update, delete, replace, upsert) since vector clock.
// Variadic lsn is start vector clock. Each lsn is one clock in vector (sequentially).
// One lsn is enough for master-slave replica set.
// Subscribe sends requests asynchronously to out channel specified or use synchronous PacketIterator otherwise.
// For anonymous replica it is not necessary to call Join or JoinWithSnap before Subscribe.
func (s *AnonSlave) Subscribe(lsns ...uint64) (it PacketIterator, err error) {
if len(lsns) == 0 || len(lsns) >= VClockMax {
return nil, ErrVectorClock
}
if err = s.subscribe(lsns...); err != nil {
return nil, err
}
// set iterator for the Next method
s.next = s.nextXlog
// Start sending heartbeat messages to master
go s.heartbeat()
return s, nil
}
// Attach AnonSlave to Replica Set as an anonymous and subscribe for the new(!) DML requests.
// Attach calls Join and then Subscribe with VClock = s.VClock[1:]...
// If didn't call Join before Attach then you need to set VClock first either manually or using JoinWithSnap.
// Use out chan for asynchronous packet receiving or synchronous PacketIterator otherwise.
// If you need all requests in chan use JoinWithSnap(chan) and then s.Subscribe(s.VClock[1:]...).
func (s *AnonSlave) Attach(out ...chan *Packet) (it PacketIterator, err error) {
if err = s.Join(); err != nil {
return nil, err
}
// skip reserved zero index of the Vector Clock
if len(s.VClock) <= 1 {
return nil, ErrVectorClock
}
if it, err = s.Subscribe(s.VClock[1:]...); err != nil {
return nil, err
}
// no chan means synchronous dml request receiving
if s.isEmptyChan(out...) {
return it, nil
}
// consume new DML requests and send them to the given chan
go func(out chan *Packet) {
defer close(out)
for s.HasNext() {
out <- s.Packet()
}
}(out[0])
// return nil iterator to avoid concurrent using of the Next method
return nil, nil
}
func (s *AnonSlave) fetchSnapshot() (err error) {
pp, err := s.newPacket(&FetchSnapshot{})
if err != nil {
return
}
if err = s.send(pp); err != nil {
return err
}
s.c.releasePacket(pp)
if pp, err = s.receive(); err != nil {
return err
}
defer pp.Release()
p := &Packet{}
if err := p.UnmarshalBinary(pp.body); err != nil {
return err
}
if p.Cmd != OKCommand {
s.p = p
if p.Result == nil {
return ErrBadResult
}
return p.Result.Error
}
v := new(VClock)
_, err = v.UnmarshalMsg(pp.body)
if err != nil {
return err
}
s.VClock = v.VClock
return nil
}
// subscribe sends SUBSCRIBE request and waits for VCLOCK response.
func (s *AnonSlave) subscribe(lsns ...uint64) error {
vc := NewVectorClock(lsns...)
pp, err := s.newPacket(&Subscribe{
UUID: s.UUID,
ReplicaSetUUID: s.ReplicaSet.UUID,
VClock: vc,
Anon: true,
})
if err != nil {
return err
}
if err = s.send(pp); err != nil {
return err
}
s.c.releasePacket(pp)
if pp, err = s.receive(); err != nil {
return err
}
defer s.c.releasePacket(pp)
p := &pp.packet
err = p.UnmarshalBinary(pp.body)
if err != nil {
return err
}
sub := new(SubscribeResponse)
_, err = sub.UnmarshalMsg(pp.body)
if err != nil {
return err
}
if s.ReplicaSet.UUID != "" && s.ReplicaSet.UUID != sub.ReplicaSetUUID {
return NewUnexpectedReplicaSetUUIDError(s.ReplicaSet.UUID, sub.ReplicaSetUUID)
}
s.ReplicaSet.UUID = sub.ReplicaSetUUID
s.VClock = sub.VClock
return nil
}
// nextSnap iterates responses on JOIN request.
// At the end it returns io.EOF error and nil packet.
// While iterating all
func (s *AnonSlave) nextSnap() (p *Packet, err error) {
pp, err := s.receive()
if err != nil {
return nil, err
}
defer s.c.releasePacket(pp)
p = &Packet{}
err = p.UnmarshalBinary(pp.body)
if err != nil {
return nil, err
}
// we have to parse snapshot logs to find replica set instances, UUID
switch p.Cmd {
case InsertCommand:
q := p.Request.(*Insert)
if q.Space == SpaceSchema {
key := q.Tuple[0].(string)
if key == SchemaKeyClusterUUID {
if s.ReplicaSet.UUID != "" && s.ReplicaSet.UUID != q.Tuple[1].(string) {
return nil, NewUnexpectedReplicaSetUUIDError(s.ReplicaSet.UUID, q.Tuple[1].(string))
}
s.ReplicaSet.UUID = q.Tuple[1].(string)
}
}
case OKCommand:
v := new(VClock)
_, err = v.UnmarshalMsg(pp.body)
if err != nil {
return nil, err
}
// ignore this VClock for anon replica
return nil, io.EOF
}
return p, nil
}
| viciious/go-tarantool | anon_slave.go | GO | mit | 6,091 |
# StackGAN
- [Pytorch implementation](https://github.com/hanzhanggit/StackGAN-Pytorch)
- [Inception score evaluation](https://github.com/hanzhanggit/StackGAN-inception-model)
- [StackGAN-v2-pytorch](https://github.com/hanzhanggit/StackGAN-v2)
Tensorflow implementation for reproducing main results in the paper [StackGAN: Text to Photo-realistic Image Synthesis with Stacked Generative Adversarial Networks](https://arxiv.org/pdf/1612.03242v1.pdf) by Han Zhang, Tao Xu, Hongsheng Li, Shaoting Zhang, Xiaogang Wang, Xiaolei Huang, Dimitris Metaxas.
<img src="examples/framework.jpg" width="850px" height="370px"/>
### Dependencies
python 2.7
[TensorFlow 0.12](https://www.tensorflow.org/get_started/os_setup)
[Optional] [Torch](http://torch.ch/docs/getting-started.html#_) is needed, if use the pre-trained char-CNN-RNN text encoder.
[Optional] [skip-thought](https://github.com/ryankiros/skip-thoughts) is needed, if use the skip-thought text encoder.
In addition, please add the project folder to PYTHONPATH and `pip install` the following packages:
- `prettytensor`
- `progressbar`
- `python-dateutil`
- `easydict`
- `pandas`
- `torchfile`
**Data**
1. Download our preprocessed char-CNN-RNN text embeddings for [birds](https://drive.google.com/open?id=0B3y_msrWZaXLT1BZdVdycDY5TEE) and [flowers](https://drive.google.com/open?id=0B3y_msrWZaXLaUc0UXpmcnhaVmM) and save them to `Data/`.
- [Optional] Follow the instructions [reedscot/icml2016](https://github.com/reedscot/icml2016) to download the pretrained char-CNN-RNN text encoders and extract text embeddings.
2. Download the [birds](http://www.vision.caltech.edu/visipedia/CUB-200-2011.html) and [flowers](http://www.robots.ox.ac.uk/~vgg/data/flowers/102/) image data. Extract them to `Data/birds/` and `Data/flowers/`, respectively.
3. Preprocess images.
- For birds: `python misc/preprocess_birds.py`
- For flowers: `python misc/preprocess_flowers.py`
**Training**
- The steps to train a StackGAN model on the CUB dataset using our preprocessed data for birds.
- Step 1: train Stage-I GAN (e.g., for 600 epochs) `python stageI/run_exp.py --cfg stageI/cfg/birds.yml --gpu 0`
- Step 2: train Stage-II GAN (e.g., for another 600 epochs) `python stageII/run_exp.py --cfg stageII/cfg/birds.yml --gpu 1`
- Change `birds.yml` to `flowers.yml` to train a StackGAN model on Oxford-102 dataset using our preprocessed data for flowers.
- `*.yml` files are example configuration files for training/testing our models.
- If you want to try your own datasets, [here](https://github.com/soumith/ganhacks) are some good tips about how to train GAN. Also, we encourage to try different hyper-parameters and architectures, especially for more complex datasets.
**Pretrained Model**
- [StackGAN for birds](https://drive.google.com/open?id=0B3y_msrWZaXLNUNKa3BaRjAyTzQ) trained from char-CNN-RNN text embeddings. Download and save it to `models/`.
- [StackGAN for flowers](https://drive.google.com/open?id=0B3y_msrWZaXLX01FMC1JQW9vaFk) trained from char-CNN-RNN text embeddings. Download and save it to `models/`.
- [StackGAN for birds](https://drive.google.com/open?id=0B3y_msrWZaXLZVNRNFg4d055Q1E) trained from skip-thought text embeddings. Download and save it to `models/` (Just used the same setting as the char-CNN-RNN. We assume better results can be achieved by playing with the hyper-parameters).
**Run Demos**
- Run `sh demo/flowers_demo.sh` to generate flower samples from sentences. The results will be saved to `Data/flowers/example_captions/`. (Need to [download](https://drive.google.com/file/d/0B0ywwgffWnLLZUt0UmQ1LU1oWlU/view) the char-CNN-RNN text encoder for flowers to `models/text_encoder/`. Note: this text encoder is provided by [reedscot/icml2016](https://github.com/reedscot/icml2016)).
- Run `sh demo/birds_demo.sh` to generate bird samples from sentences. The results will be saved to `Data/birds/example_captions/`.(Need to [download](https://drive.google.com/file/d/0B0ywwgffWnLLU0F3UHA3NzFTNEE/view) the char-CNN-RNN text encoder for birds to `models/text_encoder/`. Note: this text encoder is provided by [reedscot/icml2016](https://github.com/reedscot/icml2016)).
- Run `python demo/birds_skip_thought_demo.py --cfg demo/cfg/birds-skip-thought-demo.yml --gpu 2` to generate bird samples from sentences. The results will be saved to `Data/birds/example_captions-skip-thought/`. (Need to [download](https://github.com/ryankiros/skip-thoughts) vocabulary for skip-thought vectors to `Data/skipthoughts/`).
Examples for birds (char-CNN-RNN embeddings), more on [youtube](https://youtu.be/93yaf_kE0Fg):




Examples for flowers (char-CNN-RNN embeddings), more on [youtube](https://youtu.be/SuRyL5vhCIM):




Save your favorite pictures generated by our models since the randomness from noise z and conditioning augmentation makes them creative enough to generate objects with different poses and viewpoints from the same discription :smiley:
### Citing StackGAN
If you find StackGAN useful in your research, please consider citing:
```
@inproceedings{han2017stackgan,
Author = {Han Zhang and Tao Xu and Hongsheng Li and Shaoting Zhang and Xiaogang Wang and Xiaolei Huang and Dimitris Metaxas},
Title = {StackGAN: Text to Photo-realistic Image Synthesis with Stacked Generative Adversarial Networks},
Year = {2017},
booktitle = {{ICCV}},
}
```
**Our follow-up work**
- [StackGAN++: Realistic Image Synthesis with Stacked Generative Adversarial Networks](https://arxiv.org/abs/1710.10916)
- [AttnGAN: Fine-Grained Text to Image Generation with Attentional Generative Adversarial Networks](https://arxiv.org/abs/1711.10485) [[supplementary]](https://1drv.ms/b/s!Aj4exx_cRA4ghK5-kUG-EqH7hgknUA) [[code]](https://github.com/taoxugit/AttnGAN)
**References**
- Generative Adversarial Text-to-Image Synthesis [Paper](https://arxiv.org/abs/1605.05396) [Code](https://github.com/reedscot/icml2016)
- Learning Deep Representations of Fine-grained Visual Descriptions [Paper](https://arxiv.org/abs/1605.05395) [Code](https://github.com/reedscot/cvpr2016)
| hanzhanggit/StackGAN | README.md | Markdown | mit | 6,248 |
$('div.alert').delay(4000).slideUp(400);
| alexpylypenko/GraduationWork | public/js/slide_alert.js | JavaScript | mit | 42 |
declare class CommentsWidget extends HTMLElement{
constructor(appID: string, wingetID: string, settings: {})
}
declare namespace Environment{
class Cookies{
get(name: string): string
set(name: string, value: string, options?: Cookies.Options): void
del(name: string): void
}
namespace Cookies{
type Options = {
expires?: number | Date
path?: string
domain?: string
secure?: boolean
}
}
class HTTP{
get(url: string): Promise<string>
post(url: string, data:{ [x: string]: string | number }): Promise<string>
}
class GOGSAPI{ // Described with 74c1baf8d7 specification
getRaw(props: { user: string, repo: string, path: string }): Promise<{
type: GOGSAPI.type,
code?: number,
message?: string,
res?: string,
}>
countIPsInDB(props: { user:string, repo: string, path:string }): Promise<{
type: GOGSAPI.type,
code?: number,
message?: string,
res?: number,
}>
IPcountBadge(props: { user: string, repo: string, path: string, color?: string, style?: string, longCache?: boolean }): Promise<{
type: 'error',
code: number,
message: string,
}>
getIPinfo(props: { ip: string }): Promise<{
type: GOGSAPI.type,
code?: number,
message?: string,
res?: GOGSAPI.IPInfo,
}>
FG_getPins(props: { lang: string, term_id?: number }): Promise<{
type: GOGSAPI.type,
code?: number,
message?: string,
res?: GOGSAPI.MapPin[],
}>
FG_log_err(props: { stack: string }): Promise<{
type: GOGSAPI.type,
code?: number,
message?: string,
}>
}
namespace GOGSAPI{
class IPInfo{
net: string[]
mobile: boolean
city: string | null
region: string | null
district: string | null
country: string | null
location: {
lat: number
lng: number
}
}
class MapPin{
title: string
desc: string
link: string
addr: string
lat: number
lng: number
thumbnail: string
pin: string
}
type type = 'error' | 'success'
}
class Console{
log(message?: any, ...optionalParams: any[]): void
warn(message?: any, ...optionalParams: any[]): void
err(error: Error | string): Promise<void>
error(error: Error | string): Promise<void>
}
}
declare const __dirname: string
declare const __filename: string
declare function require(url: 'https://cdn.jsdelivr.net/gh/FavoriStyle/AllBoooms-APIAssets@2/comments/widget.min.js'): Promise<typeof CommentsWidget>
declare function require(url: 'env.js' | './env.js'): Promise<{
html: HTMLHtmlElement,
body: HTMLBodyElement,
is(selector): boolean,
isAll(selectors): boolean,
isOneOf(selectors): boolean,
$(selector): NodeListOf<HTMLElement>,
Cookies: Environment.Cookies,
http: Environment.HTTP,
apiv4pjs: { [x: string]: (data: {}) => Promise<any> }, // Need to be described with specification
_: (props: { name: string, attrs: {[x: string]: string}, html: string }) => HTMLElement,
gogsAPI: Environment.GOGSAPI,
console: Environment.Console,
GET: {[x: string]: string},
}>
declare function require(url: string):Promise<any>
| FavoriStyle/FoodGuide | assets/js/index.d.ts | TypeScript | mit | 3,650 |
<?php
namespace CodeLovers\AclBundle\DependencyInjection;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;
use Symfony\Component\DependencyInjection\Loader;
/**
* This is the class that loads and manages your bundle configuration
*
* To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html}
*/
class CodeLoversAclExtension extends Extension
{
/**
* {@inheritDoc}
*/
public function load(array $configs, ContainerBuilder $container)
{
$configuration = new Configuration();
$config = $this->processConfiguration($configuration, $configs);
$loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
$loader->load('services.yml');
$container->setAlias('code_lovers_acl.handler', 'code_lovers_acl.handler.' . $config['handler']);
}
}
| CodeLoversAt/AclBundle | DependencyInjection/CodeLoversAclExtension.php | PHP | mit | 992 |
<!DOCTYPE html>
<html lang="en">
<head>
<base href="/">
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<link rel="icon" href="favicon.png">
<title>Ansible Semaphore</title>
</head>
<body>
<noscript>
<strong>
We're sorry but <%= htmlWebpackPlugin.options.title %> doesn't work properly
without JavaScript enabled. Please enable it to continue.
</strong>
</noscript>
<div id="app"></div>
<!-- built files will be auto injected -->
</body>
</html>
| ansible-semaphore/semaphore | web2/public/index.html | HTML | mit | 625 |
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("DigitsName")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("DigitsName")]
[assembly: AssemblyCopyright("Copyright © Microsoft 2013")]
[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("14a849fe-9eef-4baa-a426-b745bfd56f44")]
// 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")]
| dirk-dagger-667/telerik-c--part1-lectures | HomeWork 5 -Conditional Statements/HomeWork 5 -Conditional Statements/DigitsName/Properties/AssemblyInfo.cs | C# | mit | 1,414 |
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
from matplotlib import cm
from matplotlib.ticker import LinearLocator, FormatStrFormatter
import numpy as np
def divide(a):
return float(a[0]) / float(a[1])
def getDataTypeFromLogPart(logpart, terminalChar = "\n"):
data = {
"lights1": list(map(lambda x: x.split("Light 1: ")[1].split(" -")[0], logpart)),
"lights2": list(map(lambda x: x.split("Light 2: ")[1].split(" -")[0], logpart)),
"energy": list(map(lambda x: x.split("Energy Consumption: ")[1].split(" -")[0], logpart)),
"time": list(map(lambda x: int(x.split("Time: ")[1].split(terminalChar)[0]), logpart)),
}
data = {
"lights1": list(map(lambda x: divide(x.split("/")), data["lights1"])),
"lights2": list(map(lambda x: divide(x.split("/")), data["lights2"])),
"energy": list(map(lambda x: divide(x.split("/")), data["energy"])),
"time": list(map(lambda x: x-(x%10), data["time"]))
}
return data
def getDataTypeFromLogPartUpdate(logpart, terminalChar = " -"):
data = {
"lights1": list(map(lambda x: x.split("Light 1: ")[1].split(" -")[0], logpart)),
"lights2": list(map(lambda x: x.split("Light 2: ")[1].split(" -")[0], logpart)),
"energy": list(map(lambda x: x.split("Energy Consumption: ")[1].split(" -")[0], logpart)),
"time": list(map(lambda x: x.split("Time: ")[1].split(terminalChar)[0], logpart)),
}
data = {
"lights1": list(map(lambda x: divide(x.split("/")), data["lights1"])),
"lights2": list(map(lambda x: divide(x.split("/")), data["lights2"])),
"energy": list(map(lambda x: divide(x.split("/")), data["energy"])),
"time": list(map(lambda x: int(divide(x.split("/"))), data["time"]))
}
data["time"] = list(map(lambda x: x, data["time"]))
return data
def avgDataType(data):
maxLen = 0
for run in data:
if len(run["time"]) > maxLen:
maxLen = len(run["time"])
for run in data:
for key in run:
run[key] = np.array([0]*(maxLen - len(run[key])) + run[key])
struct = {
"lights1": np.zeros(maxLen),
"lights2": np.zeros(maxLen),
"energy": np.zeros(maxLen),
"time": np.zeros(maxLen)
}
for run in data:
for key in run:
struct[key] += run[key]
for key in struct:
struct[key] /= len(data)
return struct
def buildChart(Y, X, Y_update, X_update):
#plt.plot(X, Y[-1][:], label="Prev. Consumo de Energia")
plt.plot(X_update, Y_update[-1][:], label="Medição Consumo")
plt.plot(X_update, np.ones(X_update.shape[0])*np.average(Y_update[-1][:]), label="Consumo Médio: 32.767mW")
print(np.average(Y_update[-1][:]));
plt.legend(bbox_to_anchor=(1.00, 1.00))
plt.show()
avg_data_pred = []
avg_data_update = []
for txRate in range(10):
parsed_data_pred = []
parsed_data_update = []
for testNum in range(30):
file = "./data/"+str((txRate+1)*10)+"%/log_1_"+str(testNum+1)+".txt"
pred_log = []
update_log = []
with open(file, "r") as f:
for line in f.readlines():
if("Prediction" in line):
pred_log.append(line)
if("Model Updated - " in line):
update_log.append(line)
parsed_data_pred.append(getDataTypeFromLogPart(pred_log))
parsed_data_update.append(getDataTypeFromLogPartUpdate(update_log))
avg_data_pred.append(avgDataType(parsed_data_pred))
avg_data_update.append(avgDataType(parsed_data_update))
maxLen = 0
for txRate in avg_data_update:
if txRate["time"].shape[0] > maxLen:
maxLen = txRate["time"].shape[0]
for txRate in avg_data_update:
for key in txRate:
txRate[key] = np.array([0]*(maxLen - txRate[key].shape[0]) + list(txRate[key]))
avg_data_update = np.array(avg_data_update)
maxLen = 0
for txRate in avg_data_pred:
if txRate["time"].shape[0] > maxLen:
maxLen = txRate["time"].shape[0]
for txRate in avg_data_pred:
for key in txRate:
txRate[key] = np.array([0]*(maxLen - txRate[key].shape[0]) + list(txRate[key]))
avg_data_pred = np.array(avg_data_pred)
YE_update = []
for txRate in avg_data_update:
YE_update.append(list(txRate["energy"]))
YE_update = np.array(YE_update)
X_update = avg_data_update[-1]["time"]
YE = []
for txRate in avg_data_pred:
YE.append(list(txRate["energy"]))
YE = np.array(YE)
X = avg_data_pred[-1]["time"]
buildChart(YE, X, YE_update, X_update) | Raphael-C-Almeida/Wireless-Sensor-Network | Plots/plotConsumption.py | Python | mit | 4,562 |
<!DOCTYPE html>
<html>
<head>
<title>NeXt icons</title>
<link rel="stylesheet" href="bower_components/next-bower/css/next.min.css">
<script type="text/javascript" src="bower_components/next-bower/js/next.js"></script>
<link rel="stylesheet" href="bower_components/font-awesome/css/font-awesome.min.css">
<link rel="stylesheet" href="assets/style.css">
</head>
<body>
<i class="fa fa-apple"></i>
<div id="topology-container"></div>
<script type="text/javascript" src="app/data.js"></script>
<script type="text/javascript" src="app/extended-node.js"></script>
<script type="text/javascript" src="app/app.js"></script>
</body>
</html> | zverevalexei/next-ui-demos | next-icons/index.html | HTML | mit | 641 |
/**
* GET /
* Home page.
*/
exports.index = function(req, res) {
res.render('home', {
title: 'Home',
documentation: [
{
name: 'Term',
param: 'q',
example: '?q=shoes',
description: 'Search for a specific term on your resource'
},
{
name: 'Size',
param: 'size',
example: '?size=12',
description: 'Limit the size of the search'
},
{
name: 'From',
param: 'from',
example: '?from=12',
description: 'Skip documents of the search'
},
{
name: 'Sort',
param: 'sort',
example: '?sort=created_at',
description: 'Sort by a field in the document. For desc append add - (-created_at)'
},
{
name: 'Fields',
param: 'fields',
example: '?fields=name,description',
description: 'Only return certain fields in the document.'
},
{
name: 'Matching field',
param: ':field',
example: '?slug=2014-blog-article',
description: 'Field matching on the index.'
},
]
});
};
| StreetHub/elasticsearch.rest | controllers/home.js | JavaScript | mit | 1,102 |
gem 'rspec-rails', '~> 2.0.1', :group => [:development, :test]
gem 'steak', :group => [:development, :test]
gem 'capybara', :group => [:development, :test]
gem 'spork', '~> 0.9.0.rc2', :group => [:test]
gem 'factory_girl_rails', :group => [:test]
gem 'guard-rspec', :group => [:test]
gem 'guard-spork', :group => [:test]
gem 'libnotify', :group => [:test]
gem 'rb-inotify', :group => [:test]
gem 'metric_fu', :group => [:test]
gem 'cover_me', :group => [:test]
#Remarkable matchers
gem 'remarkable', '~> 4.0.0.alpha2', :group => [:test]
gem 'remarkable_activemodel', '~> 4.0.0.alpha4', :group => [:test]
gem 'remarkable_activerecord', '~> 4.0.0.alpha2', :group => [:test]
after_gems << lambda do
generate 'rspec:install'
generate 'steak:install'
run 'spork --bootstrap'
remove_file 'test'
remove_file 'autotest'
spec_helper_requires = %w(remarkable/active_model remarkable/active_record factory_girl cover_me).map {|requirement| "require '#{requirement}'"}.join("\n")
inject_into_file "spec/spec_helper.rb", spec_helper_requires + "\n", :after => "require 'rspec/rails'\n"
inject_into_file "spec/spec_helper.rb", "\n ActiveSupport::Dependencies.clear\n", :after => "config.use_transactional_fixtures = true\n"
inject_into_file "config/application.rb", "\n" + template_content('rspec/config/application.rb.spork'), :after => "config.filter_parameters += [:password]\n"
comment 'spec/spec_helper.rb', 'config.fixture_path'
create_file 'spec/factories/.gitkeep', ""
create_file 'Guardfile', template_content('rspec/Guardfile')
create_file 'lib/tasks/metrics.rake', template_content('rspec/lib/tasks/metrics.rake')
append_file '.gitignore', "coverage.data\n"
append_file '.rspec', "--drb\n"
repo_commit 'Added Rspec'
end
| fabiokr/rails3-templates | lib/recipes/tests/rspec.rb | Ruby | mit | 1,758 |
// Fill out your copyright notice in the Description page of Project Settings.
#include "ScoreboardPlayerController.h"
#include "Components/WidgetComponent.h"
| serengeor/PTH_0112 | Source/Parteh/Scoreboard/ScoreboardPlayerController.cpp | C++ | mit | 161 |
import { Component } from '@angular/core';
import { Ingredient } from './ingredient';
import { GroceryService } from './grocery.service';
@Component({
selector: 'grocery-list',
templateUrl: './grocery-list.component.html'
})
export class GroceryListComponent {
ingredients: Ingredient[];
constructor(private groceryService: GroceryService) {
this.groceryService.getIngredients().subscribe(ingredients => this.ingredients = ingredients);
}
/*
getIngredients(): void {
this.recipeService.getRecipe().subscribe(ingredients => this.ingredients = ingredients);
}
ngOnInit(): void {
this.getIngredients();
}
*/
}
| exualsbaby/GroceryList | app/grocery-list.component.ts | TypeScript | mit | 679 |
class GraylogAPI
class System
# class for get system information of a node
class Cluster
def initialize(client)
@client = client
end
def node
@client.request(:get, '/system/cluster/node')
end
def nodes
@client.request(:get, '/system/cluster/nodes')
end
def node_by_id(id)
@client.request(:get, "/system/cluster/nodes/#{id}")
end
def node_by_hostname(hostname)
nodes['nodes'].find { |n| n['hostname'] == hostname }
end
end
end
end
| postgred/graylogapi | lib/graylogapi/system/cluster.rb | Ruby | mit | 550 |
import { presenceStatus } from 'ringcentral-integration/enums/presenceStatus.enum';
import dndStatus from 'ringcentral-integration/modules/Presence/dndStatus';
export default {
[presenceStatus.available]: "在线",
[presenceStatus.busy]: "忙碌",
[presenceStatus.offline]: "隐身",
[dndStatus.doNotAcceptAnyCalls]: "勿扰"
};
// @key: @#@"[presenceStatus.available]"@#@ @source: @#@"Available"@#@
// @key: @#@"[presenceStatus.busy]"@#@ @source: @#@"Busy"@#@
// @key: @#@"[presenceStatus.offline]"@#@ @source: @#@"Invisible"@#@
// @key: @#@"[dndStatus.doNotAcceptAnyCalls]"@#@ @source: @#@"Do not Disturb"@#@
| ringcentral/ringcentral-js-widget | packages/ringcentral-widgets/components/PresenceItem/i18n/zh-CN.js | JavaScript | mit | 620 |
# BtcRates
[](https://badge.fury.io/rb/btcrates)
BtcRates makes it easy to get current bitcoin rates from a few popular exchanges.
## Installation
Add this line to your application's Gemfile:
```ruby
gem 'btcrates'
```
you know the rest ....
## Usage
Require the gem
require 'btcrates'
Call a rate like this
```
BtcRates.get_rate(:bitfinex)
=> 232.5
BtcRates.get_raw(:bitfinex)
=> {"mid"=>"1437.85", "bid"=>"1436.7", "ask"=>"1439.0", "last_price"=>"1439.9", "low"=>"1392.5", "high"=>"1440.0", "volume"=>"9347.69670993", "timestamp"=>"1493328040.633420628"}
```
## Avaliable Options
```
:bitfinex, :bitstamp, :ok_coin_us, :ok_coin_cny, :weighted_average
```
## Development
### To Do
Add more specs
Add more exchanges
## Contributing
Please do contribute!
Bug reports and pull requests are welcome on GitHub at https://github.com/mmplisskin/btcRates.
## License
The gem is available as open source under the terms of the [MIT License](http://opensource.org/licenses/MIT).
We are not responsible for anything--use this gem with care.
| mmplisskin/BTC-Price-Gem | README.md | Markdown | mit | 1,121 |
param($installPath, $toolsPath, $package, $project)
Initialize-EFConfiguration $project
Add-EFProvider $project 'System.Data.SqlClient' 'System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer'
Write-Host
Write-Host "Type 'get-help EntityFramework' to see all available Entity Framework commands."
# SIG # Begin signature block
# MIIdkwYJKoZIhvcNAQcCoIIdhDCCHYACAQExCzAJBgUrDgMCGgUAMGkGCisGAQQB
# gjcCAQSgWzBZMDQGCisGAQQBgjcCAR4wJgIDAQAABBAfzDtgWUsITrck0sYpfvNR
# AgEAAgEAAgEAAgEAAgEAMCEwCQYFKw4DAhoFAAQUjgytciCovTic6/jKZPk7al+/
# G+WgghhTMIIEwjCCA6qgAwIBAgITMwAAAMDeLD0HlORJeQAAAAAAwDANBgkqhkiG
# 9w0BAQUFADB3MQswCQYDVQQGEwJVUzETMBEGA1UECBMKV2FzaGluZ3RvbjEQMA4G
# A1UEBxMHUmVkbW9uZDEeMBwGA1UEChMVTWljcm9zb2Z0IENvcnBvcmF0aW9uMSEw
# HwYDVQQDExhNaWNyb3NvZnQgVGltZS1TdGFtcCBQQ0EwHhcNMTYwOTA3MTc1ODUw
# WhcNMTgwOTA3MTc1ODUwWjCBsjELMAkGA1UEBhMCVVMxEzARBgNVBAgTCldhc2hp
# bmd0b24xEDAOBgNVBAcTB1JlZG1vbmQxHjAcBgNVBAoTFU1pY3Jvc29mdCBDb3Jw
# b3JhdGlvbjEMMAoGA1UECxMDQU9DMScwJQYDVQQLEx5uQ2lwaGVyIERTRSBFU046
# N0FCNS0yREYyLURBM0YxJTAjBgNVBAMTHE1pY3Jvc29mdCBUaW1lLVN0YW1wIFNl
# cnZpY2UwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDoiKVSfklVAB4E
# Oc9+r95kl32muXNITYcTbaRtuJl+MQzEnD0eU2JUXx2mI06ONnTfFW39ZQPF1pvU
# WkHBrS6m8oKy7Em4Ol91RJ5Knwy1VvY2Tawqh+VxwdARRgOeFtFm0S+Pa+BrXtVU
# hTtGl0BGMsKGEQKdDNGJD259Iq47qPLw3CmllE3/YFw1GGoJ9C3ry+I7ntxIjJYB
# LXA122vw93OOD/zWFh1SVq2AejPxcjKtHH2hjoeTKwkFeMNtIekrUSvhbuCGxW5r
# 54KW0Yus4o8392l9Vz8lSEn2j/TgPTqD6EZlzkpw54VSwede/vyqgZIrRbat0bAh
# b8doY8vDAgMBAAGjggEJMIIBBTAdBgNVHQ4EFgQUFf5K2jOJ0xmF1WRZxNxTQRBP
# tzUwHwYDVR0jBBgwFoAUIzT42VJGcArtQPt2+7MrsMM1sw8wVAYDVR0fBE0wSzBJ
# oEegRYZDaHR0cDovL2NybC5taWNyb3NvZnQuY29tL3BraS9jcmwvcHJvZHVjdHMv
# TWljcm9zb2Z0VGltZVN0YW1wUENBLmNybDBYBggrBgEFBQcBAQRMMEowSAYIKwYB
# BQUHMAKGPGh0dHA6Ly93d3cubWljcm9zb2Z0LmNvbS9wa2kvY2VydHMvTWljcm9z
# b2Z0VGltZVN0YW1wUENBLmNydDATBgNVHSUEDDAKBggrBgEFBQcDCDANBgkqhkiG
# 9w0BAQUFAAOCAQEAGeJAuzJMR+kovMi8RK/LtfrKazWlR5Lx02hM9GFmMk1zWCSc
# pfVY6xqfzWFllCFHBtOaJZqLiV97jfNCLpG0PULz24CWSkG7jJ+mZaCSicZ7ZC3b
# WDh1zpc54llYVyyTkRVYx/mtc9GujqbS8CBZgjaT/JsECnvGAPUcLYuSGt53CU1b
# UuiNwuzAhai4glcYyq3/7qMmmAtbnbCZhR5ySoMy7BwdzN70drLtafCJQncfAHXV
# O5r6SX4U/2J2zvWhA8lqhZu9SRulFGRvf81VTf+k5rJ2TjL6dYtSchooJ5YVvUk6
# i7bfV0VBN8xpaUhk8jbBnxhDPKIvDvnZlhPuJjCCBgAwggPooAMCAQICEzMAAADD
# Dpun2LLc9ywAAAAAAMMwDQYJKoZIhvcNAQELBQAwfjELMAkGA1UEBhMCVVMxEzAR
# BgNVBAgTCldhc2hpbmd0b24xEDAOBgNVBAcTB1JlZG1vbmQxHjAcBgNVBAoTFU1p
# Y3Jvc29mdCBDb3Jwb3JhdGlvbjEoMCYGA1UEAxMfTWljcm9zb2Z0IENvZGUgU2ln
# bmluZyBQQ0EgMjAxMTAeFw0xNzA4MTEyMDIwMjRaFw0xODA4MTEyMDIwMjRaMHQx
# CzAJBgNVBAYTAlVTMRMwEQYDVQQIEwpXYXNoaW5ndG9uMRAwDgYDVQQHEwdSZWRt
# b25kMR4wHAYDVQQKExVNaWNyb3NvZnQgQ29ycG9yYXRpb24xHjAcBgNVBAMTFU1p
# Y3Jvc29mdCBDb3Jwb3JhdGlvbjCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoC
# ggEBALtX1zjRsQZ/SS2pbbNjn3q6tjohW7SYro3UpIGgxXXFLO+CQCq3gVN382MB
# CrzON4QDQENXgkvO7R+2/YBtycKRXQXH3FZZAOEM61fe/fG4kCe/dUr8dbJyWLbF
# SJszYgXRlZSlvzkirY0STUZi2jIZzqoiXFZIsW9FyWd2Yl0wiKMvKMUfUCrZhtsa
# ESWBwvT1Zy7neR314hx19E7Mx/znvwuARyn/z81psQwLYOtn5oQbm039bUc6x9nB
# YWHylRKhDQeuYyHY9Jkc/3hVge6leegggl8K2rVTGVQBVw2HkY3CfPFUhoDhYtuC
# cz4mXvBAEtI51SYDDYWIMV8KC4sCAwEAAaOCAX8wggF7MB8GA1UdJQQYMBYGCisG
# AQQBgjdMCAEGCCsGAQUFBwMDMB0GA1UdDgQWBBSnE10fIYlV6APunhc26vJUiDUZ
# rzBRBgNVHREESjBIpEYwRDEMMAoGA1UECxMDQU9DMTQwMgYDVQQFEysyMzAwMTIr
# YzgwNGI1ZWEtNDliNC00MjM4LTgzNjItZDg1MWZhMjI1NGZjMB8GA1UdIwQYMBaA
# FEhuZOVQBdOCqhc3NyK1bajKdQKVMFQGA1UdHwRNMEswSaBHoEWGQ2h0dHA6Ly93
# d3cubWljcm9zb2Z0LmNvbS9wa2lvcHMvY3JsL01pY0NvZFNpZ1BDQTIwMTFfMjAx
# MS0wNy0wOC5jcmwwYQYIKwYBBQUHAQEEVTBTMFEGCCsGAQUFBzAChkVodHRwOi8v
# d3d3Lm1pY3Jvc29mdC5jb20vcGtpb3BzL2NlcnRzL01pY0NvZFNpZ1BDQTIwMTFf
# MjAxMS0wNy0wOC5jcnQwDAYDVR0TAQH/BAIwADANBgkqhkiG9w0BAQsFAAOCAgEA
# TZdPNH7xcJOc49UaS5wRfmsmxKUk9N9E1CS6s2oIiZmayzHncJv/FB2wBzl/5DA7
# EyLeDsiVZ7tufvh8laSQgjeTpoPTSQLBrK1Z75G3p2YADqJMJdTc510HAsooNGU7
# OYOtlSqOyqDoCDoc/j57QEmUTY5UJQrlsccK7nE3xpteNvWnQkT7vIewDcA12SaH
# X/9n7yh094owBBGKZ8xLNWBqIefDjQeDXpurnXEfKSYJEdT1gtPSNgcpruiSbZB/
# AMmoW+7QBGX7oQ5XU8zymInznxWTyAbEY1JhAk9XSBz1+3USyrX59MJpX7uhnQ1p
# gyfrgz4dazHD7g7xxIRDh+4xnAYAMny3IIq5CCPqVrAY1LK9Few37WTTaxUCI8aK
# M4c60Zu2wJZZLKABU4QBX/J7wXqw7NTYUvZfdYFEWRY4J1O7UPNecd/311HcMdUa
# YzUql36fZjdfz1Uz77LKvCwjqkQe7vtnSLToQsMPilFYokYCYSZaGb9clOmoQHDn
# WzBMfIDUUGeipe4O6z218eV5HuH1WBlvu4lteOIgWCX/5Eiz5q/xskAEF0ZQ1Axs
# kRR97sri9ibeGzsEZ1EuD6QX90L/P5GJMfinvLPlOlLcKjN/SmSRZdhlEbbbare0
# bFL8v4txFsQsznOaoOldCMFFRaUphuwBMW1edMZWMQswggYHMIID76ADAgECAgph
# Fmg0AAAAAAAcMA0GCSqGSIb3DQEBBQUAMF8xEzARBgoJkiaJk/IsZAEZFgNjb20x
# GTAXBgoJkiaJk/IsZAEZFgltaWNyb3NvZnQxLTArBgNVBAMTJE1pY3Jvc29mdCBS
# b290IENlcnRpZmljYXRlIEF1dGhvcml0eTAeFw0wNzA0MDMxMjUzMDlaFw0yMTA0
# MDMxMzAzMDlaMHcxCzAJBgNVBAYTAlVTMRMwEQYDVQQIEwpXYXNoaW5ndG9uMRAw
# DgYDVQQHEwdSZWRtb25kMR4wHAYDVQQKExVNaWNyb3NvZnQgQ29ycG9yYXRpb24x
# ITAfBgNVBAMTGE1pY3Jvc29mdCBUaW1lLVN0YW1wIFBDQTCCASIwDQYJKoZIhvcN
# AQEBBQADggEPADCCAQoCggEBAJ+hbLHf20iSKnxrLhnhveLjxZlRI1Ctzt0YTiQP
# 7tGn0UytdDAgEesH1VSVFUmUG0KSrphcMCbaAGvoe73siQcP9w4EmPCJzB/LMySH
# nfL0Zxws/HvniB3q506jocEjU8qN+kXPCdBer9CwQgSi+aZsk2fXKNxGU7CG0OUo
# Ri4nrIZPVVIM5AMs+2qQkDBuh/NZMJ36ftaXs+ghl3740hPzCLdTbVK0RZCfSABK
# R2YRJylmqJfk0waBSqL5hKcRRxQJgp+E7VV4/gGaHVAIhQAQMEbtt94jRrvELVSf
# rx54QTF3zJvfO4OToWECtR0Nsfz3m7IBziJLVP/5BcPCIAsCAwEAAaOCAaswggGn
# MA8GA1UdEwEB/wQFMAMBAf8wHQYDVR0OBBYEFCM0+NlSRnAK7UD7dvuzK7DDNbMP
# MAsGA1UdDwQEAwIBhjAQBgkrBgEEAYI3FQEEAwIBADCBmAYDVR0jBIGQMIGNgBQO
# rIJgQFYnl+UlE/wq4QpTlVnkpKFjpGEwXzETMBEGCgmSJomT8ixkARkWA2NvbTEZ
# MBcGCgmSJomT8ixkARkWCW1pY3Jvc29mdDEtMCsGA1UEAxMkTWljcm9zb2Z0IFJv
# b3QgQ2VydGlmaWNhdGUgQXV0aG9yaXR5ghB5rRahSqClrUxzWPQHEy5lMFAGA1Ud
# HwRJMEcwRaBDoEGGP2h0dHA6Ly9jcmwubWljcm9zb2Z0LmNvbS9wa2kvY3JsL3By
# b2R1Y3RzL21pY3Jvc29mdHJvb3RjZXJ0LmNybDBUBggrBgEFBQcBAQRIMEYwRAYI
# KwYBBQUHMAKGOGh0dHA6Ly93d3cubWljcm9zb2Z0LmNvbS9wa2kvY2VydHMvTWlj
# cm9zb2Z0Um9vdENlcnQuY3J0MBMGA1UdJQQMMAoGCCsGAQUFBwMIMA0GCSqGSIb3
# DQEBBQUAA4ICAQAQl4rDXANENt3ptK132855UU0BsS50cVttDBOrzr57j7gu1BKi
# jG1iuFcCy04gE1CZ3XpA4le7r1iaHOEdAYasu3jyi9DsOwHu4r6PCgXIjUji8FMV
# 3U+rkuTnjWrVgMHmlPIGL4UD6ZEqJCJw+/b85HiZLg33B+JwvBhOnY5rCnKVuKE5
# nGctxVEO6mJcPxaYiyA/4gcaMvnMMUp2MT0rcgvI6nA9/4UKE9/CCmGO8Ne4F+tO
# i3/FNSteo7/rvH0LQnvUU3Ih7jDKu3hlXFsBFwoUDtLaFJj1PLlmWLMtL+f5hYbM
# UVbonXCUbKw5TNT2eb+qGHpiKe+imyk0BncaYsk9Hm0fgvALxyy7z0Oz5fnsfbXj
# pKh0NbhOxXEjEiZ2CzxSjHFaRkMUvLOzsE1nyJ9C/4B5IYCeFTBm6EISXhrIniIh
# 0EPpK+m79EjMLNTYMoBMJipIJF9a6lbvpt6Znco6b72BJ3QGEe52Ib+bgsEnVLax
# aj2JoXZhtG6hE6a/qkfwEm/9ijJssv7fUciMI8lmvZ0dhxJkAj0tr1mPuOQh5bWw
# ymO0eFQF1EEuUKyUsKV4q7OglnUa2ZKHE3UiLzKoCG6gW4wlv6DvhMoh1useT8ma
# 7kng9wFlb4kLfchpyOZu6qeXzjEp/w7FW1zYTRuh2Povnj8uVRZryROj/TCCB3ow
# ggVioAMCAQICCmEOkNIAAAAAAAMwDQYJKoZIhvcNAQELBQAwgYgxCzAJBgNVBAYT
# AlVTMRMwEQYDVQQIEwpXYXNoaW5ndG9uMRAwDgYDVQQHEwdSZWRtb25kMR4wHAYD
# VQQKExVNaWNyb3NvZnQgQ29ycG9yYXRpb24xMjAwBgNVBAMTKU1pY3Jvc29mdCBS
# b290IENlcnRpZmljYXRlIEF1dGhvcml0eSAyMDExMB4XDTExMDcwODIwNTkwOVoX
# DTI2MDcwODIxMDkwOVowfjELMAkGA1UEBhMCVVMxEzARBgNVBAgTCldhc2hpbmd0
# b24xEDAOBgNVBAcTB1JlZG1vbmQxHjAcBgNVBAoTFU1pY3Jvc29mdCBDb3Jwb3Jh
# dGlvbjEoMCYGA1UEAxMfTWljcm9zb2Z0IENvZGUgU2lnbmluZyBQQ0EgMjAxMTCC
# AiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAKvw+nIQHC6t2G6qghBNNLry
# tlghn0IbKmvpWlCquAY4GgRJun/DDB7dN2vGEtgL8DjCmQawyDnVARQxQtOJDXlk
# h36UYCRsr55JnOloXtLfm1OyCizDr9mpK656Ca/XllnKYBoF6WZ26DJSJhIv56sI
# UM+zRLdd2MQuA3WraPPLbfM6XKEW9Ea64DhkrG5kNXimoGMPLdNAk/jj3gcN1Vx5
# pUkp5w2+oBN3vpQ97/vjK1oQH01WKKJ6cuASOrdJXtjt7UORg9l7snuGG9k+sYxd
# 6IlPhBryoS9Z5JA7La4zWMW3Pv4y07MDPbGyr5I4ftKdgCz1TlaRITUlwzluZH9T
# upwPrRkjhMv0ugOGjfdf8NBSv4yUh7zAIXQlXxgotswnKDglmDlKNs98sZKuHCOn
# qWbsYR9q4ShJnV+I4iVd0yFLPlLEtVc/JAPw0XpbL9Uj43BdD1FGd7P4AOG8rAKC
# X9vAFbO9G9RVS+c5oQ/pI0m8GLhEfEXkwcNyeuBy5yTfv0aZxe/CHFfbg43sTUkw
# p6uO3+xbn6/83bBm4sGXgXvt1u1L50kppxMopqd9Z4DmimJ4X7IvhNdXnFy/dygo
# 8e1twyiPLI9AN0/B4YVEicQJTMXUpUMvdJX3bvh4IFgsE11glZo+TzOE2rCIF96e
# TvSWsLxGoGyY0uDWiIwLAgMBAAGjggHtMIIB6TAQBgkrBgEEAYI3FQEEAwIBADAd
# BgNVHQ4EFgQUSG5k5VAF04KqFzc3IrVtqMp1ApUwGQYJKwYBBAGCNxQCBAweCgBT
# AHUAYgBDAEEwCwYDVR0PBAQDAgGGMA8GA1UdEwEB/wQFMAMBAf8wHwYDVR0jBBgw
# FoAUci06AjGQQ7kUBU7h6qfHMdEjiTQwWgYDVR0fBFMwUTBPoE2gS4ZJaHR0cDov
# L2NybC5taWNyb3NvZnQuY29tL3BraS9jcmwvcHJvZHVjdHMvTWljUm9vQ2VyQXV0
# MjAxMV8yMDExXzAzXzIyLmNybDBeBggrBgEFBQcBAQRSMFAwTgYIKwYBBQUHMAKG
# Qmh0dHA6Ly93d3cubWljcm9zb2Z0LmNvbS9wa2kvY2VydHMvTWljUm9vQ2VyQXV0
# MjAxMV8yMDExXzAzXzIyLmNydDCBnwYDVR0gBIGXMIGUMIGRBgkrBgEEAYI3LgMw
# gYMwPwYIKwYBBQUHAgEWM2h0dHA6Ly93d3cubWljcm9zb2Z0LmNvbS9wa2lvcHMv
# ZG9jcy9wcmltYXJ5Y3BzLmh0bTBABggrBgEFBQcCAjA0HjIgHQBMAGUAZwBhAGwA
# XwBwAG8AbABpAGMAeQBfAHMAdABhAHQAZQBtAGUAbgB0AC4gHTANBgkqhkiG9w0B
# AQsFAAOCAgEAZ/KGpZjgVHkaLtPYdGcimwuWEeFjkplCln3SeQyQwWVfLiw++MNy
# 0W2D/r4/6ArKO79HqaPzadtjvyI1pZddZYSQfYtGUFXYDJJ80hpLHPM8QotS0LD9
# a+M+By4pm+Y9G6XUtR13lDni6WTJRD14eiPzE32mkHSDjfTLJgJGKsKKELukqQUM
# m+1o+mgulaAqPyprWEljHwlpblqYluSD9MCP80Yr3vw70L01724lruWvJ+3Q3fMO
# r5kol5hNDj0L8giJ1h/DMhji8MUtzluetEk5CsYKwsatruWy2dsViFFFWDgycSca
# f7H0J/jeLDogaZiyWYlobm+nt3TDQAUGpgEqKD6CPxNNZgvAs0314Y9/HG8VfUWn
# duVAKmWjw11SYobDHWM2l4bf2vP48hahmifhzaWX0O5dY0HjWwechz4GdwbRBrF1
# HxS+YWG18NzGGwS+30HHDiju3mUv7Jf2oVyW2ADWoUa9WfOXpQlLSBCZgB/QACnF
# sZulP0V3HjXG0qKin3p6IvpIlR+r+0cjgPWe+L9rt0uX4ut1eBrs6jeZeRhL/9az
# I2h15q/6/IvrC4DqaTuv/DDtBEyO3991bWORPdGdVk5Pv4BXIqF4ETIheu9BCrE/
# +6jMpF3BoYibV3FWTkhFwELJm3ZbCoBIa/15n8G9bW1qyVJzEw16UM0xggSqMIIE
# pgIBATCBlTB+MQswCQYDVQQGEwJVUzETMBEGA1UECBMKV2FzaGluZ3RvbjEQMA4G
# A1UEBxMHUmVkbW9uZDEeMBwGA1UEChMVTWljcm9zb2Z0IENvcnBvcmF0aW9uMSgw
# JgYDVQQDEx9NaWNyb3NvZnQgQ29kZSBTaWduaW5nIFBDQSAyMDExAhMzAAAAww6b
# p9iy3PcsAAAAAADDMAkGBSsOAwIaBQCggb4wGQYJKoZIhvcNAQkDMQwGCisGAQQB
# gjcCAQQwHAYKKwYBBAGCNwIBCzEOMAwGCisGAQQBgjcCARUwIwYJKoZIhvcNAQkE
# MRYEFKH0y9p/yy9KG2+Y8MCl+yp4fSgwMF4GCisGAQQBgjcCAQwxUDBOoCaAJABN
# AGkAYwByAG8AcwBvAGYAdAAgAEwAZQBhAHIAbgBpAG4AZ6EkgCJodHRwczovL3d3
# dy5taWNyb3NvZnQuY29tLmxlYXJuaW5nMA0GCSqGSIb3DQEBAQUABIIBADrtoBdB
# LmPlhX2VdMwYSCY371x42RGvK8GERGXOUtj7jWZ5nE1jfAWTxXPV1wHMnBfSoW05
# NejrsOUMrr4IQS/+iqlErVhNo8qzAIziJnjeLXRM3DynINZF7hDCisLkJcyI3vDx
# HGxqMCQYXIaMQ19VBR14yBBsX3f+zsfIK6uhF60WzTFH88WabyelRUqKIdMCA8fC
# jcbGlSHr3NkBDBoBMC8CZsePLNw0gWZOvh/6CFELT9MnJ1x0K35355mbstONkxl7
# ArVzUISIxe3DEfTpow5EcGR18rLfSufRckBiNgLmrbxh1PU+8bJcbbK+UfA9yvNe
# 1aUMSvQaGin/tfWhggIoMIICJAYJKoZIhvcNAQkGMYICFTCCAhECAQEwgY4wdzEL
# MAkGA1UEBhMCVVMxEzARBgNVBAgTCldhc2hpbmd0b24xEDAOBgNVBAcTB1JlZG1v
# bmQxHjAcBgNVBAoTFU1pY3Jvc29mdCBDb3Jwb3JhdGlvbjEhMB8GA1UEAxMYTWlj
# cm9zb2Z0IFRpbWUtU3RhbXAgUENBAhMzAAAAwN4sPQeU5El5AAAAAADAMAkGBSsO
# AwIaBQCgXTAYBgkqhkiG9w0BCQMxCwYJKoZIhvcNAQcBMBwGCSqGSIb3DQEJBTEP
# Fw0xNzEyMjYwODI0MzZaMCMGCSqGSIb3DQEJBDEWBBSnk36CNd9lOnO1kjy4/j+u
# WdmLKDANBgkqhkiG9w0BAQUFAASCAQDbTAN5dLMVNWIbE/IZsqy7Uj35v8xjNnCS
# fgaEWiV+m348pDX94LXZ88/kZkq3Lr+aOPKed3+f9dX6/uPeXOIEHGyIXEliOEpp
# hAzbGQU4bP9LElvTO/2MjOTQzeL6LVmu49HHZWVFJcFhWcl9Ln1+Wi6U//FjLODr
# VMbMZ+vA+ypV1SjWOM31eZwOoruSfa75eHQ/r55MKq4psWued5/WYwEvnfA0eJUM
# RyNgyO6NxRklUt56Whx27z38Wno4NE1L9IV9jqtUtnY/UHq0x1CUAsHZIM+2yKI2
# tdO3yMkTTXN8LGguIo+0wASm5PBVUgIewEgyHm7hM5Uh98Pz1uTN
# SIG # End signature block
| MicrosoftLearning/20486-DevelopingASPNETMVCWebApplications | Allfiles/20486C/Mod12/LabFiles/PhotoSharingApplication_12_begin/packages/EntityFramework.6.1.3/tools/install.ps1 | PowerShell | mit | 10,952 |
const stylelint = require('stylelint');
const isStandardSyntaxRule = require('stylelint/lib/utils/isStandardSyntaxRule');
const isStandardSyntaxSelector = require('stylelint/lib/utils/isStandardSyntaxSelector');
const ruleName = 'material/selector-no-deep';
const messages = stylelint.utils.ruleMessages(ruleName, {
expected: selector => `Usage of the /deep/ in "${selector}" is not allowed`,
});
/**
* Stylelint plugin that prevents uses of /deep/ in selectors.
*/
const plugin = stylelint.createPlugin(ruleName, isEnabled => {
return (root, result) => {
if (!isEnabled) return;
root.walkRules(rule => {
if (rule.parent.type === 'rule' &&
isStandardSyntaxRule(rule) &&
isStandardSyntaxSelector(rule.selector) &&
rule.selector.includes('/deep/')) {
stylelint.utils.report({
result,
ruleName,
message: messages.expected(rule.selector),
node: rule
});
}
});
};
});
plugin.ruleName = ruleName;
plugin.messages = messages;
module.exports = plugin;
| ng-fortytwo/ng42 | tools/stylelint/selector-no-deep/index.js | JavaScript | mit | 1,068 |
//
// PMInputAccessoryView.h
// Pinmarker
//
// Created by Kyle Stevens on 1/27/14.
// Copyright (c) 2014 kilovolt42. All rights reserved.
//
@interface PMInputAccessoryView : UIInputView
@property (nonatomic, weak) IBOutlet UICollectionView *collectionView;
@end
| kilovolt42/Pinmarker | Pinmark/PMInputAccessoryView.h | C | mit | 271 |
//
// MRProphecy.cs
//
// Author:
// Steve Jakab <>
//
// Copyright (c) 2014 Steve Jakab
//
// 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.
using System;
using System.Collections.Generic;
using AssemblyCSharp;
namespace PortableRealm
{
public class MRProphecy : MRSpell
{
#region Properties
#endregion
#region Methods
public MRProphecy()
{
}
public MRProphecy(JSONObject data, int index) :
base((JSONObject)data["MRSpell"], index)
{
}
public override void Activate(MRCharacter caster, MRMagicChit magic, MRIColorSource source, List<MRISpellTarget> spellTargets)
{
}
#endregion
#region Members
#endregion
}
} | portablemagicrealm/portablerealm | Assets/Standard Assets (Mobile)/Scripts/Spells/Type 2/MRProphecy.cs | C# | mit | 1,669 |
<?xml version="1.0" encoding="utf-8"?>
<!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>
<title>Rails::Info</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link rel="stylesheet" href="../../css/reset.css" type="text/css" media="screen" />
<link rel="stylesheet" href="../../css/main.css" type="text/css" media="screen" />
<link rel="stylesheet" href="../../css/github.css" type="text/css" media="screen" />
<script src="../../js/jquery-1.3.2.min.js" type="text/javascript" charset="utf-8"></script>
<script src="../../js/jquery-effect.js" type="text/javascript" charset="utf-8"></script>
<script src="../../js/main.js" type="text/javascript" charset="utf-8"></script>
<script src="../../js/highlight.pack.js" type="text/javascript" charset="utf-8"></script>
</head>
<body>
<div class="banner">
<span>Ruby on Rails 4.0.0</span><br />
<h1>
<span class="type">Module</span>
Rails::Info
</h1>
<ul class="files">
<li><a href="../../files/__/__/_rvm/gems/ruby-2_1_2/gems/railties-4_0_0/lib/rails/info_rb.html">/Users/alec/.rvm/gems/ruby-2.1.2/gems/railties-4.0.0/lib/rails/info.rb</a></li>
</ul>
</div>
<div id="bodyContent">
<div id="content">
<!-- Namespace -->
<div class="sectiontitle">Namespace</div>
<ul>
<li>
<span class="type">MODULE</span>
<a href="Info/Gem.html">Rails::Info::Gem</a>
</li>
</ul>
<!-- Method ref -->
<div class="sectiontitle">Methods</div>
<dl class="methods">
<dt>F</dt>
<dd>
<ul>
<li>
<a href="#method-i-framework_version">framework_version</a>,
</li>
<li>
<a href="#method-i-frameworks">frameworks</a>
</li>
</ul>
</dd>
<dt>P</dt>
<dd>
<ul>
<li>
<a href="#method-i-property">property</a>
</li>
</ul>
</dd>
<dt>T</dt>
<dd>
<ul>
<li>
<a href="#method-i-to_html">to_html</a>,
</li>
<li>
<a href="#method-i-to_s">to_s</a>
</li>
</ul>
</dd>
</dl>
<!-- Methods -->
<div class="sectiontitle">Instance Public methods</div>
<div class="method">
<div class="title method-title" id="method-i-framework_version">
<b>framework_version</b>(framework)
<a href="../../classes/Rails/Info.html#method-i-framework_version" name="method-i-framework_version" class="permalink">Link</a>
</div>
<div class="description">
</div>
<div class="sourcecode">
<p class="source-link">
Source:
<a href="javascript:toggleSource('method-i-framework_version_source')" id="l_method-i-framework_version_source">show</a>
</p>
<div id="method-i-framework_version_source" class="dyn-source">
<pre><span class="ruby-comment"># File ../../.rvm/gems/ruby-2.1.2/gems/railties-4.0.0/lib/rails/info.rb, line 29</span>
<span class="ruby-keyword">def</span> <span class="ruby-keyword ruby-title">framework_version</span>(<span class="ruby-identifier">framework</span>)
<span class="ruby-keyword">if</span> <span class="ruby-constant">Object</span>.<span class="ruby-identifier">const_defined?</span>(<span class="ruby-identifier">framework</span>.<span class="ruby-identifier">classify</span>)
<span class="ruby-identifier">require</span> <span class="ruby-node">"#{framework}/version"</span>
<span class="ruby-identifier">framework</span>.<span class="ruby-identifier">classify</span>.<span class="ruby-identifier">constantize</span>.<span class="ruby-identifier">version</span>.<span class="ruby-identifier">to_s</span>
<span class="ruby-keyword">end</span>
<span class="ruby-keyword">end</span></pre>
</div>
</div>
</div>
<div class="method">
<div class="title method-title" id="method-i-frameworks">
<b>frameworks</b>()
<a href="../../classes/Rails/Info.html#method-i-frameworks" name="method-i-frameworks" class="permalink">Link</a>
</div>
<div class="description">
</div>
<div class="sourcecode">
<p class="source-link">
Source:
<a href="javascript:toggleSource('method-i-frameworks_source')" id="l_method-i-frameworks_source">show</a>
</p>
<div id="method-i-frameworks_source" class="dyn-source">
<pre><span class="ruby-comment"># File ../../.rvm/gems/ruby-2.1.2/gems/railties-4.0.0/lib/rails/info.rb, line 25</span>
<span class="ruby-keyword">def</span> <span class="ruby-keyword ruby-title">frameworks</span>
<span class="ruby-node">%w( active_record action_pack action_mailer active_support )</span>
<span class="ruby-keyword">end</span></pre>
</div>
</div>
</div>
<div class="method">
<div class="title method-title" id="method-i-property">
<b>property</b>(name, value = nil)
<a href="../../classes/Rails/Info.html#method-i-property" name="method-i-property" class="permalink">Link</a>
</div>
<div class="description">
</div>
<div class="sourcecode">
<p class="source-link">
Source:
<a href="javascript:toggleSource('method-i-property_source')" id="l_method-i-property_source">show</a>
</p>
<div id="method-i-property_source" class="dyn-source">
<pre><span class="ruby-comment"># File ../../.rvm/gems/ruby-2.1.2/gems/railties-4.0.0/lib/rails/info.rb, line 19</span>
<span class="ruby-keyword">def</span> <span class="ruby-keyword ruby-title">property</span>(<span class="ruby-identifier">name</span>, <span class="ruby-identifier">value</span> = <span class="ruby-keyword">nil</span>)
<span class="ruby-identifier">value</span> <span class="ruby-operator">||=</span> <span class="ruby-keyword">yield</span>
<span class="ruby-identifier">properties</span> <span class="ruby-operator"><<</span> [<span class="ruby-identifier">name</span>, <span class="ruby-identifier">value</span>] <span class="ruby-keyword">if</span> <span class="ruby-identifier">value</span>
<span class="ruby-keyword">rescue</span> <span class="ruby-constant">Exception</span>
<span class="ruby-keyword">end</span></pre>
</div>
</div>
</div>
<div class="method">
<div class="title method-title" id="method-i-to_html">
<b>to_html</b>()
<a href="../../classes/Rails/Info.html#method-i-to_html" name="method-i-to_html" class="permalink">Link</a>
</div>
<div class="description">
</div>
<div class="sourcecode">
<p class="source-link">
Source:
<a href="javascript:toggleSource('method-i-to_html_source')" id="l_method-i-to_html_source">show</a>
</p>
<div id="method-i-to_html_source" class="dyn-source">
<pre><span class="ruby-comment"># File ../../.rvm/gems/ruby-2.1.2/gems/railties-4.0.0/lib/rails/info.rb, line 48</span>
<span class="ruby-keyword">def</span> <span class="ruby-keyword ruby-title">to_html</span>
<span class="ruby-string">'<table>'</span>.<span class="ruby-identifier">tap</span> <span class="ruby-keyword">do</span> <span class="ruby-operator">|</span><span class="ruby-identifier">table</span><span class="ruby-operator">|</span>
<span class="ruby-identifier">properties</span>.<span class="ruby-identifier">each</span> <span class="ruby-keyword">do</span> <span class="ruby-operator">|</span>(<span class="ruby-identifier">name</span>, <span class="ruby-identifier">value</span>)<span class="ruby-operator">|</span>
<span class="ruby-identifier">table</span> <span class="ruby-operator"><<</span> <span class="ruby-node">%Q(<tr><td class="name">#{CGI.escapeHTML(name.to_s)}</td>)</span>
<span class="ruby-identifier">formatted_value</span> = <span class="ruby-keyword">if</span> <span class="ruby-identifier">value</span>.<span class="ruby-identifier">kind_of?</span>(<span class="ruby-constant">Array</span>)
<span class="ruby-string">"<ul>"</span> <span class="ruby-operator">+</span> <span class="ruby-identifier">value</span>.<span class="ruby-identifier">map</span> { <span class="ruby-operator">|</span><span class="ruby-identifier">v</span><span class="ruby-operator">|</span> <span class="ruby-node">"<li>#{CGI.escapeHTML(v.to_s)}</li>"</span> }.<span class="ruby-identifier">join</span> <span class="ruby-operator">+</span> <span class="ruby-string">"</ul>"</span>
<span class="ruby-keyword">else</span>
<span class="ruby-constant">CGI</span>.<span class="ruby-identifier">escapeHTML</span>(<span class="ruby-identifier">value</span>.<span class="ruby-identifier">to_s</span>)
<span class="ruby-keyword">end</span>
<span class="ruby-identifier">table</span> <span class="ruby-operator"><<</span> <span class="ruby-node">%Q(<td class="value">#{formatted_value}</td></tr>)</span>
<span class="ruby-keyword">end</span>
<span class="ruby-identifier">table</span> <span class="ruby-operator"><<</span> <span class="ruby-string">'</table>'</span>
<span class="ruby-keyword">end</span>
<span class="ruby-keyword">end</span></pre>
</div>
</div>
</div>
<div class="method">
<div class="title method-title" id="method-i-to_s">
<b>to_s</b>()
<a href="../../classes/Rails/Info.html#method-i-to_s" name="method-i-to_s" class="permalink">Link</a>
</div>
<div class="description">
</div>
<div class="sourcecode">
<p class="source-link">
Source:
<a href="javascript:toggleSource('method-i-to_s_source')" id="l_method-i-to_s_source">show</a>
</p>
<div id="method-i-to_s_source" class="dyn-source">
<pre><span class="ruby-comment"># File ../../.rvm/gems/ruby-2.1.2/gems/railties-4.0.0/lib/rails/info.rb, line 36</span>
<span class="ruby-keyword">def</span> <span class="ruby-keyword ruby-title">to_s</span>
<span class="ruby-identifier">column_width</span> = <span class="ruby-identifier">properties</span>.<span class="ruby-identifier">names</span>.<span class="ruby-identifier">map</span> {<span class="ruby-operator">|</span><span class="ruby-identifier">name</span><span class="ruby-operator">|</span> <span class="ruby-identifier">name</span>.<span class="ruby-identifier">length</span>}.<span class="ruby-identifier">max</span>
<span class="ruby-identifier">info</span> = <span class="ruby-identifier">properties</span>.<span class="ruby-identifier">map</span> <span class="ruby-keyword">do</span> <span class="ruby-operator">|</span><span class="ruby-identifier">name</span>, <span class="ruby-identifier">value</span><span class="ruby-operator">|</span>
<span class="ruby-identifier">value</span> = <span class="ruby-identifier">value</span>.<span class="ruby-identifier">join</span>(<span class="ruby-string">", "</span>) <span class="ruby-keyword">if</span> <span class="ruby-identifier">value</span>.<span class="ruby-identifier">is_a?</span>(<span class="ruby-constant">Array</span>)
<span class="ruby-node">"%-#{column_width}s %s"</span> <span class="ruby-operator">%</span> [<span class="ruby-identifier">name</span>, <span class="ruby-identifier">value</span>]
<span class="ruby-keyword">end</span>
<span class="ruby-identifier">info</span>.<span class="ruby-identifier">unshift</span> <span class="ruby-string">"About your application's environment"</span>
<span class="ruby-identifier">info</span> <span class="ruby-operator">*</span> <span class="ruby-string">"\n"</span>
<span class="ruby-keyword">end</span></pre>
</div>
</div>
</div>
</div>
</div>
</body>
</html> | alombardo4/Agendue | AgendueWeb/doc/api/classes/Rails/Info.html | HTML | mit | 14,069 |
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript" src="setactiontarget.js">
</script>
</head>
<body>
<form name="input" action="" method="get">
<b>Operation:</b>
<input type="text" name="OPERATION" value="DELETEREPOSITORY" size="50">
<p> Version:
<input type="text" name="VERSION" value="1.0.0" size="10">
<p> Locale:
<input type="text" name="LOCALE" value="en" size="10">
<p> Client Agent:
<input type="text" name="CLIENTAGENT" value="MapGuide Developer" size="100">
<p> Resource ID:
<input type="text" name="RESOURCEID" value="Session:ABC123//" size="100">
<p>
<input type="submit" value="Submit" onclick="SetActionTarget()"> <input type="reset">
</form>
</body>
</html>
| jumpinjackie/mapguide4j | internal/MapAgentForms/deleterepositoryform.html | HTML | mit | 736 |
const apiKey = process.env.AIRTABLE_KEY
const base = process.env.AIRTABLE_LAYOUT_BASE
const table = process.env.AIRTABLE_LAYOUT_TABLE
const view = process.env.AIRTABLE_LAYOUT_VIEW
var Airtable = require('airtable-node')
var Raven = require('raven');
const getRecords = () => {
try {
var airtable = new Airtable({base, table, view, apiKey}, 800)
return airtable.list()
} catch(e) {
Raven.captureException(e);
}
}
module.exports = getRecords | focuswish/scheduletext | src/server/layout/getRecords.js | JavaScript | mit | 459 |
---
title: Pretty Monsters
written_by:
available: 'June 10th, 2010'
isbn: '9780142416723'
binding: Paperback
link_to_buy_page:
image_path: 'https://images.booksense.com/images/723/416/9780142416723.jpg'
link:
---
The crossover literary sensation...now in paperback
<br>Through the lens of Kelly Link's vivid imagination, nothing is what it seems, and everything deserves a second look. From the multiple award- winning "The Faery Handbag," in which a teenager's grandmother carries an entire village (or is it a man-eating dog?) in her handbag, to the near-future of "The Surfer," whose narrator (a soccer-playing skeptic) waits with a planeload of refugees for the aliens to arrive, these ten stories are funny and full of unexpected insights and skewed perspectives on the world. Kelly Link's fans range from Michael Chabon to Peter Buck of R.E.M. to Holly Black of Spiderwick Chronicles fame. Now teens can have their world rocked too. | Frontmatter/brooklinebooksmith | _books/pretty-monsters.md | Markdown | mit | 946 |
FROM alpine:3.3
MAINTAINER JJ Buckley <[email protected]>
LABEL Description="A minimal vanilla NginX image"
RUN apk add --no-cache nginx curl
COPY nginx.conf /etc/nginx
VOLUME ["/etc/nginx/conf.d", "/var/www", "/etc/nginx/certs"]
EXPOSE 80 443
CMD nginx
| bjjb/dockerfiles | nginx/Dockerfile | Dockerfile | mit | 248 |
class UseBraces
{
void f() { }
void g() { }
void h() { }
void test(boolean bb)
{
int x = 0, y;
int[] branches = new int[10];
// If-then statement
if(1==1)
{
f();
}
g(); // No alert
if(1==1)
f();
g(); // No alert
if(1==1)
f();
g(); // Alert
if(1==1)
f(); g(); // Alert
// If-then-else statement
if (1 + 2 == 3)
{
f();
}
else
{
g();
}
g(); // No alert
if(1==2)
f();
else
g();
f(); // No alert
if(true)
{
f();
}
else
f();
g(); // Alert
if(true)
{
f();
}
else
f(); g(); // Alert
// While statement
while(bb)
{
f();
}
g(); // No alert
while(bb)
f();
g();
while(bb )
f();
g(); // Alert
g(); // No alert
while(bb )
f(); g(); // Alert
while(bb)
if (x != 0) x = 1;
// Do-while statement
do
f();
while(false);
g(); // No alert
// For statement
for(int i=0; i<10; ++i)
{
f();
}
g();
for(int i=0; i<10; ++i)
f();
g();
for(int i=0; i<10; ++i)
f();
g(); // Alert
for(int i=0; i<10; ++i)
f(); g(); // Alert
// Foreach statement
for( int b : branches)
x += b;
f();
for( int b : branches)
{
x += b;
}
f();
for( int b : branches)
f();
g(); // Alert
for( int b : branches)
f(); g(); // Alert
// Nested ifs
if( true )
if(false)
f();
g(); // No alert
if( true )
if(false)
f();
g(); // Alert
if( true )
;
else
if (false)
f();
g(); // No alert
if( true )
;
else
if (false)
f();
g(); // false negative
if( true )
;
else if (false)
f();
g(); // Alert
// Nested combinations
if (true)
while (x<10)
f();
g(); // No alert
if (true)
while (x<10)
f();
g(); // Alert
while (x<10)
if (true)
f();
g(); // No alert
while (x<10)
if (true)
f();
g(); // Alert
if (true)
f();
class C {} // No alert
if (true)
f();
g(); // No alert
}
}
| github/codeql | java/ql/test/query-tests/UseBraces/UseBraces.java | Java | mit | 2,067 |
<html>
<html
xmlns="http://www.w3.org/1999/xhtml"
xmlns:vtex="http://www.vtex.com.br/2009/vtex-common"
xmlns:vtex.cmc="http://www.vtex.com.br/2009/vtex-commerce"
lang="en-us" class="light-rounded palette1 colorful night light jabuti sandwich"
>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Controles Vtex</title>
</head>
<body>
<div>
<h2>Bread Crumb</h2>
<p>Funciona apenas nas páginas de Produto, Departamento, Categoria e Busca.</p>
<vtex.cmc:breadCrumb />
</div>
<div>
<h2>Busca Total</h2>
<vtex.cmc:fullTextSearchBox/>
</div>
<div>
<h2>Histórico de Navegação</h2>
<p>Utilizado apenas para compor o conteúdo dos controles </p>
<vtex.cmc:navigationHistory/>
</div>
<div>
<h2>Localizador de Lojas </h2>
<p>Requisitos: Cadastrar no ADMIN as Lojas Físicas e seus endereços. Além disso, pesquisar cada endereço no Google Maps e preencher os devidos campos. Necessário configurar no banco de conexão da Loja a chave do Google Maps adquirida pela Loja.</p>
<vtex.cmc:storeFlagLocator/>
</div>
<div>
<h2>Mensagem de Boas Vindas </h2>
<p>No admin, na aba Configurações > Textos, é possível alterar a frase de Bem vindo.</p>
<vtex.cmc:welcomeMessage/>
</div>
<div>
<h2>Links de Departamentos</h2>
<p>Apresenta o primeiro nível de categorias criado no Admin. Necessário configurar no Departamento que o mesmo será apresentado no Menu Superior.</p>
<vtex.cmc:departmentLinks/>
</div>
<div>
<h2>Menu de Departamentos</h2>
<p>Os Departamentos e Categorias são apresentadas de acordo com o cadastro dos 1º e 2º Níveis. Para exibir o Link “Lista Completa”, também é necessário uma configuração nas Categorias Ativas do Departamento.</p>
<vtex.cmc:departmentNavigator/>
</div>
<div>
<h2> Título da Página </h2>
<p>Exibe o título das páginas de Departamento, Categoria e Busca.</p>
<vtex.cmc:searchTitle />
</div>
<div>
<h2>Espiar (QuickView) </h2>
<p>Controle deve ser adicionado antes do fechamento da tag body do template de página de Quickview. Ele é fundamental para o carregamento dos arquivos necessários da página.</p>
<vtex.cmc:productQuickView/>
</div>
<div>
<h2>Prateleira</h2>
<vtex.cmc:ProductQueryStringReferenceShelf layout="e2ed81f5-6241-4418-a47b-018d7482fcf0" itemCount="3" columnCount="3" showUnavailable="true" isTrackable="true" InternalCampaign="Destaque landing" InternalPart="Prateleira destaque" />
</div>
</body>
</html>
| jomarcardoso/vtex | src/arquivos/componentes/controles-vtex.html | HTML | mit | 2,657 |
---
layout: post
title: Party Recruit (Web)
date: 2014-07-11 12:00:00
tags: [Web, Ruby on Rails, Location Based, SNS]
categories: [Draft]
comments: true
excerpt: "Location-based SNS inspired from party recruiting system in online games"
image:
feature: party-recruit-mockup.png
---
{: .feature-image }
#### Location-based Instant Event Planning SNS
* Designed and built a web service similar to party recruitment system in online games.
* Based on [Ruby on Rails](http://rubyonrails.org) framework with [PostgreSQL](http://www.postgresql.org)
* Implemented Map-based party with [Google Maps API](https://developers.google.com/maps/) and [Bootstrap](http://getbootstrap.com).
* Learned Web MVC pattern with Ruby on Rails framework and cloud platforms with using [Heroku](https://www.heroku.com)
* Demo available on [here](http://partyrecruit.herokuapp.com/) | rokoroku/rokoroku.github.io | _works/Party-Recruit.md | Markdown | mit | 921 |
# kdine.github.io | Kdine/kdine.github.io | README.md | Markdown | mit | 17 |
//------------------------------------------------------------------------------
// <auto-generated>
// 此代码由工具生成。
// 运行时版本:4.0.30319.34014
//
// 对此文件的更改可能会导致不正确的行为,并且如果
// 重新生成代码,这些更改将会丢失。
// </auto-generated>
//------------------------------------------------------------------------------
namespace HolyLight.Properties {
using System;
/// <summary>
/// 一个强类型的资源类,用于查找本地化的字符串等。
/// </summary>
// 此类是由 StronglyTypedResourceBuilder
// 类通过类似于 ResGen 或 Visual Studio 的工具自动生成的。
// 若要添加或移除成员,请编辑 .ResX 文件,然后重新运行 ResGen
// (以 /str 作为命令选项),或重新生成 VS 项目。
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Resources {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources() {
}
/// <summary>
/// 返回此类使用的缓存的 ResourceManager 实例。
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("HolyLight.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// 使用此强类型资源类,为所有资源查找
/// 重写当前线程的 CurrentUICulture 属性。
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
}
}
| SASUKE40/HolyLight | HolyLight/Properties/Resources.Designer.cs | C# | mit | 2,795 |
<?php
namespace Aviogram\Common\PHPClass\Element;
use Aviogram\Common\PHPClass\ClassFile;
use Aviogram\Common\PHPClass\ElementInterface;
use Aviogram\Common\PHPClass\ScopeInterface;
use Aviogram\Common\PHPClass\ScopeTrait;
class Property implements ElementInterface, ScopeInterface
{
use ScopeTrait;
/**
* @var string
*/
protected $name;
/**
* @var string
*/
protected $default;
/**
* @var DocBlock
*/
protected $docBlock;
/**
* @param ClassFile $classFile
* @param string $name The name of the property
* @param string $scope The scope of the property. See self::SCOPE_*
* @param string|null $default The default value. Should be a string, when you a text as default use ''
*
* @throws \Aviogram\Common\PHPClass\Exception\Scope
*/
public function __construct(ClassFile $classFile, $name, $scope = self::SCOPE_PROTECTED, $default = null)
{
$this->name = $name;
$this->default = $default;
$this->docBlock = new DocBlock($classFile);
$this->setScope($scope);
}
/**
* @return DocBlock
*/
public function getDocBlock()
{
return $this->docBlock;
}
/**
* Convert element to a PHP string
*
* @return string
*/
public function __toString()
{
$string = "{$this->getDocBlock()}";
if ($string !== '') {
$string .= "\n";
}
$string .= "{$this->getScope()} \${$this->name}";
if ($this->default !== null) {
$string .= " = {$this->default}";
}
return "{$string};";
}
}
| Aviogram/Common | src/PHPClass/Element/Property.php | PHP | mit | 1,681 |
module Parser where
import Text.Parsec
import Text.Parsec.String
import Control.Monad (void)
import Arith
boolTrue :: Parser Term
boolTrue = do
void $ string "T" <* spaces
return TmTrue
boolFalse :: Parser Term
boolFalse = do
void $ string "F" <* spaces
return TmFalse
ifThen :: Parser Term
ifThen = do
void $ string "if" <* spaces
b <- expr
void $ spaces *> string "then" <* spaces
t1 <- expr
void $ spaces *> string "else" <* spaces
t2 <- expr
return $ TmIf b t1 t2
succ' :: Parser Term
succ' = do
void $ string "S" <* spaces
t1 <- expr
return $ TmSucc t1
isZero :: Parser Term
isZero = do
void $ string "Z?" <* spaces
t1 <- expr
return $ TmIsZero t1
zero :: Parser Term
zero = do
void $ string "Z" <* spaces
return TmZero
expr :: Parser Term
expr = try boolFalse
<|> try boolTrue
<|> ifThen
<|> succ'
<|> try isZero
<|> zero
modl :: Parser [Term]
modl = many expr
contents :: Parser a -> Parser a
contents p = do
r <- p
eof
return r
parseProgram :: SourceName -> String -> Either ParseError [Term]
parseProgram = parse (contents modl)
| kellino/TypeSystems | arith/Parser.hs | Haskell | mit | 1,155 |
A positivity filter for Tweetbot in the morning.
## Warning
This Tweetbot «plugin» is nothing, but a huge set of dirty and unstable hacks.
Don't use it (^^,).
## Usage
Quit `Tweetbot.app` if it was launched and do the following:
```bash
$ git clone https://github.com/rodionovd/ABetterPlaceForTweetbot.git
$ cd ./ABetterPlaceForTweetbot
$ rake
```
This will build and run Tweetbot with all the filters applied.
To rebuild a library:
```bash
$ rake clean
$ rake
```
## In case of emergency
Just quit the app and launch original Tweetbot.
## Credits
Original idea by @Jonty: [`abetterplace`](https://github.com/Jonty/abetterplace).
A Tweetbot plugin idea was stolen from @orta: https://twitter.com/orta/status/554968403040288768.
-----
Dmitry Rodionov, 2014
[email protected]
| rodionovd/ABetterPlaceForTweetbot | README.md | Markdown | mit | 832 |
<?php
namespace Incenteev\DynamicParametersBundle\DependencyInjection;
use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;
class Configuration implements ConfigurationInterface
{
public function getConfigTreeBuilder()
{
$treeBuilder = new TreeBuilder();
$treeBuilder->root('incenteev_dynamic_parameters')
->fixXmlConfig('parameter')
->children()
->booleanNode('import_parameter_handler_map')->defaultFalse()->end()
->scalarNode('composer_file')
->defaultValue('%kernel.root_dir%/../composer.json')
->cannotBeEmpty()
->info('The path to the composer.json file to load the ParameterHandler env-map')
->end()
->arrayNode('parameters')
->useAttributeAsKey('name')
->prototype('array')
->beforeNormalization()
->ifString()
->then(function ($v) {
return array('variable' => $v);
})
->end()
->children()
->scalarNode('variable')->isRequired()->cannotBeEmpty()->end()
->booleanNode('yaml')->defaultFalse()->end()
->end()
->end()
->end()
->end();
return $treeBuilder;
}
}
| Incenteev/DynamicParametersBundle | src/DependencyInjection/Configuration.php | PHP | mit | 1,580 |
using System;
using System.Text;
using TV.Core.Log;
namespace TV.CoreImpl.Log
{
internal class LogMessageGenerator : ILogMessageGenerator
{
public string GenerateMessag(LogLevel level, object sender, string message)
{
_logMessageBuilder.Length = 0;
_logMessageBuilder.Append(GetLevelString(level));
_logMessageBuilder.Append(": [");
_logMessageBuilder.Append(String.Format("{0:MM/dd/yyy hh:mm:ss.fff}", DateTime.Now));
_logMessageBuilder.Append("] - [");
if (sender != null)
{
_logMessageBuilder.Append(sender.GetType().FullName);
}
else
{
_logMessageBuilder.Append("null");
}
_logMessageBuilder.Append("] - ");
_logMessageBuilder.Append(message);
return _logMessageBuilder.ToString();
}
private string GetLevelString(LogLevel level)
{
switch (level)
{
case LogLevel.Debug:
return "Debug";
case LogLevel.Info:
return "Info";
case LogLevel.Warning:
return "Warning";
case LogLevel.Error:
return "Error";
case LogLevel.Critical:
return "Critical";
}
throw new AggregateException(string.Format("Unknown LogLevel type {0}", level));
}
private readonly StringBuilder _logMessageBuilder = new StringBuilder(256);
}
} | jruncik/Tiskarna | TV.CoreImpl/Log/LogMessageGenerator.cs | C# | mit | 1,616 |
(function() {
module("tinymce.plugins.Table", {
setupModule: function() {
QUnit.stop();
tinymce.init({
selector: "textarea",
add_unload_trigger: false,
skin: false,
indent: false,
plugins: 'table',
valid_styles: {
'*' : 'width,height,vertical-align,text-align,float,border-color,background-color,border,padding,border-spacing,border-collapse'
},
init_instance_callback: function(ed) {
window.editor = ed;
QUnit.start();
}
});
},
teardown: function() {
var win = Utils.getFrontmostWindow();
if (win) {
win.close();
}
delete editor.settings.table_advtab;
delete editor.settings.table_cell_advtab;
delete editor.settings.table_class_list;
delete editor.settings.table_cell_class_list;
delete editor.settings.table_row_class_list;
delete editor.settings.table_style_by_css;
editor.off('newcell newrow');
}
});
function fillAndSubmitWindowForm(data) {
var win = Utils.getFrontmostWindow();
win.fromJSON(data);
win.find('form')[0].submit();
win.close();
}
function testCommand(command, tests) {
tinymce.util.Tools.each(tests, function (test) {
editor.getBody().innerHTML = test.before;
editor.selection.select(editor.dom.select('td[data-mce-selected]')[0], true);
editor.selection.collapse(true);
editor.execCommand(command);
equal(cleanTableHtml(editor.getContent()), test.after, test.message);
});
}
function cleanTableHtml(html) {
return Utils.cleanHtml(html).replace(/<p>( |<br[^>]+>)<\/p>$/, '');
}
test("Table properties dialog (get data from plain table)", function() {
editor.setContent('<table><tr><td>X</td></tr></table>');
Utils.setSelection('td', 0);
editor.execCommand('mceTableProps');
deepEqual(Utils.getFrontmostWindow().toJSON(), {
"align": "",
"border": "",
"caption": false,
"cellpadding": "",
"cellspacing": "",
"height": "",
"width": "",
"backgroundColor": "",
"borderColor": "",
"style": ""
});
});
test("Table properties dialog (get/set data from/to plain table, no adv tab)", function() {
editor.settings.table_advtab = false;
editor.setContent('<table><tr><td>X</td></tr></table>');
Utils.setSelection('td', 0);
editor.execCommand('mceTableProps');
deepEqual(Utils.getFrontmostWindow().toJSON(), {
"align": "",
"border": "",
"caption": false,
"cellpadding": "",
"cellspacing": "",
"height": "",
"width": ""
});
fillAndSubmitWindowForm({
width: "100",
height: "101"
});
equal(
cleanTableHtml(editor.getContent()),
'<table style="width: 100px; height: 101px;"><tbody><tr><td>x</td></tr></tbody></table>'
);
});
test("Table properties dialog (get/set data from/to plain table, class list)", function() {
editor.settings.table_class_list = [{title: 'Class1', value: 'class1'}];
editor.setContent('<table><tr><td>X</td></tr></table>');
Utils.setSelection('td', 0);
editor.execCommand('mceTableProps');
deepEqual(Utils.getFrontmostWindow().toJSON(), {
"align": "",
"border": "",
"caption": false,
"cellpadding": "",
"cellspacing": "",
"height": "",
"width": "",
"backgroundColor": "",
"borderColor": "",
"style": "",
"class": ""
});
fillAndSubmitWindowForm({
width: "100",
height: "101"
});
equal(
cleanTableHtml(editor.getContent()),
'<table style="width: 100px; height: 101px;"><tbody><tr><td>x</td></tr></tbody></table>'
);
});
test("Table properties dialog (get data from full table)", function() {
editor.setContent(
'<table style="width: 100px; height: 101px;" border="4" cellspacing="2" cellpadding="3">' +
'<caption> </caption>' +
'<tbody>' +
'<tr>' +
'<td> </td>' +
'</tr>' +
'</tbody>' +
'</table>'
);
Utils.setSelection('td', 0);
editor.execCommand('mceTableProps');
deepEqual(Utils.getFrontmostWindow().toJSON(), {
"align": "",
"border": "4",
"caption": true,
"cellpadding": "3",
"cellspacing": "2",
"height": "101",
"width": "100",
"backgroundColor": "",
"borderColor": "",
"style": "width: 100px; height: 101px;"
});
});
test("Table properties dialog (add caption)", function() {
editor.setContent('<table><tr><td>X</td></tr></table>');
Utils.setSelection('td', 0);
editor.execCommand('mceTableProps');
fillAndSubmitWindowForm({
caption: true
});
equal(
cleanTableHtml(editor.getContent()),
'<table><caption> </caption><tbody><tr><td>x</td></tr></tbody></table>'
);
});
test("Table properties dialog (remove caption)", function() {
editor.setContent('<table><caption> </caption><tr><td>X</td></tr></table>');
Utils.setSelection('td', 0);
editor.execCommand('mceTableProps');
fillAndSubmitWindowForm({
caption: false
});
equal(
cleanTableHtml(editor.getContent()),
'<table><tbody><tr><td>x</td></tr></tbody></table>'
);
});
test("Table properties dialog (change size in pixels)", function() {
editor.setContent('<table><tr><td>X</td></tr></table>');
Utils.setSelection('td', 0);
editor.execCommand('mceTableProps');
fillAndSubmitWindowForm({
width: 100,
height: 101
});
equal(
cleanTableHtml(editor.getContent()),
'<table style="width: 100px; height: 101px;"><tbody><tr><td>x</td></tr></tbody></table>'
);
});
test("Table properties dialog (change size in %)", function() {
editor.setContent('<table><tr><td>X</td></tr></table>');
Utils.setSelection('td', 0);
editor.execCommand('mceTableProps');
fillAndSubmitWindowForm({
width: "100%",
height: "101%"
});
equal(
cleanTableHtml(editor.getContent()),
'<table style="width: 100%; height: 101%;"><tbody><tr><td>x</td></tr></tbody></table>'
);
});
test("Table properties dialog (change: border,cellpadding,cellspacing,align,backgroundColor,borderColor)", function() {
editor.setContent('<table style="border-color: red; background-color: blue"><tr><td>X</td></tr></table>');
Utils.setSelection('td', 0);
editor.execCommand('mceTableProps');
fillAndSubmitWindowForm({
border: "1",
cellpadding: "2",
cellspacing: "3",
align: "right"
});
equal(
cleanTableHtml(editor.getContent()),
'<table style="float: right; border-color: red; background-color: blue;" border="1" cellspacing="3" cellpadding="2"><tbody><tr><td>x</td></tr></tbody></table>'
);
});
test("Table properties dialog css border", function() {
editor.settings.table_style_by_css = true;
editor.setContent('<table><tr><td>X</td><td>Z</td></tr></table>');
Utils.setSelection('td', 0);
editor.execCommand('mceTableProps');
fillAndSubmitWindowForm({
border: "1px solid green"
});
equal(
cleanTableHtml(editor.getContent()),
'<table style=\"border: 1px solid green;\"><tbody><tr><td style=\"border: 1px solid green;\">x</td><td style=\"border: 1px solid green;\">z</td></tr></tbody></table>'
);
});
test("Table properties dialog css cell padding", function() {
editor.settings.table_style_by_css = true;
editor.setContent('<table><tr><td>X</td><td>Z</td></tr></table>');
Utils.setSelection('td', 0);
editor.execCommand('mceTableProps');
fillAndSubmitWindowForm({
cellpadding: "2"
});
equal(
cleanTableHtml(editor.getContent()),
'<table><tbody><tr><td style=\"padding: 2px;\">x</td><td style=\"padding: 2px;\">z</td></tr></tbody></table>'
);
});
test("Table properties dialog cell spacing", function() {
editor.settings.table_style_by_css = true;
editor.setContent('<table><tr><td>X</td><td>Z</td></tr></table>');
Utils.setSelection('td', 0);
editor.execCommand('mceTableProps');
fillAndSubmitWindowForm({
cellspacing: "3"
});
equal(
cleanTableHtml(editor.getContent()),
'<table style=\"border-spacing: 3px;\"><tbody><tr><td>x</td><td>z</td></tr></tbody></table>'
);
});
test("Table properties dialog border-color", function() {
editor.settings.table_style_by_css = true;
editor.setContent('<table><tr><td>X</td><td>Z</td></tr></table>');
Utils.setSelection('td', 0);
editor.execCommand('mceTableProps');
fillAndSubmitWindowForm({
borderColor: "green"
});
equal(
cleanTableHtml(editor.getContent()),
'<table style=\"border-color: green;\"><tbody><tr><td>x</td><td>z</td></tr></tbody></table>'
);
});
test("Table properties dialog css border, style", function() {
editor.settings.table_style_by_css = true;
editor.setContent('<table><tr><td>X</td><td>Z</td></tr></table>');
Utils.setSelection('td', 0);
editor.execCommand('mceTableProps');
fillAndSubmitWindowForm({
border: "1px solid green",
style: "border-collapse: collapse"
});
equal(
cleanTableHtml(editor.getContent()),
'<table style=\"border: 1px solid green; border-collapse: collapse;\"><tbody><tr><td style=\"border: 1px solid green;\">x</td><td style=\"border: 1px solid green;\">z</td></tr></tbody></table>'
);
});
test("Table properties dialog (get cell padding from styled cells)", function() {
editor.settings.table_style_by_css = true;
editor.setContent('<table><tr><td style="padding: 5px">X</td></tr><tr><td style="padding: 5px">X</td></tr></table>' +
'<table><tr><td style="padding: 15px">X</td></tr><tr><td style="padding: 15px">X</td></tr></table>');
Utils.setSelection('td', 0);
editor.execCommand('mceTableProps');
deepEqual(Utils.getFrontmostWindow().toJSON(), {
"align": "",
"backgroundColor": "",
"border": "",
"borderColor": "",
"caption": false,
"cellpadding": "5px",
"cellspacing": "",
"height": "",
"style": "",
"width": ""
});
});
test("Table cell properties dialog (get data from plain cell)", function() {
editor.setContent('<table><tr><td>X</td></tr></table>');
Utils.setSelection('td', 0);
editor.execCommand('mceTableCellProps');
deepEqual(Utils.getFrontmostWindow().toJSON(), {
"align": "",
"valign": "",
"height": "",
"scope": "",
"type": "td",
"width": "",
"backgroundColor": "",
"borderColor": "",
"style": ""
});
});
test("Table cell properties dialog (get/set data from/to plain cell, no adv tab)", function() {
editor.settings.table_cell_advtab = false;
editor.setContent('<table><tr><td>X</td></tr></table>');
Utils.setSelection('td', 0);
editor.execCommand('mceTableCellProps');
deepEqual(Utils.getFrontmostWindow().toJSON(), {
"align": "",
"valign": "",
"height": "",
"scope": "",
"type": "td",
"width": ""
});
fillAndSubmitWindowForm({
width: 100,
height: 101
});
equal(
cleanTableHtml(editor.getContent()),
'<table><tbody><tr><td style="width: 100px; height: 101px;">x</td></tr></tbody></table>'
);
});
test("Table cell properties dialog (get data from complex cell)", function() {
editor.setContent('<table><tr><th style="text-align: right; vertical-align: top; width: 10px; height: 11px; border-color: red; background-color: blue" scope="row">X</th></tr></table>');
Utils.setSelection('th', 0);
editor.execCommand('mceTableCellProps');
deepEqual(Utils.getFrontmostWindow().toJSON(), {
"align": "right",
"valign": "top",
"height": "11",
"scope": "row",
"type": "th",
"width": "10",
"backgroundColor": "blue",
"borderColor": "red",
"style": "width: 10px; height: 11px; vertical-align: top; text-align: right; border-color: red; background-color: blue;"
});
});
test("Table cell properties dialog (update all)", function() {
editor.setContent('<table><tr><td>X</td></tr></table>');
Utils.setSelection('td', 0);
editor.execCommand('mceTableCellProps');
fillAndSubmitWindowForm({
"align": "right",
"height": "11",
"scope": "row",
"type": "th",
"width": "10"
});
equal(
cleanTableHtml(editor.getContent()),
'<table><tbody><tr><th style="width: 10px; height: 11px; text-align: right;" scope="row">x</th></tr></tbody></table>'
);
});
test("Table cell properties dialog update multiple cells", function() {
editor.getBody().innerHTML = (
'<table>' +
'<tbody>' +
'<tr>' +
'<td style="width: 10px;" data-mce-selected="1">a</td>' +
'<td style="width: 20px;" data-mce-selected="1">b</td>' +
'</tr>' +
'</tbody>' +
'</table>'
);
Utils.setSelection('td:nth-child(2)', 0);
editor.execCommand('mceTableCellProps');
deepEqual(Utils.getFrontmostWindow().toJSON(), {
"align": "",
"valign": "",
"height": "",
"scope": "",
"type": "td",
"width": "",
"backgroundColor": "",
"borderColor": "",
"style": ""
}, 'Should not contain width');
fillAndSubmitWindowForm({
"height": "20"
});
equal(
cleanTableHtml(editor.getContent()),
(
'<table>' +
'<tbody>' +
'<tr>' +
'<td style="width: 10px; height: 20px;">a</td>' +
'<td style="width: 20px; height: 20px;">b</td>' +
'</tr>' +
'</tbody>' +
'</table>'
),
'Width should be retained height should be changed'
);
});
test("Table row properties dialog (get data from plain cell)", function() {
editor.setContent('<table><tr><td>X</td></tr></table>');
Utils.setSelection('td', 0);
editor.execCommand('mceTableRowProps');
deepEqual(Utils.getFrontmostWindow().toJSON(), {
"align": "",
"height": "",
"type": "tbody",
"backgroundColor": "",
"borderColor": "",
"style": ""
});
});
test("Table row properties dialog (get data from complex row)", function() {
editor.setContent('<table><thead><tr style="height: 10px; text-align: right; border-color: red; background-color: blue"><td>X</td></tr></thead></table>');
Utils.setSelection('td', 0);
editor.execCommand('mceTableRowProps');
deepEqual(Utils.getFrontmostWindow().toJSON(), {
"align": "right",
"height": "10",
"type": "thead",
"backgroundColor": "blue",
"borderColor": "red",
"style": "height: 10px; text-align: right; border-color: red; background-color: blue;"
});
});
test("Table row properties dialog (update all)", function() {
editor.setContent('<table><tr><td>X</td></tr></table>');
Utils.setSelection('td', 0);
editor.execCommand('mceTableRowProps');
fillAndSubmitWindowForm({
"align": "right",
"height": "10",
"type": "thead"
});
equal(
cleanTableHtml(editor.getContent()),
'<table><thead><tr style="height: 10px; text-align: right;"><td>x</td></tr></thead></table>'
);
});
test("Table row properties dialog update multiple rows", function() {
editor.getBody().innerHTML = (
'<table>' +
'<tbody>' +
'<tr style="height: 20px;">' +
'<td data-mce-selected="1">a</td>' +
'<td data-mce-selected="1">b</td>' +
'</tr>' +
'<tr style="height: 20px;">' +
'<td data-mce-selected="1">c</td>' +
'<td data-mce-selected="1">d</td>' +
'</tr>' +
'</tbody>' +
'</table>'
);
Utils.setSelection('tr:nth-child(2) td:nth-child(2)', 0);
editor.execCommand('mceTableRowProps');
deepEqual(Utils.getFrontmostWindow().toJSON(), {
"align": "",
"height": "",
"type": "tbody",
"backgroundColor": "",
"borderColor": "",
"style": ""
}, 'Should not contain height');
fillAndSubmitWindowForm({
"align": "center"
});
equal(
cleanTableHtml(editor.getContent()),
(
'<table>' +
'<tbody>' +
'<tr style="height: 20px; text-align: center;">' +
'<td>a</td>' +
'<td>b</td>' +
'</tr>' +
'<tr style="height: 20px; text-align: center;">' +
'<td>c</td>' +
'<td>d</td>' +
'</tr>' +
'</tbody>' +
'</table>'
),
'Width should be retained height should be changed'
);
});
test("mceTableDelete command", function() {
editor.setContent('<table><tr><td>X</td></tr></table>');
Utils.setSelection('td', 0);
editor.execCommand('mceTableDelete');
equal(cleanTableHtml(editor.getContent()), '');
});
test("mceTableDeleteCol command", function() {
editor.setContent('<table><tr><td>1</td><td>2</td></tr></table>');
Utils.setSelection('td', 0);
editor.execCommand('mceTableDeleteCol');
equal(cleanTableHtml(editor.getContent()), '<table><tbody><tr><td>2</td></tr></tbody></table>');
});
test("mceTableDeleteRow command", function() {
editor.setContent('<table><tr><td>1</td></tr><tr><td>2</td></tr></table>');
Utils.setSelection('td', 0);
editor.execCommand('mceTableDeleteRow');
equal(cleanTableHtml(editor.getContent()), '<table><tbody><tr><td>2</td></tr></tbody></table>');
});
test("mceTableInsertColAfter command", function() {
editor.setContent('<table><tr><td>1</td></tr><tr><td>2</td></tr></table>');
Utils.setSelection('td', 0);
editor.execCommand('mceTableInsertColAfter');
equal(cleanTableHtml(editor.getContent()), '<table><tbody><tr><td>1</td><td> </td></tr><tr><td>2</td><td> </td></tr></tbody></table>');
});
test("mceTableInsertColBefore command", function() {
editor.setContent('<table><tr><td>1</td></tr><tr><td>2</td></tr></table>');
Utils.setSelection('td', 0);
editor.execCommand('mceTableInsertColBefore');
equal(cleanTableHtml(editor.getContent()), '<table><tbody><tr><td> </td><td>1</td></tr><tr><td> </td><td>2</td></tr></tbody></table>');
});
test("mceTableInsertRowAfter command", function() {
editor.setContent('<table><tr><td>1</td><td>2</td></tr></table>');
Utils.setSelection('td', 0);
editor.execCommand('mceTableInsertRowAfter');
equal(cleanTableHtml(editor.getContent()), '<table><tbody><tr><td>1</td><td>2</td></tr><tr><td> </td><td> </td></tr></tbody></table>');
});
test("mceTableInsertRowAfter command on merged cells", function() {
editor.setContent(
'<table>' +
'<tr><td>1</td><td>2</td><td>3</td></tr>' +
'<tr><td>4</td><td colspan="2" rowspan="2">5</td></tr>' +
'<tr><td>6</td></tr>' +
'</table>'
);
Utils.setSelection('tr:nth-child(2) td', 0);
editor.execCommand('mceTableInsertRowAfter');
equal(
cleanTableHtml(editor.getContent()),
'<table>' +
'<tbody>' +
'<tr><td>1</td><td>2</td><td>3</td></tr>' +
'<tr><td>4</td><td colspan="2" rowspan="3">5</td></tr>' +
'<tr><td> </td></tr>' +
'<tr><td>6</td></tr>' +
'</tbody>' +
'</table>'
);
});
test("mceTablePasteRowBefore command", function() {
editor.setContent(
'<table>' +
'<tr><td>1</td><td>2</td></tr>' +
'<tr><td>2</td><td>3</td></tr>' +
'</table>'
);
Utils.setSelection('tr:nth-child(1) td', 0);
editor.execCommand('mceTableCopyRow');
Utils.setSelection('tr:nth-child(2) td', 0);
editor.execCommand('mceTablePasteRowBefore');
equal(
cleanTableHtml(editor.getContent()),
'<table>' +
'<tbody>' +
'<tr><td>1</td><td>2</td></tr>' +
'<tr><td>1</td><td>2</td></tr>' +
'<tr><td>2</td><td>3</td></tr>' +
'</tbody>' +
'</table>'
);
Utils.setSelection('tr:nth-child(2) td', 0);
editor.execCommand('mceTablePasteRowBefore');
equal(
cleanTableHtml(editor.getContent()),
'<table>' +
'<tbody>' +
'<tr><td>1</td><td>2</td></tr>' +
'<tr><td>1</td><td>2</td></tr>' +
'<tr><td>1</td><td>2</td></tr>' +
'<tr><td>2</td><td>3</td></tr>' +
'</tbody>' +
'</table>'
);
});
test("mceTablePasteRowAfter command", function() {
editor.setContent(
'<table>' +
'<tr><td>1</td><td>2</td></tr>' +
'<tr><td>2</td><td>3</td></tr>' +
'</table>'
);
Utils.setSelection('tr:nth-child(1) td', 0);
editor.execCommand('mceTableCopyRow');
Utils.setSelection('tr:nth-child(2) td', 0);
editor.execCommand('mceTablePasteRowAfter');
equal(
cleanTableHtml(editor.getContent()),
'<table>' +
'<tbody>' +
'<tr><td>1</td><td>2</td></tr>' +
'<tr><td>2</td><td>3</td></tr>' +
'<tr><td>1</td><td>2</td></tr>' +
'</tbody>' +
'</table>'
);
Utils.setSelection('tr:nth-child(2) td', 0);
editor.execCommand('mceTablePasteRowAfter');
equal(
cleanTableHtml(editor.getContent()),
'<table>' +
'<tbody>' +
'<tr><td>1</td><td>2</td></tr>' +
'<tr><td>2</td><td>3</td></tr>' +
'<tr><td>1</td><td>2</td></tr>' +
'<tr><td>1</td><td>2</td></tr>' +
'</tbody>' +
'</table>'
);
});
test("mceTablePasteRowAfter from merged row source", function() {
editor.setContent(
'<table>' +
'<tbody>' +
'<tr><td colspan="2">1 2</td><td rowspan="2">3</td></tr>' +
'<tr><td>1</td><td>2</td></tr>' +
'</tbody>' +
'</table>'
);
Utils.setSelection('tr:nth-child(1) td', 0);
editor.execCommand('mceTableCopyRow');
Utils.setSelection('tr:nth-child(2) td:nth-child(2)', 0);
editor.execCommand('mceTablePasteRowAfter');
equal(
cleanTableHtml(editor.getContent()),
'<table>' +
'<tbody>' +
'<tr><td colspan="2">1 2</td><td rowspan="2">3</td></tr>' +
'<tr><td>1</td><td>2</td></tr>' +
'<tr><td>1 2</td><td>3</td><td> </td></tr>' +
'</tbody>' +
'</table>'
);
});
test("mceTablePasteRowAfter from merged row source to merged row target", function() {
editor.setContent(
'<table>' +
'<tbody>' +
'<tr><td colspan="2">1 2</td><td rowspan="2">3</td></tr>' +
'<tr><td>1</td><td>2</td></tr>' +
'</tbody>' +
'</table>'
);
Utils.setSelection('tr:nth-child(1) td', 0);
editor.execCommand('mceTableCopyRow');
Utils.setSelection('tr:nth-child(1) td', 0);
editor.execCommand('mceTablePasteRowAfter');
equal(
cleanTableHtml(editor.getContent()),
'<table>' +
'<tbody>' +
'<tr><td colspan="2">1 2</td><td>3</td></tr>' +
'<tr><td>1 2</td><td>3</td><td> </td></tr>' +
'<tr><td>1</td><td>2</td><td> </td></tr>' +
'</tbody>' +
'</table>'
);
});
test("mceTablePasteRowAfter to wider table", function() {
editor.setContent(
'<table>' +
'<tbody>' +
'<tr><td>1a</td><td>2a</td><td>3a</td></tr>' +
'</tbody>' +
'</table>' +
'<table>' +
'<tbody>' +
'<tr><td>1b</td><td>2b</td><td>3b</td><td>4b</td></tr>' +
'</tbody>' +
'</table>'
);
Utils.setSelection('table:nth-child(1) tr:nth-child(1) td', 0);
editor.execCommand('mceTableCopyRow');
Utils.setSelection('table:nth-child(2) td', 0);
editor.execCommand('mceTablePasteRowAfter');
equal(
cleanTableHtml(editor.getContent()),
'<table>' +
'<tbody>' +
'<tr><td>1a</td><td>2a</td><td>3a</td></tr>' +
'</tbody>' +
'</table>' +
'<table>' +
'<tbody>' +
'<tr><td>1b</td><td>2b</td><td>3b</td><td>4b</td></tr>' +
'<tr><td>1a</td><td>2a</td><td>3a</td><td> </td></tr>' +
'</tbody>' +
'</table>'
);
});
test("mceTablePasteRowAfter to narrower table", function() {
editor.setContent(
'<table>' +
'<tbody>' +
'<tr><td>1a</td><td>2a</td><td>3a</td></tr>' +
'</tbody>' +
'</table>' +
'<table>' +
'<tbody>' +
'<tr><td>1b</td><td>2b</td></tr>' +
'</tbody>' +
'</table>'
);
Utils.setSelection('table:nth-child(1) tr:nth-child(1) td', 0);
editor.execCommand('mceTableCopyRow');
Utils.setSelection('table:nth-child(2) td', 0);
editor.execCommand('mceTablePasteRowAfter');
equal(
cleanTableHtml(editor.getContent()),
'<table>' +
'<tbody>' +
'<tr><td>1a</td><td>2a</td><td>3a</td></tr>' +
'</tbody>' +
'</table>' +
'<table>' +
'<tbody>' +
'<tr><td>1b</td><td>2b</td></tr>' +
'<tr><td>1a</td><td>2a</td></tr>' +
'</tbody>' +
'</table>'
);
});
test("row clipboard api", function() {
var clipboardRows;
function createRow(cellContents) {
var tr = editor.dom.create('tr');
tinymce.each(cellContents, function (html) {
tr.appendChild(editor.dom.create('td', null, html));
});
return tr;
}
editor.setContent(
'<table>' +
'<tr><td>1</td><td>2</td></tr>' +
'<tr><td>2</td><td>3</td></tr>' +
'</table>'
);
Utils.setSelection('tr:nth-child(1) td', 0);
editor.execCommand('mceTableCopyRow');
clipboardRows = editor.plugins.table.getClipboardRows();
equal(clipboardRows.length, 1);
equal(clipboardRows[0].tagName, 'TR');
editor.plugins.table.setClipboardRows(clipboardRows.concat([
createRow(['a', 'b']),
createRow(['c', 'd'])
]));
Utils.setSelection('tr:nth-child(2) td', 0);
editor.execCommand('mceTablePasteRowAfter');
equal(
cleanTableHtml(editor.getContent()),
'<table>' +
'<tbody>' +
'<tr><td>1</td><td>2</td></tr>' +
'<tr><td>2</td><td>3</td></tr>' +
'<tr><td>1</td><td>2</td></tr>' +
'<tr><td>a</td><td>b</td></tr>' +
'<tr><td>c</td><td>d</td></tr>' +
'</tbody>' +
'</table>'
);
});
test("mceSplitColsBefore", function() {
testCommand('mceSplitColsBefore', [
{
message: 'Should not change anything these is no table cell selection',
before: '<p>a</p>',
after: '<p>a</p>'
},
{
message: 'Should not change anything since there is nothing to split (1 row)',
before: (
'<table>' +
'<tbody>' +
'<tr><td data-mce-selected="1">1a</td><td>2a</td><td>3a</td></tr>' +
'</tbody>' +
'</table>'
),
after: (
'<table>' +
'<tbody>' +
'<tr><td>1a</td><td>2a</td><td>3a</td></tr>' +
'</tbody>' +
'</table>'
)
},
{
message: 'Should not change anything since there is nothing to split (2 rows)',
before: (
'<table>' +
'<tbody>' +
'<tr><td>1a</td><td>2a</td><td>3a</td></tr>' +
'<tr><td data-mce-selected="1">1b</td><td>2b</td><td>3b</td></tr>' +
'</tbody>' +
'</table>'
),
after: (
'<table>' +
'<tbody>' +
'<tr><td>1a</td><td>2a</td><td>3a</td></tr>' +
'<tr><td>1b</td><td>2b</td><td>3b</td></tr>' +
'</tbody>' +
'</table>'
)
},
{
message: 'Should split at second row and remove rowspan',
before: (
'<table>' +
'<tbody>' +
'<tr><td rowspan="2">1a</td><td>2a</td><td rowspan="2">3a</td></tr>' +
'<tr><td data-mce-selected="1">2b</td></tr>' +
'</tbody>' +
'</table>'
),
after: (
'<table>' +
'<tbody>' +
'<tr><td>1a</td><td>2a</td><td>3a</td></tr>' +
'<tr><td> </td><td>2b</td><td> </td></tr>' +
'</tbody>' +
'</table>'
)
},
{
message: 'Should split at third row and decrease rowspan',
before: (
'<table>' +
'<tbody>' +
'<tr><td rowspan="3">1a</td><td>2a</td><td rowspan="3">3a</td></tr>' +
'<tr><td>2b</td></tr>' +
'<tr><td data-mce-selected="1">2c</td></tr>' +
'</tbody>' +
'</table>'
),
after: (
'<table>' +
'<tbody>' +
'<tr><td rowspan="2">1a</td><td>2a</td><td rowspan="2">3a</td></tr>' +
'<tr><td>2b</td></tr>' +
'<tr><td> </td><td>2c</td><td> </td></tr>' +
'</tbody>' +
'</table>'
)
}
]);
});
test("mceSplitColsAfter", function() {
testCommand('mceSplitColsAfter', [
{
message: 'Should not change anything these is no table cell selection',
before: '<p>a</p>',
after: '<p>a</p>'
},
{
message: 'Should not change anything since there is nothing to split (1 row)',
before: (
'<table>' +
'<tbody>' +
'<tr><td data-mce-selected="1">1a</td><td>2a</td><td>3a</td></tr>' +
'</tbody>' +
'</table>'
),
after: (
'<table>' +
'<tbody>' +
'<tr><td>1a</td><td>2a</td><td>3a</td></tr>' +
'</tbody>' +
'</table>'
)
},
{
message: 'Should not change anything since there is nothing to split (2 rows)',
before: (
'<table>' +
'<tbody>' +
'<tr><td data-mce-selected="1">1a</td><td>2a</td><td>3a</td></tr>' +
'<tr><td>1b</td><td>2b</td><td>3b</td></tr>' +
'</tbody>' +
'</table>'
),
after: (
'<table>' +
'<tbody>' +
'<tr><td>1a</td><td>2a</td><td>3a</td></tr>' +
'<tr><td>1b</td><td>2b</td><td>3b</td></tr>' +
'</tbody>' +
'</table>'
)
},
{
message: 'Should split at second row and remove rowspan',
before: (
'<table>' +
'<tbody>' +
'<tr><td rowspan="2" data-mce-selected="1">1a</td><td>2a</td><td rowspan="2">3a</td></tr>' +
'<tr><td>2b</td></tr>' +
'</tbody>' +
'</table>'
),
after: (
'<table>' +
'<tbody>' +
'<tr><td>1a</td><td>2a</td><td>3a</td></tr>' +
'<tr><td> </td><td>2b</td><td> </td></tr>' +
'</tbody>' +
'</table>'
)
},
{
message: 'Should split at first row and produce td:s with decreased rowspans below',
before: (
'<table>' +
'<tbody>' +
'<tr><td rowspan="3" data-mce-selected="1">1a</td><td>2a</td><td rowspan="3">3a</td></tr>' +
'<tr><td>2b</td></tr>' +
'<tr><td>2c</td></tr>' +
'</tbody>' +
'</table>'
),
after: (
'<table>' +
'<tbody>' +
'<tr><td>1a</td><td>2a</td><td>3a</td></tr>' +
'<tr><td rowspan="2"> </td><td>2b</td><td rowspan="2"> </td></tr>' +
'<tr><td>2c</td></tr>' +
'</tbody>' +
'</table>'
)
}
]);
});
test("mceTableInsertRowBefore command", function() {
editor.setContent('<table><tr><td>1</td><td>2</td></tr></table>');
Utils.setSelection('td', 0);
editor.execCommand('mceTableInsertRowBefore');
equal(cleanTableHtml(editor.getContent()), '<table><tbody><tr><td> </td><td> </td></tr><tr><td>1</td><td>2</td></tr></tbody></table>');
});
test("mceTableMergeCells", function() {
testCommand('mceTableMergeCells', [
{
message: 'Should merge all cells into one',
before: (
'<table>' +
'<tbody>' +
'<tr><td data-mce-selected="1">a1</td><td data-mce-selected="1">b1</td></tr>' +
'<tr><td data-mce-selected="1">a2</td><td data-mce-selected="1">b2</td></tr>' +
'</tbody>' +
'</table>'
),
after: (
'<table>' +
'<tbody>' +
'<tr><td>a1b1a2b2</td></tr>' +
'</tbody>' +
'</table>'
)
},
{
message: 'Should merge cells in two cols/rows into one cell with colspan',
before: (
'<table>' +
'<tbody>' +
'<tr><td data-mce-selected="1">a1</td><td data-mce-selected="1">b1</td></tr>' +
'<tr><td data-mce-selected="1">a2</td><td data-mce-selected="1">b2</td></tr>' +
'<tr><td>a3</td><td>b3</td></tr>' +
'</tbody>' +
'</table>'
),
after: (
'<table>' +
'<tbody>' +
'<tr><td colspan="2">a1b1a2b2</td></tr>' +
'<tr><td>a3</td><td>b3</td></tr>' +
'</tbody>' +
'</table>'
)
},
{
message: 'Should remove all rowspans since the table is fully merged',
before: (
'<table>' +
'<tbody>' +
'<tr><td rowspan="2">a1</td><td data-mce-selected="1">b1</td></tr>' +
'<tr><td data-mce-selected="1">b2</td></tr>' +
'</tbody>' +
'</table>'
),
after: (
'<table>' +
'<tbody>' +
'<tr><td>a1</td><td>b1b2</td></tr>' +
'</tbody>' +
'</table>'
)
},
{
message: 'Should remove all colspans since the table is fully merged',
before: (
'<table>' +
'<tbody>' +
'<tr><td colspan="2">a1</td></tr>' +
'<tr><td data-mce-selected="1">a2</td><td data-mce-selected="1">b2</td></tr>' +
'</tbody>' +
'</table>'
),
after: (
'<table>' +
'<tbody>' +
'<tr><td>a1</td></tr>' +
'<tr><td>a2b2</td></tr>' +
'</tbody>' +
'</table>'
)
},
{
message: 'Should remove rowspans since the table is fully merged',
before: (
'<table>' +
'<tbody>' +
'<tr><td rowspan="3">a1</td><td rowspan="3">b1</td><td data-mce-selected="1">c1</td></tr>' +
'<tr><td data-mce-selected="1">c2</td></tr>' +
'<tr><td data-mce-selected="1">c3</td></tr>' +
'</tbody>' +
'</table>'
),
after: (
'<table>' +
'<tbody>' +
'<tr><td>a1</td><td>b1</td><td>c1c2c3</td></tr>' +
'</tbody>' +
'</table>'
)
},
{
message: 'Should remove colspans since the table is fully merged',
before: (
'<table>' +
'<tbody>' +
'<tr><td data-mce-selected="1">a1</td><td data-mce-selected="1">b1</td><td data-mce-selected="1">c1</td></tr>' +
'<tr><td colspan="3">a2</td></tr>' +
'<tr><td colspan="3">a3</td></tr>' +
'</tbody>' +
'</table>'
),
after: (
'<table>' +
'<tbody>' +
'<tr><td>a1b1c1</td></tr>' +
'<tr><td>a2</td></tr>' +
'<tr><td>a3</td></tr>' +
'</tbody>' +
'</table>'
)
},
{
message: 'Should reduce rowspans to 2 keep the colspan and remove one tr',
before: (
'<table>' +
'<tbody>' +
'<tr><td colspan="2" rowspan="2">a1</td><td rowspan="3">b1</td><td data-mce-selected="1">c1</td></tr>' +
'<tr><td data-mce-selected="1">c2</td></tr>' +
'<tr><td>a3</td><td>b3</td><td data-mce-selected="1">c3</td></tr>' +
'</tbody>' +
'</table>'
),
after: (
'<table>' +
'<tbody>' +
'<tr><td colspan="2">a1</td><td rowspan="2">b1</td><td rowspan="2">c1c2c3</td></tr>' +
'<tr><td>a3</td><td>b3</td></tr>' +
'</tbody>' +
'</table>'
)
},
{
message: 'Should reduce colspans to 2 keep the rowspan',
before: (
'<table>' +
'<tbody>' +
'<tr><td data-mce-selected="1">a1</td><td data-mce-selected="1">b1</td><td data-mce-selected="1">c1</td></tr>' +
'<tr><td colspan="3">a2</td></tr>' +
'<tr><td colspan="2" rowspan="2">a3</td><td>c3</td></tr>' +
'<tr><td>c4</td></tr>' +
'</tbody>' +
'</table>'
),
after: (
'<table>' +
'<tbody>' +
'<tr><td colspan="2">a1b1c1</td></tr>' +
'<tr><td colspan="2">a2</td></tr>' +
'<tr><td rowspan="2">a3</td><td>c3</td></tr>' +
'<tr><td>c4</td></tr>' +
'</tbody>' +
'</table>'
)
},
{
message: 'Should merge b3+c3 but not reduce a2a3',
before: (
'<table>' +
'<tbody>' +
'<tr>' +
'<td>a1</td>' +
'<td>b1</td>' +
'<td>c1</td>' +
'</tr>' +
'<tr>' +
'<td rowspan="2">a2a3</td>' +
'<td>b2</td>' +
'<td>c2</td>' +
'</tr>' +
'<tr>' +
'<td data-mce-selected="1">b3</td>' +
'<td data-mce-selected="1">c3</td>' +
'</tr>' +
'</tbody>' +
'</table>'
),
after: (
'<table>' +
'<tbody>' +
'<tr>' +
'<td>a1</td>' +
'<td>b1</td>' +
'<td>c1</td>' +
'</tr>' +
'<tr>' +
'<td rowspan="2">a2a3</td>' +
'<td>b2</td>' +
'<td>c2</td>' +
'</tr>' +
'<tr>' +
'<td colspan="2">b3c3</td>' +
'</tr>' +
'</tbody>' +
'</table>'
)
},
{
message: 'Should merge b1+c1 and reduce a2',
before: (
'<table>' +
'<tbody>' +
'<tr>' +
'<td>a1</td>' +
'<td data-mce-selected="1">b1</td>' +
'<td data-mce-selected="1">c1</td>' +
'</tr>' +
'<tr>' +
'<td colspan="3">a2</td>' +
'</tr>' +
'</tbody>' +
'</table>'
),
after: (
'<table>' +
'<tbody>' +
'<tr>' +
'<td>a1</td>' +
'<td>b1c1</td>' +
'</tr>' +
'<tr>' +
'<td colspan="2">a2</td>' +
'</tr>' +
'</tbody>' +
'</table>'
)
},
{
message: 'Should merge a2+a3 and reduce b1',
before: (
'<table>' +
'<tbody>' +
'<tr>' +
'<td>a1</td>' +
'<td rowspan="3">b1</td>' +
'</tr>' +
'<tr>' +
'<td data-mce-selected="1">a2</td>' +
'</tr>' +
'<tr>' +
'<td data-mce-selected="1">a3</td>' +
'</tr>' +
'</tbody>' +
'</table>'
),
after: (
'<table>' +
'<tbody>' +
'<tr>' +
'<td>a1</td>' +
'<td rowspan="2">b1</td>' +
'</tr>' +
'<tr>' +
'<td>a2a3</td>' +
'</tr>' +
'</tbody>' +
'</table>'
)
}
]);
});
test("mceTableSplitCells command", function() {
editor.setContent('<table><tbody><tr><td colspan="2">12</td></tr></tbody></table>');
Utils.setSelection('td', 0);
editor.execCommand('mceTableSplitCells');
equal(
cleanTableHtml(editor.getContent()),
'<table><tbody><tr><td>12</td><td> </td></tr></tbody></table>'
);
});
test("Tab key navigation", function() {
editor.setContent('<table><tbody><tr><td>A1</td><td>A2</td></tr><tr><td>B1</td><td>B2</td></tr></tbody></table><p>x</p>');
Utils.setSelection('td', 0);
editor.fire('keydown', {keyCode: 9});
equal(editor.selection.getStart().innerHTML, 'A2');
Utils.setSelection('td', 0);
editor.fire('keydown', {keyCode: 9, shiftKey: true});
equal(editor.selection.getStart().innerHTML, 'A1');
Utils.setSelection('td:nth-child(2)', 0);
editor.fire('keydown', {keyCode: 9, shiftKey: true});
equal(editor.selection.getStart().innerHTML, 'A1');
Utils.setSelection('tr:nth-child(2) td:nth-child(2)', 0);
editor.fire('keydown', {keyCode: 9});
equal(editor.selection.getStart(true).nodeName, 'TD');
equal(
editor.getContent(),
'<table><tbody><tr><td>A1</td><td>A2</td></tr><tr><td>B1</td><td>B2</td></tr><tr><td> </td><td> </td></tr></tbody></table><p>x</p>'
);
});
test("Delete selected cells", function() {
editor.getBody().innerHTML = (
'<table><tbody>' +
'<tr><td data-mce-selected="1">A1</td><td>A2</td></tr>' +
'<tr><td data-mce-selected="1">B1</td><td>B2</td></tr>' +
'</tbody></table>' +
'<p>x</p>'
);
Utils.setSelection('td', 0, 'td', 2);
editor.fire('keydown', {keyCode: 46});
equal(
editor.getContent(),
'<table><tbody><tr><td> </td><td>A2</td></tr><tr><td> </td><td>B2</td></tr></tbody></table><p>x</p>'
);
});
test("Delete all cells", function() {
editor.getBody().innerHTML = (
'<table><tbody>' +
'<tr><td data-mce-selected="1">A1</td><td data-mce-selected="1">A2</td></tr>' +
'<tr><td data-mce-selected="1">B1</td><td data-mce-selected="1">B2</td></tr>' +
'</tbody></table>' +
'<p>x</p>'
);
Utils.setSelection('td', 0, 'td', 2);
editor.fire('keydown', {keyCode: 46});
equal(
editor.getContent(),
'<p>x</p>'
);
});
test("Delete empty like table cell contents", function() {
editor.getBody().innerHTML = (
'<table><tbody>' +
'<tr><td><p><br></p></td><td><p>a</p></td>' +
'</tbody></table>' +
'<p>x</p>'
);
Utils.setSelection('td', 0);
editor.fire('keydown', {keyCode: 46});
equal(
editor.getContent(),
'<table><tbody><tr><td> </td><td><p>a</p></td></tr></tbody></table><p>x</p>'
);
});
var testResizeTable1 = '<table style="width: 426px"><tbody>' +
'<tr><td style="height: 20px; width: 200px;" colspan="2" data-mce-style="height: 20px; width: 200px;">A1</td><td style="height: 20px; width: 100px;" data-mce-style="height: 20px; width: 100px;">A2</td><td style="height: 20px; width: 100px;" data-mce-style="height: 20px; width: 100px;">A3</td></tr>' +
'<tr><td style="height: 20px; width: 100px;" data-mce-style="height: 20px; width: 100px;">B1</td><td style="height: 20px; width: 200px;" colspan="2" data-mce-style="height: 20px; width: 200px;">B2</td><td style="height: 20px; width: 100px;" data-mce-style="height: 20px; width: 100px;">B3</td></tr>' +
'<tr><td style="height: 20px; width: 100px;" data-mce-style="height: 20px; width: 100px;">C1</td><td style="height: 20px; width: 100px;" data-mce-style="height: 20px; width: 100px;">C2</td><td style="height: 20px; width: 200px;" colspan="2" data-mce-style="height: 20px; width: 200px;">C3</td></tr>' +
'<tr><td style="height: 20px; width: 400px;" colspan="4" data-mce-style="height: 20px; width: 400px;">D1</td></tr></tbody></table>';
var testResizeTable2 = '<table border="1"><tbody>' +
'<tr><th style="height: 20px; width: 20px;" data-mce-style="height: 20px; width: 20px;">A0</th><th style="height: 20px; width: 20px;" data-mce-style="height: 20px; width: 20px;">A1</th><th style="height: 20px; width: 20px;" data-mce-style="height: 20px; width: 20px;">A2</th>' +
'<th style="height: 20px; width: 40px;" data-mce-style="height: 20px; width: 40px;">A3</th><th style="height: 20px; width: 10px;" data-mce-style="height: 20px; width: 10px;">A4</th></tr><tr><td style="height: 20px; width: 20px;" data-mce-style="height: 20px; width: 20px;">B0</td><td style="height: 20px; width: 20px; "' +
'data-mce-style="height: 20px; width: 20px;">B1</td><td style="height: 20px; width: 20px;" data-mce-style="height: 20px; width: 20px;">B2</td><td style="height: 20px; width: 40px;" data-mce-style="height: 20px; width: 40px;">B3</td><td style="height: 40px; width: 10px;" rowspan="2" data-mce-style="height: 20px; width: 10px;">' +
'B3</td></tr><tr><td style="height: 20px; width: 20px;" data-mce-style="height: 20px; width: 20px;">C0</td><td style="height: 20px; width: 20px;" data-mce-style="height: 20px; width: 20px;">C1</td><td style="height: 20px; width: 20px;" data-mce-style="height: 20px; width: 20px;">C2</td><td style="height: 20px; width: 40px;" ' +
'data-mce-style="height: 20px; width: 40px;">C3</td></tr></tbody></table>';
var testResizeTable3 = '<div style=\"display: block; width: 400px;\"><table style=\"border-collapse: collapse; border: 1px solid black;\" width=\"100%\" cellspacing=\"0\" cellpadding=\"0\"><tbody><tr><td rowspan=\"2\" width=\"25%\"> a</td><td width=\"25%\"> b</td><td width=\"25%\"> </td>' +
'<td width=\"25%\"> c</td></tr><tr><td width=\"25%\"> d</td><td width=\"25%\"> </td><td rowspan=\"2\" width=\"25%\"> e</td></tr><tr><td width=\"25%\"> f</td><td width=\"25%\"> g</td><td width=\"25%\"> </td></tr><tr><td width=\"25%\"> h</td><td width=\"25%\"> i</td><td width=\"25%\"> </td><td width=\"25%\">j </td></tr></tbody></table></div>';
var testResizeTable4 = (
'<table>' +
'<tbody>' +
'<tr>' +
'<td>a</td>' +
'<td>b</td>' +
'</tr>' +
'<tr>' +
'<td>a</td>' +
'<td>b</td>' +
'<td>c</td>' +
'</tr>' +
'<tr>' +
'<td>a</td>' +
'</tr>' +
'<tr>' +
'<td>a</td>' +
'<td>b</td>' +
'<td colspan="2">c</td>' +
'</tr>' +
'</tbody>' +
'</table>'
);
test("Is Pixel/Percentage Based Width", function() {
var pixelWidths = ['125px', '200px', '300em'];
var percentageWidths = ['25%', '30%', '100%'];
var i, pixelBasedSize, percentBasedSize;
for (i = 0; i < pixelWidths.length; i++) {
pixelBasedSize = editor.plugins.table.resizeBars.isPixelBasedSize(pixelWidths[i]);
deepEqual(pixelBasedSize, true);
percentBasedSize = editor.plugins.table.resizeBars.isPercentageBasedSize(pixelWidths[i]);
deepEqual(percentBasedSize, false);
}
for (i = 0; i < percentageWidths.length; i++) {
pixelBasedSize = editor.plugins.table.resizeBars.isPixelBasedSize(percentageWidths[i]);
deepEqual(pixelBasedSize, false);
percentBasedSize = editor.plugins.table.resizeBars.isPercentageBasedSize(percentageWidths[i]);
deepEqual(percentBasedSize, true);
}
});
test("Get widths/heights", function() {
editor.setContent(testResizeTable1);
var table = editor.dom.select('table')[0];
var details = editor.plugins.table.resizeBars.getTableDetails(table);
var tableGrid = editor.plugins.table.resizeBars.getTableGrid(details);
deepEqual(
editor.plugins.table.resizeBars.getWidths(tableGrid, false, table),
[100, 100, 100, 100]
);
deepEqual(
editor.plugins.table.resizeBars.getPixelHeights(tableGrid),
[20, 20, 20, 20]
);
editor.setContent(testResizeTable2);
table = editor.dom.select('table')[0];
details = editor.plugins.table.resizeBars.getTableDetails(table);
tableGrid = editor.plugins.table.resizeBars.getTableGrid(details);
deepEqual(
editor.plugins.table.resizeBars.getWidths(tableGrid, false, table),
[20, 20, 20, 40, 10]
);
deepEqual(
editor.plugins.table.resizeBars.getPixelHeights(tableGrid),
[20, 20, 20]
);
editor.setContent(testResizeTable3);
table = editor.dom.select('table')[0];
details = editor.plugins.table.resizeBars.getTableDetails(table);
tableGrid = editor.plugins.table.resizeBars.getTableGrid(details);
deepEqual(
editor.plugins.table.resizeBars.getWidths(tableGrid, true, table),
[25, 25, 25, 25]
);
});
test("Draw bars/clear bars", function() {
editor.setContent(testResizeTable1);
var table = editor.dom.select('table')[0];
editor.plugins.table.resizeBars.drawBars(table);
equal(editor.dom.select('.mce-resize-bar-row').length,
4);
equal(editor.dom.select('.mce-resize-bar-col').length,
4);
editor.plugins.table.resizeBars.clearBars();
equal(editor.dom.select('.mce-resize-bar-row').length,
0);
equal(editor.dom.select('.mce-resize-bar-col').length,
0);
});
test("Draw bars/clear bars on invalid table", function() {
editor.setContent(testResizeTable4);
var table = editor.dom.select('table')[0];
editor.plugins.table.resizeBars.drawBars(table);
equal(editor.dom.select('.mce-resize-bar-row').length,
4);
equal(editor.dom.select('.mce-resize-bar-col').length,
4);
editor.plugins.table.resizeBars.clearBars();
equal(editor.dom.select('.mce-resize-bar-row').length,
0);
equal(editor.dom.select('.mce-resize-bar-col').length,
0);
});
test("Determine deltas", function() {
var deltas = editor.plugins.table.resizeBars.determineDeltas([100, 100, 100, 100], 0, 50, 10, false);
deepEqual(deltas, [50, -50, 0, 0]);
deltas = editor.plugins.table.resizeBars.determineDeltas([100, 100, 100, 100], 1, 50, 10, false);
deepEqual(deltas, [0, 50, -50, 0]);
deltas = editor.plugins.table.resizeBars.determineDeltas([100, 100, 100, 100], 2, 50, 10, false);
deepEqual(deltas, [0, 0, 50, -50]);
deltas = editor.plugins.table.resizeBars.determineDeltas([100, 100, 100, 100], 3, 50, 10, false);
deepEqual(deltas, [0, 0, 0, 50]);
deltas = editor.plugins.table.resizeBars.determineDeltas([50], 0, 5, 10, true);
deepEqual(deltas, [50]); // 50 + 50 = 100, one column, percent case
deltas = editor.plugins.table.resizeBars.determineDeltas([25, 25, 25, 25], 1, 5, 10, true);
deepEqual(deltas, [0, 5, -5, 0]);
});
test("Adjust width", function() {
editor.setContent(testResizeTable1);
var table = editor.dom.select('table')[0];
editor.plugins.table.resizeBars.adjustWidth(table, 50, 0);
equal(editor.getContent(),
'<table style=\"width: 426px;\">' +
'<tbody>' +
'<tr>' +
'<td style=\"width: 200px; height: 20px;\" colspan=\"2\">A1</td>' +
'<td style=\"width: 100px; height: 20px;\">A2</td>' +
'<td style=\"width: 100px; height: 20px;\">A3</td>' +
'</tr>' +
'<tr>' +
'<td style=\"width: 150px; height: 20px;\">B1</td>' +
'<td style=\"width: 150px; height: 20px;\" colspan=\"2\">B2</td>' +
'<td style=\"width: 100px; height: 20px;\">B3</td>' +
'</tr>' +
'<tr>' +
'<td style=\"width: 150px; height: 20px;\">C1</td>' +
'<td style=\"width: 50px; height: 20px;\">C2</td>' +
'<td style=\"width: 200px; height: 20px;\" colspan=\"2\">C3</td>' +
'</tr>' +
'<tr>' +
'<td style=\"width: 400px; height: 20px;\" colspan=\"4\">D1</td>' +
'</tr>' +
'</tbody>' +
'</table>');
editor.setContent(testResizeTable1);
table = editor.dom.select('table')[0];
editor.plugins.table.resizeBars.adjustWidth(table, 50, 1);
equal(editor.getContent(),
'<table style=\"width: 426px;\">' +
'<tbody>' +
'<tr>' +
'<td style=\"width: 250px; height: 20px;\" colspan=\"2\">A1</td>' +
'<td style=\"width: 50px; height: 20px;\">A2</td>' +
'<td style=\"width: 100px; height: 20px;\">A3</td>' +
'</tr>' +
'<tr>' +
'<td style=\"width: 100px; height: 20px;\">B1</td>' +
'<td style=\"width: 200px; height: 20px;\" colspan=\"2\">B2</td>' +
'<td style=\"width: 100px; height: 20px;\">B3</td>' +
'</tr>' +
'<tr>' +
'<td style=\"width: 100px; height: 20px;\">C1</td>' +
'<td style=\"width: 150px; height: 20px;\">C2</td>' +
'<td style=\"width: 150px; height: 20px;\" colspan=\"2\">C3</td>' +
'</tr>' +
'<tr>' +
'<td style=\"width: 400px; height: 20px;\" colspan=\"4\">D1</td>' +
'</tr>' +
'</tbody>' +
'</table>');
editor.setContent(testResizeTable1);
table = editor.dom.select('table')[0];
editor.plugins.table.resizeBars.adjustWidth(table, 50, 2);
equal(editor.getContent(),
'<table style=\"width: 426px;\">' +
'<tbody>' +
'<tr>' +
'<td style=\"width: 200px; height: 20px;\" colspan=\"2\">A1</td>' +
'<td style=\"width: 150px; height: 20px;\">A2</td>' +
'<td style=\"width: 50px; height: 20px;\">A3</td>' +
'</tr>' +
'<tr>' +
'<td style=\"width: 100px; height: 20px;\">B1</td>' +
'<td style=\"width: 250px; height: 20px;\" colspan=\"2\">B2</td>' +
'<td style=\"width: 50px; height: 20px;\">B3</td>' +
'</tr>' +
'<tr>' +
'<td style=\"width: 100px; height: 20px;\">C1</td>' +
'<td style=\"width: 100px; height: 20px;\">C2</td>' +
'<td style=\"width: 200px; height: 20px;\" colspan=\"2\">C3</td>' +
'</tr>' +
'<tr>' +
'<td style=\"width: 400px; height: 20px;\" colspan=\"4\">D1</td>' +
'</tr>' +
'</tbody>' +
'</table>');
editor.setContent(testResizeTable1);
table = editor.dom.select('table')[0];
editor.plugins.table.resizeBars.adjustWidth(table, 50, 3);
equal(editor.getContent(),
'<table style=\"width: 476px;\">' +
'<tbody>' +
'<tr>' +
'<td style=\"width: 200px; height: 20px;\" colspan=\"2\">A1</td>' +
'<td style=\"width: 100px; height: 20px;\">A2</td>' +
'<td style=\"width: 150px; height: 20px;\">A3</td>' +
'</tr>' +
'<tr>' +
'<td style=\"width: 100px; height: 20px;\">B1</td>' +
'<td style=\"width: 200px; height: 20px;\" colspan=\"2\">B2</td>' +
'<td style=\"width: 150px; height: 20px;\">B3</td>' +
'</tr>' +
'<tr>' +
'<td style=\"width: 100px; height: 20px;\">C1</td>' +
'<td style=\"width: 100px; height: 20px;\">C2</td>' +
'<td style=\"width: 250px; height: 20px;\" colspan=\"2\">C3</td>' +
'</tr>' +
'<tr>' +
'<td style=\"width: 450px; height: 20px;\" colspan=\"4\">D1</td>' +
'</tr>' +
'</tbody>' +
'</table>');
});
test("Adjust height", function() {
editor.setContent(testResizeTable2);
var table = editor.dom.select('table')[0];
editor.plugins.table.resizeBars.adjustHeight(table, 50, 0);
equal(editor.getContent(),
'<table border=\"1\">' +
'<tbody>' +
'<tr style=\"height: 70px;\">' +
'<th style=\"width: 20px; height: 70px;\">A0</th>' +
'<th style=\"width: 20px; height: 70px;\">A1</th>' +
'<th style=\"width: 20px; height: 70px;\">A2</th>' +
'<th style=\"width: 40px; height: 70px;\">A3</th>' +
'<th style=\"width: 10px; height: 70px;\">A4</th>' +
'</tr>' +
'<tr style=\"height: 20px;\">' +
'<td style=\"width: 20px; height: 20px;\">B0</td>' +
'<td style=\"width: 20px; height: 20px;\">B1</td>' +
'<td style=\"width: 20px; height: 20px;\">B2</td>' +
'<td style=\"width: 40px; height: 20px;\">B3</td>' +
'<td style=\"width: 10px; height: 40px;\" rowspan=\"2\">B3</td>' +
'</tr>' +
'<tr style=\"height: 20px;\">' +
'<td style=\"width: 20px; height: 20px;\">C0</td>' +
'<td style=\"width: 20px; height: 20px;\">C1</td>' +
'<td style=\"width: 20px; height: 20px;\">C2</td>' +
'<td style=\"width: 40px; height: 20px;\">C3</td>' +
'</tr>' +
'</tbody>' +
'</table>');
editor.setContent(testResizeTable2);
table = editor.dom.select('table')[0];
editor.plugins.table.resizeBars.adjustHeight(table, 50, 1);
equal(editor.getContent(),
'<table border=\"1\">' +
'<tbody>' +
'<tr style=\"height: 20px;\">' +
'<th style=\"width: 20px; height: 20px;\">A0</th>' +
'<th style=\"width: 20px; height: 20px;\">A1</th>' +
'<th style=\"width: 20px; height: 20px;\">A2</th>' +
'<th style=\"width: 40px; height: 20px;\">A3</th>' +
'<th style=\"width: 10px; height: 20px;\">A4</th>' +
'</tr>' +
'<tr style=\"height: 70px;\">' +
'<td style=\"width: 20px; height: 70px;\">B0</td>' +
'<td style=\"width: 20px; height: 70px;\">B1</td>' +
'<td style=\"width: 20px; height: 70px;\">B2</td>' +
'<td style=\"width: 40px; height: 70px;\">B3</td>' +
'<td style=\"width: 10px; height: 90px;\" rowspan=\"2\">B3</td>' +
'</tr>' +
'<tr style=\"height: 20px;\">' +
'<td style=\"width: 20px; height: 20px;\">C0</td>' +
'<td style=\"width: 20px; height: 20px;\">C1</td>' +
'<td style=\"width: 20px; height: 20px;\">C2</td>' +
'<td style=\"width: 40px; height: 20px;\">C3</td>' +
'</tr>' +
'</tbody>' +
'</table>');
editor.setContent(testResizeTable2);
table = editor.dom.select('table')[0];
editor.plugins.table.resizeBars.adjustHeight(table, 50, 2);
equal(editor.getContent(),
'<table border=\"1\">' +
'<tbody>' +
'<tr style=\"height: 20px;\">' +
'<th style=\"width: 20px; height: 20px;\">A0</th>' +
'<th style=\"width: 20px; height: 20px;\">A1</th>' +
'<th style=\"width: 20px; height: 20px;\">A2</th>' +
'<th style=\"width: 40px; height: 20px;\">A3</th>' +
'<th style=\"width: 10px; height: 20px;\">A4</th>' +
'</tr>' +
'<tr style=\"height: 20px;\">' +
'<td style=\"width: 20px; height: 20px;\">B0</td>' +
'<td style=\"width: 20px; height: 20px;\">B1</td>' +
'<td style=\"width: 20px; height: 20px;\">B2</td>' +
'<td style=\"width: 40px; height: 20px;\">B3</td>' +
'<td style=\"width: 10px; height: 90px;\" rowspan=\"2\">B3</td>' +
'</tr>' +
'<tr style=\"height: 70px;\">' +
'<td style=\"width: 20px; height: 70px;\">C0</td>' +
'<td style=\"width: 20px; height: 70px;\">C1</td>' +
'<td style=\"width: 20px; height: 70px;\">C2</td>' +
'<td style=\"width: 40px; height: 70px;\">C3</td>' +
'</tr>' +
'</tbody>' +
'</table>');
});
test("Table newcell/newrow events", function() {
var cells = [], rows = [], counter = 0;
editor.on('newcell', function(e) {
cells.push(e.node);
e.node.setAttribute('data-counter', counter++);
});
editor.on('newrow', function(e) {
rows.push(e.node);
e.node.setAttribute('data-counter', counter++);
});
editor.plugins.table.insertTable(2, 3);
equal(cells.length, 6);
equal(rows.length, 3);
equal(cells[cells.length - 1].getAttribute('data-counter'), "8");
equal(rows[rows.length - 1].getAttribute('data-counter'), "6");
});
function assertTableSelection(tableHtml, selectCells, cellContents) {
function selectRangeXY(table, startTd, endTd) {
editor.fire('mousedown', {target: startTd});
editor.fire('mouseover', {target: endTd});
editor.fire('mouseup', {target: endTd});
}
function getCells(table) {
return editor.$(table).find('td').toArray();
}
function getSelectedCells(table) {
return editor.$(table).find('td[data-mce-selected]').toArray();
}
editor.setContent(tableHtml);
var table = editor.$('table')[0];
var cells = getCells(table);
var startTd = tinymce.grep(cells, function(elm) {
return elm.innerHTML === selectCells[0];
})[0];
var endTd = tinymce.grep(cells, function(elm) {
return elm.innerHTML === selectCells[1];
})[0];
selectRangeXY(table, startTd, endTd);
var selection = getSelectedCells(table);
selection = tinymce.map(selection, function(elm) {
return elm.innerHTML;
});
deepEqual(selection, cellContents);
}
test("Table grid selection", function() {
assertTableSelection('<table><tr><td>1</td><td>2</td></tr><tr><td>3</td><td>4</td></tr></table>', ['1', '2'], ['1', '2']);
assertTableSelection('<table><tr><td>1</td><td>2</td></tr><tr><td>3</td><td>4</td></tr></table>', ['1', '3'], ['1', '3']);
assertTableSelection('<table><tr><td>1</td><td>2</td></tr><tr><td>3</td><td>4</td></tr></table>', ['1', '4'], ['1', '2', '3', '4']);
assertTableSelection('<table><tr><td colspan="2" rowspan="2">1</td><td>3</td></tr><tr><td>6</td></tr></table>', ['1', '6'], ['1', '3', '6']);
assertTableSelection(
'<table>' +
'<tr>' +
'<td>1</td>' +
'<td>2</td>' +
'<td>3</td>' +
'</tr>' +
'<tr>' +
'<td colspan="2" rowspan="2">4</td>' +
'<td>5</td>' +
'</tr>' +
'<tr>' +
'<td>6</td>' +
'</tr>' +
'</table>',
['2', '6'],
['2', '3', '4', '5', '6']
);
});
})();
| wicak29/takon-seek | assets/tinymce/tests/plugins/table.js | JavaScript | mit | 58,221 |
/**
* This should be called by all clients, specifying whether extra widgets are
* needed via `loadExtraWidgets`. It is idempotent, so it's not a problem to
* call it multiple times.
*
* skipMathJax:
* if false/undefined, MathJax will be configured, and the
* promise will wait for MathJax to load (if it hasn't already).
* loadExtraWidgets:
* if true, `extra-widgets` will be required. The client must have already
* loaded the file, either by using the full perseus bundle
* `/build/perseus.js`, or by loading `/build/perseus-extras.js` prior to
* calling `Perseus.init()`.
*/
const init = function(options) {
// Pass skipMathJax: true if MathJax is already loaded and configured.
const skipMathJax = options.skipMathJax;
const mathJaxDeferred = $.Deferred();
if (skipMathJax) {
mathJaxDeferred.resolve();
} else {
MathJax.Hub.Config({
messageStyle: "none",
skipStartupTypeset: "none",
"HTML-CSS": {
availableFonts: ["TeX"],
imageFont: null,
scale: 100,
showMathMenu: false,
},
});
MathJax.Hub.Configured();
MathJax.Hub.Queue(mathJaxDeferred.resolve);
}
return mathJaxDeferred;
};
module.exports = init;
| learningequality/perseus | src/init.js | JavaScript | mit | 1,317 |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>mathcomp-analysis: Not compatible 👼</title>
<link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" />
<link href="../../../../../bootstrap.min.css" rel="stylesheet">
<link href="../../../../../bootstrap-custom.css" rel="stylesheet">
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">
<script src="../../../../../moment.min.js"></script>
<!-- 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/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="container">
<div class="navbar navbar-default" role="navigation">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a>
</div>
<div id="navbar" class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li><a href="../..">clean / released</a></li>
<li class="active"><a href="">8.8.2 / mathcomp-analysis - 0.3.2</a></li>
</ul>
</div>
</div>
</div>
<div class="article">
<div class="row">
<div class="col-md-12">
<a href="../..">« Up</a>
<h1>
mathcomp-analysis
<small>
0.3.2
<span class="label label-info">Not compatible 👼</span>
</small>
</h1>
<p>📅 <em><script>document.write(moment("2022-02-08 15:53:49 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-02-08 15:53:49 UTC)</em><p>
<h2>Context</h2>
<pre># Packages matching: installed
# Name # Installed # Synopsis
base-bigarray base
base-num base Num library distributed with the OCaml compiler
base-threads base
base-unix base
camlp5 7.14 Preprocessor-pretty-printer of OCaml
conf-findutils 1 Virtual package relying on findutils
conf-perl 2 Virtual package relying on perl
coq 8.8.2 Formal proof management system
num 0 The Num library for arbitrary-precision integer and rational arithmetic
ocaml 4.03.0 The OCaml compiler (virtual package)
ocaml-base-compiler 4.03.0 Official 4.03.0 release
ocaml-config 1 OCaml Switch Configuration
ocamlfind 1.9.3 A library manager for OCaml
# opam file:
opam-version: "2.0"
maintainer: "[email protected]"
homepage: "https://github.com/math-comp/analysis"
bug-reports: "https://github.com/math-comp/analysis/issues"
dev-repo: "git+https://github.com/math-comp/analysis.git"
license: "CECILL-C"
authors: [
"Reynald Affeldt"
"Cyril Cohen"
"Assia Mahboubi"
"Damien Rouhling"
"Pierre-Yves Strub"
]
build: [
[make "INSTMODE=global" "config"]
[make "-j%{jobs}%"]
]
install: [
[make "install"]
]
depends: [
"coq" { ((>= "8.10" & < "8.13~") | = "dev") }
"coq-mathcomp-bigenough" {(>= "1.0.0")}
"coq-mathcomp-field" {(>= "1.11.0" & < "1.12~")}
"coq-mathcomp-finmap" {(>= "1.5.0" & < "1.6~")}
]
synopsis: "An analysis library for mathematical components"
description: """
This repository contains an experimental library for real analysis for
the Coq proof-assistant and using the Mathematical Components library.
It is inspired by the Coquelicot library.
"""
tags: [
"category:Mathematics/Real Calculus and Topology"
"keyword: analysis"
"keyword: topology"
"keyword: real numbers"
"logpath: mathcomp.analysis"
"date:2020-08-11"
]
url {
http: "https://github.com/math-comp/analysis/archive/0.3.2.tar.gz"
checksum: "sha512=aa2ffac487d71d3aceea9dafca21d7c8bfcbaaf52d9977fd9bf19a055d65597b95d9e2e10dc7da10676ab2f86a8cc205aac9e0fa08360fc127971f60f68c5430"
}
</pre>
<h2>Lint</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Dry install 🏜️</h2>
<p>Dry install with the current Coq version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam install -y --show-action coq-mathcomp-analysis.0.3.2 coq.8.8.2</code></dd>
<dt>Return code</dt>
<dd>5120</dd>
<dt>Output</dt>
<dd><pre>[NOTE] Package coq is already installed (current version is 8.8.2).
The following dependencies couldn't be met:
- coq-mathcomp-analysis -> coq >= dev -> ocaml >= 4.05.0
base of this switch (use `--unlock-base' to force)
No solution found, exiting
</pre></dd>
</dl>
<p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-mathcomp-analysis.0.3.2</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Install dependencies</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Install 🚀</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Installation size</h2>
<p>No files were installed.</p>
<h2>Uninstall 🧹</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Missing removes</dt>
<dd>
none
</dd>
<dt>Wrong removes</dt>
<dd>
none
</dd>
</dl>
</div>
</div>
</div>
<hr/>
<div class="footer">
<p class="text-center">
Sources are on <a href="https://github.com/coq-bench">GitHub</a> © Guillaume Claret 🐣
</p>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="../../../../../bootstrap.min.js"></script>
</body>
</html>
| coq-bench/coq-bench.github.io | clean/Linux-x86_64-4.03.0-2.0.5/released/8.8.2/mathcomp-analysis/0.3.2.html | HTML | mit | 7,588 |
\newcommand{\U}[1]{\ensuremath{\,\textrm{#1}}}
\newcommand{\tref}{\ensuremath{\textrm{ref}}}
\newcommand{\vthref}{\ensuremath{v_\textrm{thref}}}
\newcommand{\gkw}{\ensuremath{\texttt{GKW}}}
\newcommand{\gkdb}{\ensuremath{\texttt{GKDB}}}
\documentclass[a4paper]{report}
\usepackage{fullpage}
\usepackage{amsmath}
\usepackage{amssymb}
\usepackage{bm}
\usepackage{graphicx}
\usepackage{tabularx}
\usepackage{hyperref}
\hypersetup{plainpages=false, colorlinks=true, linkcolor=blue, citecolor=blue, urlcolor=blue, pdftitle={GKDB documentation}}
\begin{document}
\title{GKW to GKDB data conversion}
\author{Y. Camenen on behalf of the GKDB working group}
\date{Last update: June 4, 2018}
\maketitle
\tableofcontents
\chapter{Preamble}
This document describes how to transform inputs and outputs from a GKW flux-tube simulation to match the format used in the GyroKinetic DataBase (GKDB). \\
The reader is assumed to have some knowledge of GKW \cite{Peeters:CPC09,GKW:wiki} and to have read the documentation of the GKDB \cite{GKDB:wiki}. The structure of the present document follows that of the GKDB documentation.
\chapter{Conventions and normalisations}
\section{Coordinate systems}
In GKW, the toroidal direction is defined to have the cylindrical coordinate system $(R,Z,\varphi)$ right-handed whereas in the GKDB it is defined to have $(R,\varphi,Z)$ right-handed, see Fig.\ref{fig:coord1}. In practice, it means that:
\begin{equation}
\varphi^\gkdb=-\varphi^\gkw
\end{equation}
\begin{figure}[h]
\begin{center}
\includegraphics[width=7cm]{GKW_coord.pdf}
\includegraphics[width=7cm]{GKDB_coord.pdf}
\caption{\label{fig:coord1} Cylindrical coordinate system used in GKW (left) and the GKDB (right).}
\end{center}
\end{figure}\\
The flux surface centre definition depends on how the magnetic equilibrium is specified. For \texttt{miller} geometry, the definition of $R_0$ is identical to that used in the GKDB and $Z_0$ is given as an input in the geometry namelist:
\begin{equation}
R_0^\texttt{GKW-miller} = R_0^\gkdb \qquad \qquad Z_0^\texttt{GKW-miller} = \texttt{zmil}R_\tref^\gkw
\end{equation}
For \texttt{chease} geometry, $R_0$ is taken to be the value of \texttt{R0EXP} specified in the \texttt{hamada.dat} file and $Z_0$ is the elevation of the magnetic axis.
\begin{equation}
R_0^\texttt{GKW-chease} = \texttt{R0EXP} \qquad \qquad Z_0^\texttt{GKW-chease} = Z_\textrm{axis}
\end{equation}
The definition of the (dimensional) radial coordinate $r$ is identical in GKW and the GKDB:
\begin{equation}
r^\gkw = r^\gkdb
\end{equation}
The calculation of the poloidal angle $\theta$ used in the GKDB from GKW inputs is documented in section~\ref{sec:magequil}. At this stage, just notice that most of the time $Z_0^\gkw\neq Z_0^\gkdb$, therefore, the points $s=0$ and $\theta=0$ do not necessarily coincide.
\section{Reference quantities}
In GKW and the GKDB, all quantities are normalised and made dimensionless by making use of reference quantities. In what follows, normalised quantities are denoted with a "N" subscript. For instance, the normalised version of an arbitrary quantity $\mathcal{A}$ with the dimension of a length will be $\mathcal{A}_N^\gkw=\mathcal{A}/R_\tref^\gkw$ in GKW and $\mathcal{A}_N^\gkdb=\mathcal{A}/R_\tref^\gkdb$ in the GKDB. The conversion from GKW to the GKDB involves the ratio of reference quantities. For the example above:
\begin{equation}
\mathcal{A}_N^\gkdb = \frac{R_\tref^\gkw}{R_\tref^\gkdb} \mathcal{A}_N^\gkw
\end{equation}
The ratio of the various reference quantities used in GKW and the GKDB are:
\begin{align*}
q_\textrm{rat} &= \frac{q_\tref^\gkw}{q_\tref^\gkdb} = - \frac{1}{\texttt{z}^\gkw_{e^-}} & R_\textrm{rat}^\texttt{miller} &= \frac{R_\tref^\texttt{GKW-miller}}{R_\tref^\gkdb} = 1 \\
m_\textrm{rat} &= \frac{m_\tref^\gkw}{m_\tref^\gkdb} = \frac{m_e}{m_D}\frac{1}{\texttt{mass}^\gkw_{e^-}} & B_\textrm{rat}^\texttt{miller} &= \frac{B_\tref^\texttt{GKW-miller}}{B_\tref^\gkdb} = 1 \\
T_\textrm{rat} &= \frac{T_\tref^\gkw}{T_\tref^\gkdb} = \frac{1}{\texttt{temp}^\gkw_{e^-}} &R_\textrm{rat}^\texttt{chease} &= \frac{R_\tref^\texttt{GKW-chease}}{R_\tref^\gkdb} = \frac{\texttt{R0EXP}}{R_0^\gkdb} \\
n_\textrm{rat} &= \frac{n_\tref^\gkw}{n_\tref^\gkdb} = \frac{1}{\texttt{dens}^\gkw_{e^-}} \frac{n_e(s=0)}{n_e(\theta=0)} & B_\textrm{rat}^\texttt{chease} &= \frac{B_\tref^\texttt{GKW-chease}}{B_\tref^\gkdb} = \frac{\texttt{B0EXP}}{B_0^\gkdb}
\end{align*}
where the $e^-$ subscript denotes the electron species and the electron to deuterium mass ratio is taken to be $\frac{m_e}{m_D}=2.7237 \times 10^{-4}$ in the GKDB.\\
The reference charge, mass, temperature and density ratio can be computed from the electron species parameters in the \texttt{SPECIES} namelist of the GKW input file. The poloidal asymmetry factor for the electron density can be computed from data in the \texttt{cfdens} file (GKW output). With \texttt{chease} geometry, the ratios $ R_\textrm{rat}$ and $ B_\textrm{rat}$ can be computed from data in the \texttt{hamada.dat} file (GKW input).\\
The following derived quantities will also be used for the conversion:
\begin{align*}
v_\textrm{thrat} &= \sqrt{\frac{T_\textrm{rat}}{m_\textrm{rat}}} & \rho_\textrm{rat} = \frac{q_\textrm{rat} B_\textrm{rat}}{m_\textrm{rat}v_\textrm{thrat}}
\end{align*}
\chapter{Inputs}
\section{Magnetic equilibrium} \label{sec:magequil}
Only \texttt{miller} and \texttt{chease} magnetic equilibrium specifications are compatible with the GKDB format (\texttt{s-alpha} and \texttt{circ} are not an exact solution of the Grad-Shafranov equation).
\subsection{Flux surface centre}
Let's call $\{R_{\Psi_0},Z_{\Psi_0}\}$ a set of points discretizing the flux surface of interest.\\
The values of $\{R_{\Psi_0},Z_{\Psi_0}\}/R_\tref^\gkw$ are available in the \texttt{geom.dat} file (GKW output) and can be used to compute $\{R_0^\gkdb,Z_0^\gkdb\}/R_\tref^\gkw$.
\subsection{Poloidal angle}
With these values, one can then compute the GKDB poloidal angle $\theta$:
\begin{equation}
\tan \theta = - \frac{Z_{\Psi_0}/R_\tref^\gkw-Z_0^\gkdb/R_\tref^\gkw}{R_{\Psi_0}/R_\tref^\gkw-R_0^\gkdb/R_\tref^\gkw}
\end{equation}
As the discretisation of the flux surface in \texttt{geom.dat} is done on the GKW $s$ grid, the equation above gives the relationship between $\theta$ and $s$.
\subsection{Radial coordinate}
\begin{equation}
r_N^\gkdb = r_N^\gkw \cdot R_\textrm{rat}= \texttt{eps}\cdot R_\textrm{rat}
\end{equation}
\subsection{Toroidal field and current direction}
\begin{equation}
s_b^\gkdb = - s_b^\gkw=-\texttt{signb} \qquad \textrm{and} \qquad s_j^\gkw=-s_j^\gkw=-\texttt{signj}
\end{equation}
\subsection{Safety factor}
\begin{equation}
q^\gkdb = s_b^\gkw s_j^\gkw q^\gkw = \texttt{signb}\cdot\texttt{signj}\cdot\texttt{q}
\end{equation}
\subsection{Magnetic shear}
\begin{equation}
\hat{s}^\gkdb = \hat{s}^\gkw = \texttt{shat}
\end{equation}
\subsection{Pressure gradient (entering the curvature drift)}
\begin{equation}
\beta^{' \gkdb}_N = - \beta^{' \gkw}_N \frac{B_\textrm{rat}^2}{R_\textrm{rat}}
\end{equation}
The value of $\beta^{' \gkw}_N $ is taken from \texttt{betaprime\_ref} for \texttt{miller} geometry or from the \texttt{geom.dat} file for \texttt{chease} geometry.
\subsection{Plasma shape}
To compute the shaping Fourier coefficients and their radial derivatives, one first need to compute:
\begin{equation}
a_N^\gkdb(r,\theta)=\frac{1}{R_\tref^\gkdb}\sqrt{\left[R_{\Psi_0}(r,\theta)-R_0^\gkdb\right]^2 + \left[Z_{\Psi_0}(r,\theta)-Z_0^\gkdb\right]^2}
\end{equation}
For \texttt{miller} geometry, this can be done by computing $\{R_{\Psi_0}(r,\theta),Z_{\Psi_0}(r,\theta)\}/R_\tref^\gkw$ from the Miller parameters of the GKW input files and then perform the Fourier expansion.\\
For \texttt{chease} geometry $\{R_{\Psi_0}(r,s),Z_{\Psi_0}(r,s)\}$ is directly available in the \texttt{hamada.dat} file and can be used together with the relationship between $\theta$ and $s$ to compute the Fourier coefficients.
\section{Species}
\subsection{Charge}
\begin{equation}
Z_{sN}^\gkdb = Z_{sN}^\gkw \cdot q_\textrm{rat} = \texttt{z}_s \cdot q_\textrm{rat}
\end{equation}
\subsection{Mass}
\begin{equation}
m_{sN}^\gkdb = m_{sN}^\gkw \cdot m_\textrm{rat} = \texttt{mass}_s \cdot m_\textrm{rat}
\end{equation}
\subsection{Density}
\begin{equation}
n_{sN}^\gkdb(\theta=0) = n_{sN}^\gkw(\theta=0) \cdot n_\textrm{rat} = \texttt{dens}_s \cdot n_\textrm{rat} \cdot \frac{n_{sN}^\gkw(\theta=0)}{n_{sN}^\gkw(s=0)}
\end{equation}
In the presence of poloidal asymmetries, the density at $\theta=0$ can be obtained from the \texttt{cfdens} output file. In this file, the first column is the $s$ grid, then comes the logarithmic density gradient for each species and finally the density for each species (all with GKW normalisations).
\subsection{Logarithmic density gradient}
\begin{equation}
\frac{R_\tref^\gkdb}{L_{n_s}^\gkdb}(\theta=0) = \frac{R_\tref^\gkw}{L_{n_s}^\gkw}(\theta=0) \cdot R_\textrm{rat} = \texttt{rln}_s \cdot R_\textrm{rat} \cdot \frac{{L_{n_s}^\gkw}(\theta=0)}{{L_{n_s}^\gkw}(s=0)}
\end{equation}
In the presence of poloidal asymmetries, the logarithmic density gradient at $\theta=0$ can be obtained from the \texttt{cfdens} output file. In this file, the first column is the $s$ grid, then comes the logarithmic density gradient for each species and finally the density for each species (all with GKW normalisations).
\subsection{Temperature}
\begin{equation}
T_{sN}^\gkdb = T_{sN}^\gkw \cdot T_\textrm{rat} = \texttt{temp}_s \cdot T_\textrm{rat}
\end{equation}
\subsection{Logarithmic temperature gradient}
\begin{equation}
\frac{R_\tref^\gkdb}{L_{T_s}^\gkdb} = \frac{R_\tref^\gkw}{L_{T_s}^\gkw} \cdot R_\textrm{rat} = \texttt{rlt}_s \cdot R_\textrm{rat}
\end{equation}
\subsection{Toroidal velocity}
\begin{equation}
u_N^\gkdb = s_b^\gkw\cdot u_N^\gkw \cdot \frac{v_\textrm{thrat}}{R_\textrm{rat}} = \texttt{signb} \cdot \texttt{vcor} \cdot \frac{v_\textrm{thrat}}{R_\textrm{rat}}
\end{equation}
\subsection{Toroidal velocity gradient}
\begin{equation}
u^{'\gkdb}_{sN} = s_b^\gkw\cdot u^{'\gkw}_{sN} \cdot \frac{v_\textrm{thrat}}{R_\textrm{rat}^2} = \texttt{signb} \cdot \texttt{uprim}_s \cdot \frac{v_\textrm{thrat}}{R_\textrm{rat}^2}
\end{equation}
\subsection{Plasma beta}
\begin{equation}
\beta_{eN}^\gkdb = \beta_N^\gkw \cdot n_\textrm{rat} \cdot T_\textrm{rat} \cdot B_\textrm{rat}^2
\end{equation}
The value of $\beta_N^\gkw$ is either taken from the input \texttt{beta\_ref} of the \texttt{SPCGENERAL} namelist when the \texttt{beta\_type='ref'} option is used or extracted from the output file \texttt{out} when the \texttt{beta\_type='eq'} option is used.
\subsection{Collisionality}
\begin{equation}
\nu_{eN}^\gkdb = \frac{e^4}{4\pi\varepsilon_0^2}\frac{1}{q_\textrm{rat}^4}\frac{T_\textrm{rat}^2}{n_\textrm{rat}R_\textrm{rat}}\frac{n_\tref^\gkw R_\tref^\gkw}{\left.T_\tref^{\gkw}\right.^2} = \frac{e^4}{4\pi\varepsilon_0^2}\frac{1}{q_\textrm{rat}^4}\frac{T_\textrm{rat}^2}{n_\textrm{rat}R_\textrm{rat}} \frac{\texttt{nref}\cdot\texttt{rref}}{\texttt{tref}^2}
\end{equation}
Note that the expression above assumes that the \texttt{freq\_override} option is set to false.
\subsection{Debye length}
Always zero in GKW runs.
\section{Wave vector}
\subsection{Radial wave vector}
\begin{equation}
\left. k_{r*}\rho_\tref\right.^\gkdb = \texttt{krrho}\cdot\frac{1}{\rho_\textrm{rat}}\cdot\sqrt{\frac{g^{\psi\psi}(\theta=0)}{g^{\psi\psi}(s=0)}}
\end{equation}
The quantity $g^{\psi \psi}$ is given on the $s$ grid in \texttt{geom.dat}
\subsection{Binormal wave vector}
\begin{equation}
\left. k_{\theta*}\rho_\tref\right.^\gkdb = \texttt{kthrho}\cdot\frac{1}{\rho_\textrm{rat}}\cdot\sqrt{\frac{g^{\zeta\zeta}(\theta=0)}{g^{\zeta\zeta}(s=0)}}
\end{equation}
The quantity $g^{\zeta \zeta}$ is given on the $s$ grid in \texttt{geom.dat}
\chapter{Outputs}
\section{Mode amplitude}
The normalised fields in GKW and the GKDB are related as follows:
\begin{equation}
\hat{\phi}_N^\gkdb = \hat{\phi}_N^\gkw\cdot\frac{T_\textrm{rat}\rho_\textrm{rat}}{q_\textrm{rat}R_\textrm{rat}}, \qquad \qquad
\hat{A}_{\parallel N}^\gkdb = \hat{A}_{\parallel N}^\gkw\cdot\frac{B_\textrm{rat}\rho_\textrm{rat}^2}{R_\textrm{rat}}, \qquad \qquad
\hat{B}_{\parallel N}^\gkdb = \hat{B}_{\parallel N}^\gkw\cdot\frac{B_\textrm{rat}\rho_\textrm{rat}}{R_\textrm{rat}},
\end{equation}
In GKW linear runs, the exponentially growing fields are further normalised with respect to the mode amplitude:
\begin{equation}
\hat{\phi}_{NN}^\gkw = \frac{1}{\mathcal{A}_f^\gkw}\hat{\phi}_N^\gkw, \qquad \qquad \hat{A_\parallel}_{NN}^\gkw = \frac{1}{\mathcal{A}_f^\gkw}\hat{A_\parallel}_N^\gkw, \qquad \qquad \hat{B_\parallel}_{NN}^\gkw = \frac{1}{\mathcal{A}_f^\gkw}\hat{B_\parallel}_N^\gkw
\end{equation}
with
\begin{equation}
\mathcal{A}_f^\gkw = \sqrt{\int \left[|\hat{\phi}_N^\gkw|^2 + |\hat{A}_{\parallel N}^\gkw|^2+|\hat{B}_{\parallel N}^\gkw|^2\right] \,\textrm{d}s} \bigg/ \int \,\textrm{d}s
\end{equation}
The mode amplitude used to normalise linear runs and compute the mode growth rate in the GKDB is
\begin{equation}
\mathcal{A}_f^\gkdb = \sqrt{\frac{1}{2\pi}\left.\int \left[|\hat{\phi}_N^\gkdb|^2 + |\hat{A}_{\parallel N}^\gkdb|^2 + |\hat{B}_{\parallel N}^\gkdb|^2\right] \,\textrm{d}\theta \right.}
\end{equation}
and the ratio of the GKDB to GKW mode amplitudes is therefore given by:
\begin{equation}
\frac{1}{\mathcal{A}_\textrm{rat}} = \frac{\mathcal{A}_f^\gkdb}{\mathcal{A}_f^\gkw} = \sqrt{\frac{1}{2\pi}\left[ |\frac{T_\textrm{rat}\rho_\textrm{rat}}{q_\textrm{rat}R_\textrm{rat}}\cdot\hat{\phi}_{NN}^\gkw|^2 + |\frac{B_\textrm{rat}\rho_\textrm{rat}^2}{R_\textrm{rat}}\cdot\hat{A}_{\parallel NN}^\gkw|^2+|\frac{B_\textrm{rat}\rho_\textrm{rat}}{R_\textrm{rat}}\cdot\hat{B}_{\parallel NN}^\gkw|^2\right]\,\textrm{d}\theta }
\end{equation}
The mode amplitude ratio can therefore be computed from the GKW output file \texttt{parallel.dat} which contains $\hat{\phi}_{NN}^\gkw(s)$, $\hat{A_\parallel}_{NN}^\gkw(s)$ and $\hat{B_\parallel}_{NN}^\gkw(s)$. Note that in this file, the fields may have been rotated in the complex plane, but this does not impact the mode amplitude calculation.
\section{Mode growth rate and frequency}
\begin{equation}
\gamma_N^\gkdb= \gamma_N^\gkw \cdot \frac{v_\textrm{thrat}}{R_\textrm{thrat}} \qquad\qquad \textrm{and}
\qquad \qquad \omega_{rN}^\gkdb= \omega_{rN}^\gkw \cdot \frac{v_\textrm{thrat}}{R_\textrm{thrat}}
\end{equation}
The tolerance on the mode growth rate convergence can be computed directly from the values of $\gamma_N^\gkw(t)$ stored in the GKW output file \texttt{time.dat}.
\section{Fluxes}
\begin{align}
\Gamma_{Ns}^\gkdb &= \Gamma_{Ns}^\gkw \cdot \mathcal{A}_\textrm{rat}^2\frac{v_\textrm{thrat}\rho_\textrm{rat}^2}{R_\textrm{rat}^2}\frac{n_{sN}^\gkw(s=0)}{n_{sN}^\gkw(\theta=0)}\\
\Pi_{Ns}^\gkdb &= \Pi_{Ns}^\gkw \cdot \mathcal{A}_\textrm{rat}^2\frac{m_\textrm{rat}v_\textrm{thrat}^2\rho_\textrm{rat}^2}{R_\textrm{rat}}\frac{n_{sN}^\gkw(s=0)}{n_{sN}^\gkw(\theta=0)}\sqrt{2T_{sN}^\gkw m_{sN}^\gkw}\\
Q_{Ns}^\gkdb &= Q_{Ns}^\gkw \cdot \mathcal{A}_\textrm{rat}^2\frac{v_\textrm{thrat}T_\textrm{rat}\rho_\textrm{rat}^2}{R_\textrm{rat}^2}\frac{n_{sN}^\gkw(s=0)}{n_{sN}^\gkw(\theta=0)}T_{sN}^\gkw
\end{align}
where $\Gamma_{Ns}^\gkw$, $\Pi_{Ns}^\gkw$ and $Q_{Ns}^\gkw$ are the entries \texttt{pflux}, \texttt{vflux} and \texttt{eflux} in the GKW output file \texttt{fluxes.dat}.
TO DO: add a comment on where to find the Laboratory frame fluxes and conversion gyro-center fluxes to particle fluxes
\section{Parallel mode structure}
\subsection{Fields}
\begin{align}
\phi_{Nf}^\gkdb &= \hat{\phi}_{NN}^\gkw\cdot \mathcal{A}_\textrm{rat}\frac{T_\textrm{rat}\rho_\textrm{rat}}{q_\textrm{rat}R_\textrm{rat}}\cdot \textrm{e}^{i\alpha}\\
A_{\parallel Nf}^\gkdb &= \hat{A}_{\parallel NN}^\gkw\cdot \mathcal{A}_\textrm{rat}\frac{B_\textrm{rat}\rho_\textrm{rat}^2}{R_\textrm{rat}}\cdot \textrm{e}^{i\alpha}\\
B_{\parallel Nf}^\gkdb &= \hat{B}_{\parallel NN}^\gkw\cdot \mathcal{A}_\textrm{rat}\frac{B_\textrm{rat}\rho_\textrm{rat}}{R_\textrm{rat}}\cdot \textrm{e}^{i\alpha}
\end{align}
with
\begin{equation}
\textrm{e}^{i\alpha} = \frac{|\hat{\phi}_{NN}^\gkw(\theta=0)|}{\hat{\phi}_{NN}^\gkw(\theta=0)}
\end{equation}
\subsection{Moments of the distribution function}
\begin{align}
\delta n_{sN}^\gkdb & = \delta n_{sN}^\gkw \cdot \mathcal{A}_\textrm{rat} \frac{\rho_\textrm{rat}}{R_\textrm{rat}}\frac{n_{sN}^\gkw(s=0)}{n_{sN}^\gkw(\theta=0)} \\
\delta v_{\parallel sN}^\gkdb & = \delta n_{sN}^\gkw\cdot \mathcal{A}_\textrm{rat} \frac{\rho_\textrm{rat}}{R_\textrm{rat}}\sqrt{\frac{T_\textrm{rat}}{m_\textrm{rat}}} \frac{n_{sN}^\gkw(s=0)}{n_{sN}^\gkw(\theta=0)}\sqrt{\frac{T_{sN}^\gkw }{m_{sN}^\gkw }}\\
\delta T_{\perp sN}^\gkdb & = \delta n_{sN}^\gkw\cdot \mathcal{A}_\textrm{rat} \frac{\rho_\textrm{rat}}{R_\textrm{rat}}T_\textrm{rat}\frac{n_{sN}^\gkw(s=0)}{n_{sN}^\gkw(\theta=0)}T_{sN}^\gkw\\
\delta T_{\parallel sN}^\gkdb & = \delta n_{sN}^\gkw\cdot \mathcal{A}_\textrm{rat} \frac{\rho_\textrm{rat}}{R_\textrm{rat}}T_\textrm{rat}\frac{n_{sN}^\gkw(s=0)}{n_{sN}^\gkw(\theta=0)}T_{sN}^\gkw
\end{align}
\bibliographystyle{unsrt}
\bibliography{gkw2gkdb}
\end{document}
| gkdb/gkdb | doc/gkw2gkdb/gkw2gkdb.tex | TeX | mit | 17,221 |
namespace treeDiM.EdgeCrushTest.Desktop
{
partial class AboutBox
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(AboutBox));
this.tableLayoutPanel = new System.Windows.Forms.TableLayoutPanel();
this.logoPictureBox = new System.Windows.Forms.PictureBox();
this.labelProductName = new System.Windows.Forms.Label();
this.labelVersion = new System.Windows.Forms.Label();
this.labelCopyright = new System.Windows.Forms.Label();
this.labelCompanyName = new System.Windows.Forms.Label();
this.textBoxDescription = new System.Windows.Forms.TextBox();
this.okButton = new System.Windows.Forms.Button();
this.tableLayoutPanel.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.logoPictureBox)).BeginInit();
this.SuspendLayout();
//
// tableLayoutPanel
//
this.tableLayoutPanel.ColumnCount = 2;
this.tableLayoutPanel.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 33F));
this.tableLayoutPanel.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 67F));
this.tableLayoutPanel.Controls.Add(this.logoPictureBox, 0, 0);
this.tableLayoutPanel.Controls.Add(this.labelProductName, 1, 0);
this.tableLayoutPanel.Controls.Add(this.labelVersion, 1, 1);
this.tableLayoutPanel.Controls.Add(this.labelCopyright, 1, 2);
this.tableLayoutPanel.Controls.Add(this.labelCompanyName, 1, 3);
this.tableLayoutPanel.Controls.Add(this.textBoxDescription, 1, 4);
this.tableLayoutPanel.Controls.Add(this.okButton, 1, 5);
this.tableLayoutPanel.Dock = System.Windows.Forms.DockStyle.Fill;
this.tableLayoutPanel.Location = new System.Drawing.Point(9, 9);
this.tableLayoutPanel.Name = "tableLayoutPanel";
this.tableLayoutPanel.RowCount = 6;
this.tableLayoutPanel.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 10F));
this.tableLayoutPanel.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 10F));
this.tableLayoutPanel.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 10F));
this.tableLayoutPanel.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 10F));
this.tableLayoutPanel.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 50F));
this.tableLayoutPanel.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 10F));
this.tableLayoutPanel.Size = new System.Drawing.Size(417, 265);
this.tableLayoutPanel.TabIndex = 0;
//
// logoPictureBox
//
this.logoPictureBox.Dock = System.Windows.Forms.DockStyle.Fill;
this.logoPictureBox.Image = ((System.Drawing.Image)(resources.GetObject("logoPictureBox.Image")));
this.logoPictureBox.Location = new System.Drawing.Point(3, 3);
this.logoPictureBox.Name = "logoPictureBox";
this.tableLayoutPanel.SetRowSpan(this.logoPictureBox, 6);
this.logoPictureBox.Size = new System.Drawing.Size(131, 259);
this.logoPictureBox.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage;
this.logoPictureBox.TabIndex = 12;
this.logoPictureBox.TabStop = false;
//
// labelProductName
//
this.labelProductName.Dock = System.Windows.Forms.DockStyle.Fill;
this.labelProductName.Location = new System.Drawing.Point(143, 0);
this.labelProductName.Margin = new System.Windows.Forms.Padding(6, 0, 3, 0);
this.labelProductName.MaximumSize = new System.Drawing.Size(0, 17);
this.labelProductName.Name = "labelProductName";
this.labelProductName.Size = new System.Drawing.Size(271, 17);
this.labelProductName.TabIndex = 19;
this.labelProductName.Text = "Product Name";
this.labelProductName.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// labelVersion
//
this.labelVersion.Dock = System.Windows.Forms.DockStyle.Fill;
this.labelVersion.Location = new System.Drawing.Point(143, 26);
this.labelVersion.Margin = new System.Windows.Forms.Padding(6, 0, 3, 0);
this.labelVersion.MaximumSize = new System.Drawing.Size(0, 17);
this.labelVersion.Name = "labelVersion";
this.labelVersion.Size = new System.Drawing.Size(271, 17);
this.labelVersion.TabIndex = 0;
this.labelVersion.Text = "Version";
this.labelVersion.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// labelCopyright
//
this.labelCopyright.Dock = System.Windows.Forms.DockStyle.Fill;
this.labelCopyright.Location = new System.Drawing.Point(143, 52);
this.labelCopyright.Margin = new System.Windows.Forms.Padding(6, 0, 3, 0);
this.labelCopyright.MaximumSize = new System.Drawing.Size(0, 17);
this.labelCopyright.Name = "labelCopyright";
this.labelCopyright.Size = new System.Drawing.Size(271, 17);
this.labelCopyright.TabIndex = 21;
this.labelCopyright.Text = "Copyright";
this.labelCopyright.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// labelCompanyName
//
this.labelCompanyName.Dock = System.Windows.Forms.DockStyle.Fill;
this.labelCompanyName.Location = new System.Drawing.Point(143, 78);
this.labelCompanyName.Margin = new System.Windows.Forms.Padding(6, 0, 3, 0);
this.labelCompanyName.MaximumSize = new System.Drawing.Size(0, 17);
this.labelCompanyName.Name = "labelCompanyName";
this.labelCompanyName.Size = new System.Drawing.Size(271, 17);
this.labelCompanyName.TabIndex = 22;
this.labelCompanyName.Text = "Company Name";
this.labelCompanyName.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// textBoxDescription
//
this.textBoxDescription.Dock = System.Windows.Forms.DockStyle.Fill;
this.textBoxDescription.Location = new System.Drawing.Point(143, 107);
this.textBoxDescription.Margin = new System.Windows.Forms.Padding(6, 3, 3, 3);
this.textBoxDescription.Multiline = true;
this.textBoxDescription.Name = "textBoxDescription";
this.textBoxDescription.ReadOnly = true;
this.textBoxDescription.ScrollBars = System.Windows.Forms.ScrollBars.Both;
this.textBoxDescription.Size = new System.Drawing.Size(271, 126);
this.textBoxDescription.TabIndex = 23;
this.textBoxDescription.TabStop = false;
this.textBoxDescription.Text = "Description";
//
// okButton
//
this.okButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.okButton.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.okButton.Location = new System.Drawing.Point(339, 239);
this.okButton.Name = "okButton";
this.okButton.Size = new System.Drawing.Size(75, 23);
this.okButton.TabIndex = 24;
this.okButton.Text = "&OK";
//
// AboutBox
//
this.AcceptButton = this.okButton;
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(435, 283);
this.Controls.Add(this.tableLayoutPanel);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "AboutBox";
this.Padding = new System.Windows.Forms.Padding(9);
this.ShowIcon = false;
this.ShowInTaskbar = false;
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
this.Text = "AboutBox";
this.tableLayoutPanel.ResumeLayout(false);
this.tableLayoutPanel.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.logoPictureBox)).EndInit();
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.TableLayoutPanel tableLayoutPanel;
private System.Windows.Forms.PictureBox logoPictureBox;
private System.Windows.Forms.Label labelProductName;
private System.Windows.Forms.Label labelVersion;
private System.Windows.Forms.Label labelCopyright;
private System.Windows.Forms.Label labelCompanyName;
private System.Windows.Forms.TextBox textBoxDescription;
private System.Windows.Forms.Button okButton;
}
}
| treeDiM/StackBuilder | Sources/treeDiM.EdgeCrushTest.Desktop/AboutBox.Designer.cs | C# | mit | 10,291 |
/**
* @author Richard Davey <[email protected]>
* @copyright 2019 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* @namespace Phaser.Sound.Types
*/
| englercj/phaser | src/sound/typedefs/index.js | JavaScript | mit | 243 |
---
title: Accessibility Tools
author: jlord
date: '2016-08-23'
---
Making accessible applications is important and we're happy to introduce new functionality to [Devtron](https://electronjs.org/devtron) and [Spectron](https://electronjs.org/spectron) that gives developers the opportunity to make their apps better for everyone.
---
Accessibility concerns in Electron applications are similar to those of websites because they're both ultimately HTML. With Electron apps, however, you can't use the online resources for accessibility audits because your app doesn't have a URL to point the auditor to.
These new features bring those auditing tools to your Electron app. You can choose to add audits to your tests with Spectron or use them within DevTools with Devtron. Read on for a summary of the tools or checkout our [accessibility documentation](https://electronjs.org/docs/tutorial/accessibility/) for more information.
### Spectron
In the testing framework Spectron, you can now audit each window and `<webview>` tag in your application. For example:
```javascript
app.client.auditAccessibility().then(function (audit) {
if (audit.failed) {
console.error(audit.message)
}
})
```
You can read more about this feature in [Spectron's documentation](https://github.com/electron/spectron#accessibility-testing).
### Devtron
In Devtron there is a new accessibility tab which will allow you to audit a page in your app, sort and filter the results.

Both of these tools are using the [Accessibility Developer Tools](https://github.com/GoogleChrome/accessibility-developer-tools) library built by Google for Chrome. You can learn more about the accessibility audit rules this library uses on that [repository's wiki](https://github.com/GoogleChrome/accessibility-developer-tools/wiki/Audit-Rules).
If you know of other great accessibility tools for Electron, add them to the [accessibility documentation](https://electronjs.org/docs/tutorial/accessibility/) with a pull request.
| dahmian/dahmian.github.io | data/blog/accessibility-tools.md | Markdown | mit | 2,123 |
<?php
namespace Timeline;
class Controller_Member_Setting extends \Controller_Site
{
protected $check_not_auth_action = array();
public function before()
{
parent::before();
}
/**
* Mmeber setting viewtype
*
* @access public
* @return Response
*/
public function action_viewtype()
{
$page_name = term('timeline.view', 'site.display', 'site.setting');
$val = \Form_MemberConfig::get_validation($this->u->id, 'viewtype', 'Timeline');
if (\Input::method() == 'POST')
{
\Util_security::check_csrf();
try
{
if (!$val->run()) throw new \FuelException($val->show_errors());
$post = $val->validated();
\DB::start_transaction();
\Form_MemberConfig::save($this->u->id, $val, $post);
\DB::commit_transaction();
\Session::set_flash('message', __('message_change_complete_for', array('label' => $page_name)));
\Response::redirect('member/setting');
}
catch(\FuelException $e)
{
if (\DB::in_transaction()) \DB::rollback_transaction();
\Session::set_flash('error', $e->getMessage());
}
}
$this->set_title_and_breadcrumbs($page_name, array('member/setting' => t('site.setting')), $this->u);
$this->template->content = \View::forge('member/setting/_parts/form', array('val' => $val));
}
}
| uzura8/flockbird | fuel/app/modules/timeline/classes/controller/member/setting.php | PHP | mit | 1,270 |
<!DOCTYPE html>
{%include 'head.html' %}
<body>
<article>
{% include 'header.html' %}
{% import 'macro.html' as macros %}
<section class="container">
<div class=content>
<article >
<div class="ans-verification">
<h2>You were {{validation}}!</h2>
</div>
<div class="ans-choices">
<section class="ans-correct">
<div class="ans-lead">
<h3>The answer was..</h3>
</div>
<div class="ans-pic">
<img class = "ans-img" src={{species_data[question.answer].picture}}>
</div>
<div class="ans-name">
<a href="{{ species_data[question.answer].web_url}}" target="_blank">{{ macros.italicise_names(species_data[question.answer]) }}</a>
</div>
</section>
<section class="ans-others">
<div class="ans-others-lead">
<h3>Your other choices were: </h4>
</div>
<div class="ans-others-list">
{% for species in question.species %}
{% if species != question.answer %}
<div class="row">
<div class="cell"><img class = thumb src={{species_data[species].thumb}}></div>
<div class="cell"><b><a href="{{ species_data[species].web_url }}" target="_blank">{{ macros.italicise_names(species_data[species])}}</a></b> </div>
</div>
{% endif %}
{% endfor %}
<div class=buttoncontainer>
<form method="post" action = "/next">
<button type="submit" > {%if question_num == total_questions%} Get your score! {%else%} Next question {%endif%} </button>
</form>
</div>
</section>
</div>
<section class="ans-description">
<h2> About this species </h2>
<div class="ans-text">
<p>
{{ species_data[question.answer].text }}
</p>
</div>
</section>
</article>
</div>
</section>
{% include 'footer.html' %}
</article>
</body>
| linbug/planigale | templates/answer.html | HTML | mit | 3,036 |
package P07;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
/**
* Created by Yana on 7/1/2017.
*/
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
int numberOfStudents = Integer.parseInt(reader.readLine());
List<Student> students = new ArrayList<>();
for (int i = 0; i < numberOfStudents ; i++) {
String[] data = reader.readLine().split("\\s");
String name = data[0];
List<Double> grades = new ArrayList<>();
for (int j = 1; j < data.length; j++) {
grades.add(Double.parseDouble(data[j]));
}
Student student = new Student(name, grades);
students.add(student);
}
students.stream().filter(a->a.getAverageGrade()>=5.00).sorted((a,b) ->{
int result = a.getName().compareTo(b.getName());
if(result == 0){
result = Double.compare(b.getAverageGrade(), a.getAverageGrade());
}
return result;
}).forEach(a-> System.out.printf("%s -> %.2f\n", a.getName(),a.getAverageGrade()));
}
}
| yangra/SoftUni | Java-DB-Fundamentals/DatabasesFrameworks-Hibernate&SpringData/02.OOPOverview/src/P07/Main.java | Java | mit | 1,358 |
<?php
namespace cncap\yii2\oauth2server;
class Request extends \OAuth2\Request
{
use traits\ClassNamespace;
}
| cncap/yii2OAuthServer | Request.php | PHP | mit | 116 |
/******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId])
/******/ return installedModules[moduleId].exports;
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ exports: {},
/******/ id: moduleId,
/******/ loaded: false
/******/ };
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/ // Flag the module as loaded
/******/ module.loaded = true;
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/ // Load entry module and return exports
/******/ return __webpack_require__(0);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ function(module, exports, __webpack_require__) {
var makeFolders = __webpack_require__(1);
var getQueryStringParameter = function (param) {
var params = document.URL.split("?")[1].split("&");
var strParams = "";
for (var i = 0; i < params.length; i = i + 1) {
var singleParam = params[i].split("=");
if (singleParam[0] == param) {
return decodeURIComponent(singleParam[1]);
}
}
};
var appWebUrl = getQueryStringParameter('SPAppWebUrl');
var listTitle = 'TestList';
var folderPath = 'Folder1/Folder2';
makeFolders(appWebUrl, listTitle, folderPath, false, function (sender, args) {
var clientContext = SP.ClientContext.get_current();
var list = clientContext.get_web().get_lists().getByTitle(listTitle);
var folderUrls = [appWebUrl + '/Lists/TestList/Folder1', appWebUrl + '/Lists/TestList/Folder1/Folder2'];
for (var i = 0; i < 2; i++) {
var listItemCreateInfo = new SP.ListItemCreationInformation();
listItemCreateInfo.set_folderUrl(folderUrls[i]);
var listItem = list.addItem(listItemCreateInfo);
listItem.set_item('Title', 'Item ' + (i + 1));
listItem.update();
clientContext.load(listItem);
}
clientContext.executeQueryAsync(function (sender, args) {
$('#message').html('Folders are createdly successfully. <a href=\'' + appWebUrl + '/Lists/TestList/Folder1\'>Folder1</a>, <a href=\'' + appWebUrl + '/Lists/TestList/Folder1/Folder2\'>Folder1/Folder2</a>');
}, function (sender, args) {
$('#message').text(args.get_message());
});
}, function (sender, args) {
$('#message').text(args.get_message());
});
/***/ },
/* 1 */
/***/ function(module, exports, __webpack_require__) {
var contextHelper = __webpack_require__(2);
function makeFolders(webUrl, listTitle, folderPath, crossSite, done, error) {
var contextWrapper = contextHelper(webUrl, crossSite);
var clientContext = contextWrapper.clientContext;
var web = contextWrapper.web;
var folderNames = folderPath.split('/');
if (folderNames.length === 0) {
return;
}
var list = web.get_lists().getByTitle(listTitle);
var parentFolder = list.get_rootFolder();
makeFoldersRecursively(parentFolder, folderNames, done, error);
}
function makeFoldersRecursively(parentFolder, folderNames, done, error) {
var clientContext = parentFolder.get_context();
var folderName = folderNames.shift();
var newFolder = parentFolder.get_folders().add(folderName);
clientContext.load(newFolder);
clientContext.executeQueryAsync(function (sender, args) {
if (folderNames.length === 0) {
done();
} else {
makeFoldersRecursively(newFolder, folderNames, done, error);
}
}, error);
}
module.exports = makeFolders;
/***/ },
/* 2 */
/***/ function(module, exports) {
function contextHelper(webUrl, crossSite) {
var web = null;
var site = null;
var clientContext = null;
var appContextSite = null;
if (crossSite) {
clientContext = SP.ClientContext.get_current();
appContextSite = new SP.AppContextSite(clientContext, webUrl);
web = appContextSite.get_web();
site = appContextSite.get_site();
} else {
clientContext = new SP.ClientContext(webUrl);
web = clientContext.get_web();
site = clientContext.get_site();
}
return {
web: web,
site: site,
clientContext: clientContext,
appContextSite: appContextSite
};
}
module.exports = contextHelper;
/***/ }
/******/ ]); | Frederick-S/sp-make-folders | test/Scripts/App.js | JavaScript | mit | 5,024 |
<div class="jumbotron">
<div class="container">
<h1>Angular/Bootstrap Match Game</h1>
<p>This is a simple "card match" game written with AngularJS and Bootstrap CSS.</p>
<p><a href="https://github.com/zoul0813/angular-match" class="btn btn-primary btn-lg" target="_blank">View Source on GitHub</a>
</div>
</div>
<div class="container">
<div class="row mb-3">
<div class="col-md-12">
<div class="btn-toolbar">
<div class="btn-group mr-2">
<button type="button" class="btn btn-lg btn-success" (click)="onNewGame()">New Game</button>
</div>
<div class="input-group">
<div class="input-group-addon">Size</div>
<input class="form-control" type="number" min="1" max="14" step="1" [(ngModel)]="deckSize" />
</div>
</div>
</div>
</div>
<match-component [deckSize]="deckSize" (guess)="onGuess($event)" (match)="onMatch($event)" (complete)="onComplete($event)"></match-component>
<div class="row mb-3">
<div class="col-md-6 card card-inverse card-primary p-3 text-center">
Guesses: {{ guesses }}, Matches: {{ matches }}
</div>
<div class="col-md-6 card card-inverse card-success p-3 text-center">
Games: {{ games }}, Complete: {{ completed }}
</div>
</div>
</div> | zoul0813/angular-match | src/app/app.component.html | HTML | mit | 1,289 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.