repo_name stringlengths 4 116 | path stringlengths 4 379 | size stringlengths 1 7 | content stringlengths 3 1.05M | license stringclasses 15
values |
|---|---|---|---|---|
aasiutin/electrum | plugins/trezor/qt_generic.py | 24505 | from functools import partial
import threading
from PyQt4.Qt import Qt
from PyQt4.Qt import QGridLayout, QInputDialog, QPushButton
from PyQt4.Qt import QVBoxLayout, QLabel, SIGNAL
from electrum_gui.qt.util import *
from .plugin import TIM_NEW, TIM_RECOVER, TIM_MNEMONIC
from ..hw_wallet.qt import QtHandlerBase, QtPluginBase
from electrum.i18n import _
from electrum.plugins import hook, DeviceMgr
from electrum.util import PrintError, UserCancelled
from electrum.wallet import Wallet, Standard_Wallet
PASSPHRASE_HELP_SHORT =_(
"Passphrases allow you to access new wallets, each "
"hidden behind a particular case-sensitive passphrase.")
PASSPHRASE_HELP = PASSPHRASE_HELP_SHORT + " " + _(
"You need to create a separate Electrum wallet for each passphrase "
"you use as they each generate different addresses. Changing "
"your passphrase does not lose other wallets, each is still "
"accessible behind its own passphrase.")
RECOMMEND_PIN = _(
"You should enable PIN protection. Your PIN is the only protection "
"for your bitcoins if your device is lost or stolen.")
PASSPHRASE_NOT_PIN = _(
"If you forget a passphrase you will be unable to access any "
"bitcoins in the wallet behind it. A passphrase is not a PIN. "
"Only change this if you are sure you understand it.")
CHARACTER_RECOVERY = (
"Use the recovery cipher shown on your device to input your seed words. "
"The cipher changes with every keypress.\n"
"After at most 4 letters the device will auto-complete a word.\n"
"Press SPACE or the Accept Word button to accept the device's auto-"
"completed word and advance to the next one.\n"
"Press BACKSPACE to go back a character or word.\n"
"Press ENTER or the Seed Entered button once the last word in your "
"seed is auto-completed.")
class CharacterButton(QPushButton):
def __init__(self, text=None):
QPushButton.__init__(self, text)
def keyPressEvent(self, event):
event.setAccepted(False) # Pass through Enter and Space keys
class CharacterDialog(WindowModalDialog):
def __init__(self, parent):
super(CharacterDialog, self).__init__(parent)
self.setWindowTitle(_("KeepKey Seed Recovery"))
self.character_pos = 0
self.word_pos = 0
self.loop = QEventLoop()
self.word_help = QLabel()
self.char_buttons = []
vbox = QVBoxLayout(self)
vbox.addWidget(WWLabel(CHARACTER_RECOVERY))
hbox = QHBoxLayout()
hbox.addWidget(self.word_help)
for i in range(4):
char_button = CharacterButton('*')
char_button.setMaximumWidth(36)
self.char_buttons.append(char_button)
hbox.addWidget(char_button)
self.accept_button = CharacterButton(_("Accept Word"))
self.accept_button.clicked.connect(partial(self.process_key, 32))
self.rejected.connect(partial(self.loop.exit, 1))
hbox.addWidget(self.accept_button)
hbox.addStretch(1)
vbox.addLayout(hbox)
self.finished_button = QPushButton(_("Seed Entered"))
self.cancel_button = QPushButton(_("Cancel"))
self.finished_button.clicked.connect(partial(self.process_key,
Qt.Key_Return))
self.cancel_button.clicked.connect(self.rejected)
buttons = Buttons(self.finished_button, self.cancel_button)
vbox.addSpacing(40)
vbox.addLayout(buttons)
self.refresh()
self.show()
def refresh(self):
self.word_help.setText("Enter seed word %2d:" % (self.word_pos + 1))
self.accept_button.setEnabled(self.character_pos >= 3)
self.finished_button.setEnabled((self.word_pos in (11, 17, 23)
and self.character_pos >= 3))
for n, button in enumerate(self.char_buttons):
button.setEnabled(n == self.character_pos)
if n == self.character_pos:
button.setFocus()
def is_valid_alpha_space(self, key):
# Auto-completion requires at least 3 characters
if key == ord(' ') and self.character_pos >= 3:
return True
# Firmware aborts protocol if the 5th character is non-space
if self.character_pos >= 4:
return False
return (key >= ord('a') and key <= ord('z')
or (key >= ord('A') and key <= ord('Z')))
def process_key(self, key):
self.data = None
if key == Qt.Key_Return and self.finished_button.isEnabled():
self.data = {'done': True}
elif key == Qt.Key_Backspace and (self.word_pos or self.character_pos):
self.data = {'delete': True}
elif self.is_valid_alpha_space(key):
self.data = {'character': chr(key).lower()}
if self.data:
self.loop.exit(0)
def keyPressEvent(self, event):
self.process_key(event.key())
if not self.data:
QDialog.keyPressEvent(self, event)
def get_char(self, word_pos, character_pos):
self.word_pos = word_pos
self.character_pos = character_pos
self.refresh()
if self.loop.exec_():
self.data = None # User cancelled
class QtHandler(QtHandlerBase):
char_signal = pyqtSignal(object)
pin_signal = pyqtSignal(object)
def __init__(self, win, pin_matrix_widget_class, device):
super(QtHandler, self).__init__(win, device)
self.char_signal.connect(self.update_character_dialog)
self.pin_signal.connect(self.pin_dialog)
self.pin_matrix_widget_class = pin_matrix_widget_class
self.character_dialog = None
def get_char(self, msg):
self.done.clear()
self.char_signal.emit(msg)
self.done.wait()
data = self.character_dialog.data
if not data or 'done' in data:
self.character_dialog.accept()
self.character_dialog = None
return data
def get_pin(self, msg):
self.done.clear()
self.pin_signal.emit(msg)
self.done.wait()
return self.response
def pin_dialog(self, msg):
# Needed e.g. when resetting a device
self.clear_dialog()
dialog = WindowModalDialog(self.top_level_window(), _("Enter PIN"))
matrix = self.pin_matrix_widget_class()
vbox = QVBoxLayout()
vbox.addWidget(QLabel(msg))
vbox.addWidget(matrix)
vbox.addLayout(Buttons(CancelButton(dialog), OkButton(dialog)))
dialog.setLayout(vbox)
dialog.exec_()
self.response = str(matrix.get_value())
self.done.set()
def update_character_dialog(self, msg):
if not self.character_dialog:
self.character_dialog = CharacterDialog(self.top_level_window())
self.character_dialog.get_char(msg.word_pos, msg.character_pos)
self.done.set()
class QtPlugin(QtPluginBase):
# Derived classes must provide the following class-static variables:
# icon_file
# pin_matrix_widget_class
def create_handler(self, window):
return QtHandler(window, self.pin_matrix_widget_class(), self.device)
@hook
def receive_menu(self, menu, addrs, wallet):
if type(wallet) is not Standard_Wallet:
return
keystore = wallet.get_keystore()
if type(keystore) == self.keystore_class and len(addrs) == 1:
def show_address():
keystore.thread.add(partial(self.show_address, wallet, addrs[0]))
menu.addAction(_("Show on %s") % self.device, show_address)
def show_settings_dialog(self, window, keystore):
device_id = self.choose_device(window, keystore)
if device_id:
SettingsDialog(window, self, keystore, device_id).exec_()
def request_trezor_init_settings(self, wizard, method, device):
vbox = QVBoxLayout()
next_enabled = True
label = QLabel(_("Enter a label to name your device:"))
name = QLineEdit()
hl = QHBoxLayout()
hl.addWidget(label)
hl.addWidget(name)
hl.addStretch(1)
vbox.addLayout(hl)
def clean_text(widget):
text = unicode(widget.toPlainText()).strip()
return ' '.join(text.split())
if method in [TIM_NEW, TIM_RECOVER]:
gb = QGroupBox()
hbox1 = QHBoxLayout()
gb.setLayout(hbox1)
# KeepKey recovery doesn't need a word count
if method == TIM_NEW or self.device == 'TREZOR':
vbox.addWidget(gb)
gb.setTitle(_("Select your seed length:"))
bg = QButtonGroup()
for i, count in enumerate([12, 18, 24]):
rb = QRadioButton(gb)
rb.setText(_("%d words") % count)
bg.addButton(rb)
bg.setId(rb, i)
hbox1.addWidget(rb)
rb.setChecked(True)
cb_pin = QCheckBox(_('Enable PIN protection'))
cb_pin.setChecked(True)
else:
text = QTextEdit()
text.setMaximumHeight(60)
if method == TIM_MNEMONIC:
msg = _("Enter your BIP39 mnemonic:")
else:
msg = _("Enter the master private key beginning with xprv:")
def set_enabled():
wizard.next_button.setEnabled(Wallet.is_xprv(clean_text(text)))
text.textChanged.connect(set_enabled)
next_enabled = False
vbox.addWidget(QLabel(msg))
vbox.addWidget(text)
pin = QLineEdit()
pin.setValidator(QRegExpValidator(QRegExp('[1-9]{0,10}')))
pin.setMaximumWidth(100)
hbox_pin = QHBoxLayout()
hbox_pin.addWidget(QLabel(_("Enter your PIN (digits 1-9):")))
hbox_pin.addWidget(pin)
hbox_pin.addStretch(1)
if method in [TIM_NEW, TIM_RECOVER]:
vbox.addWidget(WWLabel(RECOMMEND_PIN))
vbox.addWidget(cb_pin)
else:
vbox.addLayout(hbox_pin)
passphrase_msg = WWLabel(PASSPHRASE_HELP_SHORT)
passphrase_warning = WWLabel(PASSPHRASE_NOT_PIN)
passphrase_warning.setStyleSheet("color: red")
cb_phrase = QCheckBox(_('Enable passphrases'))
cb_phrase.setChecked(False)
vbox.addWidget(passphrase_msg)
vbox.addWidget(passphrase_warning)
vbox.addWidget(cb_phrase)
wizard.set_main_layout(vbox, next_enabled=next_enabled)
if method in [TIM_NEW, TIM_RECOVER]:
item = bg.checkedId()
pin = cb_pin.isChecked()
else:
item = ' '.join(str(clean_text(text)).split())
pin = str(pin.text())
return (item, unicode(name.text()), pin, cb_phrase.isChecked())
class SettingsDialog(WindowModalDialog):
'''This dialog doesn't require a device be paired with a wallet.
We want users to be able to wipe a device even if they've forgotten
their PIN.'''
def __init__(self, window, plugin, keystore, device_id):
title = _("%s Settings") % plugin.device
super(SettingsDialog, self).__init__(window, title)
self.setMaximumWidth(540)
devmgr = plugin.device_manager()
config = devmgr.config
handler = keystore.handler
thread = keystore.thread
hs_rows, hs_cols = (64, 128)
def invoke_client(method, *args, **kw_args):
unpair_after = kw_args.pop('unpair_after', False)
def task():
client = devmgr.client_by_id(device_id)
if not client:
raise RuntimeError("Device not connected")
if method:
getattr(client, method)(*args, **kw_args)
if unpair_after:
devmgr.unpair_id(device_id)
return client.features
thread.add(task, on_success=update)
def update(features):
self.features = features
set_label_enabled()
bl_hash = features.bootloader_hash.encode('hex')
bl_hash = "\n".join([bl_hash[:32], bl_hash[32:]])
noyes = [_("No"), _("Yes")]
endis = [_("Enable Passphrases"), _("Disable Passphrases")]
disen = [_("Disabled"), _("Enabled")]
setchange = [_("Set a PIN"), _("Change PIN")]
version = "%d.%d.%d" % (features.major_version,
features.minor_version,
features.patch_version)
coins = ", ".join(coin.coin_name for coin in features.coins)
device_label.setText(features.label)
pin_set_label.setText(noyes[features.pin_protection])
passphrases_label.setText(disen[features.passphrase_protection])
bl_hash_label.setText(bl_hash)
label_edit.setText(features.label)
device_id_label.setText(features.device_id)
initialized_label.setText(noyes[features.initialized])
version_label.setText(version)
coins_label.setText(coins)
clear_pin_button.setVisible(features.pin_protection)
clear_pin_warning.setVisible(features.pin_protection)
pin_button.setText(setchange[features.pin_protection])
pin_msg.setVisible(not features.pin_protection)
passphrase_button.setText(endis[features.passphrase_protection])
language_label.setText(features.language)
def set_label_enabled():
label_apply.setEnabled(label_edit.text() != self.features.label)
def rename():
invoke_client('change_label', unicode(label_edit.text()))
def toggle_passphrase():
title = _("Confirm Toggle Passphrase Protection")
currently_enabled = self.features.passphrase_protection
if currently_enabled:
msg = _("After disabling passphrases, you can only pair this "
"Electrum wallet if it had an empty passphrase. "
"If its passphrase was not empty, you will need to "
"create a new wallet with the install wizard. You "
"can use this wallet again at any time by re-enabling "
"passphrases and entering its passphrase.")
else:
msg = _("Your current Electrum wallet can only be used with "
"an empty passphrase. You must create a separate "
"wallet with the install wizard for other passphrases "
"as each one generates a new set of addresses.")
msg += "\n\n" + _("Are you sure you want to proceed?")
if not self.question(msg, title=title):
return
invoke_client('toggle_passphrase', unpair_after=currently_enabled)
def change_homescreen():
from PIL import Image # FIXME
dialog = QFileDialog(self, _("Choose Homescreen"))
filename = dialog.getOpenFileName()
if filename:
im = Image.open(str(filename))
if im.size != (hs_cols, hs_rows):
raise Exception('Image must be 64 x 128 pixels')
im = im.convert('1')
pix = im.load()
img = ''
for j in range(hs_rows):
for i in range(hs_cols):
img += '1' if pix[i, j] else '0'
img = ''.join(chr(int(img[i:i + 8], 2))
for i in range(0, len(img), 8))
invoke_client('change_homescreen', img)
def clear_homescreen():
invoke_client('change_homescreen', '\x00')
def set_pin():
invoke_client('set_pin', remove=False)
def clear_pin():
invoke_client('set_pin', remove=True)
def wipe_device():
if wallet and sum(wallet.get_balance()):
title = _("Confirm Device Wipe")
msg = _("Are you SURE you want to wipe the device?\n"
"Your wallet still has bitcoins in it!")
if not self.question(msg, title=title,
icon=QMessageBox.Critical):
return
invoke_client('wipe_device', unpair_after=True)
def slider_moved():
mins = timeout_slider.sliderPosition()
timeout_minutes.setText(_("%2d minutes") % mins)
def slider_released():
config.set_session_timeout(timeout_slider.sliderPosition() * 60)
# Information tab
info_tab = QWidget()
info_layout = QVBoxLayout(info_tab)
info_glayout = QGridLayout()
info_glayout.setColumnStretch(2, 1)
device_label = QLabel()
pin_set_label = QLabel()
passphrases_label = QLabel()
version_label = QLabel()
device_id_label = QLabel()
bl_hash_label = QLabel()
bl_hash_label.setWordWrap(True)
coins_label = QLabel()
coins_label.setWordWrap(True)
language_label = QLabel()
initialized_label = QLabel()
rows = [
(_("Device Label"), device_label),
(_("PIN set"), pin_set_label),
(_("Passphrases"), passphrases_label),
(_("Firmware Version"), version_label),
(_("Device ID"), device_id_label),
(_("Bootloader Hash"), bl_hash_label),
(_("Supported Coins"), coins_label),
(_("Language"), language_label),
(_("Initialized"), initialized_label),
]
for row_num, (label, widget) in enumerate(rows):
info_glayout.addWidget(QLabel(label), row_num, 0)
info_glayout.addWidget(widget, row_num, 1)
info_layout.addLayout(info_glayout)
# Settings tab
settings_tab = QWidget()
settings_layout = QVBoxLayout(settings_tab)
settings_glayout = QGridLayout()
# Settings tab - Label
label_msg = QLabel(_("Name this %s. If you have mutiple devices "
"their labels help distinguish them.")
% plugin.device)
label_msg.setWordWrap(True)
label_label = QLabel(_("Device Label"))
label_edit = QLineEdit()
label_edit.setMinimumWidth(150)
label_edit.setMaxLength(plugin.MAX_LABEL_LEN)
label_apply = QPushButton(_("Apply"))
label_apply.clicked.connect(rename)
label_edit.textChanged.connect(set_label_enabled)
settings_glayout.addWidget(label_label, 0, 0)
settings_glayout.addWidget(label_edit, 0, 1, 1, 2)
settings_glayout.addWidget(label_apply, 0, 3)
settings_glayout.addWidget(label_msg, 1, 1, 1, -1)
# Settings tab - PIN
pin_label = QLabel(_("PIN Protection"))
pin_button = QPushButton()
pin_button.clicked.connect(set_pin)
settings_glayout.addWidget(pin_label, 2, 0)
settings_glayout.addWidget(pin_button, 2, 1)
pin_msg = QLabel(_("PIN protection is strongly recommended. "
"A PIN is your only protection against someone "
"stealing your bitcoins if they obtain physical "
"access to your %s.") % plugin.device)
pin_msg.setWordWrap(True)
pin_msg.setStyleSheet("color: red")
settings_glayout.addWidget(pin_msg, 3, 1, 1, -1)
# Settings tab - Homescreen
if plugin.device != 'KeepKey': # Not yet supported by KK firmware
homescreen_layout = QHBoxLayout()
homescreen_label = QLabel(_("Homescreen"))
homescreen_change_button = QPushButton(_("Change..."))
homescreen_clear_button = QPushButton(_("Reset"))
homescreen_change_button.clicked.connect(change_homescreen)
homescreen_clear_button.clicked.connect(clear_homescreen)
homescreen_msg = QLabel(_("You can set the homescreen on your "
"device to personalize it. You must "
"choose a %d x %d monochrome black and "
"white image.") % (hs_rows, hs_cols))
homescreen_msg.setWordWrap(True)
settings_glayout.addWidget(homescreen_label, 4, 0)
settings_glayout.addWidget(homescreen_change_button, 4, 1)
settings_glayout.addWidget(homescreen_clear_button, 4, 2)
settings_glayout.addWidget(homescreen_msg, 5, 1, 1, -1)
# Settings tab - Session Timeout
timeout_label = QLabel(_("Session Timeout"))
timeout_minutes = QLabel()
timeout_slider = QSlider(Qt.Horizontal)
timeout_slider.setRange(1, 60)
timeout_slider.setSingleStep(1)
timeout_slider.setTickInterval(5)
timeout_slider.setTickPosition(QSlider.TicksBelow)
timeout_slider.setTracking(True)
timeout_msg = QLabel(
_("Clear the session after the specified period "
"of inactivity. Once a session has timed out, "
"your PIN and passphrase (if enabled) must be "
"re-entered to use the device."))
timeout_msg.setWordWrap(True)
timeout_slider.setSliderPosition(config.get_session_timeout() // 60)
slider_moved()
timeout_slider.valueChanged.connect(slider_moved)
timeout_slider.sliderReleased.connect(slider_released)
settings_glayout.addWidget(timeout_label, 6, 0)
settings_glayout.addWidget(timeout_slider, 6, 1, 1, 3)
settings_glayout.addWidget(timeout_minutes, 6, 4)
settings_glayout.addWidget(timeout_msg, 7, 1, 1, -1)
settings_layout.addLayout(settings_glayout)
settings_layout.addStretch(1)
# Advanced tab
advanced_tab = QWidget()
advanced_layout = QVBoxLayout(advanced_tab)
advanced_glayout = QGridLayout()
# Advanced tab - clear PIN
clear_pin_button = QPushButton(_("Disable PIN"))
clear_pin_button.clicked.connect(clear_pin)
clear_pin_warning = QLabel(
_("If you disable your PIN, anyone with physical access to your "
"%s device can spend your bitcoins.") % plugin.device)
clear_pin_warning.setWordWrap(True)
clear_pin_warning.setStyleSheet("color: red")
advanced_glayout.addWidget(clear_pin_button, 0, 2)
advanced_glayout.addWidget(clear_pin_warning, 1, 0, 1, 5)
# Advanced tab - toggle passphrase protection
passphrase_button = QPushButton()
passphrase_button.clicked.connect(toggle_passphrase)
passphrase_msg = WWLabel(PASSPHRASE_HELP)
passphrase_warning = WWLabel(PASSPHRASE_NOT_PIN)
passphrase_warning.setStyleSheet("color: red")
advanced_glayout.addWidget(passphrase_button, 3, 2)
advanced_glayout.addWidget(passphrase_msg, 4, 0, 1, 5)
advanced_glayout.addWidget(passphrase_warning, 5, 0, 1, 5)
# Advanced tab - wipe device
wipe_device_button = QPushButton(_("Wipe Device"))
wipe_device_button.clicked.connect(wipe_device)
wipe_device_msg = QLabel(
_("Wipe the device, removing all data from it. The firmware "
"is left unchanged."))
wipe_device_msg.setWordWrap(True)
wipe_device_warning = QLabel(
_("Only wipe a device if you have the recovery seed written down "
"and the device wallet(s) are empty, otherwise the bitcoins "
"will be lost forever."))
wipe_device_warning.setWordWrap(True)
wipe_device_warning.setStyleSheet("color: red")
advanced_glayout.addWidget(wipe_device_button, 6, 2)
advanced_glayout.addWidget(wipe_device_msg, 7, 0, 1, 5)
advanced_glayout.addWidget(wipe_device_warning, 8, 0, 1, 5)
advanced_layout.addLayout(advanced_glayout)
advanced_layout.addStretch(1)
tabs = QTabWidget(self)
tabs.addTab(info_tab, _("Information"))
tabs.addTab(settings_tab, _("Settings"))
tabs.addTab(advanced_tab, _("Advanced"))
dialog_vbox = QVBoxLayout(self)
dialog_vbox.addWidget(tabs)
dialog_vbox.addLayout(Buttons(CloseButton(self)))
# Update information
invoke_client(None)
| mit |
ashmaroli/jekyll-plus | lib/jekyll-plus.rb | 1015 | require "jekyll"
require "jekyll-plus/version"
require_relative "jekyll/commands/new_site"
require_relative "jekyll/commands/extract_theme"
# Plugins
require "jekyll-data" # read "_config.yml" and data files within a theme-gem
# ------------------------------ Temporary Patches ------------------------------
# TODO:
# - remove patch to Jekyll Configuration after jekyll/jekyll/pull/5487 is merged.
# - modify patch to Mercenary after jekyll/mercenary/pull/44 and
# jekyll/mercenary/pull/48 are merged.
# - remove patch to Jekyll::Watcher after jekyll/jekyll-watch/pull/42 is merged.
# - remove patch to Listen Adapter only if any issues regarding that crop up.
require_relative "patches/idempotent_jekyll_config"
require "mercenary"
require_relative "patches/mercenary_presenter"
require "jekyll-watch"
require_relative "patches/jekyll_watcher"
require "listen"
require_relative "patches/listen_windows_adapter"
# --------------------------- End of Temporary Patches ---------------------------
| mit |
lsaFreedev/Portfolio | app/cache/dev/annotations/4ca0c3fa9d8720c7c2c0dc5656cd9e5aafc7a71e$school.cache.php | 262 | <?php return unserialize('a:1:{i:0;O:27:"Doctrine\\ORM\\Mapping\\Column":9:{s:4:"name";s:6:"school";s:4:"type";s:6:"string";s:6:"length";N;s:9:"precision";i:0;s:5:"scale";i:0;s:6:"unique";b:0;s:8:"nullable";b:0;s:7:"options";a:0:{}s:16:"columnDefinition";N;}}'); | mit |
jmcaffee/admin_module | spec/lib/admin_module/rulesets_spec.rb | 2306 | require 'spec_helper'
describe AdminModule::Rulesets do
context "api" do
let(:rs_list) { ['TstRuleset1', 'TstRuleset2'] }
let(:rulesets_page_stub) do
obj = double('rulesets_page')
allow(obj).to receive(:get_rulesets).and_return(rs_list)
allow(obj).to receive(:open_ruleset).and_return(obj)
allow(obj).to receive(:set_name).and_return(obj)
allow(obj).to receive(:save)
#allow(obj).to receive(:add_version).and_return(obj)
obj
end
let(:page_factory) do
obj = MockPageFactory.new
obj.login_page = double('login_page')
obj.rulesets_page = rulesets_page_stub
obj
end
let(:default_comment) { 'no comment' }
context "#list" do
it "returns list of rulesets" do
expect(page_factory.rulesets_page)
.to receive(:get_rulesets)
rs = AdminModule::Rulesets.new(page_factory)
rulesets = rs.list()
expect( rulesets ).to include 'TstRuleset1'
expect( rulesets ).to include 'TstRuleset2'
end
end
context "#rename" do
context "source name exists and destination name does not exist" do
it "renames the ruleset" do
src = 'TstRuleset1'
dest = 'RnTstRuleset1'
expect(page_factory.rulesets_page)
.to receive(:open_ruleset)
.with(src)
expect(page_factory.rulesets_page)
.to receive(:set_name)
.with(dest)
expect(page_factory.rulesets_page)
.to receive(:save)
rs = AdminModule::Rulesets.new(page_factory)
rs.rename(src, dest)
end
end
context "source name does not exist" do
it "raises exception" do
src = 'NotARuleset1'
dest = 'TstRuleset2'
rs = AdminModule::Rulesets.new(page_factory)
expect { rs.rename(src, dest) }.to raise_exception /named 'NotARuleset1' does not exist/
end
end
context "destination name already exists" do
it "raises exception" do
src = 'TstRuleset1'
dest = 'TstRuleset2'
rs = AdminModule::Rulesets.new(page_factory)
expect { rs.rename(src, dest) }.to raise_exception /named 'TstRuleset2' already exists/
end
end
end
end
end
| mit |
IDCI-Consulting/StepBundle | Navigation/NavigatorType.php | 4944 | <?php
/**
* @author: Gabriel BONDAZ <gabriel.bondaz@idci-consulting.fr>
* @license: MIT
*/
namespace IDCI\Bundle\StepBundle\Navigation;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\HiddenType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\Form\FormView;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use IDCI\Bundle\StepBundle\Navigation\Event\NavigationEventSubscriber;
use IDCI\Bundle\StepBundle\Step\Event\StepEventActionRegistryInterface;
use IDCI\Bundle\StepBundle\Path\Event\PathEventActionRegistryInterface;
class NavigatorType extends AbstractType
{
/**
* @var StepEventActionRegistryInterface
*/
protected $stepEventActionRegistry;
/**
* @var PathEventActionRegistryInterface
*/
protected $pathEventActionRegistry;
/**
* @var \Twig_Environment
*/
protected $merger;
/**
* @var TokenStorageInterface
*/
private $tokenStorage;
/**
* @var SessionInterface
*/
private $session;
/**
* Constructor.
*
* @param StepEventActionRegistryInterface $stepEventActionRegistry the step event action registry
* @param PathEventActionRegistryInterface $pathEventActionRegistry the path event action registry
* @param Twig_Environment $merger the twig merger
* @param TokenStorageInterface $tokenStorage the security context
* @param SessionInterface $session the session
*/
public function __construct(
StepEventActionRegistryInterface $stepEventActionRegistry,
PathEventActionRegistryInterface $pathEventActionRegistry,
\Twig_Environment $merger,
TokenStorageInterface $tokenStorage,
SessionInterface $session
) {
$this->stepEventActionRegistry = $stepEventActionRegistry;
$this->pathEventActionRegistry = $pathEventActionRegistry;
$this->merger = $merger;
$this->tokenStorage = $tokenStorage;
$this->session = $session;
}
/**
* {@inheritdoc}
*/
public function buildView(FormView $view, FormInterface $form, array $options)
{
$stepOptions = $options['navigator']->getCurrentStep()->getOptions();
$view->vars = array_merge($view->vars, array(
'attr' => $stepOptions['attr'],
));
}
/**
* {@inheritdoc}
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('_map_name', HiddenType::class, array(
'data' => $options['navigator']->getMap()->getName(),
))
->add('_map_footprint', HiddenType::class, array(
'data' => $options['navigator']->getMap()->getFootprint(),
))
->add('_current_step', HiddenType::class, array(
'data' => $options['navigator']->getCurrentStep()->getName(),
))
;
if (null !== $options['navigator']->getPreviousStep()) {
$builder->add('_previous_step', HiddenType::class, array(
'data' => $options['navigator']->getPreviousStep()->getName(),
));
}
if (null !== $options['navigator']->getMap()->getFormAction()) {
$builder->setAction($options['navigator']->getMap()->getFormAction());
}
$this->buildStep($builder, $options);
$builder->addEventSubscriber(new NavigationEventSubscriber(
$options['navigator'],
$this->stepEventActionRegistry,
$this->pathEventActionRegistry,
$this->merger,
$this->tokenStorage,
$this->session
));
}
/**
* Build step.
*
* @param FormBuilderInterface $builder the builder
* @param array $options the options
*/
protected function buildStep(FormBuilderInterface $builder, array $options)
{
$currentStep = $options['navigator']->getCurrentStep();
$configuration = $currentStep->getConfiguration();
$currentStep->getType()->buildNavigationStepForm(
$builder,
$configuration['options']
);
}
/**
* {@inheritdoc}
*/
public function configureOptions(OptionsResolver $resolver)
{
$resolver
->setRequired(array('navigator'))
->setAllowedTypes('navigator', array('IDCI\Bundle\StepBundle\Navigation\NavigatorInterface'))
;
}
/**
* {@inheritdoc}
*/
public function getBlockPrefix()
{
return 'idci_step_navigator';
}
}
| mit |
IT-Berater/TWRestUmgebung | src/main/java/de/wenzlaff/umgebung/resource/Mindmap.java | 223 | package de.wenzlaff.umgebung.resource;
import org.restlet.resource.Get;
/**
* Das Interface für die Mindmap.
*
* @author Thomas Wenzlaff
*
*/
public interface Mindmap {
@Get
public MindmapModell getMindmap();
}
| mit |
PedrosWits/smart-cameras | smartcameras/test/test_azure.py | 1568 | import smartcameras.azurehook
import mock
import time
azure = smartcameras.azurehook.AzureHook()
def test_constructor():
assert azure.serviceBus.service_namespace == 'middle-earth'
def test_pupsub():
test_topic = "TESTING_TOPIC"
azure.createTopic(test_topic)
azure.publish(test_topic, "Hello")
subscription = "helloworld"
azure.subscribe(test_topic, subscription)
message = azure.getMessage(test_topic, subscription, timeout='5')
if message.body is not None:
assert message.body == "Hello"
azure.serviceBus.delete_subscription(test_topic, subscription)
azure.serviceBus.delete_topic(test_topic)
def test_queue():
test_queue = "TESTING_QUEUE"
azure.createQueue(test_queue)
azure.sendQueueMessage(test_queue, "Hello")
assert azure.receiveQueueMessage(test_queue).body == "Hello"
azure.serviceBus.delete_queue(test_queue)
# # Manual Test so far -- unable to mockup - but its working!
# def test_offline_behavior():
# test_topic = "TESTING_TOPIC"
#
# azure.createTopic(test_topic)
#
# print("Turn off internet")
# time.sleep(15)
#
# assert not smartcameras.azurehook.hasConnectivity()
#
# assert not azure.publish(test_topic, "Hello")
#
# assert not azure.queue.empty()
#
# print("Turn on internet")
# time.sleep(15)
#
# assert smartcameras.azurehook.hasConnectivity()
# # Past messages are flushed on next publish
# assert azure.publish(test_topic, "Hello Back")
#
# assert azure.queue.empty()
# azure.serviceBus.delete_topic(test_topic)
| mit |
papyLaPlage/Ripple | Assets/Scripts/MyGUIManager.cs | 1893 | using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using UnityEngine.EventSystems;
public enum eGUIScreen
{
E_None,
E_Greyscale,
E_MainTitle,
E_MainMenu,
E_LevelSelect,
E_Credits,
E_InGame,
E_Pause
}
public class MyGUIManager : MonoBehaviour
{
public static MyGUIManager Instance { get; private set; }
public eGUIScreen GuiState { get { return guiState; } set { ShowGUI(false); guiState = value; ShowGUI(true); } }
private eGUIScreen guiState;
public GameObject GUIGreyscale;
public GameObject GUIMainTitle;
public GameObject GUIMainMenu;
public GameObject GUILevelSelect;
public GameObject GUICredits;
public GameObject GUIInGame;
public GameObject GUIPause;
void Awake()
{
Instance = this;
}
private void ShowGUI(bool show)
{
//Debug.Log("Show GUI : " + guiState);
switch (guiState)
{
case eGUIScreen.E_None:
break;
case eGUIScreen.E_Greyscale:
GUIGreyscale.SetActive(show);
break;
case eGUIScreen.E_MainTitle:
GUIMainTitle.SetActive(show);
break;
case eGUIScreen.E_MainMenu:
GetComponent<SaveManager>().ShowClearedLevels();
GUIMainMenu.SetActive(show);
break;
case eGUIScreen.E_LevelSelect:
GUILevelSelect.SetActive(show);
break;
case eGUIScreen.E_Credits:
GUICredits.SetActive(show);
break;
case eGUIScreen.E_InGame:
GUIMainMenu.SetActive(show);
break;
case eGUIScreen.E_Pause:
GUIMainMenu.SetActive(show);
break;
default:
break;
}
}
} | mit |
YoannDupont/SEM | sem/modules/label_consistency.py | 19226 | #-*- coding:utf-8 -*-
"""
file: label_consistency.py
author: Yoann Dupont
MIT License
Copyright (c) 2018 Yoann Dupont
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""
import sys, codecs, logging, re
from .sem_module import SEMModule as RootModule
from sem.storage import Tag, Trie
from sem.storage.annotation import chunk_annotation_from_sentence
from sem.IO.columnIO import Reader
from sem.features import MultiwordDictionaryFeature, NUL
from sem.misc import longest_common_substring
def normalize(token):
apostrophes = re.compile(u"[\u2019]", re.U)
lower_a = re.compile(u"[àáâãäåæ]", re.U)
upper_a = re.compile(u"[ÀÁÂÃÄÅÆ]", re.U)
lower_e = re.compile(u"[éèêë]", re.U)
upper_e = re.compile(u"[ÉÈÊË]", re.U)
lower_i = re.compile(u"[ìíîï]", re.U)
upper_i = re.compile(u"[ÌÍÎÏ]", re.U)
normalized = apostrophes.sub(u"'", token)
normalized = lower_a.sub(u"a", normalized)
normalized = upper_a.sub(u"A", normalized)
normalized = lower_e.sub(u"e", normalized)
normalized = upper_e.sub(u"E", normalized)
normalized = lower_i.sub(u"i", normalized)
normalized = upper_i.sub(u"I", normalized)
return normalized
def abbrev_candidate(token):
return token.isupper() and all([c.isalpha() for c in token])
def tokens_from_bounds(document, start, end):
word_spans = document.segmentation("tokens")
toks = []
for i, span in enumerate(word_spans):
if span.lb >= start:
toks.append(document.content[span.lb : span.ub])
if span.ub >= end:
break
if span.lb > end:
break
return toks
def tokens2regex(tokens, flags=re.U):
apostrophes = u"['\u2019]"
apos_re = re.compile(apostrophes, re.U)
pattern = u"\\b" + u"\\b *\\b".join(tokens) + u"\\b"
pattern = apos_re.sub(apostrophes, pattern)
pattern = re.escape(pattern)
return re.compile(pattern, flags)
def detect_abbreviations(document, field):
content = document.content
word_spans = document.segmentation("tokens")
if document.segmentation("sentences") is not None:
sentence_spans = document.segmentation("sentences").spans
sentence_spans_ref = document.segmentation("sentences").get_reference_spans()
else:
sentence_spans_ref = [Span(0, len(document.content))]
tokens = [content[span.lb : span.ub] for span in word_spans]
annotations = document.annotation(field).get_reference_annotations()
counts = {}
positions = {}
for i, token in enumerate(tokens):
if abbrev_candidate(token) and len(token) > 1 and not ((i > 1 and abbrev_candidate(tokens[i-1])) or (i < len(tokens)-1 and abbrev_candidate(tokens[i+1]))):
if token not in counts:
counts[token] = 0
positions[token] = []
counts[token] += 1
positions[token].append(i)
position2sentence = {}
for token, indices in positions.items():
for index in indices:
for i, span in enumerate(sentence_spans):
if span.lb <= index and span.ub >= index:
position2sentence[index] = sentence_spans_ref[i]
reg2type = {}
for key, val in counts.items():
all_solutions = []
for position in positions[key]:
span = position2sentence[position]
word_span = word_spans[position]
lb = span.lb
ub = word_span.lb
solutions = longest_common_substring(content[lb : ub], tokens[position], casesensitive=False)
if solutions == []:
solutions = longest_common_substring(normalize(content[lb : ub]), tokens[position], casesensitive=False)
solutions = [solution for solution in solutions if len(solution) == len(tokens[position])]
if len(solutions) > 0:
all_solutions.extend([[(x+lb, y+lb) for (x,y) in solution] for solution in solutions])
if len(all_solutions) > 0:
all_solutions.sort(key=lambda x: x[-1][0] - x[0][0])
best_solution = all_solutions[0]
lo = best_solution[0][0]
hi = best_solution[-1][0]
lo_tokens = [tok for tok in word_spans if tok.lb <= lo and tok.ub > lo]
hi_tokens = [tok for tok in word_spans if tok.lb <= hi and tok.ub > hi]
abbrev_annots = []
for position in positions[key]:
span = word_spans[position]
abbrev_annots.extend([annotation for annotation in annotations if annotation.lb == span.lb and annotation.ub == span.ub])
try:
toks = tokens_from_bounds(document, lo_tokens[0].lb, hi_tokens[0].ub)
reg = tokens2regex(toks, re.U + re.I)
for match in reg.finditer(content):
annots = [annotation for annotation in annotations if ((annotation.lb <= match.start() and match.start() <= annotation.ub) or (annotation.lb <= match.end() and match.end() <= annotation.ub))]
if len(annots) > 0:
annot = annots[0]
new_toks = tokens_from_bounds(document, min(annot.lb, match.start()), max(annot.ub, match.end()))
new_reg = tokens2regex(new_toks, re.U + re.I)
if new_reg.pattern not in reg2type:
reg2type[new_reg.pattern] = []
reg2type[new_reg.pattern].append(annots[0].value)
if abbrev_annots == []:
abbrev_reg = tokens2regex([key], re.U)
if abbrev_reg.pattern not in reg2type:
reg2type[abbrev_reg.pattern] = []
reg2type[abbrev_reg.pattern].append(annots[0].value)
if len(abbrev_annots) > 0:
tag = abbrev_annots[0]
new_reg = tokens2regex(toks, re.U + re.I)
if new_reg.pattern not in reg2type:
reg2type[new_reg.pattern] = []
reg2type[new_reg.pattern].append(tag.value)
except IndexError:
pass
new_tags = []
for v in reg2type.keys():
type_counts = sorted([(the_type, reg2type[v].count(the_type)) for the_type in set(reg2type[v])], key=lambda x: (-x[-1], x[0]))
fav_type = type_counts[0][0]
regexp = re.compile(v, re.U + re.I*(u" " in v))
for match in regexp.finditer(content):
lo_tok = word_spans.spans.index([t for t in word_spans if t.lb == match.start()][0])
hi_tok = word_spans.spans.index([t for t in word_spans if t.ub == match.end()][0])+1
new_tags.append(Tag(fav_type, lo_tok, hi_tok))
to_remove_tags = []
for new_tag in new_tags:
to_remove_tags.extend([ann for ann in document.annotation(field) if new_tag.lb <= ann.lb and ann.ub <= new_tag.ub and ann.value == new_tag.value])
for to_remove_tag in to_remove_tags:
try:
document.annotation(field)._annotations.remove(to_remove_tag)
except ValueError:
pass
all_tags = [[token[field] for token in sent] for sent in document.corpus.sentences]
new_tags.sort(key=lambda x: (x.lb, -x.ub))
for new_tag in new_tags:
nth_word = 0
nth_sent = 0
sents = document.corpus.sentences
while nth_word + len(sents[nth_sent]) - 1 < new_tag.lb:
nth_word += len(sents[nth_sent])
nth_sent += 1
start = new_tag.lb - nth_word
end = new_tag.ub - nth_word
document.corpus.sentences[nth_sent][start][field] = u"B-{}".format(new_tag.value)
all_tags[nth_sent][start] = u"B-{0}".format(new_tag.value)
for index in range(start+1, end):
document.corpus.sentences[nth_sent][index][field] = u"I-{0}".format(new_tag.value)
all_tags[nth_sent][index] = u"I-{0}".format(new_tag.value)
document.add_annotation_from_tags(all_tags, field, field)
class LabelConsistencyFeature(MultiwordDictionaryFeature):
def __init__(self, form2entity, ne_entry, *args, **kwargs):
super(LabelConsistencyFeature, self).__init__(*args, **kwargs)
self._form2entity = form2entity
self._ne_entry = ne_entry
def __call__(self, list2dict, token_entry=None, annot_entry=None, *args, **kwargs):
ne_entry = (annot_entry if annot_entry is not None else self._ne_entry)
l = [t[ne_entry][:] for t in list2dict]
form2entity = self._form2entity
tmp = self._value._data
length = len(list2dict)
fst = 0
lst = -1 # last match found
cur = 0
entry = (token_entry if token_entry is not None else self._entry)
ckey = None # Current KEY
while fst < length - 1:
cont = True
while cont and (cur < length):
ckey = list2dict[cur][entry]
if l[cur] == "O":
if NUL in tmp: lst = cur
tmp = tmp.get(ckey, {})
cont = len(tmp) != 0
cur += int(cont)
else:
cont = False
if NUL in tmp: lst = cur
if lst != -1:
form = u" ".join([list2dict[i][entry] for i in range(fst,lst)])
appendice = u"-" + form2entity[form]
l[fst] = u'B' + appendice
for i in range(fst+1, lst):
l[i] = u'I' + appendice
fst = lst
cur = fst
else:
fst += 1
cur = fst
tmp = self._value._data
lst = -1
if NUL in self._value._data.get(list2dict[-1][entry], []) and l[-1] == "O":
l[-1] = u'B-' + form2entity[list2dict[-1][entry]]
return l
class OverridingLabelConsistencyFeature(LabelConsistencyFeature):
"""
This is the second label consistency strategy.
It can change CRF entities if it finds a wider one.
Gives lower results on FTB
"""
def __call__(self, list2dict, token_entry=None, annot_entry=None, *args, **kwargs):
l = [u"O" for _ in range(len(list2dict))]
form2entity = self._form2entity
tmp = self._value._data
length = len(list2dict)
fst = 0
lst = -1 # last match found
cur = 0
entry = (token_entry if token_entry is not None else self._entry)
ckey = None # Current KEY
entities = []
while fst < length - 1:
cont = True
while cont and (cur < length):
ckey = list2dict[cur][entry]
if l[cur] == "O":
if NUL in tmp: lst = cur
tmp = tmp.get(ckey, {})
cont = len(tmp) != 0
cur += int(cont)
else:
cont = False
if NUL in tmp: lst = cur
if lst != -1:
form = u" ".join([list2dict[i][entry] for i in range(fst, lst)])
entities.append(Tag(form2entity[form], fst, lst))
fst = lst
cur = fst
else:
fst += 1
cur = fst
tmp = self._value._data
lst = -1
if NUL in self._value._data.get(list2dict[-1][entry], []):
entities.append(Tag(form2entity[list2dict[-1][entry]], len(list2dict)-1, len(list2dict)))
ne_entry = (annot_entry if annot_entry is not None else self._ne_entry)
gold = chunk_annotation_from_sentence(list2dict, ne_entry).annotations
for i in reversed(range(len(entities))):
e = entities[i]
for r in gold:
if (r.lb == e.lb and r.ub == e.ub):
del entities[i]
break
for i in reversed(range(len(gold))):
r = gold[i]
for e in entities:
if (r.lb >= e.lb and r.ub <= e.ub):
del gold[i]
break
for r in gold + entities:
appendice = u"-" + r.value
l[r.lb] = u"B" + appendice
for i in range(r.lb+1,r.ub):
l[i] = u"I" + appendice
return l
class SEMModule(RootModule):
def __init__(self, field, log_level="WARNING", log_file=None, token_field="word", label_consistency="overriding", **kwargs):
super(SEMModule, self).__init__(log_level=log_level, log_file=log_file, **kwargs)
self._field = field
self._token_field = token_field
if label_consistency == "overriding":
self._feature = OverridingLabelConsistencyFeature(None, ne_entry=self._field, entry=self._token_field, entries=None)
else:
self._feature = LabelConsistencyFeature(None, ne_entry=self._field, entry=self._token_field, entries=None)
def process_document(self, document, abbreviation_resolution=True, **kwargs):
corpus = document.corpus.sentences
field = self._field
token_field = self._token_field
entities = {}
counts = {}
for p in corpus:
G = chunk_annotation_from_sentence(p, column=field)
for entity in G:
id = entity.value
form = u" ".join([p[index][token_field] for index in range(entity.lb, entity.ub)])
if form not in counts:
counts[form] = {}
if id not in counts[form]:
counts[form][id] = 0
counts[form][id] += 1
for form, count in counts.items():
if len(count) == 1:
entities[form] = list(count.keys())[0]
else:
best = sorted(count.keys(), key=lambda x: -count[x])[0]
entities[form] = best
self._feature._form2entity = entities
self._feature._entries = entities.keys()
self._feature._value = Trie()
for entry in self._feature._entries:
entry = entry.strip()
if entry:
self._feature._value.add(entry.split())
for p in corpus:
for i, value in enumerate(self._feature(p, token_entry=token_field, annot_entry=field)):
p[i][field] = value
tags = [[token[field] for token in sentence] for sentence in corpus]
document.add_annotation_from_tags(tags, field, field)
if abbreviation_resolution:
detect_abbreviations(document, field)
def main(args):
ienc = args.ienc or args.enc
oenc = args.oenc or args.enc
entities = {}
counts = {}
for p in Reader(args.infile, ienc):
G = chunk_annotation_from_sentence(p, column=args.tag_column)
for entity in G:
id = entity.value
form = u" ".join([p[index][args.token_column] for index in range(entity.lb, entity.ub)])
if form not in counts:
counts[form] = {}
if id not in counts[form]:
counts[form][id] = 0
counts[form][id] += 1
for form, count in counts.items():
if len(count) == 1:
entities[form] = list(count.keys())[0]
else:
best = sorted(count.keys(), key=lambda x: -count[x])[0]
entities[form] = best
if args.label_consistency == "non-overriding":
feature = LabelConsistencyFeature(entities, ne_entry=args.tag_column, entry=args.token_column, entries=entities.keys())
else:
feature = OverridingLabelConsistencyFeature(entities, ne_entry=args.tag_column, entry=args.token_column, entries=entities.keys())
with codecs.open(args.outfile, "w", oenc) as O:
for p in Reader(args.infile, ienc):
for i, value in enumerate(feature(p)):
p[i][args.tag_column] = value
O.write(u"\t".join(p[i]) + u"\n")
O.write(u"\n")
import os.path
import sem
_subparsers = sem.argument_subparsers
parser = _subparsers.add_parser(os.path.splitext(os.path.basename(__file__))[0], description="Broadcasts annotations based on form.")
parser.add_argument("infile",
help="The input file (CoNLL format)")
parser.add_argument("outfile",
help="The output file")
parser.add_argument("-t", "--token-column", dest="token_column", type=int, default=0,
help="Token column")
parser.add_argument("-c", "--tag-column", dest="tag_column", type=int, default=-1,
help="Tagging column")
parser.add_argument("--label-consistency", dest="label_consistency", choices=("non-overriding","overriding"), default="overriding",
help="Non-overriding leaves CRF's annotation as they are, overriding label_consistency erases them if it finds a longer one (default=%(default)s).")
parser.add_argument("--input-encoding", dest="ienc",
help="Encoding of the input (default: utf-8)")
parser.add_argument("--output-encoding", dest="oenc",
help="Encoding of the input (default: utf-8)")
parser.add_argument("-e", "--encoding", dest="enc", default="utf-8",
help="Encoding of both the input and the output (default: utf-8)")
parser.add_argument("-v", "--verbose", dest="verbose", action="store_true",
help="Writes feedback during process (default: no output)")
| mit |
andremourato/programacao | programacao-3/guiao4/ex3/aula4_e3/VideoClube.java | 3581 | package aula4_e3;
import java.util.*;
public class VideoClube {
private UserList users = new UserList();
private VideoList videos = new VideoList();
private int movieLimit;
public VideoClube(int N) {
movieLimit = N;
}
public void addUser(Utilizador student) {
users.addUser(student);
}
public void removeUser(int cc) {
users.removeUser(users.getUser(cc));
}
public void printUserVideos(int cc) {
Utilizador user = users.getUser(cc);
System.out.println("---------------------------------------------");
System.out.println("| Videos de: "+user+" |");
System.out.println("---------------------------------------------");
for(Video video : user.watchedVideosToArray())
System.out.println("| "+ video +" |");
}
public void addVideo(String title, String age, String category) {
videos.addVideo(new Video(title,age,category));
}
public void removeVideo(int id) {
videos.removeVideo(videos.getVideo(id));
}
public void checkAvailability(int id) {
String status = "available";
if(!videos.getVideo(id).isAvailable())
status = "unavailable";
System.out.println("Status of video "+id+": "+status);
}
public void lendVideo(int id, int cc) {
Video video = videos.getVideo(id);
Utilizador user = users.getUser(cc);
if(user.numberOfVideosOwned()>=movieLimit) {
System.out.println("O utilizador "+user.nome()+" atingiu a sua quota de videos.");
return;
}
if(!video.isAvailable()) {
System.out.println("Video "+id+" está indisponivel de momento e não pode requisitado!");
return;
}
video.lendVideo();
user.lendVideoToUser(video);
System.out.println("Video requisitado com sucesso");
}
public void returnVideo(int id, int cc, int r) {
Video video = videos.getVideo(id);
Utilizador user = users.getUser(cc);
if(video.isAvailable()) {
System.out.println("Video "+id+" is available at the moment. Cannot have 2 similar videos!");
return;
}
video.returnVideo(r);
user.returnVideoFromUser(video);
System.out.println("Video devolvido com sucesso");
}
public void printUserVideoHistory(int cc) {
Utilizador user = users.getUser(cc);
System.out.println("---------------------------------------------");
System.out.println("| Historico de videos de "+user.nome()+" |");
System.out.println("---------------------------------------------");
for(Video video : user.historyVideosToArray()) {
System.out.println("| " + video + " |");
}
}
public void printCatalog() {
System.out.println("---------------------------------------------");
System.out.println("| Catálogo de videos |");
System.out.println("---------------------------------------------");
for(Video video : videos.videosToArray()) {
System.out.println("| " + video + " |");
}
}
public void printCatalogByRating() {
Video[] sortedArray = videos.videosToArray().clone();
/*Sorts the videos by rating*/
Arrays.sort(sortedArray, new Comparator<Video>() {
@Override
public int compare(Video v1, Video v2) {
int i = -2;
if(v1.rating() > v2.rating())
i = -1;
else if(v1.rating() < v2.rating())
i = 1;
else
i = 0;
return i;
}
});
System.out.println("---------------------------------------------");
System.out.println("| Catálogo de videos por Rating |");
System.out.println("---------------------------------------------");
for(Video video : sortedArray) {
System.out.println("| " + video + " |");
}
}
}
| mit |
akhilpm/Masters-Project | UMKL/textData/getdata_20NG.py | 3671 | '''
KPCA based feature engineering for 20-newsgroup document classification
Author : Akhil P M
Kernel used : Arc-cosine Kernel
'''
from settings import *
import kernel
def size_mb(docs):
return sum(len(s.encode('utf-8')) for s in docs) / 1e6
def trim(s):
"""Trim string to fit on terminal (assuming 80-column display)"""
return s if len(s) <= 80 else s[:77] + "..."
def get20newsgroup_data(op):
#set the timer
start = time()
#ignore all warnings
warnings.filterwarnings("ignore")
# Display progress logs on stdout
logging.basicConfig(level=logging.INFO, format='%(asctime)s %(levelname)s %(message)s')
(opts, args) = op.parse_args()
#print args, opts
#if len(args) > 0:
#op.error("this script takes no arguments")
#sys.exit(1)
# Load some categories from the training set
if opts.all_categories:
categories = None
else:
categories = [
'alt.atheism',
'talk.religion.misc',
'comp.graphics',
'sci.space',
]
if opts.filtered:
remove = ('headers', 'footers', 'quotes')
else:
remove = ()
print("Loading 20 newsgroups dataset for categories:")
print(categories if categories else "all")
data_train = fetch_20newsgroups(subset='train', categories=categories,
shuffle=True, random_state=42, remove=remove)
data_test = fetch_20newsgroups(subset='test', categories=categories,
shuffle=True, random_state=42, remove=remove)
print('\n!!! Data Loading Completed !!!\n')
categories = data_train.target_names # for case categories == None
data_train_size_mb = size_mb(data_train.data)
data_test_size_mb = size_mb(data_test.data)
print("%d documents - %0.3fMB (training set)" % (len(data_train.data), data_train_size_mb))
print("%d documents - %0.3fMB (test set)" % (len(data_test.data), data_test_size_mb))
print("%d categories" % len(categories))
print('\n'+'=' * 80+'\n')
# split a training set and a test set
trainY, testY = data_train.target, data_test.target
print("Extracting features from the training data using a sparse vectorizer")
t0 = time()
if opts.use_hashing:
vectorizer = HashingVectorizer(stop_words='english', non_negative=True,
n_features=opts.n_features)
trainX = vectorizer.transform(data_train.data)
else:
vectorizer = TfidfVectorizer(sublinear_tf=True, max_df=0.5, stop_words='english')
trainX = vectorizer.fit_transform(data_train.data)
duration = time() - t0
print("done in %fs at %0.3fMB/s" % (duration, data_train_size_mb / duration))
print("n_samples: %d, n_features: %d" % trainX.shape)
print('\n'+'=' * 80+'\n')
print("Extracting features from the test data using the same vectorizer")
t0 = time()
testX = vectorizer.transform(data_test.data)
duration = time() - t0
print("done in %fs at %0.3fMB/s" % (duration, data_test_size_mb / duration))
print("n_samples: %d, n_features: %d" % testX.shape)
print('\n'+'=' * 80+'\n')
# mapping from integer feature name to original token string
if opts.use_hashing:
feature_names = None
else:
feature_names = vectorizer.get_feature_names()
if opts.select_chi2:
print("Extracting %d best features by a chi-squared test" %opts.select_chi2)
t0 = time()
ch2 = SelectKBest(chi2, k=opts.select_chi2)
trainX = ch2.fit_transform(trainX, trainY)
testX = ch2.transform(testX)
if feature_names:
# keep selected feature names
feature_names = [feature_names[i] for i in ch2.get_support(indices=True)]
print("done in %fs" % (time() - t0))
print()
if feature_names:
feature_names = np.asarray(feature_names)
'''
trainX = np.load('trainX.npy')
testX = np.load('testX.npy')
trainY = np.load('trainY.npy')
testY = np.load('testY.npy')
'''
return trainX, testX, trainY, testY
| mit |
ublaboo/api-router | src/Exception/ApiRouteWrongPropertyException.php | 153 | <?php
declare(strict_types=1);
namespace Contributte\ApiRouter\Exception;
use Exception;
class ApiRouteWrongPropertyException extends Exception
{
}
| mit |
9swampy/NEventStoreExample | NEventStoreExample.Infrastructure/Tests/SimpleDomain/SimpleAggregateUpdated.cs | 435 | namespace NEventStoreExample.Infrastructure.Tests.SimpleDomain
{
using System;
using System.Linq;
using NEventStoreExample.Infrastructure;
public class SimpleAggregateUpdated : DomainEvent
{
public SimpleAggregateUpdated(Guid aggregateID, int originalVersion, DateTime lastUpdate) : base(aggregateID, originalVersion)
{
this.LastUpdate = lastUpdate;
}
public DateTime LastUpdate { get; set; }
}
} | mit |
byllyfish/libofp | test/ofp/setasync_unittest.cpp | 1501 | // Copyright (c) 2015-2018 William W. Fisher (at gmail dot com)
// This file is distributed under the MIT License.
#include "ofp/setasync.h"
#include "ofp/asyncconfigproperty.h"
#include "ofp/unittest.h"
using namespace ofp;
const OFPPacketInFlags kPacketInFlags =
static_cast<OFPPacketInFlags>(0x11111112);
const OFPPortStatusFlags kPortStatusFlags =
static_cast<OFPPortStatusFlags>(0x22222221);
const OFPFlowRemovedFlags kFlowRemovedFlags =
static_cast<OFPFlowRemovedFlags>(0x33333331);
TEST(setasync, builder) {
PropertyList props;
props.add(AsyncConfigPropertyPacketInSlave{kPacketInFlags});
props.add(AsyncConfigPropertyPacketInMaster{kPacketInFlags});
props.add(AsyncConfigPropertyPortStatusSlave{kPortStatusFlags});
props.add(AsyncConfigPropertyPortStatusMaster{kPortStatusFlags});
props.add(AsyncConfigPropertyFlowRemovedSlave{kFlowRemovedFlags});
props.add(AsyncConfigPropertyFlowRemovedMaster{kFlowRemovedFlags});
SetAsyncBuilder builder;
builder.setProperties(props);
{
MemoryChannel channel{OFP_VERSION_5};
builder.send(&channel);
EXPECT_HEX(
"051C003800000001000000081111111200010008111111120002000822222221000300"
"082222222100040008333333310005000833333331",
channel.data(), channel.size());
}
{
MemoryChannel channel{OFP_VERSION_4};
builder.send(&channel);
EXPECT_HEX(
"041C002000000001111111121111111222222221222222213333333133333331",
channel.data(), channel.size());
}
}
| mit |
gaal/shstat | internal/lib.go | 2051 | package internal
import (
"flag"
"fmt"
"os"
"regexp"
"strconv"
)
// AtoiList runs strconv.Atoi on every element in nums. If this fails it
// returns the first error encountered.
func AtoiList(nums []string) ([]int, error) {
var res []int
for _, v := range nums {
n, err := strconv.Atoi(v)
if err != nil {
return nil, fmt.Errorf("not an integer: %q", v)
}
res = append(res, n)
}
return res, nil
}
// splitb is very similar to regexp.Split(s, -1) but returns [][]byte.
func splitb(re *regexp.Regexp, b []byte) [][]byte {
matches := re.FindAllIndex(b, -1)
outs := make([][]byte, 0, len(matches))
var beg, end int
for _, m := range matches {
end = m[0]
if m[1] != 0 {
outs = append(outs, b[beg:end])
beg = m[1]
}
}
if end != len(b) {
outs = append(outs, b[beg:])
}
return outs
}
// Parter parts lines into fields specified by a regexp, and returns certain
// parts of the split using 1-based indexing. Negative values are allowed and
// count from the input end.
type Parter struct {
re *regexp.Regexp
idx []int
}
// NewParter creates a new Parter using ifs and the given index list.
func NewParter(ifs *regexp.Regexp, idx []int) *Parter {
return &Parter{re: ifs, idx: append([]int(nil), idx...)}
}
// Fields returns the fields in line matching the Parter spec.
func (p Parter) Fields(line []byte) [][]byte {
parts := splitb(p.re, line)
// No idx means all fields (simple way to change delim / normalize its width)
if len(p.idx) == 0 {
return parts
}
var out [][]byte
for _, v := range p.idx {
if v < 0 {
v = len(parts) + v
} else if v > 0 {
v--
}
if v >= 0 && v < len(parts) {
out = append(out, parts[v])
} else {
out = append(out, nil)
}
}
return out
}
// SetUsage updates flag.Usage with help text. It should be called before flag.Parse.
//
// TODO: our convention is to repeat the package doc string here. Is there a way to
// extract that from the binary?
func SetUsage(s string) {
flag.Usage = func() {
fmt.Fprintf(os.Stderr, s)
flag.PrintDefaults()
}
}
| mit |
nickhsine/keystone | admin/server/api/cloudinary.js | 1630 | var cloudinary = require('cloudinary');
var keystone = require('../../../');
module.exports = {
upload: function (req, res) {
if (req.files && req.files.file) {
var options = {};
if (keystone.get('wysiwyg cloudinary images filenameAsPublicID')) {
options.public_id = req.files.file.originalname.substring(0, req.files.file.originalname.lastIndexOf('.'));
}
cloudinary.uploader.upload(req.files.file.path, function (result) {
var sendResult = function () {
if (result.error) {
res.send({ error: { message: result.error.message } });
} else {
res.send({ image: { url: result.url } });
}
};
// TinyMCE upload plugin uses the iframe transport technique
// so the response type must be text/html
res.format({
html: sendResult,
json: sendResult,
});
}, options);
} else {
res.json({ error: { message: 'No image selected' } });
}
},
autocomplete: function (req, res) {
var max = req.query.max || 10;
var prefix = req.query.prefix || '';
var next = req.query.next || null;
cloudinary.api.resources(function (result) {
if (result.error) {
res.json({ error: { message: result.error.message } });
} else {
res.json({
next: result.next_cursor,
items: result.resources,
});
}
}, {
type: 'upload',
prefix: prefix,
max_results: max,
next_cursor: next,
});
},
get: function (req, res) {
cloudinary.api.resource(req.query.id, function (result) {
if (result.error) {
res.json({ error: { message: result.error.message } });
} else {
res.json({ item: result });
}
});
},
};
| mit |
ramonh/sunshine-app | app/src/main/java/com/example/ramonh/sunshine/app/SettingsActivity.java | 2846 | package com.example.ramonh.sunshine.app;
import android.os.Bundle;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.preference.PreferenceManager;
/**
* A {@link PreferenceActivity} that presents a set of application settings.
* <p>
* See <a href="http://developer.android.com/design/patterns/settings.html">
* Android Design: Settings</a> for design guidelines and the <a
* href="http://developer.android.com/guide/topics/ui/settings.html">Settings
* API Guide</a> for more information on developing a Settings UI.
*/
public class SettingsActivity extends PreferenceActivity
implements Preference.OnPreferenceChangeListener {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Add 'general' preferences, defined in the XML file
addPreferencesFromResource(R.xml.pref_general);
// For all preferences, attach an OnPreferenceChangeListener so the UI summary can be
// updated when the preference changes.
bindPreferenceSummaryToValue(findPreference(getString(R.string.pref_location_key)));
bindPreferenceSummaryToValue(findPreference(getString(R.string.pref_units_key)));
}
/**
* Attaches a listener so the summary is always updated with the preference value.
* Also fires the listener once, to initialize the summary (so it shows up before the value
* is changed.)
*/
private void bindPreferenceSummaryToValue(Preference preference) {
// Set the listener to watch for value changes.
preference.setOnPreferenceChangeListener(this);
// Trigger the listener immediately with the preference's
// current value.
onPreferenceChange(preference,
PreferenceManager
.getDefaultSharedPreferences(preference.getContext())
.getString(preference.getKey(), ""));
}
@Override
public boolean onPreferenceChange(Preference preference, Object value) {
String stringValue = value.toString();
if (preference instanceof ListPreference) {
// For list preferences, look up the correct display value in
// the preference's 'entries' list (since they have separate labels/values).
ListPreference listPreference = (ListPreference) preference;
int prefIndex = listPreference.findIndexOfValue(stringValue);
if (prefIndex >= 0) {
preference.setSummary(listPreference.getEntries()[prefIndex]);
}
} else {
// For other preferences, set the summary to the value's simple string representation.
preference.setSummary(stringValue);
}
return true;
}
}
| mit |
reactjs/react-codemod | transforms/__testfixtures__/create-element-to-jsx-preserve-comments.output.js | 793 | var React = require('react');
const render = () => {
return (
/*1*//*4*//*2*//*3*/<div
/*8*/className/*9*/=/*10*/"foo"/*11*/
/*12*/
/*13*///17
onClick/*14*/={/*15*/ this.handleClick}/*16*/>
{/*19*///25
<TodoList.Item />/*24*//*20*//*23*//*21*//*22*//*20*//*23*//*21*//*22*//*21*//*22*/}
<span {.../*26*/getProps()/*27*/} />
{<input /> /*28*//*29*/}
</div>
/*5*//*6*//*7*//*18*/
);
};
const render2 = () => {
return (
<div
// Prop comment.
className="foo">
{// Child string comment.
'hello'}
</div>
);
};
const render3 = () => {
return (
<div>
{// Child element comment.
<span />}
</div>
);
};
const render4 = () => {
return <Foo />/* No props to see here! */;
};
| mit |
opendata-heilbronn/poetryslam | src/modules/admin/EntityUtils.js | 412 | (function () {
'use strict';
angular.module('psadmin').service('EntityUtils', function () {
this.getUid = function () {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
return v.toString(16);
});
};
return this;
});
})(); | mit |
dnshi/Leetcode | algorithms/BinaryTreeInorderTraversal.js | 1192 | // Source : https://leetcode.com/problems/binary-tree-inorder-traversal
// Author : Dean Shi
// Date : 2017-02-27
/***************************************************************************************
*
* Given a binary tree, return the inorder traversal of its nodes' values.
*
* For example:
* Given binary tree [1,null,2,3],
*
* 1
* \
* 2
* /
* 3
*
* return [1,3,2].
*
* Note: Recursive solution is trivial, could you do it iteratively?
*
*
***************************************************************************************/
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @return {number[]}
*/
var inorderTraversal = function(root) {
const stack = []
const result = []
while (root) {
if (root.right) stack.push(root.right)
stack.push(root.val)
if (root.left) stack.push(root.left)
root = stack.pop()
while (root !== void(0) && typeof root !== 'object') {
result.push(root)
root = stack.pop()
}
}
return result
};
| mit |
innogames/gitlabhq | app/controllers/passwords_controller.rb | 2138 | # frozen_string_literal: true
class PasswordsController < Devise::PasswordsController
skip_before_action :require_no_authentication, only: [:edit, :update]
before_action :resource_from_email, only: [:create]
before_action :check_password_authentication_available, only: [:create]
before_action :throttle_reset, only: [:create]
feature_category :authentication_and_authorization
# rubocop: disable CodeReuse/ActiveRecord
def edit
super
reset_password_token = Devise.token_generator.digest(
User,
:reset_password_token,
resource.reset_password_token
)
unless reset_password_token.nil?
user = User.where(
reset_password_token: reset_password_token
).first_or_initialize
unless user.reset_password_period_valid?
flash[:alert] = _('Your password reset token has expired.')
redirect_to(new_user_password_url(user_email: user['email']))
end
end
end
# rubocop: enable CodeReuse/ActiveRecord
def update
super do |resource|
if resource.valid?
resource.password_automatically_set = false
resource.password_expires_at = nil
resource.save(validate: false) if resource.changed?
end
end
end
protected
def resource_from_email
email = resource_params[:email]
self.resource = resource_class.find_by_email(email)
end
def check_password_authentication_available
if resource
return if resource.allow_password_authentication?
else
return if Gitlab::CurrentSettings.password_authentication_enabled?
end
redirect_to after_sending_reset_password_instructions_path_for(resource_name),
alert: _("Password authentication is unavailable.")
end
def throttle_reset
return unless resource && resource.recently_sent_password_reset?
# Throttle reset attempts, but return a normal message to
# avoid user enumeration attack.
redirect_to new_user_session_path,
notice: I18n.t('devise.passwords.send_paranoid_instructions')
end
def context_user
resource
end
end
PasswordsController.prepend_mod_with('PasswordsController')
| mit |
Steffkn/ASP.NET | MVC/BlogSystem/Source/Web/Blog.Web/Controllers/AccountController.cs | 17912 | namespace Blog.Web.Controllers
{
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using Blog.Data.Models;
using Blog.Web.ViewModels.Account;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.Owin;
using Microsoft.Owin.Security;
[Authorize]
public class AccountController : BaseController
{
// Used for XSRF protection when adding external logins
private const string XsrfKey = "XsrfId";
private ApplicationSignInManager signInManager;
private ApplicationUserManager userManager;
public AccountController()
{
}
public AccountController(ApplicationUserManager userManager, ApplicationSignInManager signInManager)
{
this.UserManager = userManager;
this.SignInManager = signInManager;
}
public ApplicationSignInManager SignInManager
{
get
{
return this.signInManager ?? this.HttpContext.GetOwinContext().Get<ApplicationSignInManager>();
}
private set
{
this.signInManager = value;
}
}
public ApplicationUserManager UserManager
{
get
{
return this.userManager ?? this.HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();
}
private set
{
this.userManager = value;
}
}
private IAuthenticationManager AuthenticationManager => this.HttpContext.GetOwinContext().Authentication;
// GET: /Account/Login
[AllowAnonymous]
public ActionResult Login(string returnUrl)
{
this.ViewBag.ReturnUrl = returnUrl;
return this.View();
}
// POST: /Account/Login
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
{
if (!this.ModelState.IsValid)
{
return this.View(model);
}
// This doesn't count login failures towards account lockout
// To enable password failures to trigger account lockout, change to shouldLockout: true
var result =
await
this.SignInManager.PasswordSignInAsync(
model.Email,
model.Password,
model.RememberMe,
shouldLockout: false);
switch (result)
{
case SignInStatus.Success:
return this.RedirectToLocal(returnUrl);
case SignInStatus.LockedOut:
return this.View("Lockout");
case SignInStatus.RequiresVerification:
return this.RedirectToAction(
"SendCode",
new { ReturnUrl = returnUrl, model.RememberMe });
case SignInStatus.Failure:
default:
this.ModelState.AddModelError(string.Empty, "Invalid login attempt.");
return this.View(model);
}
}
// GET: /Account/VerifyCode
[AllowAnonymous]
public async Task<ActionResult> VerifyCode(string provider, string returnUrl, bool rememberMe)
{
// Require that the user has already logged in via username/password or external login
if (!await this.SignInManager.HasBeenVerifiedAsync())
{
return this.View("Error");
}
return
this.View(
new VerifyCodeViewModel { Provider = provider, ReturnUrl = returnUrl, RememberMe = rememberMe });
}
// POST: /Account/VerifyCode
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> VerifyCode(VerifyCodeViewModel model)
{
if (!this.ModelState.IsValid)
{
return this.View(model);
}
// The following code protects for brute force attacks against the two factor codes.
// If a user enters incorrect codes for a specified amount of time then the user account
// will be locked out for a specified amount of time.
// You can configure the account lockout settings in IdentityConfig
var result =
await
this.SignInManager.TwoFactorSignInAsync(
model.Provider,
model.Code,
isPersistent: model.RememberMe,
rememberBrowser: model.RememberBrowser);
switch (result)
{
case SignInStatus.Success:
return this.RedirectToLocal(model.ReturnUrl);
case SignInStatus.LockedOut:
return this.View("Lockout");
case SignInStatus.Failure:
default:
this.ModelState.AddModelError(string.Empty, "Invalid code.");
return this.View(model);
}
}
// GET: /Account/Register
[AllowAnonymous]
public ActionResult Register()
{
return this.View();
}
// POST: /Account/Register
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Register(RegisterViewModel model)
{
if (this.ModelState.IsValid)
{
var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
var result = await this.UserManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
await this.SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);
// For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771
// Send an email with this link
// string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
// var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
// await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>");
return this.RedirectToAction("Index", "Home");
}
this.AddErrors(result);
}
// If we got this far, something failed, redisplay form
return this.View(model);
}
// GET: /Account/ConfirmEmail
[AllowAnonymous]
public async Task<ActionResult> ConfirmEmail(string userId, string code)
{
if (userId == null || code == null)
{
return this.View("Error");
}
var result = await this.UserManager.ConfirmEmailAsync(userId, code);
return this.View(result.Succeeded ? "ConfirmEmail" : "Error");
}
// GET: /Account/ForgotPassword
[AllowAnonymous]
public ActionResult ForgotPassword()
{
return this.View();
}
// POST: /Account/ForgotPassword
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> ForgotPassword(ForgotPasswordViewModel model)
{
if (this.ModelState.IsValid)
{
var user = await this.UserManager.FindByNameAsync(model.Email);
if (user == null || !await this.UserManager.IsEmailConfirmedAsync(user.Id))
{
// Don't reveal that the user does not exist or is not confirmed
return this.View("ForgotPasswordConfirmation");
}
// For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771
// Send an email with this link
// string code = await UserManager.GeneratePasswordResetTokenAsync(user.Id);
// var callbackUrl = Url.Action("ResetPassword", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
// await UserManager.SendEmailAsync(user.Id, "Reset Password", "Please reset your password by clicking <a href=\"" + callbackUrl + "\">here</a>");
// return RedirectToAction("ForgotPasswordConfirmation", "Account");
}
// If we got this far, something failed, redisplay form
return this.View(model);
}
// GET: /Account/ForgotPasswordConfirmation
[AllowAnonymous]
public ActionResult ForgotPasswordConfirmation()
{
return this.View();
}
// GET: /Account/ResetPassword
[AllowAnonymous]
public ActionResult ResetPassword(string code)
{
return code == null ? this.View("Error") : this.View();
}
// POST: /Account/ResetPassword
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> ResetPassword(ResetPasswordViewModel model)
{
if (!this.ModelState.IsValid)
{
return this.View(model);
}
var user = await this.UserManager.FindByNameAsync(model.Email);
if (user == null)
{
// Don't reveal that the user does not exist
return this.RedirectToAction("ResetPasswordConfirmation", "Account");
}
var result = await this.UserManager.ResetPasswordAsync(user.Id, model.Code, model.Password);
if (result.Succeeded)
{
return this.RedirectToAction("ResetPasswordConfirmation", "Account");
}
this.AddErrors(result);
return this.View();
}
// GET: /Account/ResetPasswordConfirmation
[AllowAnonymous]
public ActionResult ResetPasswordConfirmation()
{
return this.View();
}
// POST: /Account/ExternalLogin
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult ExternalLogin(string provider, string returnUrl)
{
// Request a redirect to the external login provider
return new ChallengeResult(
provider,
this.Url.Action("ExternalLoginCallback", "Account", new { ReturnUrl = returnUrl }));
}
// GET: /Account/SendCode
[AllowAnonymous]
public async Task<ActionResult> SendCode(string returnUrl, bool rememberMe)
{
var userId = await this.SignInManager.GetVerifiedUserIdAsync();
if (userId == null)
{
return this.View("Error");
}
var userFactors = await this.UserManager.GetValidTwoFactorProvidersAsync(userId);
var factorOptions =
userFactors.Select(purpose => new SelectListItem { Text = purpose, Value = purpose }).ToList();
return
this.View(
new SendCodeViewModel { Providers = factorOptions, ReturnUrl = returnUrl, RememberMe = rememberMe });
}
// POST: /Account/SendCode
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> SendCode(SendCodeViewModel model)
{
if (!this.ModelState.IsValid)
{
return this.View();
}
// Generate the token and send it
if (!await this.SignInManager.SendTwoFactorCodeAsync(model.SelectedProvider))
{
return this.View("Error");
}
return this.RedirectToAction(
"VerifyCode",
new { Provider = model.SelectedProvider, model.ReturnUrl, model.RememberMe });
}
// GET: /Account/ExternalLoginCallback
[AllowAnonymous]
public async Task<ActionResult> ExternalLoginCallback(string returnUrl)
{
var loginInfo = await this.AuthenticationManager.GetExternalLoginInfoAsync();
if (loginInfo == null)
{
return this.RedirectToAction("Login");
}
// Sign in the user with this external login provider if the user already has a login
var result = await this.SignInManager.ExternalSignInAsync(loginInfo, isPersistent: false);
switch (result)
{
case SignInStatus.Success:
return this.RedirectToLocal(returnUrl);
case SignInStatus.LockedOut:
return this.View("Lockout");
case SignInStatus.RequiresVerification:
return this.RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = false });
case SignInStatus.Failure:
default:
// If the user does not have an account, then prompt the user to create an account
this.ViewBag.ReturnUrl = returnUrl;
this.ViewBag.LoginProvider = loginInfo.Login.LoginProvider;
return this.View(
"ExternalLoginConfirmation",
new ExternalLoginConfirmationViewModel { Email = loginInfo.Email });
}
}
// POST: /Account/ExternalLoginConfirmation
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> ExternalLoginConfirmation(
ExternalLoginConfirmationViewModel model,
string returnUrl)
{
if (this.User.Identity.IsAuthenticated)
{
return this.RedirectToAction("Index", "Manage");
}
if (this.ModelState.IsValid)
{
// Get the information about the user from the external login provider
var info = await this.AuthenticationManager.GetExternalLoginInfoAsync();
if (info == null)
{
return this.View("ExternalLoginFailure");
}
var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
var result = await this.UserManager.CreateAsync(user);
if (result.Succeeded)
{
result = await this.UserManager.AddLoginAsync(user.Id, info.Login);
if (result.Succeeded)
{
await this.SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);
return this.RedirectToLocal(returnUrl);
}
}
this.AddErrors(result);
}
this.ViewBag.ReturnUrl = returnUrl;
return this.View(model);
}
// POST: /Account/LogOff
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult LogOff()
{
this.AuthenticationManager.SignOut(DefaultAuthenticationTypes.ApplicationCookie);
return this.RedirectToAction("Index", "Home");
}
// GET: /Account/ExternalLoginFailure
[AllowAnonymous]
public ActionResult ExternalLoginFailure()
{
return this.View();
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
if (this.userManager != null)
{
this.userManager.Dispose();
this.userManager = null;
}
if (this.signInManager != null)
{
this.signInManager.Dispose();
this.signInManager = null;
}
}
base.Dispose(disposing);
}
private void AddErrors(IdentityResult result)
{
foreach (var error in result.Errors)
{
this.ModelState.AddModelError(string.Empty, error);
}
}
private ActionResult RedirectToLocal(string returnUrl)
{
if (this.Url.IsLocalUrl(returnUrl))
{
return this.Redirect(returnUrl);
}
return this.RedirectToAction("Index", "Home");
}
internal class ChallengeResult : HttpUnauthorizedResult
{
public ChallengeResult(string provider, string redirectUri, string userId = null)
{
this.LoginProvider = provider;
this.RedirectUri = redirectUri;
this.UserId = userId;
}
public string LoginProvider { get; set; }
public string RedirectUri { get; set; }
public string UserId { get; set; }
public override void ExecuteResult(ControllerContext context)
{
var properties = new AuthenticationProperties { RedirectUri = this.RedirectUri };
if (this.UserId != null)
{
properties.Dictionary[XsrfKey] = this.UserId;
}
context.HttpContext.GetOwinContext().Authentication.Challenge(properties, this.LoginProvider);
}
}
}
}
| mit |
CrustyJew/OwinOAuthProviders | Owin.Security.Providers/Properties/AssemblyInfo.cs | 1423 | 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("Owin.Security.Providers")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Owin.Security.Providers")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[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("c745499f-213a-461d-9dfb-c46935ec44e9")]
// 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.21.0.0")]
[assembly: AssemblyFileVersion("1.21.0.0")]
| mit |
farpostdesign/activeadmin-dropzone | app/helpers/active_admin/view_helpers/dropzone_helper.rb | 786 | module ActiveAdmin::ViewHelpers::DropzoneHelper
def dropzone_object_title dropzone_object
title = dropzone_object.send(dropzone_object.class.dropzone_field(:title))
if title.present?
title.squish
else
''
end
end
def render_mock_dropzone_files dropzone_objects
dropzone_objects.map.with_index do |dropzone_object, index|
{
id: dropzone_object.id,
title: dropzone_object_title(dropzone_object),
size: dropzone_object.send(dropzone_object.class.dropzone_field(:file_size)),
url: dropzone_object.send(dropzone_object.class.dropzone_field(:url)),
name: dropzone_object.send(dropzone_object.class.dropzone_field(:data)).original_filename,
index: index,
}
end.to_json.html_safe
end
end
| mit |
darkless456/Python | 循环语句_无限循环.py | 149 | # 无限循环
var = 1
while var == 1:
num = input ("Enter a number : ")
print("You entered: ", num)
print("Good bye!")
| mit |
mjeanroy/junit-servers | junit-servers-core/src/main/java/com/github/mjeanroy/junit/servers/client/impl/async/AsyncHttpResponse.java | 3710 | /**
* The MIT License (MIT)
*
* Copyright (c) 2014-2022 <mickael.jeanroy@gmail.com>
*
* 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.github.mjeanroy.junit.servers.client.impl.async;
import com.github.mjeanroy.junit.servers.client.HttpHeader;
import com.github.mjeanroy.junit.servers.client.HttpResponse;
import com.github.mjeanroy.junit.servers.client.impl.AbstractHttpResponse;
import com.github.mjeanroy.junit.servers.commons.lang.ToStringBuilder;
import io.netty.handler.codec.http.HttpHeaders;
import org.asynchttpclient.Response;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import static com.github.mjeanroy.junit.servers.commons.lang.Preconditions.notNull;
/**
* Implementation of {@link HttpResponse} delegating calls to original {@link Response}
* instance.
*/
final class AsyncHttpResponse extends AbstractHttpResponse {
/**
* The original response.
*/
private final Response response;
/**
* Create the response from AsyncHttpClient.
*
* @param response The original response.
* @param duration Request duration.
*/
AsyncHttpResponse(Response response, long duration) {
super(duration);
this.response = notNull(response, "Response");
}
@Override
public int status() {
return response.getStatusCode();
}
@Override
protected String readResponseBody() {
return response.getResponseBody();
}
@Override
public Collection<HttpHeader> getHeaders() {
HttpHeaders headers = response.getHeaders();
List<HttpHeader> results = new ArrayList<>(headers.size());
for (Map.Entry<String, String> entry : headers) {
String name = entry.getKey();
List<String> values = headers.getAll(name);
results.add(HttpHeader.header(name, values));
}
return results;
}
@Override
public HttpHeader getHeader(String name) {
List<String> values = response.getHeaders(name);
if (values == null || values.isEmpty()) {
return null;
}
return HttpHeader.header(name, values);
}
@Override
public String toString() {
return ToStringBuilder.create(getClass())
.append("duration", getRequestDuration())
.append("response", response)
.build();
}
@Override
public boolean equals(Object o) {
if (o == this) {
return true;
}
if (o instanceof AsyncHttpResponse) {
AsyncHttpResponse r = (AsyncHttpResponse) o;
return super.equals(r) && Objects.equals(response, r.response);
}
return false;
}
@Override
public int hashCode() {
return Objects.hash(super.hashCode(), response);
}
@Override
protected boolean canEqual(AbstractHttpResponse o) {
return o instanceof AsyncHttpResponse;
}
}
| mit |
yoshuawuyts/base-package-json | test.js | 774 | const concat = require('concat-stream')
const test = require('tape')
const pkg = require('./')
test('should create a base package.json', function (t) {
t.plan(1)
pkg().pipe(concat({ object: true }, function (arr) {
const obj = arr[0]
t.deepEqual(obj, {
name: '<name>',
version: '1.0.0',
scripts: {},
dependencies: {},
devDependencies: {}
})
}))
})
test('should accept options', function (t) {
t.plan(1)
const opts = { name: 'foo', version: '2.0.0', private: true }
pkg(opts).pipe(concat({ object: true }, function (arr) {
const obj = arr[0]
t.deepEqual(obj, {
name: 'foo',
version: '2.0.0',
private: true,
scripts: {},
dependencies: {},
devDependencies: {}
})
}))
})
| mit |
jsGiven/jsGiven | examples/jest-node-8/parameter-formatting.parametrized.test.js | 721 | import {
scenario,
scenarios,
setupForRspec,
Stage,
buildParameterFormatter,
} from 'js-given';
import { sum } from './sum';
setupForRspec(describe, it);
const LoudFormatter = bangCharacter =>
buildParameterFormatter(text => text.toUpperCase() + `${bangCharacter}`);
class MyStage extends Stage {
@LoudFormatter('!')('value')
a_value(value) {
return this;
}
}
scenarios(
'parameter-formatting-parametrized',
MyStage,
({ given, when, then }) => {
return {
parameters_can_be_formatted: scenario({}, () => {
given().a_value('hello world');
// Will be converted to
// Given a value HELLO WORLD !!!
when();
then();
}),
};
}
);
| mit |
nsarno/knock | test/dummy/app/controllers/vendor_token_controller.rb | 61 | class VendorTokenController < Knock::AuthTokenController
end
| mit |
thoughtram/blog | gatsby/src/pages/404.js | 986 | import React from "react"
import { Link, graphql } from "gatsby"
import Layout from "../components/layout"
import SEO from "../components/seo"
class NotFoundPage extends React.Component {
render() {
const { data } = this.props
const siteTitle = data.site.siteMetadata.title
return (
<Layout location={this.props.location} title={siteTitle}>
<SEO title="404: Not Found" />
<section className="thtrm-section thtrm-section--centered u-flex--justify-center">
<div>
<h1 className="thtrm-section__heading">Lost in Space.</h1>
<p>The page you have requested could not be found.</p>
<div className="thtrm-section__footer">
<Link to="/all">Take me to all blog posts</Link>
</div>
</div>
</section>
</Layout>
)
}
}
export default NotFoundPage
export const pageQuery = graphql`
query {
site {
siteMetadata {
title
}
}
}
`
| mit |
AideTechBot/expo | pi/gps.py | 1734 | #!/usr/bin/env python
"""
GPS.PY
v.2
written by: Manuel Dionne
credit to: the internet
"""
import time
import os
import urllib2
from subprocess import *
fname = "send.wav"
baud = "1000"
pos = "300_600"
identifier = 1
def internet_on():
try:
response=urllib2.urlopen('http://74.125.228.100',timeout=1)
return True
except urllib2.URLError as err: pass
return False
def send_data( filename, freq ):
call(["./PiFmDma", filename, freq])
return
def createdata():
#making the data
data = "START" + "|" + str("%.20f" % time.time()) + "|" + pos + "|" + str(identifier) + "|" + "END" +"\n"
data_size = len(data)
def encodedata(data):
p1 = Popen(["echo", "-e","\"" + data + "\""], stdout=PIPE)
p2 = Popen(["minimodem", "--tx", "-f", fname, "-8", baud], stdin=p1.stdout, stdout=PIPE)
output = p2.communicate()[0]
print output
refreshtime = 0
while(True):
data = createdata()
print "[GPS] packet created: " + data
encodedata(data)
print "[GPS] data encoded"
print "[GPS] sending out packet"
send_data(fname,"103.3")
print "[GPS] sleeping..."
time.sleep(2)
refreshtime = refreshtime + 1
if refreshtime >= 400:
if internet_on():
print "[GPS] internet connection found"
print "[GPS] syncing time..."
call(["date"])
call(["sudo","service","ntpd","stop"])
call(["sudo","ntpd","-qg"])
call(["sudo","service","ntpd","start"])
call(["date"])
print "[GPS] Time synced"
else:
print "[GPS] no internet connection: time sync failed"
refreshtime = 0 | mit |
NeonWilderness/f5skin2day | src/js/app/directives/index.js | 269 | 'use strict';
/**
* Browserify all directives
*
*/
require('angular')
.module('f5SkinApp')
.directive('convertcss', [require('./convertcss')])
.directive('encode', [require('./encode')])
.directive('resizable', ['$window', require('./resizable')]); | mit |
skyostil/tracy | src/analyzer/TraceOperationsTest.py | 3155 | # Copyright (c) 2011 Nokia
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
import unittest
import Trace
import TraceOperations
import BinaryCodec
import StringIO
testTrace1 = "data/note.bin"
testTrace2 = "data/simplecube.bin"
class TraceOperationsTest(unittest.TestCase):
def loadTrace(self, traceFile):
trace = Trace.Trace()
reader = BinaryCodec.Reader(trace, open(traceFile, "rb"))
reader.load()
return trace
def assertEqualEventLists(self, events1, events2):
for e1, e2 in zip(events1, events2):
self.assertEquals(e1.name, e2.name)
self.assertEquals(len(e1.values), len(e2.values))
for v1, v2 in zip(e1.values.values(), e2.values.values()):
if isinstance(v1, Trace.VoidValue):
continue
elif isinstance(v1, Trace.Object):
for a1, a2 in zip(v1.attrs.values(), v2.attrs.values()):
self.assertEquals(a1, a2)
else:
self.assertEquals(v1, v2)
def testExtraction(self):
for traceFile in [testTrace1, testTrace2]:
trace = self.loadTrace(traceFile)
newTrace = TraceOperations.extract(trace, 10, 20)
assert len(newTrace.events) == 10
assert newTrace.events[0].time == 0
assert newTrace.events[0].seq == 0
assert newTrace.events[9].seq == 9
self.assertEqualEventLists(newTrace.events, trace.events[10:20])
newTrace.events[0].name = "foo"
assert trace.events[0].name != "foo"
def testJoining(self):
for traceFile in [testTrace1, testTrace2]:
trace = self.loadTrace(traceFile)
l = len(trace.events)
a = TraceOperations.extract(trace, 0, l / 2)
b = TraceOperations.extract(trace, l / 2, l)
assert len(a.events) + len(b.events) == l
newTrace = TraceOperations.join(a, b)
self.assertEqualEventLists(newTrace.events, trace.events)
for i, event in enumerate(newTrace.events):
self.assertEqual(event.seq, i)
if __name__ == "__main__":
unittest.main()
| mit |
gisele-tool/gisele-vm | spec/unit/kernel/runner/test_stack.rb | 642 | require 'spec_helper'
module Gisele
class VM
class Kernel
describe Runner, "stack" do
it 'pushes at the end' do
runner.stack = [:hello]
runner.push :world
runner.stack.should eq([:hello, :world])
end
it 'pops from the end' do
runner.stack = [:hello, :world]
runner.pop.should eq(:world)
runner.stack.should eq([:hello])
end
it 'peeks at the the end' do
runner.stack = [:hello, :world]
runner.peek.should eq(:world)
runner.stack.should eq([:hello, :world])
end
end
end
end
end
| mit |
geometryzen/davinci-eight | build/module/lib/math/Vector4.js | 6442 | import { __extends } from "tslib";
import { Coords } from '../math/Coords';
/**
* @hidden
*/
var Vector4 = /** @class */ (function (_super) {
__extends(Vector4, _super);
/**
* @param data Default is [0, 0, 0, 0] corresponding to x, y, z, and w coordinate labels.
* @param modified Default is false.
*/
function Vector4(data, modified) {
if (data === void 0) { data = [0, 0, 0, 0]; }
if (modified === void 0) { modified = false; }
return _super.call(this, data, modified, 4) || this;
}
Object.defineProperty(Vector4.prototype, "x", {
/**
* @property x
* @type Number
*/
get: function () {
return this.coords[0];
},
set: function (value) {
this.modified = this.modified || this.x !== value;
this.coords[0] = value;
},
enumerable: false,
configurable: true
});
Object.defineProperty(Vector4.prototype, "y", {
/**
* @property y
* @type Number
*/
get: function () {
return this.coords[1];
},
set: function (value) {
this.modified = this.modified || this.y !== value;
this.coords[1] = value;
},
enumerable: false,
configurable: true
});
Object.defineProperty(Vector4.prototype, "z", {
/**
* @property z
* @type Number
*/
get: function () {
return this.coords[2];
},
set: function (value) {
this.modified = this.modified || this.z !== value;
this.coords[2] = value;
},
enumerable: false,
configurable: true
});
Object.defineProperty(Vector4.prototype, "w", {
/**
* @property w
* @type Number
*/
get: function () {
return this.coords[3];
},
set: function (value) {
this.modified = this.modified || this.w !== value;
this.coords[3] = value;
},
enumerable: false,
configurable: true
});
Vector4.prototype.setW = function (w) {
this.w = w;
return this;
};
Vector4.prototype.add = function (vector, α) {
if (α === void 0) { α = 1; }
this.x += vector.x * α;
this.y += vector.y * α;
this.z += vector.z * α;
this.w += vector.w * α;
return this;
};
Vector4.prototype.add2 = function (a, b) {
this.x = a.x + b.x;
this.y = a.y + b.y;
this.z = a.z + b.z;
this.w = a.w + b.w;
return this;
};
/**
* Pre-multiplies the column vector corresponding to this vector by the matrix.
* The result is applied to this vector.
*
* @method applyMatrix
* @param σ The 4x4 matrix that pre-multiplies this column vector.
* @return {Vector4} <code>this</code>
* @chainable
*/
Vector4.prototype.applyMatrix = function (σ) {
var x = this.x;
var y = this.y;
var z = this.z;
var w = this.w;
var e = σ.elements;
this.x = e[0x0] * x + e[0x4] * y + e[0x8] * z + e[0xC] * w;
this.y = e[0x1] * x + e[0x5] * y + e[0x9] * z + e[0xD] * w;
this.z = e[0x2] * x + e[0x6] * y + e[0xA] * z + e[0xE] * w;
this.w = e[0x3] * x + e[0x7] * y + e[0xB] * z + e[0xF] * w;
return this;
};
/**
* @method approx
* @param n {number}
* @return {Vector4}
* @chainable
*/
Vector4.prototype.approx = function (n) {
_super.prototype.approx.call(this, n);
return this;
};
Vector4.prototype.clone = function () {
return new Vector4([this.x, this.y, this.z, this.w], this.modified);
};
Vector4.prototype.copy = function (v) {
this.x = v.x;
this.y = v.y;
this.z = v.z;
this.w = v.w;
return this;
};
Vector4.prototype.divByScalar = function (α) {
this.x /= α;
this.y /= α;
this.z /= α;
this.w /= α;
return this;
};
Vector4.prototype.lerp = function (target, α) {
this.x += (target.x - this.x) * α;
this.y += (target.y - this.y) * α;
this.z += (target.z - this.z) * α;
this.w += (target.w - this.w) * α;
return this;
};
Vector4.prototype.lerp2 = function (a, b, α) {
this.sub2(b, a).scale(α).add(a);
return this;
};
Vector4.prototype.neg = function () {
this.x = -this.x;
this.y = -this.y;
this.z = -this.z;
this.w = -this.w;
return this;
};
Vector4.prototype.scale = function (α) {
this.x *= α;
this.y *= α;
this.z *= α;
this.w *= α;
return this;
};
Vector4.prototype.reflect = function (n) {
// TODO
return this;
};
Vector4.prototype.rotate = function (rotor) {
// TODO
return this;
};
Vector4.prototype.stress = function (σ) {
this.x *= σ.x;
this.y *= σ.y;
this.z *= σ.z;
this.w *= σ.w;
return this;
};
Vector4.prototype.sub = function (v, α) {
this.x -= v.x * α;
this.y -= v.y * α;
this.z -= v.z * α;
this.w -= v.w * α;
return this;
};
Vector4.prototype.sub2 = function (a, b) {
this.x = a.x - b.x;
this.y = a.y - b.y;
this.z = a.z - b.z;
this.w = a.w - b.w;
return this;
};
Vector4.prototype.magnitude = function () {
throw new Error("TODO: Vector4.magnitude()");
};
Vector4.prototype.squaredNorm = function () {
throw new Error("TODO: Vector4.squaredNorm()");
};
Vector4.prototype.toExponential = function (fractionDigits) {
return "TODO Vector4.toExponential";
};
Vector4.prototype.toFixed = function (fractionDigits) {
return "TODO Vector4.toFixed";
};
Vector4.prototype.toPrecision = function (precision) {
return "TODO Vector4.toFixed";
};
Vector4.prototype.toString = function (radix) {
return "TODO Vector4.toString";
};
Vector4.prototype.zero = function () {
this.x = 0;
this.y = 0;
this.z = 0;
this.w = 0;
return this;
};
return Vector4;
}(Coords));
export { Vector4 };
| mit |
chriswilley/leash | leash/run.py | 92 | from leash import app
if (__name__) == '__main__':
app.run(host='0.0.0.0', port=5000)
| mit |
Drillster/drillster-api | src/main/java/com/drillster/api2/invoice/InvoiceRecipient.java | 887 | package com.drillster.api2.invoice;
import com.drillster.api2.user.Organization;
public class InvoiceRecipient {
private String name;
private String emailAddress;
private String vatNumber;
private Organization organization;
public InvoiceRecipient setName(String name) { this.name = name; return this; }
public InvoiceRecipient setEmailAddress(String emailAddress) { this.emailAddress = emailAddress; return this; }
public InvoiceRecipient setVatNummber(String vatNumber) { this.vatNumber = vatNumber; return this; }
public InvoiceRecipient setOrganization(Organization organization) { this.organization = organization; return this; }
public String getName() { return this.name; }
public String getEmailAddress() { return this.emailAddress; }
public String getVatNumber() { return this.vatNumber; }
public Organization getOrganization() { return this.organization; }
}
| mit |
claytuna/pixlogic-c5 | application/blocks/pix_tabs/view.php | 2524 | <?php defined('C5_EXECUTE') or die("Access Denied.");
$c = Page::getCurrentPage();?>
<div class="tabs-row">
<div class="tabs-row__title-group">
<div class="container">
<div class="row">
<div class="col-xs-12">
<h2 class="tabs-row__title"><?php print $tabTitle ?></h2>
</div>
</div>
</div>
</div>
<div class="container">
<div class="row">
<div class="col-xs-12">
<div class="tabs <?php if($allowIntroText == 1){ echo 'tabs--lg'; } ?>" style="min-height:<?php if($minHeight){ echo $minHeight; } else { echo '510px'; }?>;">
<?php if(count($rows) > 0) { ?>
<?php foreach($rows as $idx=>$row) { ?>
<div class="tab">
<input type="radio" id="tab-<?php echo $idx?>" name="tab-group-<?php echo $bID?>" <?php if($idx == '0') { print 'checked'; } ?>>
<label for="tab-<?php echo $idx?>">
<?php
$f = File::getByID($row['fID']);
if(is_object($f)) {
print '<span class="tab__icon">';
$tag = Core::make('html/image', array($f, false))->getTag();
$tag->alt('tab-icon');
print $tag;
print '</span>';
} ?>
<?php if($allowIntroText == 1){?> <span class="tab__intro"><?php echo $row['titleIntro'] ?></span><br/><?php }?>
<?php echo $row['title'] ?>
</label>
<div class="content">
<div class="row">
<div class="col-sm-9">
<?php echo $row['description'] ?>
</div>
<div class="col-sm-3">
<?php if($row['linkURL']){?>
<a href="<?php echo $row['linkURL'] ?>" class="btn btn--primary btn--block">
<?php echo $row['linkText'] ? $row['linkText'] : 'Learn More'?>
</a>
<?php } ?>
</div>
</div>
</div>
</div>
<?php } ?><!--end foreach-->
<?php } else { ?>
<div class="ccm-image-slider-placeholder">
<p><?php echo t('No Tabs Added.'); ?></p>
</div>
<?php } ?><!--end countrows-->
</div>
</div>
</div>
</div>
</div>
| mit |
mindsnacks/Zinc | src/zinc/archives.py | 1085 | import os
import tarfile
import tempfile
import zinc.utils as utils
import zinc.helpers as helpers
from zinc.formats import Formats
def build_archive_with_manifest(manifest, src_dir, dst_path, flavor=None):
files = manifest.get_all_files(flavor=flavor)
with tarfile.open(dst_path, 'w') as tar:
for f in files:
format, format_info = manifest.get_format_info_for_file(f)
assert format is not None
assert format_info is not None
sha = manifest.sha_for_file(f)
ext = helpers.file_extension_for_format(format)
path = os.path.join(src_dir, f)
arcname = helpers.append_file_extension(sha, ext)
## TODO: write a test to ensure that file formats are written correctly
if format == Formats.RAW:
tar.add(path, arcname=arcname)
elif format == Formats.GZ:
gz_path = tempfile.mkstemp()[1]
utils.gzip_path(path, gz_path)
tar.add(gz_path, arcname=arcname)
os.remove(gz_path)
| mit |
nicky-lenaers/ngx-scroll-to | projects/ngx-scroll-to/src/lib/scroll-to.directive.spec.ts | 3076 | import { async, ComponentFixture, fakeAsync, TestBed, tick } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { ScrollToModule } from './scroll-to.module';
import { ScrollToDirective } from './scroll-to.directive';
import { ScrollToService } from './scroll-to.service';
import { DEFAULTS, EVENTS } from './scroll-to-helpers';
import { BUTTON_ID, DummyComponent, TARGET } from '../test/test-dummy.component';
import { ScrollToServiceMock } from '../test/test-mock.service';
import { CompileTemplateConfigOptions, createTestComponent } from '../test/test-helpers';
import { ScrollToEvent } from './scroll-to-event.interface';
describe('ScrollToDirective', () => {
beforeEach(async(() => {
TestBed
.configureTestingModule({
imports: [
ScrollToModule.forRoot()
],
declarations: [
DummyComponent
],
providers: [
{
provide: ScrollToService,
useClass: ScrollToServiceMock
}
]
});
}));
it('should be created', () => {
const fixture = TestBed.createComponent(DummyComponent);
const directive = fixture.debugElement.query(By.directive(ScrollToDirective));
expect(directive).toBeTruthy();
});
it('should have default values', fakeAsync(() => {
const fixture: ComponentFixture<DummyComponent> = TestBed.createComponent(DummyComponent);
const service: ScrollToService = TestBed.inject(ScrollToService);
const component: DummyComponent = fixture.componentInstance;
component.ngOnInit();
fixture.detectChanges();
spyOn(service, 'scrollTo');
const btn = fixture.debugElement.query(By.css(`#${BUTTON_ID}`));
btn.triggerEventHandler('click', null);
tick();
expect(service.scrollTo).toHaveBeenCalledWith({
target: TARGET,
duration: DEFAULTS.duration,
easing: DEFAULTS.easing,
offset: DEFAULTS.offset,
offsetMap: DEFAULTS.offsetMap
});
}));
const testMouseEvent = (event: ScrollToEvent) => {
it(`should handle a '${event}' event`, fakeAsync(() => {
const templateConfig: CompileTemplateConfigOptions = {
target: TARGET
};
const fixture: ComponentFixture<DummyComponent> = createTestComponent(DummyComponent, templateConfig, event);
const service: ScrollToService = TestBed.inject(ScrollToService);
const component: DummyComponent = fixture.componentInstance;
component.ngOnInit();
fixture.detectChanges();
spyOn(service, 'scrollTo');
const btn = fixture.debugElement.query(By.css(`#${BUTTON_ID}`));
btn.triggerEventHandler(event, null);
tick();
expect(service.scrollTo).toHaveBeenCalledTimes(1);
expect(service.scrollTo).toHaveBeenCalledWith({
target: TARGET,
duration: DEFAULTS.duration,
easing: DEFAULTS.easing,
offset: DEFAULTS.offset,
offsetMap: DEFAULTS.offsetMap
});
}));
};
EVENTS.forEach((event: ScrollToEvent) => {
testMouseEvent(event);
});
});
| mit |
AcademiaBinaria/SemillaBinaria | src/client/lib/services/usersDataService.js | 2585 | import * as angular from 'angular'
import * as ngrs from 'angular-resource'
import * as ngstorage from 'ngstorage'
const name = 'usersDataService'
function theService($localStorage, $resource, $q, $rootScope) {
var User = $resource(
'/api/users/:id',
{
id: '@_id'
},
{
'update':
{
method: 'PUT'
}
});
var Session = $resource('/api/users/sessions');
/** saves the response token for later use in requests */
let saveToken = (response) => {
$localStorage.xAccessToken = response.token;
$rootScope.isLogged = true;
return response;
}
/** saves the response token for later use in requests */
let deleteToken = (response) => {
delete $localStorage['xAccessToken'];
$rootScope.isLogged = false;
return response;
}
/** creates a new user resource */
this.newUser = (email, password) => {
var user = new User();
user.email = email;
user.password = password;
return user;
}
/** creates a new session resource */
this.newSession = (email, password) => {
var session = new Session();
session.email = email;
session.password = password;
return session;
}
/** saves a new user posting it to the server, is a register operation */
this.postingUser = (user) => {
return user.$save()
.then((response) => {
return saveToken(response);
}, (reason) => {
return $q.reject(reason);
});
}
/** saves a new session posting it to the server, is a login operation*/
this.postingSession = (session) => {
return session.$save()
.then((response) => {
return saveToken(response);
}, (reason) => {
return $q.reject(reason);
});
}
/** asks to get the user object from the server */
this.gettingUser = () => {
return User.get().$promise;
}
/** ask to update the user object at the server */
this.updatingUser = (user) => {
user.$update();
}
/** ask delete the user object at the server */
this.deletingUser = (user) => {
user.$delete()
.then((response) => {
return deleteToken();
}, (reason) => {
return $q.reject(reason);
});
}
}
angular.module(name, ['ngResource', 'ngStorage'])
.service(name, theService)
export default name | mit |
jmurty/xml4h | xml4h/impls/lxml_etree.py | 19913 | import re
import copy
from xml4h.impls.interface import XmlImplAdapter
from xml4h import nodes, exceptions
try:
from lxml import etree
except ImportError:
pass
class LXMLAdapter(XmlImplAdapter):
"""
Adapter to the `lxml <http://lxml.de>`_ XML library implementation.
"""
SUPPORTED_FEATURES = {
'xpath': True,
}
@classmethod
def is_available(cls):
try:
etree.Element
return True
except:
return False
@classmethod
def parse_string(cls, xml_str, ignore_whitespace_text_nodes=True):
impl_root_elem = etree.fromstring(xml_str)
wrapped_doc = LXMLAdapter.wrap_document(impl_root_elem.getroottree())
if ignore_whitespace_text_nodes:
cls.ignore_whitespace_text_nodes(wrapped_doc)
return wrapped_doc
@classmethod
def parse_bytes(cls, xml_bytes, ignore_whitespace_text_nodes=True):
return LXMLAdapter.parse_string(xml_bytes, ignore_whitespace_text_nodes)
@classmethod
def parse_file(cls, xml_file, ignore_whitespace_text_nodes=True):
impl_doc = etree.parse(xml_file)
wrapped_doc = LXMLAdapter.wrap_document(impl_doc)
if ignore_whitespace_text_nodes:
cls.ignore_whitespace_text_nodes(wrapped_doc)
return wrapped_doc
@classmethod
def new_impl_document(cls, root_tagname, ns_uri=None, **kwargs):
root_nsmap = {}
if ns_uri is not None:
root_nsmap[None] = ns_uri
else:
ns_uri = nodes.Node.XMLNS_URI
root_nsmap[None] = ns_uri
root_elem = etree.Element('{%s}%s' % (ns_uri, root_tagname),
nsmap=root_nsmap)
doc = etree.ElementTree(root_elem)
return doc
def map_node_to_class(self, node):
if isinstance(node, etree._ProcessingInstruction):
return nodes.ProcessingInstruction
elif isinstance(node, etree._Comment):
return nodes.Comment
elif isinstance(node, etree._ElementTree):
return nodes.Document
elif isinstance(node, etree._Element):
return nodes.Element
elif isinstance(node, LXMLAttribute):
return nodes.Attribute
elif isinstance(node, LXMLText):
if node.is_cdata:
return nodes.CDATA
else:
return nodes.Text
raise exceptions.Xml4hImplementationBug(
'Unrecognized type for implementation node: %s' % node)
def get_impl_root(self, node):
return self._impl_document.getroot()
# Document implementation methods
def new_impl_element(self, tagname, ns_uri=None, parent=None):
if ns_uri is not None:
if ':' in tagname:
tagname = tagname.split(':')[1]
my_nsmap = {None: ns_uri}
# Add any xmlns attribute prefix mappings from parent's document
# TODO This doesn't seem to help
curr_node = parent
while curr_node.__class__ == etree._Element:
for n, v in list(curr_node.attrib.items()):
if '{%s}' % nodes.Node.XMLNS_URI in n:
_, prefix = n.split('}')
my_nsmap[prefix] = v
curr_node = self.get_node_parent(curr_node)
return etree.Element('{%s}%s' % (ns_uri, tagname), nsmap=my_nsmap)
else:
return etree.Element(tagname)
def new_impl_text(self, text):
return LXMLText(text)
def new_impl_comment(self, text):
return etree.Comment(text)
def new_impl_instruction(self, target, data):
return etree.ProcessingInstruction(target, data)
def new_impl_cdata(self, text):
return LXMLText(text, is_cdata=True)
def find_node_elements(self, node, name='*', ns_uri='*'):
# TODO Any proper way to find namespaced elements by name?
name_match_nodes = node.getiterator()
# Filter nodes by name and ns_uri if necessary
results = []
for n in name_match_nodes:
# Ignore the current node
if n == node:
continue
# Ignore non-Elements
if not n.__class__ == etree._Element:
continue
if ns_uri != '*' and self.get_node_namespace_uri(n) != ns_uri:
continue
if name != '*' and self.get_node_local_name(n) != name:
continue
results.append(n)
return results
find_node_elements.__doc__ = XmlImplAdapter.find_node_elements.__doc__
def xpath_on_node(self, node, xpath, **kwargs):
"""
Return result of performing the given XPath query on the given node.
All known namespace prefix-to-URI mappings in the document are
automatically included in the XPath invocation.
If an empty/default namespace (i.e. None) is defined, this is
converted to the prefix name '_' so it can be used despite empty
namespace prefixes being unsupported by XPath.
"""
if isinstance(node, etree._ElementTree):
# Document node lxml.etree._ElementTree has no nsmap, lookup root
root = self.get_impl_root(node)
namespaces_dict = root.nsmap.copy()
else:
namespaces_dict = node.nsmap.copy()
if 'namespaces' in kwargs:
namespaces_dict.update(kwargs['namespaces'])
# Empty namespace prefix is not supported, convert to '_' prefix
if None in namespaces_dict:
default_ns_uri = namespaces_dict.pop(None)
namespaces_dict['_'] = default_ns_uri
# Include XMLNS namespace if it's not already defined
if not 'xmlns' in namespaces_dict:
namespaces_dict['xmlns'] = nodes.Node.XMLNS_URI
return node.xpath(xpath, namespaces=namespaces_dict)
# Node implementation methods
def get_node_namespace_uri(self, node):
if '}' in node.tag:
return node.tag.split('}')[0][1:]
elif isinstance(node, LXMLAttribute):
return node.namespace_uri
elif isinstance(node, etree._ElementTree):
return None
elif isinstance(node, etree._Element):
qname, ns_uri = self._unpack_name(node.tag, node)[:2]
return ns_uri
else:
return None
def set_node_namespace_uri(self, node, ns_uri):
node.nsmap[None] = ns_uri
def get_node_parent(self, node):
if isinstance(node, etree._ElementTree):
return None
else:
parent = node.getparent()
# Return ElementTree as root element's parent
if parent is None:
return self.impl_document
return parent
def get_node_children(self, node):
if isinstance(node, etree._ElementTree):
children = [node.getroot()]
else:
if not hasattr(node, 'getchildren'):
return []
children = node.getchildren()
# Hack to treat text attribute as child text nodes
if node.text is not None:
children.insert(0, LXMLText(node.text, parent=node))
return children
def get_node_name(self, node):
if isinstance(node, etree._Comment):
return '#comment'
elif isinstance(node, etree._ProcessingInstruction):
return node.target
prefix = self.get_node_name_prefix(node)
local_name = self.get_node_local_name(node)
if prefix is not None:
return '%s:%s' % (prefix, local_name)
else:
return local_name
def get_node_local_name(self, node):
return re.sub('{.*}', '', node.tag)
def get_node_name_prefix(self, node):
# Believe non-Element nodes that have a prefix set (e.g. LXMLAttribute)
if node.prefix and not isinstance(node, etree._Element):
return node.prefix
# Derive prefix by unpacking node name
qname, ns_uri, prefix, local_name = self._unpack_name(node.tag, node)
if prefix:
# Don't add unnecessary excess namespace prefixes for elements
# with a local default namespace declaration
xmlns_val = self.get_node_attribute_value(node, 'xmlns')
if xmlns_val == ns_uri:
return None
# Don't add unnecessary excess namespace prefixes for default ns
if prefix == 'xmlns':
return None
else:
return prefix
else:
return None
def get_node_value(self, node):
if isinstance(node, (etree._ProcessingInstruction, etree._Comment)):
return node.text
elif hasattr(node, 'value'):
return node.value
else:
return node.text
def set_node_value(self, node, value):
if hasattr(node, 'value'):
node.value = value
else:
self.set_node_text(node, value)
def get_node_text(self, node):
return node.text
def set_node_text(self, node, text):
node.text = text
def get_node_attributes(self, element, ns_uri=None):
# TODO: Filter by ns_uri
attribs_by_qname = {}
for n, v in list(element.attrib.items()):
qname, ns_uri, prefix, local_name = self._unpack_name(n, element)
attribs_by_qname[qname] = LXMLAttribute(
qname, ns_uri, prefix, local_name, v, element)
# Include namespace declarations, which we also treat as attributes
if element.nsmap:
for n, v in list(element.nsmap.items()):
# Only add namespace as attribute if not defined in ancestors
# and not the global xmlns namespace
if (self._is_ns_in_ancestor(element, n, v)
or v == nodes.Node.XMLNS_URI):
continue
if n is None:
ns_attr_name = 'xmlns'
else:
ns_attr_name = 'xmlns:%s' % n
qname, ns_uri, prefix, local_name = self._unpack_name(
ns_attr_name, element)
attribs_by_qname[qname] = LXMLAttribute(
qname, ns_uri, prefix, local_name, v, element)
return list(attribs_by_qname.values())
def has_node_attribute(self, element, name, ns_uri=None):
return name in [a.qname for a
in self.get_node_attributes(element, ns_uri)]
def get_node_attribute_node(self, element, name, ns_uri=None):
for attr in self.get_node_attributes(element, ns_uri):
if attr.qname == name:
return attr
return None
def get_node_attribute_value(self, element, name, ns_uri=None):
if ns_uri is not None:
prefix = self.lookup_ns_prefix_for_uri(element, ns_uri)
name = '%s:%s' % (prefix, name)
for attr in self.get_node_attributes(element, ns_uri):
if attr.qname == name:
return attr.value
return None
def set_node_attribute_value(self, element, name, value, ns_uri=None):
prefix = None
if ':' in name:
prefix, name = name.split(':')
if ns_uri is None and prefix is not None:
ns_uri = self.lookup_ns_uri_by_attr_name(element, prefix)
if ns_uri is not None:
name = '{%s}%s' % (ns_uri, name)
if name.startswith('{%s}' % nodes.Node.XMLNS_URI):
if element.nsmap.get(name) != value:
# Ideally we would apply namespace (xmlns) attributes to the
# element's `nsmap` only, but the lxml/etree nsmap attribute
# is immutable and there's no non-hacky way around this.
# TODO Is there a better way?
pass
if name.split('}')[1] == 'xmlns':
# Hack to remove namespace URI from 'xmlns' attributes so
# the name is just a simple string
name = 'xmlns'
element.attrib[name] = value
else:
element.attrib[name] = value
def remove_node_attribute(self, element, name, ns_uri=None):
if ns_uri is not None:
name = '{%s}%s' % (ns_uri, name)
elif ':' in name:
prefix, name = name.split(':')
if prefix == 'xmlns':
name = '{%s}%s' % (nodes.Node.XMLNS_URI, name)
else:
name = '{%s}%s' % (element.nsmap[prefix], name)
if name in element.attrib:
del(element.attrib[name])
def add_node_child(self, parent, child, before_sibling=None):
if isinstance(child, LXMLText):
# Add text values directly to parent's 'text' attribute
if parent.text is not None:
parent.text = parent.text + child.text
else:
parent.text = child.text
return None
else:
if before_sibling is not None:
offset = 0
for c in parent.getchildren():
if c == before_sibling:
break
offset += 1
parent.insert(offset, child)
else:
parent.append(child)
return child
def import_node(self, parent, node, original_parent=None, clone=False):
original_node = node
if clone:
node = self.clone_node(node)
self.add_node_child(parent, node)
# Hack to remove text node content from original parent by manually
# deleting matching text content
if not clone and isinstance(original_node, LXMLText):
original_parent = self.get_node_parent(original_node)
if original_parent.text == original_node.text:
# Must set to None if there would be no remaining text,
# otherwise parent element won't realise it's empty
original_parent.text = None
else:
original_parent.text = \
original_parent.text.replace(original_node.text, '', 1)
def clone_node(self, node, deep=True):
if deep:
return copy.deepcopy(node)
else:
return copy.copy(node)
def remove_node_child(self, parent, child, destroy_node=True):
if isinstance(child, LXMLText):
parent.text = None
return
parent.remove(child)
if destroy_node:
child.clear()
return None
else:
return child
def lookup_ns_uri_by_attr_name(self, node, name):
ns_name = None
if name == 'xmlns':
ns_name = None
elif name.startswith('xmlns:'):
_, ns_name = name.split(':')
if ns_name in node.nsmap:
return node.nsmap[ns_name]
# If namespace is not in `nsmap` it may be in an XML DOM attribute
# TODO Generalize this block
curr_node = node
while (curr_node is not None
and curr_node.__class__ != etree._ElementTree):
uri = self.get_node_attribute_value(curr_node, name)
if uri is not None:
return uri
curr_node = self.get_node_parent(curr_node)
return None
def lookup_ns_prefix_for_uri(self, node, uri):
if uri == nodes.Node.XMLNS_URI:
return 'xmlns'
result = None
if hasattr(node, 'nsmap') and uri in list(node.nsmap.values()):
for n, v in list(node.nsmap.items()):
if v == uri:
result = n
break
# TODO This is a slow hack necessary due to lxml's immutable nsmap
if result is None or re.match('ns\d', result):
# We either have no namespace prefix in the nsmap, in which case we
# will try looking for a matching xmlns attribute, or we have
# a namespace prefix that was probably assigned automatically by
# lxml and we'd rather use a human-assigned prefix if available.
curr_node = node # self.get_node_parent(node)
while curr_node.__class__ == etree._Element:
for n, v in list(curr_node.attrib.items()):
if v == uri and ('{%s}' % nodes.Node.XMLNS_URI) in n:
result = n.split('}')[1]
return result
curr_node = self.get_node_parent(curr_node)
return result
def _unpack_name(self, name, node):
qname = prefix = local_name = ns_uri = None
if name == 'xmlns':
# Namespace URI of 'xmlns' is a constant
ns_uri = nodes.Node.XMLNS_URI
elif '}' in name:
# Namespace URI is contained in {}, find URI's defined prefix
ns_uri, local_name = name.split('}')
ns_uri = ns_uri[1:]
prefix = self.lookup_ns_prefix_for_uri(node, ns_uri)
elif ':' in name:
# Namespace prefix is before ':', find prefix's defined URI
prefix, local_name = name.split(':')
if prefix == 'xmlns':
# All 'xmlns' attributes are in XMLNS URI by definition
ns_uri = nodes.Node.XMLNS_URI
else:
ns_uri = self.lookup_ns_uri_by_attr_name(node, prefix)
# Catch case where a prefix other than 'xmlns' points at XMLNS URI
if name != 'xmlns' and ns_uri == nodes.Node.XMLNS_URI:
prefix = 'xmlns'
# Construct fully-qualified name from prefix + local names
if prefix is not None:
qname = '%s:%s' % (prefix, local_name)
else:
qname = local_name = name
return (qname, ns_uri, prefix, local_name)
def _is_ns_in_ancestor(self, node, name, value):
"""
Return True if the given namespace name/value is defined in an
ancestor of the given node, meaning that the given node need not
have its own attributes to apply that namespacing.
"""
curr_node = self.get_node_parent(node)
while curr_node.__class__ == etree._Element:
if (hasattr(curr_node, 'nsmap')
and curr_node.nsmap.get(name) == value):
return True
for n, v in list(curr_node.attrib.items()):
if v == value and '{%s}' % nodes.Node.XMLNS_URI in n:
return True
curr_node = self.get_node_parent(curr_node)
return False
class LXMLText(object):
def __init__(self, text, parent=None, is_cdata=False):
self._text = text
self._parent = parent
self._is_cdata = is_cdata
@property
def is_cdata(self):
return self._is_cdata
@property
def value(self):
return self._text
text = value # Alias
def getparent(self):
return self._parent
@property
def prefix(self):
return None
@property
def tag(self):
if self.is_cdata:
return "#cdata-section"
else:
return "#text"
class LXMLAttribute(object):
def __init__(self, qname, ns_uri, prefix, local_name, value, element):
self._qname, self._ns_uri, self._prefix, self._local_name = (
qname, ns_uri, prefix, local_name)
self._value, self._element = (value, element)
def getroottree(self):
return self._element.getroottree()
@property
def qname(self):
return self._qname
@property
def namespace_uri(self):
return self._ns_uri
@property
def prefix(self):
return self._prefix
@property
def local_name(self):
return self._local_name
@property
def value(self):
return self._value
name = tag = local_name # Alias
| mit |
GMaiolo/remove-w3schools | scripts/remover.js | 4036 | (function() {
var W3SchoolsRemover = {
currentUrl: {},
constants: {
queries: {
result_links: '.g div > a[href*="www.w3schools.com"]',
link_parent_node: '#rso div.g',
main_google_node: 'main'
},
events: {
get_info: 'get_tId_and_wId',
inactive: 'inactive',
active: 'active'
},
console: {
needs_to_be_updated: 'W3SchoolsRemover selectors need to be updated!',
removed: 'W3Schools links were removed from this search.'
},
observerConfig: { childList: true, subtree: true }
},
init: function() {
var mainGoogleNode = document.getElementById(this.constants.queries.main_google_node);
/* avoiding google new tab page and other variations */
if(!mainGoogleNode) {
return chrome.runtime.sendMessage({ event: this.constants.events.inactive, url: window.location.href });
}
chrome.runtime.sendMessage({ event: this.constants.events.get_info }, (info) => {
var tId = info.tId;
var wId = info.wId;
this.currentUrl[wId] = this.currentUrl[wId] ? this.currentUrl[wId] : {};
this.currentUrl[wId][tId] = window.location.href;
this.remove(info);
this.createResultsObserver(mainGoogleNode);
});
},
getAllW3Links: function() {
return document.querySelectorAll(this.constants.queries.result_links);
},
remove: function(info) {
var tId = info.tId;
var wId = info.wId;
// ignoring dropdown items and huge card on the right
var links = Array.from(this.getAllW3Links()).filter(function (link) {
var isAccordionItem = Boolean(link.closest('g-accordion-expander'))
var isHugeCardOnTheRight = Boolean(link.closest('#wp-tabs-container'))
return !isAccordionItem && !isHugeCardOnTheRight
});
var count = links.length;
if(!count) {
if(!this.isSameUrl(window.location.href, info)) {
chrome.runtime.sendMessage({ event: this.constants.events.inactive });
this.currentUrl[wId][tId] = window.location.href;
}
return;
}
this.currentUrl[wId][tId] = window.location.href;
chrome.runtime.sendMessage({ event: this.constants.events.active, count: count });
console.info(count + ' ' + this.constants.console.removed);
links.forEach(this.deleteOldGrandpaNode.bind(this));
},
createResultsObserver: function(mainGoogleNode) {
this.resultsObserver = new MutationObserver(() => {
chrome.runtime.sendMessage({ event: this.constants.events.get_info }, info => {
var tId = info.tId;
var wId = info.wId;
this.currentUrl[wId] = this.currentUrl[wId] ? this.currentUrl[wId] : {};
this.remove(info);
});
});
this.resultsObserver.observe(mainGoogleNode, this.constants.observerConfig);
},
isSameUrl: function(currentUrl, info) {
var tId = info.tId;
var wId = info.wId;
return this.currentUrl[wId][tId] === currentUrl;
},
deleteOldGrandpaNode: function(el) {
var parent = el.closest(this.constants.queries.link_parent_node);
if(!parent) return console.warn(this.constants.console.needs_to_be_updated);
parent.style.display = 'none';
}
};
/* may need to tune this timeout in the future
otherwise we get progressive removals instead of all them toghether */
setTimeout(() => {
W3SchoolsRemover.init();
}, 250)
})();
| mit |
Masa331/pohoda | lib/pohoda/parsers/stk/categories_type.rb | 402 | module Pohoda
module Parsers
module Stk
class CategoriesType
include ParserCore::BaseParser
def id_category
array_of_at(String, ['stk:idCategory'])
end
def to_h
hash = {}
hash[:attributes] = attributes
hash[:id_category] = id_category if has? 'stk:idCategory'
hash
end
end
end
end
end | mit |
tangrams/mapillary-explorer | node_modules/mapillary-js/src/utils/Settings.ts | 470 | import {IViewerOptions} from "../Viewer";
export class Settings {
private static _baseImageSize: number;
public static setOptions(options: IViewerOptions): void {
if (options.baseImageSize) {
Settings._baseImageSize = options.baseImageSize;
} else {
Settings._baseImageSize = 640;
}
}
public static get baseImageSize(): number {
return Settings._baseImageSize;
}
}
export default Settings;
| mit |
takaruz/Schema2XML | lib/driver/postgres.php | 5544 | <?php
/**
* File: postgres.php
*
* PHP version 5
*
* @category Backend
* @package Driver
* @author Pongpat Poapetch <p.poapetch@gmail.com>
* @license The MIT License (MIT) Copyright (c) 2014 takaruz
* @version GIT: master In development. Very unstable.
* @link https://github.com/takaruz/Schema2XML
*/
/**
* Class Driver POSTGRES
*
* @category Backend
* @package Driver
* @author Pongpat Poapetch <p.poapetch@gmail.com>
* @license The MIT License (MIT) Copyright (c) 2014 takaruz
* @version GIT: master In development. Very unstable.
* @link https://github.com/takaruz/Schema2XML
*/
class Driver
{
/**
* @var constant COLUMN_TYPE contain type string.
*/
const COLUMN_TYPE = "udt_name";
/**
* Get result from query statement from passing argument.
*
* @param connection $conn connection resource
* @param string $query query statement.
*
* @return result
*/
public static function get($conn, $query)
{
$result = pg_query($conn, $query) or die('Query failed: ' . pg_last_error());
return $result;
}
/**
* Get schemas list that owner by $user except .
*
* @param connection $conn connection resource.
*
* @return result
*/
public static function getSchemas($conn)
{
$query = "SELECT schema_name from information_schema.schemata ";
$query .= "WHERE schema_name <> 'test' and schema_name <> 'information_schema'";
$result = pg_query($conn, $query) or die('Query failed: ' . pg_last_error());
return $result;
}
/**
* Get tables list from schema from passing argument.
*
* @param connection $conn connection resource.
* @param string $schema schema name, DEFAULT is 'null'
*
* @return result
*/
public static function getTables($conn, $schema)
{
$query = "SELECT table_name FROM information_schema.tables ";
$query .= "WHERE table_schema='$schema' AND table_type='BASE TABLE'";
$result = pg_query($conn, $query) or die('Query failed: ' . pg_last_error());
return $result;
}
/**
* Get views list from schema from passing argument.
*
* @param connection $conn connection resource.
* @param string $schema schema name, DEFAULT is 'null'
*
* @return result
*/
public static function getViews($conn, $schema)
{
$query = "SELECT table_name FROM information_schema.tables ";
$query .= "WHERE table_schema='$schema' AND table_type='VIEW'";
$result = pg_query($conn, $query) or die('Query failed: ' . pg_last_error());
return $result;
}
/**
* Get columns list from table and schema by passing arguments.
*
* @param connection $conn connection resource.
* @param string $table table name
* @param string $schema schema name, DEFAULT is 'null'
*
* @return result
*/
public static function getColumns($conn, $table, $schema)
{
$query = "SELECT * FROM information_schema.columns ";
$query .= "WHERE table_schema='$schema' AND table_name='$table'";
$result = pg_query($conn, $query) or die('Query failed: ' . pg_last_error());
return $result;
}
/**
* Get number of schemas from query statement.
*
* @param connection $conn connection resource.
*
* @return integer
*/
public static function getNumSchemas($conn)
{
$result = Driver::getSchemas($conn);
return pg_num_rows($result);
}
/**
* Get number of tables from query statement.
*
* @param connection $conn connection resource.
* @param string $schema schema name, DEFAULT is 'null'
*
* @return integer
*/
public static function getNumTables($conn, $schema)
{
$result = Driver::getTables($conn, $schema);
return pg_num_rows($result);
}
/**
* Get number of tables from query statement.
*
* @param connection $conn connection resource.
* @param string $schema schema name, DEFAULT is 'null'
*
* @return integer
*/
public static function getNumViews($conn, $schema)
{
$result = Driver::getViews($conn, $schema);
return pg_num_rows($result);
}
/**
* Get number of columns from query statement.
*
* @param connection $conn connection resource.
* @param string $table table name
* @param string $schema schema name, DEFAULT is 'null'
*
* @return integer
*/
public static function getNumColumns($conn, $table, $schema)
{
$result = Driver::getColumns($conn, $table, $schema);
return pg_num_rows($result);
}
/**
* print all result resouce from query statement.
*
* @param result $result result resource from query statement
*
* @return void
*/
public static function printDebug($result)
{
echo '<pre>';
print_r(pg_fetch_all($result));
echo '</pre>';
}
/**
* Get result from query statement to array.
*
* @param result $result result resource from query statement
*
* @return array
*/
public static function getResultArray($result)
{
return pg_fetch_all($result);
}
}
?> | mit |
afroraydude/First_Unity_Game | Real_Game/Assets/Scripts/WebFileLoader.cs | 351 | using UnityEngine;
using System.Collections;
using System.Xml;
using System.IO;
public class WebFileLoader : MonoBehaviour {
public WWW www;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
public IEnumerator GetURL (string url) {
www = new WWW (url);
yield return www;
}
}
| mit |
CSALucasNascimento/Personal-APP | modules/listings/client/admin/controllers/dashboard-listings.client.admin.controller.js | 819 | (function () {
'use strict';
angular
.module('listings.admin.controllers')
.config(['$mdIconProvider', function ($mdIconProvider) {
$mdIconProvider.icon('md-close', 'modules/core/client/common/assets/angular-material-assets/img/icons/ic_close_24px.svg', 24);
}])
.controller('ListingsDashboardAdminController', ListingsDashboardAdminController);
ListingsDashboardAdminController.$inject = ['$state', 'listingResolve', 'Authentication'];
function ListingsDashboardAdminController($state, listing, Authentication) {
var vm = this;
// Methods
vm.listing = listing;
vm.authentication = Authentication;
vm.gotoListings = gotoListings;
/**
* Go to products page
*/
function gotoListings() {
$state.go('admin.listings.list');
}
}
}());
| mit |
Nylle/JavaFixture | src/main/java/com/github/nylle/javafixture/annotations/testcases/ReflectedTestCase.java | 1835 | package com.github.nylle.javafixture.annotations.testcases;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static java.util.Arrays.stream;
public class ReflectedTestCase {
private static final Map<Class<?>, Class<?>> primitiveWrapperMap = Map.of(
Boolean.class, Boolean.TYPE,
Character.class, Character.TYPE,
Byte.class, Byte.TYPE,
Short.class, Short.TYPE,
Integer.class, Integer.TYPE,
Long.class, Long.TYPE,
Float.class, Float.TYPE,
Double.class, Double.TYPE
);
private Map<Class<?>, List<?>> matrix = new HashMap<>();
public ReflectedTestCase(TestCase testCase) {
stream(TestCase.class.getDeclaredMethods())
.sorted(Comparator.comparing(Method::getName))
.forEachOrdered(m -> matrix.compute(m.getReturnType(), (k, v) -> addTo(v, invoke(m, testCase))));
}
@SuppressWarnings("unchecked")
public <T> T getTestCaseValueFor(Class<T> type, int i) {
return (T) matrix.get(primitiveWrapperMap.getOrDefault(type, type)).get(i);
}
@SuppressWarnings("unchecked")
private <T> T invoke(Method method, TestCase testCase) {
try {
return (T) method.invoke(testCase);
} catch (IllegalAccessException | InvocationTargetException e) {
throw new TestCaseException(String.format("Unable to read test-case value for '%s'", method.getName()), e);
}
}
private <T> List<T> addTo(List<T> list, T value) {
if (list == null) {
list = new ArrayList<>();
}
list.add(value);
return list;
}
}
| mit |
AlienArc/VegasBluff | src/Bluff/_kindOfMagic.cs | 128 | using System;
namespace Bluff
{
public class MagicAttribute:Attribute{}
public class NoMagicAttribute:Attribute{ }
} | mit |
ztane/jaspyx | jaspyx/visitor/variable.py | 1563 | from __future__ import absolute_import, division, print_function
import _ast
from jaspyx.builtins import BUILTINS
from jaspyx.visitor import BaseVisitor
class Variable(BaseVisitor):
def visit_Name(self, node):
scope = self.stack[-1].scope
global_scope = scope.get_global_scope()
if isinstance(node.ctx, _ast.Store):
if scope.is_global(node.id):
global_scope.declare(node.id)
self.output(global_scope.prefixed(node.id))
else:
scope.declare(node.id)
self.output(scope.prefixed(node.id))
elif isinstance(node.ctx, _ast.Load):
if scope.is_global(node.id):
self.output(scope.get_global_scope().prefixed(node.id))
else:
var_scope = scope.get_scope(node.id)
if var_scope is not None:
self.output(var_scope.prefixed(node.id))
else:
self.output(BUILTINS.get(node.id, global_scope.prefixed(node.id)))
elif isinstance(node.ctx, _ast.Del):
if scope.is_global(node.id):
self.output(scope.get_global_scope().prefixed(node.id))
else:
if not node.id in scope.declarations:
raise UnboundLocalError("local variable '%s' referenced before assignment" % node.id)
self.output(scope.prefixed(node.id))
else:
raise NotImplementedError('name lookup not implemented for context %s' % node.ctx.__class__.__name__)
| mit |
moccalotto/hayttp | src/Exceptions/Response/ContentTypeException.php | 383 | <?php
/**
* This file is part of the Hayttp package.
*
* @author Kim Ravn Hansen <moccalotto@gmail.com>
* @copyright 2018
* @license MIT
*/
namespace Hayttp\Exceptions\Response;
use Hayttp\Exceptions\ResponseException;
/**
* Http connection exception.
*
* Thrown when the response has an invalid content type
*/
class ContentTypeException extends ResponseException
{
}
| mit |
ma2gedev/chrono_logger | lib/chrono_logger.rb | 4000 | require "chrono_logger/version"
require 'logger'
require 'pathname'
# A lock-free logger with timebased file rotation.
class ChronoLogger < Logger
# @param logdev [String, IO] `Time#strftime` formatted filename (String) or IO object (typically STDOUT, STDERR, or an open file).
# @example
#
# ChronoLogger.new('/log/production.log.%Y%m%d')
# Time.now.strftime('%F') => "2015-01-29"
# File.exist?('/log/production.log.20150129') => true
#
def initialize(logdev)
@progname = nil
@level = DEBUG
@default_formatter = ::Logger::Formatter.new
@formatter = nil
@logdev = nil
if logdev
@logdev = TimeBasedLogDevice.new(logdev)
end
end
module Period
DAILY = 1
SiD = 24 * 60 * 60
def determine_period(format)
case format
when /%[SscXrT]/ then nil # seconds
when /%[MR]/ then nil # minutes
when /%[HklI]/ then nil # hours
when /%[dejDFvx]/ then DAILY
else nil
end
end
def next_start_period(now, period)
case period
when DAILY
Time.mktime(now.year, now.month, now.mday) + SiD
else
nil
end
end
end
class TimeBasedLogDevice < LogDevice
include Period
DELAY_SECOND_TO_CLOSE_FILE = 5
def initialize(log = nil, opt = {})
@dev = @filename = @pattern = nil
if defined?(LogDeviceMutex) # Ruby < 2.3
@mutex = LogDeviceMutex.new
else
mon_initialize
@mutex = self
end
if log.respond_to?(:write) and log.respond_to?(:close)
@dev = log
else
@pattern = log
@period = determine_period(@pattern)
now = Time.now
@filename = now.strftime(@pattern)
@next_start_period = next_start_period(now, @period)
@dev = open_logfile(@filename)
@dev.sync = true
end
end
def write(message)
check_and_shift_log if @pattern
@dev.write(message)
rescue
warn("log writing failed. #{$!}")
end
def close
@dev.close rescue nil
end
private
def open_logfile(filename)
begin
open(filename, (File::WRONLY | File::APPEND))
rescue Errno::ENOENT
create_logfile(filename)
end
end
def create_logfile(filename)
begin
Pathname(filename).dirname.mkpath
logdev = open(filename, (File::WRONLY | File::APPEND | File::CREAT | File::EXCL))
logdev.sync = true
rescue Errno::EEXIST
# file is created by another process
logdev = open_logfile(filename)
logdev.sync = true
end
logdev
end
def check_and_shift_log
if next_period?(Time.now)
now = Time.now
new_filename = now.strftime(@pattern)
next_start_period = next_start_period(now, @period)
shift_log(new_filename)
@filename = new_filename
@next_start_period = next_start_period
end
end
def next_period?(now)
if @period
@next_start_period <= now
else
Time.now.strftime(@pattern) != @filename
end
end
def shift_log(filename)
begin
@mutex.synchronize do
tmp_dev = @dev
@dev = create_logfile(filename)
Thread.new(tmp_dev) do |tmp_dev|
sleep DELAY_SECOND_TO_CLOSE_FILE
tmp_dev.close rescue nil
end
end
rescue Exception => ignored
warn("log shifting failed. #{ignored}")
end
end
end
# EXPERIMENTAL: this formatter faster than default `Logger::Formatter`
class Formatter < ::Logger::Formatter
DATETIME_SPRINTF_FORMAT = "%04d-%02d-%02dT%02d:%02d:%02d.%06d ".freeze
# same as `Logger::Formatter#format_datetime`'s default behaviour
def format_datetime(t)
DATETIME_SPRINTF_FORMAT % [t.year, t.month, t.day, t.hour, t.min, t.sec, t.tv_usec]
end
def datetime_format=(datetime_format)
raise 'do not support'
end
end
end
| mit |
drebrez/DiscUtils | Library/DiscUtils.Nfs/Nfs3SetTimeMethod.cs | 142 | namespace DiscUtils.Nfs
{
public enum Nfs3SetTimeMethod
{
NoChange = 0,
ServerTime = 1,
ClientTime = 2
}
} | mit |
imdeakin/yunxi-admin | src/app/admin/msg/index.ts | 109 | /**
* Created by Deakin on 2017/5/22 0022.
*/
export * from './msg-list';
export * from './feedback-list';
| mit |
TinkuNaresh/symfony2 | app/cache/dev/twig/99/f7/f3ebf62bfc974696afd9420644563b9a9492c9a543b3e03f906c5479ddd6.php | 2966 | <?php
/* SensioDistributionBundle::Configurator/steps.html.twig */
class __TwigTemplate_99f7f3ebf62bfc974696afd9420644563b9a9492c9a543b3e03f906c5479ddd6 extends Twig_Template
{
public function __construct(Twig_Environment $env)
{
parent::__construct($env);
$this->parent = false;
$this->blocks = array(
);
}
protected function doDisplay(array $context, array $blocks = array())
{
// line 1
echo "<div class=\"symfony-block-steps\">
";
// line 2
$context['_parent'] = (array) $context;
$context['_seq'] = twig_ensure_traversable(range(1, (isset($context["count"]) ? $context["count"] : $this->getContext($context, "count"))));
foreach ($context['_seq'] as $context["_key"] => $context["i"]) {
// line 3
echo "
";
// line 4
if (((isset($context["i"]) ? $context["i"] : $this->getContext($context, "i")) == ((isset($context["index"]) ? $context["index"] : $this->getContext($context, "index")) + 1))) {
// line 5
echo " <span class=\"selected\">Step ";
echo twig_escape_filter($this->env, (isset($context["i"]) ? $context["i"] : $this->getContext($context, "i")), "html", null, true);
echo "</span>
";
} else {
// line 7
echo " <span>Step ";
echo twig_escape_filter($this->env, (isset($context["i"]) ? $context["i"] : $this->getContext($context, "i")), "html", null, true);
echo "</span>
";
}
// line 9
echo "
";
// line 10
if (((isset($context["i"]) ? $context["i"] : $this->getContext($context, "i")) != (isset($context["count"]) ? $context["count"] : $this->getContext($context, "count")))) {
// line 11
echo " >
";
}
// line 13
echo " ";
}
$_parent = $context['_parent'];
unset($context['_seq'], $context['_iterated'], $context['_key'], $context['i'], $context['_parent'], $context['loop']);
$context = array_intersect_key($context, $_parent) + $_parent;
// line 14
echo "</div>
";
}
public function getTemplateName()
{
return "SensioDistributionBundle::Configurator/steps.html.twig";
}
public function isTraitable()
{
return false;
}
public function getDebugInfo()
{
return array ( 52 => 13, 48 => 11, 43 => 9, 37 => 7, 26 => 3, 19 => 1, 98 => 40, 93 => 9, 80 => 41, 46 => 10, 44 => 9, 40 => 8, 36 => 7, 32 => 6, 27 => 4, 22 => 2, 58 => 14, 55 => 12, 53 => 11, 50 => 10, 34 => 4, 31 => 5, 88 => 6, 82 => 25, 78 => 40, 72 => 21, 68 => 20, 64 => 11, 59 => 17, 54 => 15, 47 => 9, 45 => 9, 41 => 7, 38 => 6, 35 => 5, 29 => 4,);
}
}
| mit |
MaxMorgenstern/DynDNS-Updater | dyndns updater/Properties/Resources.Designer.cs | 6137 | //------------------------------------------------------------------------------
// <auto-generated>
// Dieser Code wurde von einem Tool generiert.
// Laufzeitversion:4.0.30319.42000
//
// Änderungen an dieser Datei können falsches Verhalten verursachen und gehen verloren, wenn
// der Code erneut generiert wird.
// </auto-generated>
//------------------------------------------------------------------------------
namespace DynDNS_Updater.Properties {
using System;
/// <summary>
/// Eine stark typisierte Ressourcenklasse zum Suchen von lokalisierten Zeichenfolgen usw.
/// </summary>
// Diese Klasse wurde von der StronglyTypedResourceBuilder automatisch generiert
// -Klasse über ein Tool wie ResGen oder Visual Studio automatisch generiert.
// Um einen Member hinzuzufügen oder zu entfernen, bearbeiten Sie die .ResX-Datei und führen dann ResGen
// mit der /str-Option erneut aus, oder Sie erstellen Ihr VS-Projekt neu.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "16.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
public 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>
/// Gibt die zwischengespeicherte ResourceManager-Instanz zurück, die von dieser Klasse verwendet wird.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
public static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("DynDNS_Updater.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Überschreibt die CurrentUICulture-Eigenschaft des aktuellen Threads für alle
/// Ressourcenzuordnungen, die diese stark typisierte Ressourcenklasse verwenden.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
public static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
/// <summary>
/// Sucht eine lokalisierte Ressource vom Typ System.Drawing.Icon ähnlich wie (Symbol).
/// </summary>
public static System.Drawing.Icon IPAddress {
get {
object obj = ResourceManager.GetObject("IPAddress", resourceCulture);
return ((System.Drawing.Icon)(obj));
}
}
/// <summary>
/// Sucht eine lokalisierte Ressource vom Typ System.Drawing.Icon ähnlich wie (Symbol).
/// </summary>
public static System.Drawing.Icon WarningShield_G {
get {
object obj = ResourceManager.GetObject("WarningShield_G", resourceCulture);
return ((System.Drawing.Icon)(obj));
}
}
/// <summary>
/// Sucht eine lokalisierte Ressource vom Typ System.Drawing.Bitmap.
/// </summary>
public static System.Drawing.Bitmap WarningShield_G1 {
get {
object obj = ResourceManager.GetObject("WarningShield_G1", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Sucht eine lokalisierte Ressource vom Typ System.Drawing.Icon ähnlich wie (Symbol).
/// </summary>
public static System.Drawing.Icon WarningShield_R {
get {
object obj = ResourceManager.GetObject("WarningShield_R", resourceCulture);
return ((System.Drawing.Icon)(obj));
}
}
/// <summary>
/// Sucht eine lokalisierte Ressource vom Typ System.Drawing.Bitmap.
/// </summary>
public static System.Drawing.Bitmap WarningShield_R1 {
get {
object obj = ResourceManager.GetObject("WarningShield_R1", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Sucht eine lokalisierte Ressource vom Typ System.Drawing.Icon ähnlich wie (Symbol).
/// </summary>
public static System.Drawing.Icon WarningShield_Y {
get {
object obj = ResourceManager.GetObject("WarningShield_Y", resourceCulture);
return ((System.Drawing.Icon)(obj));
}
}
/// <summary>
/// Sucht eine lokalisierte Ressource vom Typ System.Drawing.Bitmap.
/// </summary>
public static System.Drawing.Bitmap WarningShield_Y1 {
get {
object obj = ResourceManager.GetObject("WarningShield_Y1", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Sucht eine lokalisierte Ressource vom Typ System.Drawing.Icon ähnlich wie (Symbol).
/// </summary>
public static System.Drawing.Icon World {
get {
object obj = ResourceManager.GetObject("World", resourceCulture);
return ((System.Drawing.Icon)(obj));
}
}
}
}
| mit |
HasanSa/hackathon | node_modules/radium-grid/lib/index.js | 478 | "use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.Cell = exports.Grid = undefined;
var _grid = require("./components/grid");
var _grid2 = _interopRequireDefault(_grid);
var _cell = require("./components/cell");
var _cell2 = _interopRequireDefault(_cell);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var Grid = exports.Grid = _grid2.default;
var Cell = exports.Cell = _cell2.default; | mit |
Nvt2106/angular2-code-template | app/login/googlelogin.component.ts | 2721 | import { Component, ApplicationRef } from '@angular/core';
import { Router } from '@angular/router';
import { AuthenticationService } from '../_services/authentication.service';
import { AppContainerComponent } from '../app-container.component';
// Google's login API namespace
declare const gapi:any;
@Component({
moduleId: module.id,
selector: 'google-login',
templateUrl: 'googlelogin.component.html'
})
export class GoogleLoginComponent {
constructor(private router: Router,
private authenticationService: AuthenticationService,
private appContainer: AppContainerComponent,
private appRef: ApplicationRef) { }
// Angular hook that allows for interaction with elements inserted by the rendering of a view
ngAfterViewInit() {
var that = this;
// Signout if already signed in
gapi.load('auth2', function() {
// Retrieve the singleton for the GoogleAuth library and set up the client.
var auth2 = gapi.auth2.init({
client_id: '60286824468-tiuo7kh57c7e2ja6hvsobirjpst714n1.apps.googleusercontent.com',
cookiepolicy: 'single_host_origin',
// Request scopes in addition to 'profile' and 'email'
//scope: 'additional_scope'
})
.then(() => that.logout());
});
}
logout(): void {
var auth2 = gapi.auth2.getAuthInstance().signOut().then(() => {
this.renderLogin();
});
}
renderLogin(): void {
// console.log('gapi.signin2.render');
gapi.signin2.render(
'gdbtn',
{
'scope': 'profile',
'longtitle': true,
'width': 240,
'theme': 'light',
'onsuccess': (resp) => this.onGoogleLoginSuccess(resp),
'onfailure': () => this.onGoogleLoginFailed()
});
}
// Triggered after a user successfully logs in using the Google external login provider.
onGoogleLoginSuccess(resp) {
// console.log('onGoogleLoginSuccess');
var source = 'google';
var token = resp.Zi.access_token;
this.authenticationService.login(source, token)
.subscribe(result => {
if (result === true) {
// login successful
this.appContainer.reload();
this.router.navigate(['/']);
this.appRef.tick();
} else {
// login failed
// TODO
}
});
}
onGoogleLoginFailed() {
console.log('onGoogleLoginFailed');
}
} | mit |
creyke/Orleans.Sagas | Orleans.Sagas.Samples.Activities/ChewBubblegumActivity.cs | 470 | using System.Threading.Tasks;
namespace Orleans.Sagas.Samples.Activities
{
public class ChewBubblegumActivity : IActivity
{
public Task Execute(IActivityContext context)
{
// comment in to test compensation.
//throw new AllOuttaGumException();
return Task.CompletedTask;
}
public Task Compensate(IActivityContext context)
{
return Task.CompletedTask;
}
}
}
| mit |
fulmicoton/tantivy | src/query/phrase_query/phrase_scorer.rs | 8898 | use docset::{DocSet, SkipResult};
use fieldnorm::FieldNormReader;
use postings::Postings;
use query::bm25::BM25Weight;
use query::{Intersection, Scorer};
use DocId;
struct PostingsWithOffset<TPostings> {
offset: u32,
postings: TPostings,
}
impl<TPostings: Postings> PostingsWithOffset<TPostings> {
pub fn new(segment_postings: TPostings, offset: u32) -> PostingsWithOffset<TPostings> {
PostingsWithOffset {
offset,
postings: segment_postings,
}
}
pub fn positions(&mut self, output: &mut Vec<u32>) {
self.postings.positions_with_offset(self.offset, output)
}
}
impl<TPostings: Postings> DocSet for PostingsWithOffset<TPostings> {
fn advance(&mut self) -> bool {
self.postings.advance()
}
fn skip_next(&mut self, target: DocId) -> SkipResult {
self.postings.skip_next(target)
}
fn doc(&self) -> DocId {
self.postings.doc()
}
fn size_hint(&self) -> u32 {
self.postings.size_hint()
}
}
pub struct PhraseScorer<TPostings: Postings> {
intersection_docset: Intersection<PostingsWithOffset<TPostings>, PostingsWithOffset<TPostings>>,
num_terms: usize,
left: Vec<u32>,
right: Vec<u32>,
phrase_count: u32,
fieldnorm_reader: FieldNormReader,
similarity_weight: BM25Weight,
score_needed: bool,
}
/// Returns true iff the two sorted array contain a common element
fn intersection_exists(left: &[u32], right: &[u32]) -> bool {
let mut left_i = 0;
let mut right_i = 0;
while left_i < left.len() && right_i < right.len() {
let left_val = left[left_i];
let right_val = right[right_i];
if left_val < right_val {
left_i += 1;
} else if right_val < left_val {
right_i += 1;
} else {
return true;
}
}
false
}
fn intersection_count(left: &[u32], right: &[u32]) -> usize {
let mut left_i = 0;
let mut right_i = 0;
let mut count = 0;
while left_i < left.len() && right_i < right.len() {
let left_val = left[left_i];
let right_val = right[right_i];
if left_val < right_val {
left_i += 1;
} else if right_val < left_val {
right_i += 1;
} else {
count += 1;
left_i += 1;
right_i += 1;
}
}
count
}
/// Intersect twos sorted arrays `left` and `right` and outputs the
/// resulting array in left.
///
/// Returns the length of the intersection
fn intersection(left: &mut [u32], right: &[u32]) -> usize {
let mut left_i = 0;
let mut right_i = 0;
let mut count = 0;
let left_len = left.len();
let right_len = right.len();
while left_i < left_len && right_i < right_len {
let left_val = left[left_i];
let right_val = right[right_i];
if left_val < right_val {
left_i += 1;
} else if right_val < left_val {
right_i += 1;
} else {
left[count] = left_val;
count += 1;
left_i += 1;
right_i += 1;
}
}
count
}
impl<TPostings: Postings> PhraseScorer<TPostings> {
pub fn new(
term_postings: Vec<(usize, TPostings)>,
similarity_weight: BM25Weight,
fieldnorm_reader: FieldNormReader,
score_needed: bool,
) -> PhraseScorer<TPostings> {
let max_offset = term_postings
.iter()
.map(|&(offset, _)| offset)
.max()
.unwrap_or(0);
let num_docsets = term_postings.len();
let postings_with_offsets = term_postings
.into_iter()
.map(|(offset, postings)| {
PostingsWithOffset::new(postings, (max_offset - offset) as u32)
})
.collect::<Vec<_>>();
PhraseScorer {
intersection_docset: Intersection::new(postings_with_offsets),
num_terms: num_docsets,
left: Vec::with_capacity(100),
right: Vec::with_capacity(100),
phrase_count: 0u32,
similarity_weight,
fieldnorm_reader,
score_needed,
}
}
fn phrase_match(&mut self) -> bool {
if self.score_needed {
let count = self.phrase_count();
self.phrase_count = count;
count > 0u32
} else {
self.phrase_exists()
}
}
fn phrase_exists(&mut self) -> bool {
{
self.intersection_docset
.docset_mut_specialized(0)
.positions(&mut self.left);
}
let mut intersection_len = self.left.len();
for i in 1..self.num_terms - 1 {
{
self.intersection_docset
.docset_mut_specialized(i)
.positions(&mut self.right);
}
intersection_len = intersection(&mut self.left[..intersection_len], &self.right[..]);
if intersection_len == 0 {
return false;
}
}
self.intersection_docset
.docset_mut_specialized(self.num_terms - 1)
.positions(&mut self.right);
intersection_exists(&self.left[..intersection_len], &self.right[..])
}
fn phrase_count(&mut self) -> u32 {
{
self.intersection_docset
.docset_mut_specialized(0)
.positions(&mut self.left);
}
let mut intersection_len = self.left.len();
for i in 1..self.num_terms - 1 {
{
self.intersection_docset
.docset_mut_specialized(i)
.positions(&mut self.right);
}
intersection_len = intersection(&mut self.left[..intersection_len], &self.right[..]);
if intersection_len == 0 {
return 0u32;
}
}
self.intersection_docset
.docset_mut_specialized(self.num_terms - 1)
.positions(&mut self.right);
intersection_count(&self.left[..intersection_len], &self.right[..]) as u32
}
}
impl<TPostings: Postings> DocSet for PhraseScorer<TPostings> {
fn advance(&mut self) -> bool {
while self.intersection_docset.advance() {
if self.phrase_match() {
return true;
}
}
false
}
fn skip_next(&mut self, target: DocId) -> SkipResult {
if self.intersection_docset.skip_next(target) == SkipResult::End {
return SkipResult::End;
}
if self.phrase_match() {
if self.doc() == target {
return SkipResult::Reached;
} else {
return SkipResult::OverStep;
}
}
if self.advance() {
SkipResult::OverStep
} else {
SkipResult::End
}
}
fn doc(&self) -> DocId {
self.intersection_docset.doc()
}
fn size_hint(&self) -> u32 {
self.intersection_docset.size_hint()
}
}
impl<TPostings: Postings> Scorer for PhraseScorer<TPostings> {
fn score(&mut self) -> f32 {
let doc = self.doc();
let fieldnorm_id = self.fieldnorm_reader.fieldnorm_id(doc);
self.similarity_weight
.score(fieldnorm_id, self.phrase_count)
}
}
#[cfg(test)]
mod tests {
use super::{intersection, intersection_count};
fn test_intersection_sym(left: &[u32], right: &[u32], expected: &[u32]) {
test_intersection_aux(left, right, expected);
test_intersection_aux(right, left, expected);
}
fn test_intersection_aux(left: &[u32], right: &[u32], expected: &[u32]) {
let mut left_vec = Vec::from(left);
let left_mut = &mut left_vec[..];
assert_eq!(intersection_count(left_mut, right), expected.len());
let count = intersection(left_mut, right);
assert_eq!(&left_mut[..count], expected);
}
#[test]
fn test_intersection() {
test_intersection_sym(&[1], &[1], &[1]);
test_intersection_sym(&[1], &[2], &[]);
test_intersection_sym(&[], &[2], &[]);
test_intersection_sym(&[5, 7], &[1, 5, 10, 12], &[5]);
test_intersection_sym(&[1, 5, 6, 9, 10, 12], &[6, 8, 9, 12], &[6, 9, 12]);
}
}
#[cfg(all(test, feature = "unstable"))]
mod bench {
use super::{intersection, intersection_count};
use test::Bencher;
#[bench]
fn bench_intersection_short(b: &mut Bencher) {
b.iter(|| {
let mut left = [1, 5, 10, 12];
let right = [5, 7];
intersection(&mut left, &right);
});
}
#[bench]
fn bench_intersection_count_short(b: &mut Bencher) {
b.iter(|| {
let left = [1, 5, 10, 12];
let right = [5, 7];
intersection_count(&left, &right);
});
}
}
| mit |
steindornatorinn/nyaa | util/log/logger.go | 3237 | package log
import (
"net/http"
"os"
"github.com/NyaaPantsu/nyaa/config"
"github.com/Sirupsen/logrus"
lumberjack "gopkg.in/natefinch/lumberjack.v2"
)
// LumberJackLogger : Initialize logger
func LumberJackLogger(filePath string, maxSize int, maxBackups int, maxAge int) *lumberjack.Logger {
return &lumberjack.Logger{
Filename: filePath,
MaxSize: maxSize, // megabytes
MaxBackups: maxBackups,
MaxAge: maxAge, //days
}
}
// InitLogToStdoutDebug : set logrus to debug param
func InitLogToStdoutDebug() {
logrus.SetFormatter(&logrus.TextFormatter{ForceColors: true})
logrus.SetOutput(os.Stdout)
logrus.SetLevel(logrus.DebugLevel)
}
// InitLogToStdout : set logrus to stdout
func InitLogToStdout() {
logrus.SetFormatter(&logrus.TextFormatter{})
logrus.SetOutput(os.Stdout)
logrus.SetLevel(logrus.WarnLevel)
}
// InitLogToFile : set logrus to output in file
func InitLogToFile() {
logrus.SetFormatter(&logrus.JSONFormatter{})
out := LumberJackLogger(config.ErrorLogFilePath+config.ErrorLogFileExtension, config.ErrorLogMaxSize, config.ErrorLogMaxBackups, config.ErrorLogMaxAge)
logrus.SetOutput(out)
logrus.SetLevel(logrus.WarnLevel)
}
// Init logrus
func Init(environment string) {
switch environment {
case "DEVELOPMENT":
InitLogToStdoutDebug()
case "TEST":
InitLogToFile()
case "PRODUCTION":
InitLogToFile()
}
logrus.Debugf("Environment : %s", environment)
}
// Debug logs a message with debug log level.
func Debug(msg string) {
logrus.Debug(msg)
}
// Debugf logs a formatted message with debug log level.
func Debugf(msg string, args ...interface{}) {
logrus.Debugf(msg, args...)
}
// Info logs a message with info log level.
func Info(msg string) {
logrus.Info(msg)
}
// Infof logs a formatted message with info log level.
func Infof(msg string, args ...interface{}) {
logrus.Infof(msg, args...)
}
// Warn logs a message with warn log level.
func Warn(msg string) {
logrus.Warn(msg)
}
// Warnf logs a formatted message with warn log level.
func Warnf(msg string, args ...interface{}) {
logrus.Warnf(msg, args...)
}
// Error logs a message with error log level.
func Error(msg string) {
logrus.Error(msg)
}
// Errorf logs a formatted message with error log level.
func Errorf(msg string, args ...interface{}) {
logrus.Errorf(msg, args...)
}
// Fatal logs a message with fatal log level.
func Fatal(msg string) {
logrus.Fatal(msg)
}
// Fatalf logs a formatted message with fatal log level.
func Fatalf(msg string, args ...interface{}) {
logrus.Fatalf(msg, args...)
}
// Panic logs a message with panic log level.
func Panic(msg string) {
logrus.Panic(msg)
}
// Panicf logs a formatted message with panic log level.
func Panicf(msg string, args ...interface{}) {
logrus.Panicf(msg, args...)
}
// DebugResponse : log response body data for debugging
func DebugResponse(response *http.Response) string {
bodyBuffer := make([]byte, 5000)
var str string
count, err := response.Body.Read(bodyBuffer)
if err != nil {
Debug(err.Error())
return ""
}
for ; count > 0; count, err = response.Body.Read(bodyBuffer) {
if err != nil {
Debug(err.Error())
continue
}
str += string(bodyBuffer[:count])
}
Debugf("response data : %v", str)
return str
}
| mit |
dvsa/mot | mot-web-frontend/module/Vehicle/src/Vehicle/CreateVehicle/Factory/Action/MakeActionFactory.php | 929 | <?php
namespace Vehicle\CreateVehicle\Factory\Action;
use DvsaCommon\Auth\MotAuthorisationServiceInterface;
use Vehicle\CreateVehicle\Action\MakeAction;
use Vehicle\CreateVehicle\Service\CreateVehicleStepService;
use Zend\ServiceManager\Factory\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;
use Interop\Container\ContainerInterface;
class MakeActionFactory implements FactoryInterface
{
public function createService(ServiceLocatorInterface $serviceLocator)
{
return $this($serviceLocator, MakeAction::class);
}
public function __invoke(ContainerInterface $container, $requestedName, array $options = null)
{
$authorisationService = $container->get(MotAuthorisationServiceInterface::class);
$createVehicleStepService = $container->get(CreateVehicleStepService::class);
return new MakeAction($authorisationService, $createVehicleStepService);
}
}
| mit |
icefox0801/jaguarjs-jsdoc | Gruntfile.js | 3527 | /**
* http://gruntjs.com/configuring-tasks
*/
module.exports = function (grunt) {
var path = require('path');
var DEMO_PATH = 'demo/dist';
var DEMO_SAMPLE_PATH = 'demo/sample';
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
connect: {
options: {
hostname: '*'
},
demo: {
options: {
port: 8000,
base: DEMO_PATH,
middleware: function (connect, options) {
return [
require('connect-livereload')(),
connect.static(path.resolve(options.base))
];
}
}
}
},
watch: {
options: {
livereload: true
},
less: {
files: ['less/**/*.less'],
tasks: ['less']
},
lesscopy: {
files: ['static/styles/jaguar.css'],
tasks: ['copy:css']
},
jscopy: {
files: ['static/scripts/main.js'],
tasks: ['copy:js']
},
jsdoc: {
files: ['**/*.tmpl', '*.js'],
tasks: ['jsdoc']
},
demo: {
files: ['demo/sample/**/*.js'],
tasks: ['demo']
}
},
clean: {
demo: {
src: DEMO_PATH
}
},
jsdoc: {
demo: {
src: [
DEMO_SAMPLE_PATH + '/**/*.js',
// You can add README.md file for index page at documentations.
'README.md'
],
options: {
verbose: true,
destination: DEMO_PATH,
configure: 'conf.json',
template: './',
'private': false
}
}
},
less: {
dist: {
src: 'less/**/jaguar.less',
dest: 'static/styles/jaguar.css'
}
},
uglify: {
jslib: {
src: ['bower_components/prettyPrint/prettyprint.js'],
dest: 'static/scripts/prettyprint.js'
}
},
copy: {
css: {
src: 'static/styles/jaguar.css',
dest: DEMO_PATH + '/styles/jaguar.css'
},
js: {
src: 'static/scripts/main.js',
dest: DEMO_PATH + '/scripts/main.js'
},
jslib: {
src: ['bower_components/jQuery/dist/jquery.min.js'],
dest: 'static/scripts/*'
}
}
});
// Load task libraries
[
'grunt-contrib-connect',
'grunt-contrib-watch',
'grunt-contrib-copy',
'grunt-contrib-clean',
'grunt-contrib-less',
'grunt-contrib-uglify',
'grunt-jsdoc',
].forEach(function (taskName) {
grunt.loadNpmTasks(taskName);
});
// Definitions of tasks
grunt.registerTask('default', 'Watch project files', [
'demo',
'connect:demo',
'watch'
]);
grunt.registerTask('demo', 'Create documentations for demo', [
'less',
'clean:demo',
'jsdoc:demo'
]);
};
| mit |
SetBased/py-kerapu | kerapu/boom/boom_parameter/BoomParameter.py | 778 | import abc
from kerapu.lbz.Subtraject import Subtraject
class BoomParameter:
"""
Abstracte klasse voor boomparameters.
"""
# ------------------------------------------------------------------------------------------------------------------
@abc.abstractmethod
def tel(self, waarde, subtraject: Subtraject) -> int:
"""
Geeft het aantal malen dat de boomparameter voldoet aan een waarde.
:param [int|str] waarde: De waarde waartegen getest moet worden.
:param kerapu.lbz.Subtraject.Subtraject subtraject: Het subtraject.
:rtype: int
"""
raise Exception("Not implemented")
# ----------------------------------------------------------------------------------------------------------------------
| mit |
PiotrDabkowski/Js2Py | tests/test_cases/built-ins/RegExp/S15.10.2.6_A1_T2.js | 1405 | // Copyright 2009 the Sputnik authors. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/*---
info: >
The production Assertion :: $ evaluates by returning an internal
AssertionTester closure that takes a State argument x and performs the ...
es5id: 15.10.2.6_A1_T2
description: Execute /e$/.exec("pairs\nmakes\tdouble") and check results
---*/
__executed = /e$/.exec("pairs\nmakes\tdouble");
__expected = ["e"];
__expected.index = 17;
__expected.input = "pairs\nmakes\tdouble";
//CHECK#1
if (__executed.length !== __expected.length) {
$ERROR('#1: __executed = /e$/.exec("pairs\\nmakes\\tdouble"); __executed.length === ' + __expected.length + '. Actual: ' + __executed.length);
}
//CHECK#2
if (__executed.index !== __expected.index) {
$ERROR('#2: __executed = /e$/.exec("pairs\\nmakes\\tdouble"); __executed.index === ' + __expected.index + '. Actual: ' + __executed.index);
}
//CHECK#3
if (__executed.input !== __expected.input) {
$ERROR('#3: __executed = /e$/.exec("pairs\\nmakes\\tdouble"); __executed.input === ' + __expected.input + '. Actual: ' + __executed.input);
}
//CHECK#4
for(var index=0; index<__expected.length; index++) {
if (__executed[index] !== __expected[index]) {
$ERROR('#4: __executed = /e$/.exec("pairs\\nmakes\\tdouble"); __executed[' + index + '] === ' + __expected[index] + '. Actual: ' + __executed[index]);
}
}
| mit |
pwnall/sphero_pwn | test/session_test.rb | 429 | require_relative './helper.rb'
describe SpheroPwn::Session do
describe '#valid_checksum?' do
it 'works on a correct example without data' do
assert_equal true, SpheroPwn::Session.valid_checksum?([0x00, 0x01, 0x01],
[], 0xfd)
end
it 'fails an incorrect example without data' do
assert_equal false, SpheroPwn::Session.valid_checksum?(
[0x00, 0x01, 0x01], [], 0xfa)
end
end
end
| mit |
plotly/plotly.py | packages/python/plotly/plotly/validators/indicator/gauge/axis/_dtick.py | 493 | import _plotly_utils.basevalidators
class DtickValidator(_plotly_utils.basevalidators.AnyValidator):
def __init__(
self, plotly_name="dtick", parent_name="indicator.gauge.axis", **kwargs
):
super(DtickValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
edit_type=kwargs.pop("edit_type", "plot"),
implied_edits=kwargs.pop("implied_edits", {"tickmode": "linear"}),
**kwargs
)
| mit |
M3kH/tire-bouchon | node_modules/grunt-react/node_modules/react-tools/build/modules/ReactDOMIDOperations.js | 5957 | /**
* Copyright 2013 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule ReactDOMIDOperations
* @typechecks static-only
*/
/*jslint evil: true */
"use strict";
var CSSPropertyOperations = require("./CSSPropertyOperations");
var DOMChildrenOperations = require("./DOMChildrenOperations");
var DOMPropertyOperations = require("./DOMPropertyOperations");
var ReactMount = require("./ReactMount");
var getTextContentAccessor = require("./getTextContentAccessor");
var invariant = require("./invariant");
/**
* Errors for properties that should not be updated with `updatePropertyById()`.
*
* @type {object}
* @private
*/
var INVALID_PROPERTY_ERRORS = {
dangerouslySetInnerHTML:
'`dangerouslySetInnerHTML` must be set using `updateInnerHTMLByID()`.',
style: '`style` must be set using `updateStylesByID()`.'
};
/**
* The DOM property to use when setting text content.
*
* @type {string}
* @private
*/
var textContentAccessor = getTextContentAccessor() || 'NA';
var LEADING_SPACE = /^ /;
/**
* Operations used to process updates to DOM nodes. This is made injectable via
* `ReactComponent.DOMIDOperations`.
*/
var ReactDOMIDOperations = {
/**
* Updates a DOM node with new property values. This should only be used to
* update DOM properties in `DOMProperty`.
*
* @param {string} id ID of the node to update.
* @param {string} name A valid property name, see `DOMProperty`.
* @param {*} value New value of the property.
* @internal
*/
updatePropertyByID: function(id, name, value) {
var node = ReactMount.getNode(id);
invariant(!INVALID_PROPERTY_ERRORS.hasOwnProperty(name));
// If we're updating to null or undefined, we should remove the property
// from the DOM node instead of inadvertantly setting to a string. This
// brings us in line with the same behavior we have on initial render.
if (value != null) {
DOMPropertyOperations.setValueForProperty(node, name, value);
} else {
DOMPropertyOperations.deleteValueForProperty(node, name);
}
},
/**
* Updates a DOM node to remove a property. This should only be used to remove
* DOM properties in `DOMProperty`.
*
* @param {string} id ID of the node to update.
* @param {string} name A property name to remove, see `DOMProperty`.
* @internal
*/
deletePropertyByID: function(id, name, value) {
var node = ReactMount.getNode(id);
invariant(!INVALID_PROPERTY_ERRORS.hasOwnProperty(name));
DOMPropertyOperations.deleteValueForProperty(node, name, value);
},
/**
* This should almost never be used instead of `updatePropertyByID()` due to
* the extra object allocation required by the API. That said, this is useful
* for batching up several operations across worker thread boundaries.
*
* @param {string} id ID of the node to update.
* @param {object} properties A mapping of valid property names.
* @internal
* @see {ReactDOMIDOperations.updatePropertyByID}
*/
updatePropertiesByID: function(id, properties) {
for (var name in properties) {
if (!properties.hasOwnProperty(name)) {
continue;
}
ReactDOMIDOperations.updatePropertiesByID(id, name, properties[name]);
}
},
/**
* Updates a DOM node with new style values. If a value is specified as '',
* the corresponding style property will be unset.
*
* @param {string} id ID of the node to update.
* @param {object} styles Mapping from styles to values.
* @internal
*/
updateStylesByID: function(id, styles) {
var node = ReactMount.getNode(id);
CSSPropertyOperations.setValueForStyles(node, styles);
},
/**
* Updates a DOM node's innerHTML.
*
* @param {string} id ID of the node to update.
* @param {string} html An HTML string.
* @internal
*/
updateInnerHTMLByID: function(id, html) {
var node = ReactMount.getNode(id);
// HACK: IE8- normalize whitespace in innerHTML, removing leading spaces.
// @see quirksmode.org/bugreports/archives/2004/11/innerhtml_and_t.html
node.innerHTML = html.replace(LEADING_SPACE, ' ');
},
/**
* Updates a DOM node's text content set by `props.content`.
*
* @param {string} id ID of the node to update.
* @param {string} content Text content.
* @internal
*/
updateTextContentByID: function(id, content) {
var node = ReactMount.getNode(id);
node[textContentAccessor] = content;
},
/**
* Replaces a DOM node that exists in the document with markup.
*
* @param {string} id ID of child to be replaced.
* @param {string} markup Dangerous markup to inject in place of child.
* @internal
* @see {Danger.dangerouslyReplaceNodeWithMarkup}
*/
dangerouslyReplaceNodeWithMarkupByID: function(id, markup) {
var node = ReactMount.getNode(id);
DOMChildrenOperations.dangerouslyReplaceNodeWithMarkup(node, markup);
},
/**
* Updates a component's children by processing a series of updates.
*
* @param {array<object>} updates List of update configurations.
* @param {array<string>} markup List of markup strings.
* @internal
*/
dangerouslyProcessChildrenUpdates: function(updates, markup) {
for (var i = 0; i < updates.length; i++) {
updates[i].parentNode = ReactMount.getNode(updates[i].parentID);
}
DOMChildrenOperations.processUpdates(updates, markup);
}
};
module.exports = ReactDOMIDOperations;
| mit |
venogram/ExpressiveJS | test-servers/mary-server.js | 757 | const usingExpressive = true;
const express = usingExpressive ? require('./../expressive.js') : require('express');
const app = express();
const cookieParser = require('cookie-parser');
//app.use(cookieParser);
app.listen(3000)
app.get('/', function(req, res) {
res.status(200).json({ name: 'VENOGRAM' });
});
app.get('/redirect', function(req, res){
res.redirect('/redirect2');
})
app.get('/redirect2', function(req, res){
res.status(200).json({ methodRoute: 'Mary' });
})
// const express = require('express');
// //const express = require('express');
// const request = require('request');
// const path = require('path');
// const app = express();
// const logger = require('morgan');
// app.use(logger('dev'));
module.exports = app; | mit |
kristenhazard/hanuman | db/migrate/20170120223424_add_gps_data_to_hanuman_observations.rb | 366 | class AddGpsDataToHanumanObservations < ActiveRecord::Migration
def change
add_column :hanuman_observations, :latitude, :float
add_column :hanuman_observations, :longitude, :float
add_column :hanuman_observations, :speed, :float
add_column :hanuman_observations, :direction, :float
add_column :hanuman_observations, :altitude, :float
end
end
| mit |
sivertsenstian/boom | source/code/boom/constants.js | 5699 | Boom.Constants = {
TRUE: '46e25702-b22f-4d18-a391-7f7e0bba137c',
FALSE: '1cf21342-39c3-4bf0-865c-d28f19448112',
PLAYER_CAMERA: null,
HOSTILE: '63fc00f3-416d-43db-9fcf-315ae62c01e9',
FRIENDLY: 'ba75d021-1988-4cbb-a6c5-05071b69572f',
UI: {
BASE_WIDTH:10,
HEIGHT: 0,
WIDTH: 0,
MOUSE_LOCKED: false,
PLAYER: {
NAME: 'UNREGISTERED',
SCORE: 0,
STATS:{
ENEMIES: 0,
ITEMS: 0,
SECRETS: 0,
TIME: 0,
DEATHS: 0
}
},
ELEMENT:{
TITLE: '#BoomTitle',
GAME_WON: '#BoomGameWon',
GAME_OVER: '#BoomGameOver',
HUD: '#BoomHUD',
HUD_ACTIVE: '#BoomHUD_ACTIVE',
HUD_INVENTORY: '#BoomHUD_INVENTORY',
TITLE_MENU: '#BoomTitleMenu',
HIGH_SCORE: '#BoomHighScore',
PLAYER: '#BoomPlayer',
PLAYER_REGISTRATION: '#BoomPlayerRegistration',
REGISTRATION_INPUT: '#BoomPlayerRegistrationInput',
SCORE: '#BoomScore',
SCORE_VALUE: '#BoomScoreValue',
SELECT_LEVEL: '#BoomSelectLevel',
POINTER_LOCK: '#BoomPointerLock',
SECRET: '#BoomSecret'
}
},
World:{
WIDTH: 32,
HEIGHT: 32,
SIZE: 24,
GRAVITY: new THREE.Vector3(0, -6, 0),
SKYBOX_SCALAR: 2,
LAYER: {
FLOOR: 0,
WALLS: 1,
CEILING: 2,
COLLISION: 3,
LIGHT: 4,
ACTORS: 5,
ITEMS: 6,
TRIGGERS: 7
},
END_LEVEL: 'e0c364e2-338b-4252-8a20-e9c21fda57e6',
STATS:{
ENEMIES: 0,
ITEMS: 0,
SECRETS: 0,
PAR_TIME: 0
}
},
Actors:{
FRIENDLY: {
PLAYER: '44ade206-60e5-43b7-aaa3-045e147a1c88'
},
HOSTILE:{
HOVERBOT:'0a89b621-e2ed-4618-ad90-57641ba6a563'
}
},
Items:{
POWERUP: {
HEALTH: 'db9fdc72-5195-49b2-9327-346919b644df',
BULLET: '2bccdac5-f515-4926-b203-95334bc240a1',
BULLET_LARGE: '4e41cb95-3df0-4463-8093-d9b87272ff0e',
SHELL: '1d2b839d-151e-4f4b-bbb4-f1809ec9a558',
ROCKET: '5cbd5a4b-7e83-43c4-bcd0-6809825020bf',
PISTOL: 'e6a2d0c2-ff2d-46e5-b66e-2e94c541b709',
SHOTGUN: 'e697f30b-77eb-4c32-9b0d-e1c363466b70',
RIFLE: '634cf56d-8214-4095-b8e2-e24a2aa2771e',
ROCKETLAUNCHER: 'f39b30ae-e3d8-4888-96d1-d95524b8d3ca',
},
OTHER:{
END_GOAL: 'a6c4da7d-b51c-440a-a1be-19d26872c843'
}
},
Triggers:{
DOOR: '94df0126-3382-444e-b179-df17fbfca37d',
ENTITY_SPAWN: '203a3744-5658-490c-9b28-fa0ded97cfa0',
SECRET: '291ad70f-a3b9-4ade-be8b-33f0e706a028'
},
Component:{
BOX: Boom.guid(),
SPHERE: Boom.guid(),
MODEL: Boom.guid(),
TYPE: {
BASIC: 'basic',
PHYSICAL: 'physics',
AUDIO: 'audio',
ANIMATION: 'animation',
INPUT: 'input',
ACTION: 'action',
HIT: 'hit',
UI: 'UI',
HUD: 'HUD',
LIGHT: 'light',
INVENTORY: 'inventory'
}
},
Lights:{
AMBIENT: 'a45494b9-7876-428f-b339-626c75a1a10b',
DIRECTIONAL: 'a3b53140-a4ee-43e3-bda2-fb0b37bc3527',
HEMISPHERE: 'e37e182d-1c35-47cb-9463-678b916e9362',
POINT: 'dc16baf2-c933-4db4-a071-89ef72679925'
},
Weapon: {
PISTOL: 'a55a989b-d8dc-46c9-8614-2fee2e52fc29',
SHOTGUN: '3c8e662c-44e5-4348-b959-ccd74e09dec5',
RIFLE: '6a57c256-e90c-49d4-b503-fd7b95c28c83',
ROCKETLAUNCHER: '02dac85e-416e-41bf-a1b6-c835867995a0',
HOVERBOTGUN: 'a1e12702-edfd-46b3-868b-9d6b4ad82307'
},
Ammunition:{
BULLET: '96fc013d-623b-4b0a-86ef-cdb9698d843f',
SHELL: '02709816-7162-4c37-a9e7-b037cace65e0',
ROCKET: 'c7f24327-b0f1-41c4-b882-e45d6d4cfe28',
HOVERBOTGUNLASER: '454ca313-2962-49ab-90fd-606542f3f55e'
},
Message: {
ALL: Boom.guid(),
Input: {
FORWARD: Boom.guid(),
BACKWARD: Boom.guid(),
LEFT: Boom.guid(),
RIGHT: Boom.guid(),
LEFTCLICK: Boom.guid(),
RIGHTCLICK: Boom.guid()
},
Action: {
VELOCITY_FLAT: Boom.guid(),
VELOCITY: Boom.guid(),
GRAVITY: Boom.guid(),
SHOOT: Boom.guid(),
JUMP: Boom.guid(),
SPRINT_START: Boom.guid(),
SPRINT_STOP: Boom.guid(),
SPRINTING: Boom.guid(),
LAND: Boom.guid(),
REDUCE_HEALTH: Boom.guid(),
INCREASE_HEALTH: Boom.guid(),
INCREASE_AMMO: Boom.guid(),
ADD_WEAPON: Boom.guid(),
SET_WEAPON: Boom.guid(),
PLAYER_DEATH: Boom.guid(),
HOSTILE_DEATH: Boom.guid(),
WIN: Boom.guid(),
TRIGGER: Boom.guid()
},
Hit: {
DISPOSE: Boom.guid(),
DISPOSE_DEALDAMAGE: Boom.guid(),
ITEM_PICKUP: Boom.guid()
},
HUD: {
REGISTER: Boom.guid(),
UPDATE: Boom.guid()
}
},
Objects:{
FLOOR: Boom.guid(),
SKYBOX: Boom.guid(),
WALL: Boom.guid(),
COLLECTION: Boom.guid(),
CEILING: Boom.guid(),
FOG: Boom.guid(),
GRAVITY: Boom.guid(),
LIGHT: Boom.guid(),
DEBUG: Boom.guid(),
RENDERER: Boom.guid(),
CAMERA: Boom.guid(),
SCENE: Boom.guid(),
PLAYER: Boom.guid(),
WEAPON: Boom.guid()
},
Debug:{
FLOOR: function(){
var t = new THREE.ImageUtils.loadTexture( '/resources/DEBUG/floor.png' );
t.wrapS = t.wrapT = THREE.RepeatWrapping;
t.repeat.set( Boom.Constants.World.WIDTH, Boom.Constants.World.HEIGHT );
return new THREE.MeshBasicMaterial( { map: t, side: THREE.DoubleSide });
},
WALL: function(){ return new THREE.MeshBasicMaterial({color: 0xFF00FF, wireframe: true})},
SKYBOX: function(){ return new THREE.MeshBasicMaterial({color: 0x00FFFF, wireframe: true})}
},
Colors:{
DEFAULT: 0x00FF00,
X: 0xFF0000,
Y: 0x00FF00,
Z: 0x0000FF,
CLEAR: 0x000000
},
Base:{
FOV: 75,
NEAR: 0.1,
FAR: 1000,
FPS: 60,
ANTIALIAS: false
}
}; | mit |
Happyr/Doctrine-Specification | src/Operand/PlatformFunction/Executor/CurrentDateExecutor.php | 649 | <?php
declare(strict_types=1);
/**
* This file is part of the Happyr Doctrine Specification package.
*
* (c) Tobias Nyholm <tobias@happyr.com>
* Kacper Gunia <kacper@gunia.me>
* Peter Gribanov <info@peter-gribanov.ru>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Happyr\DoctrineSpecification\Operand\PlatformFunction\Executor;
final class CurrentDateExecutor
{
/**
* @return \DateTimeImmutable
*/
public function __invoke(): \DateTimeImmutable
{
return (new \DateTimeImmutable())->setTime(0, 0);
}
}
| mit |
masonsbro/ea-competition | app/controllers/matches.server.controller.js | 111 | 'use strict';
/**
* Module dependencies.
*/
var mongoose = require('mongoose'),
_ = require('lodash');
| mit |
kybarg/material-ui | docs/src/pages/components/progress/CustomizedProgressBars.tsx | 2154 | import React from 'react';
import { lighten, makeStyles, createStyles, withStyles, Theme } from '@material-ui/core/styles';
import CircularProgress, { CircularProgressProps } from '@material-ui/core/CircularProgress';
import LinearProgress from '@material-ui/core/LinearProgress';
const ColorCircularProgress = withStyles({
root: {
color: '#00695c',
},
})(CircularProgress);
const ColorLinearProgress = withStyles({
colorPrimary: {
backgroundColor: '#b2dfdb',
},
barColorPrimary: {
backgroundColor: '#00695c',
},
})(LinearProgress);
const BorderLinearProgress = withStyles({
root: {
height: 10,
backgroundColor: lighten('#ff6c5c', 0.5),
},
bar: {
borderRadius: 20,
backgroundColor: '#ff6c5c',
},
})(LinearProgress);
// Inspired by the Facebook spinners.
const useStylesFacebook = makeStyles({
root: {
position: 'relative',
},
top: {
color: '#eef3fd',
},
bottom: {
color: '#6798e5',
animationDuration: '550ms',
position: 'absolute',
left: 0,
},
});
function FacebookProgress(props: CircularProgressProps) {
const classes = useStylesFacebook();
return (
<div className={classes.root}>
<CircularProgress
variant="determinate"
value={100}
className={classes.top}
size={24}
thickness={4}
{...props}
/>
<CircularProgress
variant="indeterminate"
disableShrink
className={classes.bottom}
size={24}
thickness={4}
{...props}
/>
</div>
);
}
const useStyles = makeStyles((theme: Theme) =>
createStyles({
root: {
flexGrow: 1,
},
margin: {
margin: theme.spacing(1),
},
}),
);
export default function CustomizedProgressBars() {
const classes = useStyles();
return (
<div className={classes.root}>
<ColorCircularProgress size={30} thickness={5} />
<ColorLinearProgress className={classes.margin} />
<BorderLinearProgress
className={classes.margin}
variant="determinate"
color="secondary"
value={50}
/>
<FacebookProgress />
</div>
);
}
| mit |
jessepeterson/commandment | ui/src/components/react-tables/DeviceCommandsTable.tsx | 1217 | import * as React from "react";
import ReactTable, {TableProps} from "react-table";
import {Command} from "../../store/device/types";
import {RelativeToNow} from "../react-table/RelativeToNow";
import {CommandStatus} from "../react-table/CommandStatus";
import {JSONAPIDataObject} from "../../store/json-api";
import {DEPAccount} from "../../store/dep/types";
export interface IDeviceCommandsTableProps {
loading: boolean;
data: Array<JSONAPIDataObject<Command>>;
onFetchData: (state: any, instance: any) => void;
}
const columns = [
{
Cell: CommandStatus,
Header: "Status",
accessor: "attributes.status",
id: "status",
maxWidth: 50,
style: { textAlign: "center" },
},
{
Header: "Type",
accessor: "attributes.request_type",
id: "request_type",
},
{
Cell: RelativeToNow,
Header: "Sent",
accessor: "attributes.sent_at",
id: "sent_at",
},
];
export const DeviceCommandsTable = ({ data, ...props }: IDeviceCommandsTableProps & Partial<TableProps>) => (
<ReactTable
manual
filterable
data={data}
columns={columns}
{...props}
/>
);
| mit |
wingmingchan/php-cascade-ws-ns-examples | recipes/data_definition_blocks/replace_structured_data.php | 924 | <?php
/* This program shows how to replace the data definition associated
with a data definition block. In effect, the block will have a new
data container, with no data inside. For data mapping, see
https://github.com/wingmingchan/php-cascade-ws-ns-examples/tree/master/recipes/data_mapping
*/
require_once( 'auth_tutorial7.php' );
use cascade_ws_AOHS as aohs;
use cascade_ws_constants as c;
use cascade_ws_asset as a;
use cascade_ws_property as p;
use cascade_ws_utility as u;
use cascade_ws_exception as e;
try
{
$block = $cascade->getAsset( a\DataBlock::TYPE, "d1ffa9298b7ffe837521e02210c6572f" );
$dd = $cascade->getAsset(
a\DataDefinition::TYPE, "1f2408778b7ffe834c5fe91ec3aefb48" );
$sd = $dd->getStructuredDataObject();
$block->setStructuredData( $sd );
}
catch( \Exception $e )
{
echo S_PRE . $e . E_PRE;
}
catch( \Error $er )
{
echo S_PRE . $er . E_PRE;
}
?> | mit |
astral-keks/vscode-folder-indexing | src/extension.ts | 971 | 'use strict'
import * as vscode from 'vscode'
import {ExtensionSettings} from './settings'
import {ExtensionCommands} from './commands'
import {ExtensionStatus} from './status'
import {IndexStorage} from './indexing/indexStorage'
import {FileSystem} from './indexing/fileSystem'
export function activate(context: vscode.ExtensionContext) {
let status = new ExtensionStatus()
context.subscriptions.push(status)
let settings = new ExtensionSettings()
let fileSystem = new FileSystem()
let index = new IndexStorage(vscode.workspace.rootPath, fileSystem, settings, status)
vscode.languages.registerWorkspaceSymbolProvider(index)
context.subscriptions.push(index)
let commands = new ExtensionCommands(settings)
let command = vscode.commands.registerCommand(commands.rebuild, () => { index.rebuild() })
context.subscriptions.push(command)
vscode.commands.executeCommand(commands.rebuild)
}
export function deactivate() {
} | mit |
mre/the-coding-interview | problems/anagram-detection/anagram-detection.java | 1267 | import java.util.HashMap;
import java.util.Vector;
public class Anagram {
public static void main(String[] args) {
System.out.println(occurences("AdnBndAndBdaBn", "dAn"));
System.out.println(occurences("AbrAcadAbRa", "cAda"));
}
static int hash(String str) {
/*
* Map letters to prime numbers... the Java way. :(
* We should only do this once and cache the result for
* better performance.
*/
HashMap<Character, Integer> letter_map = new HashMap<>();
String letters = "abcdefghijklmnopqrstuvwxyz";
Integer[] primes = {2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101};
for (int i = 0; i < letters.length(); ++i) {
// Zip anyone?
letter_map.put(letters.charAt(i), primes[i]);
}
int result = 0;
str = str.toLowerCase(); // Don't care about uppercase
for (char c : str.toCharArray()) {
result += letter_map.get(c);
}
return result;
}
private static int occurences(String parent, String child) {
int child_hash = hash(child);
int start = 0;
int end = start + child.length();
int occured = 0;
while (end < parent.length()) {
String sub = parent.substring(start, end);
if (hash(sub) == child_hash) {
occured++;
}
start++;
end++;
}
return occured;
}
}
| mit |
SLongofono/448_Project4 | REKTUser.py | 11539 | ## @file REKTUser.py
# REKTUser
# @author Stephen Longofono
# @brief The user class for the recommendation system
# @details This file defines the User class which is used to generate and manipulate a user profile from
# their Spotify profile
import Mutators
import traceback
import Variance
import functools
import sqlite3
import config_obj
user = config_obj.get_user()
localDB = config_obj.get_db()
## @class User
# @brief Manages creation and manipulation of a Spotify user profile
# @param debug An optional Boolean parameter specifying whether or not to run in verbose mode
# @param logfile An optional filename for a test file containing a user profile vector
# @details The User class manages the local representation of a Spotify user, as aggregated from a
# dataset composed of the songs in their Spotify library. A profile vector represents the
# average values for each of the features we track and recommend with, and is represented
# locally in a text file (soon to be database)
class User():
def __init__(self, logfile="userProfile.txt", debug=False):
self.db = sqlite3.connect(localDB)
# Set up the interface to always return strings if possible, since in general utf(x) != str(x)
self.db.text_factory = str
self.logfile = logfile
self.debug = debug
self.profile = None
self.stdDevs = None
self.labels = ['artists', 'genres', 'popularity', 'acousticness', 'danceability', 'energy', 'instrumentalness', 'key', 'liveness', 'valence']
self.addVector =[
Mutators.artistMutator,
Mutators.genreMutator,
Mutators.popularityMutator,
Mutators.acousticnessMutator,
Mutators.danceabilityMutator,
Mutators.energyMutator,
Mutators.instrumentalnessMutator,
Mutators.keyMutator,
Mutators.livenessMutator,
Mutators.valenceMutator
]
self.processProfile()
## addData
# @brief Processes a new song vector into the user profile vector
# @param newDataVector
# @return void
# @details This method applies the mutator functions associated with each song feature to the features
# in newDataVector, incorporating their values in the volatile state within each mutator. Note
# that changes are not applied to the user profile permenantly until saveStatus() is called.
def addData(self, newDataVector):
for i in range (len(self.addVector)):
self.addVector[i](newVal=newDataVector[i], debug=self.debug)
## calculateAverages
# @brief update the user profile with the current average of numeric values in the user database
# @return void
# @details This method is used to evaluate the mean of each column in the "numerics" table for the
# user. It is assumed that the database has been initialized, and that the "numerics" table
# already exists.
def calculateAverages(self):
print 'Assembling averages...'
payload = [self.db.execute("SELECT " + x + " FROM numerics;") for x in self.labels[2:]]
averages = []
for column in payload:
data = [x[0] for x in column]
averages.append(sum(data)/len(data))
print averages
self.profile = self.profile[:2] + averages
self.prettyPrintProfile()
## calculateStandardDeviation
# @brief Calculates and updates the Current StdDev of the saved song vectors
# @return void
# #details This method is used to evaluate the stddev of each column of the NUMERICS table;
# each column being representative of all of the user's audio features associated with the
# they've saved. Requires DB initialization and that the NUMERICS table has been filled.
def calculateStandardDeviations(self):
print 'Assembling Standard Deviations ...'
payload = [self.db.execute("SELECT " + x + " FROM numerics;") for x in self.labels[2:]]
stdDev = []
for column in payload:
vals = [x[0] for x in column]
Nval = len(vals)
mean = sum(vals)/Nval
stdDev.append((sum([(x-mean)**2 for x in vals])/Nval)**0.5)
self.stdDevs = stdDev
## getSongDifferences
# @brief Returns a list of the featurewise differences of each of a list of new song vectors and the user profile vector
# @param newSongVectors A list of song vectors to compare against
# @return A list of lists representing the feature difference of each of the song vectors passed in.
# @details This method binds the Variance.getVariance() function to the user profile, and then Curries
# with each of the song vectors in newSongvectors. See Variance.py for more details on how
# list features are handled versus value features.
def getSongDifferences(self, newSongVectors):
return map(functools.partial(Variance.getVariance, self.profile), newSongVectors)
## prettyPrintProfile
# @brief Prints a user profile in a human-friendly way
# @return void
# @brief Prints a user profile in a human-friendly way (Label: value)
def prettyPrintProfile(self):
if len(self.profile) > 2:
for i in range(10):
print self.labels[i], ':'
print self.profile[i]
else:
print "Profile has not been set up in database yet, did you forget to run calculateAverages()?"
## processProfile
# @brief Reads in a user profile from a local database, updates profile database
# @return void
# @details This method opens the database associate with the user and parses out the user profile
# into the User.profile member. After recalculating the average, the user profile is saved
# in the profile table. It is assumed that the database passed in refers to a valid
# and accesible file in the working directory and that it has been initialized with the
# schema detailed in Assemble_Profile.py.
def processProfile(self):
print 'Processing user profile data...'
self.profile = []
self.profile.append(map(lambda x: x[0], self.db.execute("SELECT name FROM artists")))
self.profile.append(map(lambda x: x[0], self.db.execute("SELECT name FROM genres")))
self.calculateAverages()
self.calculateStandardDeviations()
print "Saving user profile..."
weights = Variance.getNewWeight(self.stdDevs)
self.db.execute("INSERT INTO profile(popularity,acousticness,danceability,energy,instrumentalness,key,liveness,valence) VALUES(?,?,?,?,?,?,?,?);", tuple(self.profile[2:]))
self.db.execute("INSERT INTO deviations(popularity, acousticness,danceability,energy,instrumentalness,key,liveness,valence) VALUES(?,?,?,?,?,?,?,?);", tuple(self.stdDevs))
self.db.execute("INSERT INTO weights(artists, genres, popularity, acousticness,danceability,energy,instrumentalness,key,liveness,valence) VALUES(?,?,?,?,?,?,?,?,?,?);", tuple(weights))
self.db.commit()
## saveStatus
# @brief Saves the current user profile vector and any new songs to the user database
# @return void
# @details This method aggregates the new values in the mutator functions and writes them to
# the user profile logfile, preserving the state for future access by our program.
# Songs are then added to the user database, and the standard deviations are updated
def saveStatus(self):
# Average new values into profile
for i in range(2, len(self.profile)):
newVals = self.addVector[i]()
self.profile[i] = (self.profile[i] + sum(newVals))/(1 + len(newVals))
# Identify unique artists and genres to add to database
newArtists = Mutators.getUniques(self.profile[0], self.addVector[0]())
newGenres = Mutators.getUniques(self.profile[1], self.addVector[1]())
# Attempt to add in new artists and genres
for each in newArtists:
try:
self.db.execute("INSERT INTO artists(name) values(?);", each)
except:
pass
for each in newGenres:
try:
self.db.execute("INSERT INTO genres(name) values(?);", each)
except:
pass
# Add in new numerical values to db
newSongs = zipAll([x() for x in self.addVector[2:]])
print "Saving new songs..."
for song in newSongs:
try:
self.db.execute("INSERT INTO numerics(popularity, acousticness,danceability,energy,instrumentalness,key,liveness,valence) VALUES(?,?,?,?,?,?,?,?)", song)
except:
pass
self.calculateAverages()
self.calculateStandardDeviations()
print "Saving user profile..."
for i in range(len(self.profile[2:])):
self.db.execute("UPDATE profile SET " + self.labels[i+2] + "=" + str(self.profile[i+2]) + ";")
self.db.execute("UPDATE deviations SET " + self.labels[i+2] + "=" + str(self.profile[i+2]) + ";")
newWeight = Variance.getNewWeight(self.stdDevs)
for i in range(2, len(newWeight)):
self.db.execute("UPDATE weights SET " + self.labels[i] + "=" + str(newWeight[i]) + ";")
self.db.commit()
## zipAll
# @brief Helper function which implements zip for an arbitrary number of lists
# @param columns a list of lists representing columns in a table
# @return a list of tuples, each tuple representing the ith row in the column set
# @details This implements zip on an arbitrary number of columns. The built in zip
# will accept any number of explicitly defined lists to zip over, but it does
# not include a way to pass in a list of those lists.
def zipAll(columns):
results = []
i = 0
while i < len(columns[0]):
row = [x[i] for x in columns]
results.append(tuple(row))
i += 1
return results
# Demonstration and ad-hoc testing below
if __name__ == '__main__':
import os
print "\n\nTest run..."
# Basic setup
print "\n\nCreating user..."
tester = User(debug=True)
tester.calculateAverages()
print "\n\nUser profile vector: "
tester.prettyPrintProfile()
print "\n\nAdding a new song vector: "
testSong = [['Katy MF Perry', 'Bob Marley, Bob Vila, and Bob Ross'], ['Death Pop', 'Icelandic glam-folk'], 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0]
print testSong
tester.addData(testSong)
print "\n\nModified profile: "
tester.prettyPrintProfile()
print "\n\nSaving modified profile..."
tester.saveStatus()
# Comparison
# Build test cases
newSongs = []
artists = ['The Unicorns','New Artist 1','new Artist 2','of Montreal','Mr. Bungle','RJD2', 'TV On The Radio', 'The Beatles', 'The Who', 'The Rolling Stones']
genres = ['blues-rock','ok indie','power pop','psychedelic rock','slow core','space rock','alternative pop','jangle pop','new wave','post-hardcore','post-punk','punk','rock','shoegaze','uk post-punk','album rock','art rock','classic funk rock','classic rock','dance rock','folk rock','glam rock','hard rock','mellow gold','new wave pop','permanent wave','pop christmas','protopunk','singer-songwriter','soft rock','funk','soul','new weird america','pop rock','post-grunge','big beat','downtempo','folk-pop','ambeat','electro house','classic soundtrack','library music','spytrack','indie garage rock','indie poptimism','metropopolis','shimmer pop','compositional ambient','post rock','australian dance','electroclash','filter house','pop']
for i in range(10):
newSong = [
[artists[i]],
[genres[i]],
i,
i,
i,
i,
i,
i,
i,
i
]
newSongs.append(newSong)
print "\n\nGenerated test songs to compare against:"
for i in newSongs:
print i
diffs = tester.getSongDifferences(newSongs)
bestSong = None
bestVal = 200000
for i in range(len(newSongs)):
print "Artist: ", newSongs[i][0][0], " Difference: ", sum(diffs[i])
if sum(diffs[i]) < bestVal:
bestVal = sum(diffs[i])
bestSong = newSongs[i][0][0]
print "\n\nMost similar test song is: "
print bestSong, " with a total difference ", bestVal
| mit |
PuercoPop/EleccionesPeru | excerpt.py | 887 | #-*- coding:utf-8 -*-
from BeautifulSoup import BeautifulSoup
with open( 'test_cases/tmp_resultados.html', 'r') as f:
soup = BeautifulSoup( f.read() )
for item in soup.findAll('a'):
print item.attrs[0][1]
#print item
with open( 'test_cases/tmp_resultados.html', 'r') as f:
soup = BeautifulSoup( f.read() )
#print len(soup.findAll('tr'))
#el número de tr que tengan elementos td (para exceptuar el tr)
print len( [ i for i in soup.findAll('tr') if (len(i.findAll('td') ) > 0 )] )
for tr in soup.findAll('tr'):
if tr.findAll('td'):
if len( tr.findAll('td')) == 1:
pass
else:
print 'numero de mesa : ', tr.findAll('td')[1].string
print 'estado del acta : ', tr.findAll('td')[3].string
print 'url : ', tr.findAll('td')[4].find('a')['href']
| mit |
the-ress/vscode | src/vs/workbench/contrib/debug/browser/debugQuickAccess.ts | 4833 | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { IQuickPickSeparator } from 'vs/platform/quickinput/common/quickInput';
import { PickerQuickAccessProvider, IPickerQuickAccessItem, TriggerAction } from 'vs/platform/quickinput/browser/pickerQuickAccess';
import { localize } from 'vs/nls';
import { INotificationService } from 'vs/platform/notification/common/notification';
import { IDebugService } from 'vs/workbench/contrib/debug/common/debug';
import { IWorkspaceContextService, WorkbenchState } from 'vs/platform/workspace/common/workspace';
import { ICommandService } from 'vs/platform/commands/common/commands';
import { matchesFuzzy } from 'vs/base/common/filters';
import { StartAction } from 'vs/workbench/contrib/debug/browser/debugActions';
import { withNullAsUndefined } from 'vs/base/common/types';
import { ADD_CONFIGURATION_ID } from 'vs/workbench/contrib/debug/browser/debugCommands';
export class StartDebugQuickAccessProvider extends PickerQuickAccessProvider<IPickerQuickAccessItem> {
static PREFIX = 'debug ';
constructor(
@IDebugService private readonly debugService: IDebugService,
@IWorkspaceContextService private readonly contextService: IWorkspaceContextService,
@ICommandService private readonly commandService: ICommandService,
@INotificationService private readonly notificationService: INotificationService,
) {
super(StartDebugQuickAccessProvider.PREFIX, {
noResultsPick: {
label: localize('noDebugResults', "No matching launch configurations")
}
});
}
protected async getPicks(filter: string): Promise<(IQuickPickSeparator | IPickerQuickAccessItem)[]> {
const picks: Array<IPickerQuickAccessItem | IQuickPickSeparator> = [];
picks.push({ type: 'separator', label: 'launch.json' });
const configManager = this.debugService.getConfigurationManager();
// Entries: configs
let lastGroup: string | undefined;
for (let config of configManager.getAllConfigurations()) {
const highlights = matchesFuzzy(filter, config.name, true);
if (highlights) {
// Separator
if (lastGroup !== config.presentation?.group) {
picks.push({ type: 'separator' });
lastGroup = config.presentation?.group;
}
// Launch entry
picks.push({
label: config.name,
description: this.contextService.getWorkbenchState() === WorkbenchState.WORKSPACE ? config.launch.name : '',
highlights: { label: highlights },
buttons: [{
iconClass: 'codicon-gear',
tooltip: localize('customizeLaunchConfig', "Configure Launch Configuration")
}],
trigger: () => {
config.launch.openConfigFile(false, false);
return TriggerAction.CLOSE_PICKER;
},
accept: async () => {
if (StartAction.isEnabled(this.debugService)) {
this.debugService.getConfigurationManager().selectConfiguration(config.launch, config.name);
try {
await this.debugService.startDebugging(config.launch);
} catch (error) {
this.notificationService.error(error);
}
}
}
});
}
}
// Entries detected configurations
const dynamicProviders = await configManager.getDynamicProviders();
if (dynamicProviders.length > 0) {
picks.push({ type: 'separator', label: localize('contributed', "contributed") });
}
dynamicProviders.forEach(provider => {
picks.push({
label: `$(folder) ${provider.label}...`,
ariaLabel: localize('providerAriaLabel', "{0} contributed configurations", provider.label),
accept: async () => {
const pick = await provider.pick();
if (pick) {
this.debugService.startDebugging(pick.launch, pick.config);
}
}
});
});
// Entries: launches
const visibleLaunches = configManager.getLaunches().filter(launch => !launch.hidden);
// Separator
if (visibleLaunches.length > 0) {
picks.push({ type: 'separator', label: localize('configure', "configure") });
}
for (const launch of visibleLaunches) {
const label = this.contextService.getWorkbenchState() === WorkbenchState.WORKSPACE ?
localize("addConfigTo", "Add Config ({0})...", launch.name) :
localize('addConfiguration', "Add Configuration...");
// Add Config entry
picks.push({
label,
description: this.contextService.getWorkbenchState() === WorkbenchState.WORKSPACE ? launch.name : '',
highlights: { label: withNullAsUndefined(matchesFuzzy(filter, label, true)) },
accept: () => this.commandService.executeCommand(ADD_CONFIGURATION_ID, launch.uri.toString())
});
}
return picks;
}
}
| mit |
LegiDrone/LegiDrone | src/FOS/UserBundle/Tests/EventListener/FlashListenerTest.php | 1278 | <?php
namespace FOS\UserBundle\Tests\EventListener;
use FOS\UserBundle\EventListener\FlashListener;
use FOS\UserBundle\FOSUserEvents;
use Symfony\Component\EventDispatcher\Event;
class FlashListenerTest extends \PHPUnit_Framework_TestCase
{
/** @var Event */
private $event;
/** @var FlashListener */
private $listener;
public function setUp()
{
$this->event = new Event();
$flashBag = $this->getMock('Symfony\Component\HttpFoundation\Session\Flash\FlashBag');
$session = $this->getMock('Symfony\Component\HttpFoundation\Session\Session');
$session
->expects($this->once())
->method('getFlashBag')
->willReturn($flashBag);
$translator = $this->getMock('Symfony\Component\Translation\TranslatorInterface');
$this->listener = new FlashListener($session, $translator);
}
public function testAddSuccessFlashLegacy()
{
$this->event->setName(FOSUserEvents::CHANGE_PASSWORD_COMPLETED);
$this->listener->addSuccessFlash($this->event);
}
public function testAddSuccessFlash()
{
$this->listener->addSuccessFlash($this->event, FOSUserEvents::CHANGE_PASSWORD_COMPLETED);
}
}
| mit |
erikzhouxin/CSharpSolution | NetSiteUtilities/AopApi/Domain/AlipayDataDataserviceBillDownloadurlQueryModel.cs | 960 | using System;
using System.Xml.Serialization;
namespace EZOper.NetSiteUtilities.AopApi
{
/// <summary>
/// AlipayDataDataserviceBillDownloadurlQueryModel Data Structure.
/// </summary>
[Serializable]
public class AlipayDataDataserviceBillDownloadurlQueryModel : AopObject
{
/// <summary>
/// 账单时间:日账单格式为yyyy-MM-dd,月账单格式为yyyy-MM。
/// </summary>
[XmlElement("bill_date")]
public string BillDate { get; set; }
/// <summary>
/// 账单类型,商户通过接口或商户经开放平台授权后其所属服务商通过接口可以获取以下账单类型:trade、signcustomer;trade指商户基于支付宝交易收单的业务账单;signcustomer是指基于商户支付宝余额收入及支出等资金变动的帐务账单;
/// </summary>
[XmlElement("bill_type")]
public string BillType { get; set; }
}
}
| mit |
ReneSchwarzer/InventoryExpress | src/core/InventoryExpress/WebControl/ControlAppNavigationManufactor.cs | 1437 | using InventoryExpress.WebResource;
using WebExpress.Attribute;
using WebExpress.Html;
using WebExpress.Internationalization;
using WebExpress.UI.Attribute;
using WebExpress.UI.Component;
using WebExpress.UI.WebControl;
using WebExpress.WebApp.Components;
namespace InventoryExpress.WebControl
{
[Section(Section.AppNavigationPrimary)]
[Application("InventoryExpress")]
public sealed class ControlAppNavigationManufacturer : ControlNavigationItemLink, IComponent
{
/// <summary>
/// Konstruktor
/// </summary>
public ControlAppNavigationManufacturer()
: base()
{
Init();
}
/// <summary>
/// Initialisierung
/// </summary>
private void Init()
{
}
/// <summary>
/// In HTML konvertieren
/// </summary>
/// <param name="context">Der Kontext, indem das Steuerelement dargestellt wird</param>
/// <returns>Das Control als HTML</returns>
public override IHtmlNode Render(RenderContext context)
{
Text = context.I18N("inventoryexpress.manufacturers.label");
Uri = context.Page.Uri.Root.Append("manufacturers");
Active = context.Page is IPageManufacturer ? TypeActive.Active : TypeActive.None;
Icon = new PropertyIcon(TypeIcon.Industry);
return base.Render(context);
}
}
}
| mit |
bebraw/taskist | demo/just_instant.js | 236 | #!/usr/bin/env node
var taskist = require('../');
var tasks = require('./tasks');
var config = require('./config');
main();
function main() {
taskist(config.tasks, tasks, {
instant: true,
series: true
});
}
| mit |
PaulGilchrist/OCIdeas | src/app/ocadmin-module/option-edit.component.ts | 2900 | import { Component } from '@angular/core';
// Data
import { CONFIG } from './data/config.data';
// Models
import { Option, OptionImage, OptionHeader, OptionCategory, OptionSubcategory, OptionAttribute, OptionAttributeSelection, OptionAttributeSelectionImage } from './models/option.model';
// Services
import { OCService } from './services/oc.service';
declare let _: any; // underscore library
declare let $: any; // jQuery library
declare let toastr: any; // Popups
@Component({
moduleId: module.id.toString(),
selector: 'option-edit',
styleUrls: ['./option-edit.component.css'],
templateUrl: './option-edit.component.html'
})
export class OptionEditComponent {
_modalImage: OptionImage;
_includeInBaseHouse: boolean = false;
_thumbnailUrl: string = CONFIG.cloudinary.thumbnail;
constructor(public _ocService: OCService) { }
setupModal(optionImage: OptionImage): void {
this._modalImage = _.clone(optionImage);
}
removeImage(optionImage: OptionImage): void {
let _self = this;
$.confirm({
data: _self,
title: 'Confirm!',
content: 'Remove Image?',
confirmButtonClass: 'btn-info',
cancelButtonClass: 'btn-danger',
closeIcon: true,
icon: 'fa fa-warning',
confirm: function() {
let optionHeader = this.data._ocService.option.optionHeader;
for(let i=0; i < optionHeader.optionImages.length; i++) {
let foundImage = optionHeader.optionImages[i];
if(foundImage.url === optionImage.url) {
this.data._ocService.deleteOptionImage(parseInt(this.data._ocService.market.number, 10), optionHeader.communityId, optionHeader.id, foundImage.id)
.subscribe((response: any) => {
// Successfully removed from API, so remove from memory
optionHeader.optionImages.splice(i, 1);
});
break;
}
}
}
});
}
showAttributeEdit() {
this._ocService.optionAttribute = this._ocService.option.optionHeader.optionAttributes[0];
}
notImplemented() {
toastr.warning('Not Implemented');
}
updateImage(modifiedImage: any): void {
let optionImage = _.findWhere(this._ocService.option.optionHeader.optionImages, {url: modifiedImage.url});
// Only transfer modifiable fields
optionImage.name = modifiedImage.name;
optionImage.description = modifiedImage.description;
// Update
this._ocService.putOptionImage(parseInt(this._ocService.market.number, 10), optionImage)
.subscribe(data => {}, error => {
toastr.error('Update failed');
});
}
}
| mit |
Azure/azure-sdk-for-java | sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/network/generated/FirewallPolicyIdpsSignaturesListSamples.java | 1699 | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.
package com.azure.resourcemanager.network.generated;
import com.azure.core.util.Context;
import com.azure.resourcemanager.network.models.FilterItems;
import com.azure.resourcemanager.network.models.IdpsQueryObject;
import com.azure.resourcemanager.network.models.OrderBy;
import com.azure.resourcemanager.network.models.OrderByOrder;
import java.util.Arrays;
/** Samples for FirewallPolicyIdpsSignatures List. */
public final class FirewallPolicyIdpsSignaturesListSamples {
/*
* x-ms-original-file: specification/network/resource-manager/Microsoft.Network/stable/2021-05-01/examples/FirewallPolicyQuerySignatureOverrides.json
*/
/**
* Sample code: query signature overrides.
*
* @param azure The entry point for accessing resource management APIs in Azure.
*/
public static void querySignatureOverrides(com.azure.resourcemanager.AzureResourceManager azure) {
azure
.networks()
.manager()
.serviceClient()
.getFirewallPolicyIdpsSignatures()
.listWithResponse(
"rg1",
"firewallPolicy",
new IdpsQueryObject()
.withFilters(Arrays.asList(new FilterItems().withField("Mode").withValues(Arrays.asList("Deny"))))
.withSearch("")
.withOrderBy(new OrderBy().withField("severity").withOrder(OrderByOrder.ASCENDING))
.withResultsPerPage(20)
.withSkip(0),
Context.NONE);
}
}
| mit |
azat-co/react-quickly | spare-parts/rock-paper-scissors/client/main.js | 3395 | // import { Template } from 'meteor/templating';
// import { ReactiveVar } from 'meteor/reactive-var';
//
// import './main.html';
//
// Template.hello.onCreated(function helloOnCreated() {
// // counter starts at 0
// this.counter = new ReactiveVar(0);
// });
//
// Template.hello.helpers({
// counter() {
// return Template.instance().counter.get();
// },
// });
//
// Template.hello.events({
// 'click button'(event, instance) {
// // increment the counter when button is clicked
// instance.counter.set(instance.counter.get() + 1);
// },
// });
const React = require('react')
var choices = ['rock',
'paper',
'scissors'
]
var Games = new Mongo.Collection('games')
if (Meteor.isClient) {
var App = React.createClass({
mixins: [ReactMeteorData],
getInitialState: function(){
return {
answer: ''
}
},
getMeteorData: function() {
return {
games: Games.find({createdBy: Meteor.userId}).fetch().reverse()
}
},
makeMove: function(e) {
var opponentAnswer = Math.floor(Math.random()*3)
var answer = e.target.getAttribute('data-answer-index')
var outcome = rps.compare(answer, opponentAnswer, choices)
this.setState({opponentAnswer: opponentAnswer,
answer: answer,
outcome: outcome
})
Games.insert({
createdBy: Meteor.userId,
opponentAnswer: opponentAnswer,
answer: answer,
outcome: outcome})
},
render: function() {
var winCount = 0
return (
<div>
<h1>Welcome to Rock-paper-scissors!</h1>
<p>Make your move!
<button className="btn btn-default" onClick={this.makeMove} data-answer-index='0'>Rock</button>
<button className="btn btn-default" onClick={this.makeMove} data-answer-index='1'>Paper</button>
<button className="btn btn-default" onClick={this.makeMove} data-answer-index='2'>Scissors</button>
</p>
<figure>
<img src="/rock-paper-scissors.svg" width="300"/>
<figcaption>Rules</figcaption>
</figure>
{(!this.state.answer)? '': <div><h2>Result</h2><p>You selected {choices[this.state.answer]}.<br/>
Opponent selected {choices[this.state.opponentAnswer]}. <br/>
Outcome: {this.state.outcome}</p></div>
}
{(this.data.games.length<1) ? '' : <h2>History</h2>}
{(this.data.games.length<1) ? '' : <p>Recent games first</p>}
<table><tbody>{this.data.games.map(function(value, index){
if (value.outcome.indexOf('lose')>-1) {
var style = {color: 'red'}
}
else {
winCount++
var style = {color: 'blue'}
}
return <tr><td
key={value._id}
style={style}>
{index+1}: {choices[value.answer]} (you) vs. {choices[value.opponentAnswer]}—
{value.outcome}
</td></tr>
})}</tbody></table>
<h2>Total wins: {winCount} which is {Math.round(winCount/this.data.games.length*10000)/100}%.</h2>
</div>
)
}
})
Meteor.startup(function() {
ReactDOM.render(<App />, document.getElementById('content'))
})
}
if (Meteor.isServer) {
Meteor.startup(function () {
// Code to run on server at startup
});
}
| mit |
MobilityLabs/pdredesign-server | app/assets/javascripts/client/controllers/responses/ResponseQuestionCtrl.js | 2079 | (function() {
'use strict';
angular.module('PDRClient')
.controller('ResponseQuestionCtrl', ResponseQuestionCtrl);
ResponseQuestionCtrl.$inject = [
'$scope',
'$rootScope',
'$timeout',
'$stateParams',
'$location',
'Response',
'ResponseHelper'
];
function ResponseQuestionCtrl($scope, $rootScope, $timeout, $stateParams, $location, Response, ResponseHelper) {
$scope.isConsensus = false;
$scope.questionColor = ResponseHelper.questionColor;
$scope.saveEvidence = ResponseHelper.saveEvidence;
$scope.editAnswer = ResponseHelper.editAnswer;
$scope.answerTitle = ResponseHelper.answerTitle;
$scope.toggleCategoryAnswers = function(category) {
category.toggled = !category.toggled;
angular.forEach(category.questions, function(question, key) {
ResponseHelper.toggleCategoryAnswers(question);
});
};
$scope.toggleAnswers = function(question, $event) {
ResponseHelper.toggleAnswers(question, $event);
};
$scope.invalidEvidence = function(question) {
return question.score.evidence == null || question.score.evidence == '';
};
$scope.assignAnswerToQuestion = function(answer, question) {
question.skipped = false;
question.score.value = answer.value;
if ($scope.invalidEvidence(question)) return;
ResponseHelper.assignAnswerToQuestion($scope, answer, question);
};
$scope.$on('submit_response', function() {
Response
.submit({assessment_id: $stateParams.assessment_id, id: $stateParams.response_id}, {submit: true})
.$promise
.then(function(data) {
$location.path('/assessments');
});
});
$timeout(function() {
$rootScope.$broadcast('start_change');
Response
.get({assessment_id: $stateParams.assessment_id, id: $stateParams.response_id})
.$promise
.then(function(data) {
$scope.categories = data.categories;
$rootScope.$broadcast('success_change');
});
});
}
})();
| mit |
Absike/sf2 | src/Ens/LoginBundle/EnsLoginBundle.php | 201 | <?php
namespace Ens\LoginBundle;
use Symfony\Component\HttpKernel\Bundle\Bundle;
class EnsLoginBundle extends Bundle
{
public function getParent() {
return 'FOSUserBundle';
}
}
| mit |
NetOfficeFw/NetOffice | Source/MSHTML/DispatchInterfaces/DispHTMLWindow2.cs | 33710 | using System;
using NetRuntimeSystem = System;
using System.ComponentModel;
using NetOffice.Attributes;
namespace NetOffice.MSHTMLApi
{
/// <summary>
/// DispatchInterface DispHTMLWindow2
/// SupportByVersion MSHTML, 4
/// </summary>
[SupportByVersion("MSHTML", 4)]
[EntityType(EntityType.IsDispatchInterface), BaseType]
public class DispHTMLWindow2 : 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(DispHTMLWindow2);
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 DispHTMLWindow2(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 DispHTMLWindow2(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 DispHTMLWindow2(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 DispHTMLWindow2(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 DispHTMLWindow2(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 DispHTMLWindow2(ICOMObject replacedObject) : base(replacedObject)
{
}
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public DispHTMLWindow2() : base()
{
}
/// <param name="progId">registered progID</param>
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public DispHTMLWindow2(string progId) : base(progId)
{
}
#endregion
#region Properties
/// <summary>
/// SupportByVersion MSHTML 4
/// Get
/// </summary>
[SupportByVersion("MSHTML", 4)]
public Int32 length
{
get
{
return Factory.ExecuteInt32PropertyGet(this, "length");
}
}
/// <summary>
/// SupportByVersion MSHTML 4
/// Get
/// </summary>
[SupportByVersion("MSHTML", 4)]
[BaseResult]
public NetOffice.MSHTMLApi.IHTMLFramesCollection2 frames
{
get
{
return Factory.ExecuteBaseReferencePropertyGet<NetOffice.MSHTMLApi.IHTMLFramesCollection2>(this, "frames");
}
}
/// <summary>
/// SupportByVersion MSHTML 4
/// Get/Set
/// </summary>
[SupportByVersion("MSHTML", 4)]
public string defaultStatus
{
get
{
return Factory.ExecuteStringPropertyGet(this, "defaultStatus");
}
set
{
Factory.ExecuteValuePropertySet(this, "defaultStatus", value);
}
}
/// <summary>
/// SupportByVersion MSHTML 4
/// Get/Set
/// </summary>
[SupportByVersion("MSHTML", 4)]
public string status
{
get
{
return Factory.ExecuteStringPropertyGet(this, "status");
}
set
{
Factory.ExecuteValuePropertySet(this, "status", value);
}
}
/// <summary>
/// SupportByVersion MSHTML 4
/// Get
/// </summary>
[SupportByVersion("MSHTML", 4)]
public NetOffice.MSHTMLApi.IHTMLLocation location
{
get
{
return Factory.ExecuteKnownReferencePropertyGet<NetOffice.MSHTMLApi.IHTMLLocation>(this, "location", NetOffice.MSHTMLApi.IHTMLLocation.LateBindingApiWrapperType);
}
}
/// <summary>
/// SupportByVersion MSHTML 4
/// Get
/// </summary>
[SupportByVersion("MSHTML", 4)]
public NetOffice.MSHTMLApi.IOmHistory history
{
get
{
return Factory.ExecuteKnownReferencePropertyGet<NetOffice.MSHTMLApi.IOmHistory>(this, "history", NetOffice.MSHTMLApi.IOmHistory.LateBindingApiWrapperType);
}
}
/// <summary>
/// SupportByVersion MSHTML 4
/// Get/Set
/// </summary>
[SupportByVersion("MSHTML", 4)]
public object opener
{
get
{
return Factory.ExecuteVariantPropertyGet(this, "opener");
}
set
{
Factory.ExecuteVariantPropertySet(this, "opener", value);
}
}
/// <summary>
/// SupportByVersion MSHTML 4
/// Get
/// </summary>
[SupportByVersion("MSHTML", 4)]
public NetOffice.MSHTMLApi.IOmNavigator navigator
{
get
{
return Factory.ExecuteKnownReferencePropertyGet<NetOffice.MSHTMLApi.IOmNavigator>(this, "navigator", NetOffice.MSHTMLApi.IOmNavigator.LateBindingApiWrapperType);
}
}
/// <summary>
/// SupportByVersion MSHTML 4
/// Get/Set
/// </summary>
[SupportByVersion("MSHTML", 4)]
public string name
{
get
{
return Factory.ExecuteStringPropertyGet(this, "name");
}
set
{
Factory.ExecuteValuePropertySet(this, "name", value);
}
}
/// <summary>
/// SupportByVersion MSHTML 4
/// Get
/// </summary>
[SupportByVersion("MSHTML", 4)]
public NetOffice.MSHTMLApi.IHTMLWindow2 parent
{
get
{
return Factory.ExecuteKnownReferencePropertyGet<NetOffice.MSHTMLApi.IHTMLWindow2>(this, "parent", NetOffice.MSHTMLApi.IHTMLWindow2.LateBindingApiWrapperType);
}
}
/// <summary>
/// SupportByVersion MSHTML 4
/// Get
/// </summary>
[SupportByVersion("MSHTML", 4)]
public NetOffice.MSHTMLApi.IHTMLWindow2 self
{
get
{
return Factory.ExecuteKnownReferencePropertyGet<NetOffice.MSHTMLApi.IHTMLWindow2>(this, "self", NetOffice.MSHTMLApi.IHTMLWindow2.LateBindingApiWrapperType);
}
}
/// <summary>
/// SupportByVersion MSHTML 4
/// Get
/// </summary>
[SupportByVersion("MSHTML", 4)]
public NetOffice.MSHTMLApi.IHTMLWindow2 top
{
get
{
return Factory.ExecuteKnownReferencePropertyGet<NetOffice.MSHTMLApi.IHTMLWindow2>(this, "top", NetOffice.MSHTMLApi.IHTMLWindow2.LateBindingApiWrapperType);
}
}
/// <summary>
/// SupportByVersion MSHTML 4
/// Get
/// </summary>
[SupportByVersion("MSHTML", 4)]
public NetOffice.MSHTMLApi.IHTMLWindow2 window
{
get
{
return Factory.ExecuteKnownReferencePropertyGet<NetOffice.MSHTMLApi.IHTMLWindow2>(this, "window", NetOffice.MSHTMLApi.IHTMLWindow2.LateBindingApiWrapperType);
}
}
/// <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 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 onload
{
get
{
return Factory.ExecuteVariantPropertyGet(this, "onload");
}
set
{
Factory.ExecuteVariantPropertySet(this, "onload", value);
}
}
/// <summary>
/// SupportByVersion MSHTML 4
/// Get/Set
/// </summary>
[SupportByVersion("MSHTML", 4)]
public object onbeforeunload
{
get
{
return Factory.ExecuteVariantPropertyGet(this, "onbeforeunload");
}
set
{
Factory.ExecuteVariantPropertySet(this, "onbeforeunload", value);
}
}
/// <summary>
/// SupportByVersion MSHTML 4
/// Get/Set
/// </summary>
[SupportByVersion("MSHTML", 4)]
public object onunload
{
get
{
return Factory.ExecuteVariantPropertyGet(this, "onunload");
}
set
{
Factory.ExecuteVariantPropertySet(this, "onunload", value);
}
}
/// <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 onerror
{
get
{
return Factory.ExecuteVariantPropertyGet(this, "onerror");
}
set
{
Factory.ExecuteVariantPropertySet(this, "onerror", 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/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
/// </summary>
[SupportByVersion("MSHTML", 4)]
public NetOffice.MSHTMLApi.IHTMLDocument2 document
{
get
{
return Factory.ExecuteKnownReferencePropertyGet<NetOffice.MSHTMLApi.IHTMLDocument2>(this, "document", NetOffice.MSHTMLApi.IHTMLDocument2.LateBindingApiWrapperType);
}
}
/// <summary>
/// SupportByVersion MSHTML 4
/// Get
/// </summary>
[SupportByVersion("MSHTML", 4)]
public NetOffice.MSHTMLApi.IHTMLEventObj get_event()
{
return Factory.ExecuteKnownReferencePropertyGet<NetOffice.MSHTMLApi.IHTMLEventObj>(this, "event", NetOffice.MSHTMLApi.IHTMLEventObj.LateBindingApiWrapperType);
}
/// <summary>
/// SupportByVersion MSHTML 4
/// Get
/// Unknown COM Proxy
/// </summary>
[SupportByVersion("MSHTML", 4), ProxyResult]
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public object _newEnum
{
get
{
return Factory.ExecuteReferencePropertyGet(this, "_newEnum");
}
}
/// <summary>
/// SupportByVersion MSHTML 4
/// Get
/// </summary>
[SupportByVersion("MSHTML", 4)]
[BaseResult]
public NetOffice.MSHTMLApi.IHTMLScreen screen
{
get
{
return Factory.ExecuteBaseReferencePropertyGet<NetOffice.MSHTMLApi.IHTMLScreen>(this, "screen");
}
}
/// <summary>
/// SupportByVersion MSHTML 4
/// Get
/// </summary>
[SupportByVersion("MSHTML", 4)]
public bool closed
{
get
{
return Factory.ExecuteBoolPropertyGet(this, "closed");
}
}
/// <summary>
/// SupportByVersion MSHTML 4
/// Get
/// </summary>
[SupportByVersion("MSHTML", 4)]
public NetOffice.MSHTMLApi.IOmNavigator clientInformation
{
get
{
return Factory.ExecuteKnownReferencePropertyGet<NetOffice.MSHTMLApi.IOmNavigator>(this, "clientInformation", NetOffice.MSHTMLApi.IOmNavigator.LateBindingApiWrapperType);
}
}
/// <summary>
/// SupportByVersion MSHTML 4
/// Get/Set
/// </summary>
[SupportByVersion("MSHTML", 4)]
public object offscreenBuffering
{
get
{
return Factory.ExecuteVariantPropertyGet(this, "offscreenBuffering");
}
set
{
Factory.ExecuteVariantPropertySet(this, "offscreenBuffering", value);
}
}
/// <summary>
/// SupportByVersion MSHTML 4
/// Get
/// Unknown COM Proxy
/// </summary>
[SupportByVersion("MSHTML", 4), ProxyResult]
public object external
{
get
{
return Factory.ExecuteReferencePropertyGet(this, "external");
}
}
/// <summary>
/// SupportByVersion MSHTML 4
/// Get
/// </summary>
[SupportByVersion("MSHTML", 4)]
public Int32 screenLeft
{
get
{
return Factory.ExecuteInt32PropertyGet(this, "screenLeft");
}
}
/// <summary>
/// SupportByVersion MSHTML 4
/// Get
/// </summary>
[SupportByVersion("MSHTML", 4)]
public Int32 screenTop
{
get
{
return Factory.ExecuteInt32PropertyGet(this, "screenTop");
}
}
/// <summary>
/// SupportByVersion MSHTML 4
/// Get/Set
/// </summary>
[SupportByVersion("MSHTML", 4)]
public object onbeforeprint
{
get
{
return Factory.ExecuteVariantPropertyGet(this, "onbeforeprint");
}
set
{
Factory.ExecuteVariantPropertySet(this, "onbeforeprint", value);
}
}
/// <summary>
/// SupportByVersion MSHTML 4
/// Get/Set
/// </summary>
[SupportByVersion("MSHTML", 4)]
public object onafterprint
{
get
{
return Factory.ExecuteVariantPropertyGet(this, "onafterprint");
}
set
{
Factory.ExecuteVariantPropertySet(this, "onafterprint", value);
}
}
/// <summary>
/// SupportByVersion MSHTML 4
/// Get
/// </summary>
[SupportByVersion("MSHTML", 4)]
public NetOffice.MSHTMLApi.IHTMLDataTransfer clipboardData
{
get
{
return Factory.ExecuteKnownReferencePropertyGet<NetOffice.MSHTMLApi.IHTMLDataTransfer>(this, "clipboardData", NetOffice.MSHTMLApi.IHTMLDataTransfer.LateBindingApiWrapperType);
}
}
/// <summary>
/// SupportByVersion MSHTML 4
/// Get
/// </summary>
[SupportByVersion("MSHTML", 4)]
[BaseResult]
public NetOffice.MSHTMLApi.IHTMLFrameBase frameElement
{
get
{
return Factory.ExecuteBaseReferencePropertyGet<NetOffice.MSHTMLApi.IHTMLFrameBase>(this, "frameElement");
}
}
/// <summary>
/// SupportByVersion MSHTML 4
/// Get
/// </summary>
[SupportByVersion("MSHTML", 4)]
public NetOffice.MSHTMLApi.IHTMLStorage sessionStorage
{
get
{
return Factory.ExecuteKnownReferencePropertyGet<NetOffice.MSHTMLApi.IHTMLStorage>(this, "sessionStorage", NetOffice.MSHTMLApi.IHTMLStorage.LateBindingApiWrapperType);
}
}
/// <summary>
/// SupportByVersion MSHTML 4
/// Get
/// </summary>
[SupportByVersion("MSHTML", 4)]
public NetOffice.MSHTMLApi.IHTMLStorage localStorage
{
get
{
return Factory.ExecuteKnownReferencePropertyGet<NetOffice.MSHTMLApi.IHTMLStorage>(this, "localStorage", NetOffice.MSHTMLApi.IHTMLStorage.LateBindingApiWrapperType);
}
}
/// <summary>
/// SupportByVersion MSHTML 4
/// Get/Set
/// </summary>
[SupportByVersion("MSHTML", 4)]
public object onhashchange
{
get
{
return Factory.ExecuteVariantPropertyGet(this, "onhashchange");
}
set
{
Factory.ExecuteVariantPropertySet(this, "onhashchange", value);
}
}
/// <summary>
/// SupportByVersion MSHTML 4
/// Get
/// </summary>
[SupportByVersion("MSHTML", 4)]
public Int32 maxConnectionsPerServer
{
get
{
return Factory.ExecuteInt32PropertyGet(this, "maxConnectionsPerServer");
}
}
/// <summary>
/// SupportByVersion MSHTML 4
/// Get/Set
/// </summary>
[SupportByVersion("MSHTML", 4)]
public object onmessage
{
get
{
return Factory.ExecuteVariantPropertyGet(this, "onmessage");
}
set
{
Factory.ExecuteVariantPropertySet(this, "onmessage", 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");
}
}
#endregion
#region Methods
/// <summary>
/// SupportByVersion MSHTML 4
/// </summary>
/// <param name="pvarIndex">object pvarIndex</param>
[SupportByVersion("MSHTML", 4)]
public object item(object pvarIndex)
{
return Factory.ExecuteVariantMethodGet(this, "item", pvarIndex);
}
/// <summary>
/// SupportByVersion MSHTML 4
/// </summary>
/// <param name="timerID">Int32 timerID</param>
[SupportByVersion("MSHTML", 4)]
public void clearTimeout(Int32 timerID)
{
Factory.ExecuteMethod(this, "clearTimeout", timerID);
}
/// <summary>
/// SupportByVersion MSHTML 4
/// </summary>
/// <param name="message">optional string message = </param>
[SupportByVersion("MSHTML", 4)]
public void alert(object message)
{
Factory.ExecuteMethod(this, "alert", message);
}
/// <summary>
/// SupportByVersion MSHTML 4
/// </summary>
[CustomMethod]
[SupportByVersion("MSHTML", 4)]
public void alert()
{
Factory.ExecuteMethod(this, "alert");
}
/// <summary>
/// SupportByVersion MSHTML 4
/// </summary>
/// <param name="message">optional string message = </param>
[SupportByVersion("MSHTML", 4)]
public bool confirm(object message)
{
return Factory.ExecuteBoolMethodGet(this, "confirm", message);
}
/// <summary>
/// SupportByVersion MSHTML 4
/// </summary>
[CustomMethod]
[SupportByVersion("MSHTML", 4)]
public bool confirm()
{
return Factory.ExecuteBoolMethodGet(this, "confirm");
}
/// <summary>
/// SupportByVersion MSHTML 4
/// </summary>
/// <param name="message">optional string message = </param>
/// <param name="defstr">optional string defstr = undefined</param>
[SupportByVersion("MSHTML", 4)]
public object prompt(object message, object defstr)
{
return Factory.ExecuteVariantMethodGet(this, "prompt", message, defstr);
}
/// <summary>
/// SupportByVersion MSHTML 4
/// </summary>
[CustomMethod]
[SupportByVersion("MSHTML", 4)]
public object prompt()
{
return Factory.ExecuteVariantMethodGet(this, "prompt");
}
/// <summary>
/// SupportByVersion MSHTML 4
/// </summary>
/// <param name="message">optional string message = </param>
[CustomMethod]
[SupportByVersion("MSHTML", 4)]
public object prompt(object message)
{
return Factory.ExecuteVariantMethodGet(this, "prompt", message);
}
/// <summary>
/// SupportByVersion MSHTML 4
/// </summary>
[SupportByVersion("MSHTML", 4)]
public void close()
{
Factory.ExecuteMethod(this, "close");
}
/// <summary>
/// SupportByVersion MSHTML 4
/// </summary>
/// <param name="url">optional string url = </param>
/// <param name="name">optional string name = </param>
/// <param name="features">optional string features = </param>
/// <param name="replace">optional bool replace = false</param>
[SupportByVersion("MSHTML", 4)]
public NetOffice.MSHTMLApi.IHTMLWindow2 open(object url, object name, object features, object replace)
{
return Factory.ExecuteKnownReferenceMethodGet<NetOffice.MSHTMLApi.IHTMLWindow2>(this, "open", NetOffice.MSHTMLApi.IHTMLWindow2.LateBindingApiWrapperType, url, name, features, replace);
}
/// <summary>
/// SupportByVersion MSHTML 4
/// </summary>
[CustomMethod]
[SupportByVersion("MSHTML", 4)]
public NetOffice.MSHTMLApi.IHTMLWindow2 open()
{
return Factory.ExecuteKnownReferenceMethodGet<NetOffice.MSHTMLApi.IHTMLWindow2>(this, "open", NetOffice.MSHTMLApi.IHTMLWindow2.LateBindingApiWrapperType);
}
/// <summary>
/// SupportByVersion MSHTML 4
/// </summary>
/// <param name="url">optional string url = </param>
[CustomMethod]
[SupportByVersion("MSHTML", 4)]
public NetOffice.MSHTMLApi.IHTMLWindow2 open(object url)
{
return Factory.ExecuteKnownReferenceMethodGet<NetOffice.MSHTMLApi.IHTMLWindow2>(this, "open", NetOffice.MSHTMLApi.IHTMLWindow2.LateBindingApiWrapperType, url);
}
/// <summary>
/// SupportByVersion MSHTML 4
/// </summary>
/// <param name="url">optional string url = </param>
/// <param name="name">optional string name = </param>
[CustomMethod]
[SupportByVersion("MSHTML", 4)]
public NetOffice.MSHTMLApi.IHTMLWindow2 open(object url, object name)
{
return Factory.ExecuteKnownReferenceMethodGet<NetOffice.MSHTMLApi.IHTMLWindow2>(this, "open", NetOffice.MSHTMLApi.IHTMLWindow2.LateBindingApiWrapperType, url, name);
}
/// <summary>
/// SupportByVersion MSHTML 4
/// </summary>
/// <param name="url">optional string url = </param>
/// <param name="name">optional string name = </param>
/// <param name="features">optional string features = </param>
[CustomMethod]
[SupportByVersion("MSHTML", 4)]
public NetOffice.MSHTMLApi.IHTMLWindow2 open(object url, object name, object features)
{
return Factory.ExecuteKnownReferenceMethodGet<NetOffice.MSHTMLApi.IHTMLWindow2>(this, "open", NetOffice.MSHTMLApi.IHTMLWindow2.LateBindingApiWrapperType, url, name, features);
}
/// <summary>
/// SupportByVersion MSHTML 4
/// </summary>
/// <param name="url">string url</param>
[SupportByVersion("MSHTML", 4)]
public void navigate(string url)
{
Factory.ExecuteMethod(this, "navigate", url);
}
/// <summary>
/// SupportByVersion MSHTML 4
/// </summary>
/// <param name="dialog">string dialog</param>
/// <param name="varArgIn">optional object varArgIn</param>
/// <param name="varOptions">optional object varOptions</param>
[SupportByVersion("MSHTML", 4)]
public object showModalDialog(string dialog, object varArgIn, object varOptions)
{
return Factory.ExecuteVariantMethodGet(this, "showModalDialog", dialog, varArgIn, varOptions);
}
/// <summary>
/// SupportByVersion MSHTML 4
/// </summary>
/// <param name="dialog">string dialog</param>
[CustomMethod]
[SupportByVersion("MSHTML", 4)]
public object showModalDialog(string dialog)
{
return Factory.ExecuteVariantMethodGet(this, "showModalDialog", dialog);
}
/// <summary>
/// SupportByVersion MSHTML 4
/// </summary>
/// <param name="dialog">string dialog</param>
/// <param name="varArgIn">optional object varArgIn</param>
[CustomMethod]
[SupportByVersion("MSHTML", 4)]
public object showModalDialog(string dialog, object varArgIn)
{
return Factory.ExecuteVariantMethodGet(this, "showModalDialog", dialog, varArgIn);
}
/// <summary>
/// SupportByVersion MSHTML 4
/// </summary>
/// <param name="helpURL">string helpURL</param>
/// <param name="helpArg">optional object helpArg</param>
/// <param name="features">optional string features = </param>
[SupportByVersion("MSHTML", 4)]
public void showHelp(string helpURL, object helpArg, object features)
{
Factory.ExecuteMethod(this, "showHelp", helpURL, helpArg, features);
}
/// <summary>
/// SupportByVersion MSHTML 4
/// </summary>
/// <param name="helpURL">string helpURL</param>
[CustomMethod]
[SupportByVersion("MSHTML", 4)]
public void showHelp(string helpURL)
{
Factory.ExecuteMethod(this, "showHelp", helpURL);
}
/// <summary>
/// SupportByVersion MSHTML 4
/// </summary>
/// <param name="helpURL">string helpURL</param>
/// <param name="helpArg">optional object helpArg</param>
[CustomMethod]
[SupportByVersion("MSHTML", 4)]
public void showHelp(string helpURL, object helpArg)
{
Factory.ExecuteMethod(this, "showHelp", helpURL, helpArg);
}
/// <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="x">Int32 x</param>
/// <param name="y">Int32 y</param>
[SupportByVersion("MSHTML", 4)]
public void scroll(Int32 x, Int32 y)
{
Factory.ExecuteMethod(this, "scroll", x, y);
}
/// <summary>
/// SupportByVersion MSHTML 4
/// </summary>
/// <param name="timerID">Int32 timerID</param>
[SupportByVersion("MSHTML", 4)]
public void clearInterval(Int32 timerID)
{
Factory.ExecuteMethod(this, "clearInterval", timerID);
}
/// <summary>
/// SupportByVersion MSHTML 4
/// </summary>
/// <param name="code">string code</param>
/// <param name="language">optional string language = jScript</param>
[SupportByVersion("MSHTML", 4)]
public object execScript(string code, object language)
{
return Factory.ExecuteVariantMethodGet(this, "execScript", code, language);
}
/// <summary>
/// SupportByVersion MSHTML 4
/// </summary>
/// <param name="code">string code</param>
[CustomMethod]
[SupportByVersion("MSHTML", 4)]
public object execScript(string code)
{
return Factory.ExecuteVariantMethodGet(this, "execScript", code);
}
/// <summary>
/// SupportByVersion MSHTML 4
/// </summary>
[SupportByVersion("MSHTML", 4)]
public string toString()
{
return Factory.ExecuteStringMethodGet(this, "toString");
}
/// <summary>
/// SupportByVersion MSHTML 4
/// </summary>
/// <param name="x">Int32 x</param>
/// <param name="y">Int32 y</param>
[SupportByVersion("MSHTML", 4)]
public void scrollBy(Int32 x, Int32 y)
{
Factory.ExecuteMethod(this, "scrollBy", x, y);
}
/// <summary>
/// SupportByVersion MSHTML 4
/// </summary>
/// <param name="x">Int32 x</param>
/// <param name="y">Int32 y</param>
[SupportByVersion("MSHTML", 4)]
public void scrollTo(Int32 x, Int32 y)
{
Factory.ExecuteMethod(this, "scrollTo", x, y);
}
/// <summary>
/// SupportByVersion MSHTML 4
/// </summary>
/// <param name="x">Int32 x</param>
/// <param name="y">Int32 y</param>
[SupportByVersion("MSHTML", 4)]
public void moveTo(Int32 x, Int32 y)
{
Factory.ExecuteMethod(this, "moveTo", x, y);
}
/// <summary>
/// SupportByVersion MSHTML 4
/// </summary>
/// <param name="x">Int32 x</param>
/// <param name="y">Int32 y</param>
[SupportByVersion("MSHTML", 4)]
public void moveBy(Int32 x, Int32 y)
{
Factory.ExecuteMethod(this, "moveBy", x, y);
}
/// <summary>
/// SupportByVersion MSHTML 4
/// </summary>
/// <param name="x">Int32 x</param>
/// <param name="y">Int32 y</param>
[SupportByVersion("MSHTML", 4)]
public void resizeTo(Int32 x, Int32 y)
{
Factory.ExecuteMethod(this, "resizeTo", x, y);
}
/// <summary>
/// SupportByVersion MSHTML 4
/// </summary>
/// <param name="x">Int32 x</param>
/// <param name="y">Int32 y</param>
[SupportByVersion("MSHTML", 4)]
public void resizeBy(Int32 x, Int32 y)
{
Factory.ExecuteMethod(this, "resizeBy", x, y);
}
/// <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>
/// <param name="expression">object expression</param>
/// <param name="msec">Int32 msec</param>
/// <param name="language">optional object language</param>
[SupportByVersion("MSHTML", 4)]
public Int32 setTimeout(object expression, Int32 msec, object language)
{
return Factory.ExecuteInt32MethodGet(this, "setTimeout", expression, msec, language);
}
/// <summary>
/// SupportByVersion MSHTML 4
/// </summary>
/// <param name="expression">object expression</param>
/// <param name="msec">Int32 msec</param>
[CustomMethod]
[SupportByVersion("MSHTML", 4)]
public Int32 setTimeout(object expression, Int32 msec)
{
return Factory.ExecuteInt32MethodGet(this, "setTimeout", expression, msec);
}
/// <summary>
/// SupportByVersion MSHTML 4
/// </summary>
/// <param name="expression">object expression</param>
/// <param name="msec">Int32 msec</param>
/// <param name="language">optional object language</param>
[SupportByVersion("MSHTML", 4)]
public Int32 setInterval(object expression, Int32 msec, object language)
{
return Factory.ExecuteInt32MethodGet(this, "setInterval", expression, msec, language);
}
/// <summary>
/// SupportByVersion MSHTML 4
/// </summary>
/// <param name="expression">object expression</param>
/// <param name="msec">Int32 msec</param>
[CustomMethod]
[SupportByVersion("MSHTML", 4)]
public Int32 setInterval(object expression, Int32 msec)
{
return Factory.ExecuteInt32MethodGet(this, "setInterval", expression, msec);
}
/// <summary>
/// SupportByVersion MSHTML 4
/// </summary>
[SupportByVersion("MSHTML", 4)]
public void print()
{
Factory.ExecuteMethod(this, "print");
}
/// <summary>
/// SupportByVersion MSHTML 4
/// </summary>
/// <param name="url">optional string url = </param>
/// <param name="varArgIn">optional object varArgIn</param>
/// <param name="options">optional object options</param>
[SupportByVersion("MSHTML", 4)]
public NetOffice.MSHTMLApi.IHTMLWindow2 showModelessDialog(object url, object varArgIn, object options)
{
return Factory.ExecuteKnownReferenceMethodGet<NetOffice.MSHTMLApi.IHTMLWindow2>(this, "showModelessDialog", NetOffice.MSHTMLApi.IHTMLWindow2.LateBindingApiWrapperType, url, varArgIn, options);
}
/// <summary>
/// SupportByVersion MSHTML 4
/// </summary>
[CustomMethod]
[SupportByVersion("MSHTML", 4)]
public NetOffice.MSHTMLApi.IHTMLWindow2 showModelessDialog()
{
return Factory.ExecuteKnownReferenceMethodGet<NetOffice.MSHTMLApi.IHTMLWindow2>(this, "showModelessDialog", NetOffice.MSHTMLApi.IHTMLWindow2.LateBindingApiWrapperType);
}
/// <summary>
/// SupportByVersion MSHTML 4
/// </summary>
/// <param name="url">optional string url = </param>
[CustomMethod]
[SupportByVersion("MSHTML", 4)]
public NetOffice.MSHTMLApi.IHTMLWindow2 showModelessDialog(object url)
{
return Factory.ExecuteKnownReferenceMethodGet<NetOffice.MSHTMLApi.IHTMLWindow2>(this, "showModelessDialog", NetOffice.MSHTMLApi.IHTMLWindow2.LateBindingApiWrapperType, url);
}
/// <summary>
/// SupportByVersion MSHTML 4
/// </summary>
/// <param name="url">optional string url = </param>
/// <param name="varArgIn">optional object varArgIn</param>
[CustomMethod]
[SupportByVersion("MSHTML", 4)]
public NetOffice.MSHTMLApi.IHTMLWindow2 showModelessDialog(object url, object varArgIn)
{
return Factory.ExecuteKnownReferenceMethodGet<NetOffice.MSHTMLApi.IHTMLWindow2>(this, "showModelessDialog", NetOffice.MSHTMLApi.IHTMLWindow2.LateBindingApiWrapperType, url, varArgIn);
}
/// <summary>
/// SupportByVersion MSHTML 4
/// </summary>
/// <param name="varArgIn">optional object varArgIn</param>
[SupportByVersion("MSHTML", 4)]
public object createPopup(object varArgIn)
{
return Factory.ExecuteVariantMethodGet(this, "createPopup", varArgIn);
}
/// <summary>
/// SupportByVersion MSHTML 4
/// </summary>
[CustomMethod]
[SupportByVersion("MSHTML", 4)]
public object createPopup()
{
return Factory.ExecuteVariantMethodGet(this, "createPopup");
}
/// <summary>
/// SupportByVersion MSHTML 4
/// </summary>
/// <param name="msg">string msg</param>
/// <param name="targetOrigin">optional object targetOrigin</param>
[SupportByVersion("MSHTML", 4)]
public void postMessage(string msg, object targetOrigin)
{
Factory.ExecuteMethod(this, "postMessage", msg, targetOrigin);
}
/// <summary>
/// SupportByVersion MSHTML 4
/// </summary>
/// <param name="msg">string msg</param>
[CustomMethod]
[SupportByVersion("MSHTML", 4)]
public void postMessage(string msg)
{
Factory.ExecuteMethod(this, "postMessage", msg);
}
/// <summary>
/// SupportByVersion MSHTML 4
/// </summary>
/// <param name="bstrHTML">string bstrHTML</param>
[SupportByVersion("MSHTML", 4)]
public string toStaticHTML(string bstrHTML)
{
return Factory.ExecuteStringMethodGet(this, "toStaticHTML", bstrHTML);
}
/// <summary>
/// SupportByVersion MSHTML 4
/// </summary>
/// <param name="bstrProfilerMarkName">string bstrProfilerMarkName</param>
[SupportByVersion("MSHTML", 4)]
public void msWriteProfilerMark(string bstrProfilerMarkName)
{
Factory.ExecuteMethod(this, "msWriteProfilerMark", bstrProfilerMarkName);
}
#endregion
#pragma warning restore
}
}
| mit |
PomeloFoundation/Pomelo.EntityFrameworkCore.MySql | src/EFCore.MySql/Query/Internal/MySqlDateTimeMemberTranslator.cs | 5942 | // Copyright (c) Pomelo Foundation. All rights reserved.
// Licensed under the MIT. See LICENSE in the project root for license information.
using System;
using System.Collections.Generic;
using System.Reflection;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Diagnostics;
using Microsoft.EntityFrameworkCore.Query;
using Microsoft.EntityFrameworkCore.Query.SqlExpressions;
namespace Pomelo.EntityFrameworkCore.MySql.Query.Internal
{
public class MySqlDateTimeMemberTranslator : IMemberTranslator
{
private static readonly Dictionary<string, (string Part, int Divisor)> _datePartMapping
= new Dictionary<string, (string, int)>
{
{ nameof(DateTime.Year), ("year", 1) },
{ nameof(DateTime.Month), ("month", 1) },
{ nameof(DateTime.Day), ("day", 1) },
{ nameof(DateTime.Hour), ("hour", 1) },
{ nameof(DateTime.Minute), ("minute", 1) },
{ nameof(DateTime.Second), ("second", 1) },
{ nameof(DateTime.Millisecond), ("microsecond", 1000) },
};
private readonly MySqlSqlExpressionFactory _sqlExpressionFactory;
public MySqlDateTimeMemberTranslator(ISqlExpressionFactory sqlExpressionFactory)
{
_sqlExpressionFactory = (MySqlSqlExpressionFactory)sqlExpressionFactory;
}
public virtual SqlExpression Translate(
SqlExpression instance,
MemberInfo member,
Type returnType,
IDiagnosticsLogger<DbLoggerCategory.Query> logger)
{
var declaringType = member.DeclaringType;
if (declaringType == typeof(DateTime)
|| declaringType == typeof(DateTimeOffset)
|| declaringType == typeof(DateOnly)
|| declaringType == typeof(TimeOnly))
{
var memberName = member.Name;
if (_datePartMapping.TryGetValue(memberName, out var datePart))
{
var extract = _sqlExpressionFactory.NullableFunction(
"EXTRACT",
new[]
{
_sqlExpressionFactory.ComplexFunctionArgument(
new [] {
_sqlExpressionFactory.Fragment($"{datePart.Part} FROM"),
instance
},
" ",
typeof(string))
},
returnType,
false);
if (datePart.Divisor != 1)
{
return _sqlExpressionFactory.MySqlIntegerDivide(
extract,
_sqlExpressionFactory.Constant(datePart.Divisor));
}
return extract;
}
switch (memberName)
{
case nameof(DateTime.DayOfYear):
return _sqlExpressionFactory.NullableFunction(
"DAYOFYEAR",
new[] { instance },
returnType,
false);
case nameof(DateTime.Date):
return _sqlExpressionFactory.NullableFunction(
"CONVERT",
new[]{
instance,
_sqlExpressionFactory.Fragment("date")
},
returnType,
false);
case nameof(DateTime.TimeOfDay):
return _sqlExpressionFactory.Convert(instance, returnType);
case nameof(DateTime.Now):
return _sqlExpressionFactory.NonNullableFunction(
declaringType == typeof(DateTimeOffset)
? "UTC_TIMESTAMP"
: "CURRENT_TIMESTAMP",
Array.Empty<SqlExpression>(),
returnType);
case nameof(DateTime.UtcNow):
return _sqlExpressionFactory.NonNullableFunction(
"UTC_TIMESTAMP",
Array.Empty<SqlExpression>(),
returnType);
case nameof(DateTime.Today):
return _sqlExpressionFactory.NonNullableFunction(
declaringType == typeof(DateTimeOffset)
? "UTC_DATE"
: "CURDATE",
Array.Empty<SqlExpression>(),
returnType);
case nameof(DateTime.DayOfWeek):
return _sqlExpressionFactory.Subtract(
_sqlExpressionFactory.NullableFunction(
"DAYOFWEEK",
new[] { instance },
returnType,
false),
_sqlExpressionFactory.Constant(1));
}
}
if (declaringType == typeof(DateOnly))
{
if (member.Name == nameof(DateOnly.DayNumber))
{
return _sqlExpressionFactory.Subtract(
_sqlExpressionFactory.NullableFunction(
"TO_DAYS",
new[] { instance },
returnType),
_sqlExpressionFactory.Constant(366));
}
}
return null;
}
}
}
| mit |
rebroad/bitcoin | src/qt/clientmodel.cpp | 10120 | // Copyright (c) 2011-2016 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "clientmodel.h"
#include "bantablemodel.h"
#include "guiconstants.h"
#include "guiutil.h"
#include "peertablemodel.h"
#include "chainparams.h"
#include "checkpoints.h"
#include "clientversion.h"
#include "validation.h"
#include "net.h"
#include "stats/stats.h"
#include "txmempool.h"
#include "ui_interface.h"
#include "util.h"
#include <stdint.h>
#include <QDebug>
#include <QTimer>
class CBlockIndex;
static const int64_t nClientStartupTime = GetTime();
static int64_t nLastHeaderTipUpdateNotification = 0;
static int64_t nLastBlockTipUpdateNotification = 0;
ClientModel::ClientModel(OptionsModel *_optionsModel, QObject *parent) :
QObject(parent),
optionsModel(_optionsModel),
peerTableModel(0),
banTableModel(0),
pollTimer(0)
{
peerTableModel = new PeerTableModel(this);
banTableModel = new BanTableModel(this);
pollTimer = new QTimer(this);
connect(pollTimer, SIGNAL(timeout()), this, SLOT(updateTimer()));
pollTimer->start(MODEL_UPDATE_DELAY);
subscribeToCoreSignals();
}
ClientModel::~ClientModel()
{
unsubscribeFromCoreSignals();
}
int ClientModel::getNumConnections(unsigned int flags) const
{
CConnman::NumConnections connections = CConnman::CONNECTIONS_NONE;
if(flags == CONNECTIONS_IN)
connections = CConnman::CONNECTIONS_IN;
else if (flags == CONNECTIONS_OUT)
connections = CConnman::CONNECTIONS_OUT;
else if (flags == CONNECTIONS_ALL)
connections = CConnman::CONNECTIONS_ALL;
if(g_connman)
return g_connman->GetNodeCount(connections);
return 0;
}
int ClientModel::getNumBlocks() const
{
LOCK(cs_main);
return chainActive.Height();
}
int ClientModel::getHeaderTipHeight() const
{
LOCK(cs_main);
if (!pindexBestHeader)
return 0;
return pindexBestHeader->nHeight;
}
int64_t ClientModel::getHeaderTipTime() const
{
LOCK(cs_main);
if (!pindexBestHeader)
return 0;
return pindexBestHeader->GetBlockTime();
}
quint64 ClientModel::getTotalBytesRecv() const
{
if(!g_connman)
return 0;
return g_connman->GetTotalBytesRecv();
}
quint64 ClientModel::getTotalBytesSent() const
{
if(!g_connman)
return 0;
return g_connman->GetTotalBytesSent();
}
QDateTime ClientModel::getLastBlockDate() const
{
LOCK(cs_main);
if (chainActive.Tip())
return QDateTime::fromTime_t(chainActive.Tip()->GetBlockTime());
return QDateTime::fromTime_t(Params().GenesisBlock().GetBlockTime()); // Genesis block's time of current network
}
long ClientModel::getMempoolSize() const
{
return mempool.size();
}
size_t ClientModel::getMempoolDynamicUsage() const
{
return mempool.DynamicMemoryUsage();
}
double ClientModel::getVerificationProgress(const CBlockIndex *tipIn) const
{
CBlockIndex *tip = const_cast<CBlockIndex *>(tipIn);
if (!tip)
{
LOCK(cs_main);
tip = chainActive.Tip();
}
return GuessVerificationProgress(Params().TxData(), tip);
}
void ClientModel::updateTimer()
{
// no locking required at this point
// the following calls will acquire the required lock
Q_EMIT mempoolSizeChanged(getMempoolSize(), getMempoolDynamicUsage());
Q_EMIT bytesChanged(getTotalBytesRecv(), getTotalBytesSent());
}
void ClientModel::updateNumConnections(int numConnections)
{
Q_EMIT numConnectionsChanged(numConnections);
}
void ClientModel::updateNetworkActive(bool networkActive)
{
Q_EMIT networkActiveChanged(networkActive);
}
void ClientModel::updateAlert()
{
Q_EMIT alertsChanged(getStatusBarWarnings());
}
bool ClientModel::inInitialBlockDownload() const
{
return IsInitialBlockDownload();
}
enum BlockSource ClientModel::getBlockSource() const
{
if (fReindex)
return BLOCK_SOURCE_REINDEX;
else if (fImporting)
return BLOCK_SOURCE_DISK;
else if (getNumConnections() > 0)
return BLOCK_SOURCE_NETWORK;
return BLOCK_SOURCE_NONE;
}
void ClientModel::setNetworkActive(bool active)
{
if (g_connman) {
g_connman->SetNetworkActive(active);
}
}
bool ClientModel::getNetworkActive() const
{
if (g_connman) {
return g_connman->GetNetworkActive();
}
return false;
}
QString ClientModel::getStatusBarWarnings() const
{
return QString::fromStdString(GetWarnings("gui"));
}
OptionsModel *ClientModel::getOptionsModel()
{
return optionsModel;
}
PeerTableModel *ClientModel::getPeerTableModel()
{
return peerTableModel;
}
BanTableModel *ClientModel::getBanTableModel()
{
return banTableModel;
}
QString ClientModel::formatFullVersion() const
{
return QString::fromStdString(FormatFullVersion());
}
QString ClientModel::formatSubVersion() const
{
return QString::fromStdString(strSubVersion);
}
bool ClientModel::isReleaseVersion() const
{
return CLIENT_VERSION_IS_RELEASE;
}
QString ClientModel::formatClientStartupTime() const
{
return QDateTime::fromTime_t(nClientStartupTime).toString();
}
QString ClientModel::dataDir() const
{
return GUIUtil::boostPathToQString(GetDataDir());
}
void ClientModel::updateBanlist()
{
banTableModel->refresh();
}
void ClientModel::updateMempoolStats()
{
Q_EMIT mempoolStatsDidUpdate();
}
mempoolSamples_t ClientModel::getMempoolStatsInRange(QDateTime &from, QDateTime &to)
{
// get stats from the core stats model
uint64_t timeFrom = from.toTime_t();
uint64_t timeTo = to.toTime_t();
mempoolSamples_t samples = CStats::DefaultStats()->mempoolGetValuesInRange(timeFrom,timeTo);
from.setTime_t(timeFrom);
to.setTime_t(timeTo);
return samples;
}
// Handlers for core signals
static void ShowProgress(ClientModel *clientmodel, const std::string &title, int nProgress)
{
// emits signal "showProgress"
QMetaObject::invokeMethod(clientmodel, "showProgress", Qt::QueuedConnection,
Q_ARG(QString, QString::fromStdString(title)),
Q_ARG(int, nProgress));
}
static void NotifyNumConnectionsChanged(ClientModel *clientmodel, int newNumConnections)
{
// Too noisy: qDebug() << "NotifyNumConnectionsChanged: " + QString::number(newNumConnections);
QMetaObject::invokeMethod(clientmodel, "updateNumConnections", Qt::QueuedConnection,
Q_ARG(int, newNumConnections));
}
static void NotifyNetworkActiveChanged(ClientModel *clientmodel, bool networkActive)
{
QMetaObject::invokeMethod(clientmodel, "updateNetworkActive", Qt::QueuedConnection,
Q_ARG(bool, networkActive));
}
static void NotifyAlertChanged(ClientModel *clientmodel)
{
qDebug() << "NotifyAlertChanged";
QMetaObject::invokeMethod(clientmodel, "updateAlert", Qt::QueuedConnection);
}
static void BannedListChanged(ClientModel *clientmodel)
{
qDebug() << QString("%1: Requesting update for peer banlist").arg(__func__);
QMetaObject::invokeMethod(clientmodel, "updateBanlist", Qt::QueuedConnection);
}
static void BlockTipChanged(ClientModel *clientmodel, bool initialSync, const CBlockIndex *pIndex, bool fHeader)
{
// lock free async UI updates in case we have a new block tip
// during initial sync, only update the UI if the last update
// was > 250ms (MODEL_UPDATE_DELAY) ago
int64_t now = 0;
if (initialSync)
now = GetTimeMillis();
int64_t& nLastUpdateNotification = fHeader ? nLastHeaderTipUpdateNotification : nLastBlockTipUpdateNotification;
// if we are in-sync, update the UI regardless of last update time
if (!initialSync || now - nLastUpdateNotification > MODEL_UPDATE_DELAY) {
//pass a async signal to the UI thread
QMetaObject::invokeMethod(clientmodel, "numBlocksChanged", Qt::QueuedConnection,
Q_ARG(int, pIndex->nHeight),
Q_ARG(QDateTime, QDateTime::fromTime_t(pIndex->GetBlockTime())),
Q_ARG(double, clientmodel->getVerificationProgress(pIndex)),
Q_ARG(bool, fHeader));
nLastUpdateNotification = now;
}
}
static void MempoolStatsDidChange(ClientModel *clientmodel)
{
QMetaObject::invokeMethod(clientmodel, "updateMempoolStats", Qt::QueuedConnection);
}
void ClientModel::subscribeToCoreSignals()
{
// Connect signals to client
uiInterface.ShowProgress.connect(boost::bind(ShowProgress, this, _1, _2));
uiInterface.NotifyNumConnectionsChanged.connect(boost::bind(NotifyNumConnectionsChanged, this, _1));
uiInterface.NotifyNetworkActiveChanged.connect(boost::bind(NotifyNetworkActiveChanged, this, _1));
uiInterface.NotifyAlertChanged.connect(boost::bind(NotifyAlertChanged, this));
uiInterface.BannedListChanged.connect(boost::bind(BannedListChanged, this));
uiInterface.NotifyBlockTip.connect(boost::bind(BlockTipChanged, this, _1, _2, false));
uiInterface.NotifyHeaderTip.connect(boost::bind(BlockTipChanged, this, _1, _2, true));
CStats::DefaultStats()->MempoolStatsDidChange.connect(boost::bind(MempoolStatsDidChange, this));
}
void ClientModel::unsubscribeFromCoreSignals()
{
// Disconnect signals from client
uiInterface.ShowProgress.disconnect(boost::bind(ShowProgress, this, _1, _2));
uiInterface.NotifyNumConnectionsChanged.disconnect(boost::bind(NotifyNumConnectionsChanged, this, _1));
uiInterface.NotifyNetworkActiveChanged.disconnect(boost::bind(NotifyNetworkActiveChanged, this, _1));
uiInterface.NotifyAlertChanged.disconnect(boost::bind(NotifyAlertChanged, this));
uiInterface.BannedListChanged.disconnect(boost::bind(BannedListChanged, this));
uiInterface.NotifyBlockTip.disconnect(boost::bind(BlockTipChanged, this, _1, _2, false));
uiInterface.NotifyHeaderTip.disconnect(boost::bind(BlockTipChanged, this, _1, _2, true));
CStats::DefaultStats()->MempoolStatsDidChange.disconnect(boost::bind(MempoolStatsDidChange, this));
}
| mit |
ohmygodvt95/wevivu | vendor/assets/components/moment/locale/pa-in.js | 4770 | //! moment.js locale configuration
//! locale : Punjabi (India) [pa-in]
//! author : Harpreet Singh : https://github.com/harpreetkhalsagtbit
;(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined'
&& typeof require === 'function' ? factory(require('../moment')) :
typeof define === 'function' && define.amd ? define(['../moment'], factory) :
factory(global.moment)
}(this, (function (moment) {
'use strict';
var symbolMap = {
'1': '੧',
'2': '੨',
'3': '੩',
'4': '੪',
'5': '੫',
'6': '੬',
'7': '੭',
'8': '੮',
'9': '੯',
'0': '੦'
};
var numberMap = {
'੧': '1',
'੨': '2',
'੩': '3',
'੪': '4',
'੫': '5',
'੬': '6',
'੭': '7',
'੮': '8',
'੯': '9',
'੦': '0'
};
var paIn = moment.defineLocale('pa-in', {
// There are months name as per Nanakshahi Calender but they are not used as rigidly in modern Punjabi.
months: 'ਜਨਵਰੀ_ਫ਼ਰਵਰੀ_ਮਾਰਚ_ਅਪ੍ਰੈਲ_ਮਈ_ਜੂਨ_ਜੁਲਾਈ_ਅਗਸਤ_ਸਤੰਬਰ_ਅਕਤੂਬਰ_ਨਵੰਬਰ_ਦਸੰਬਰ'.split('_'),
monthsShort: 'ਜਨਵਰੀ_ਫ਼ਰਵਰੀ_ਮਾਰਚ_ਅਪ੍ਰੈਲ_ਮਈ_ਜੂਨ_ਜੁਲਾਈ_ਅਗਸਤ_ਸਤੰਬਰ_ਅਕਤੂਬਰ_ਨਵੰਬਰ_ਦਸੰਬਰ'.split('_'),
weekdays: 'ਐਤਵਾਰ_ਸੋਮਵਾਰ_ਮੰਗਲਵਾਰ_ਬੁਧਵਾਰ_ਵੀਰਵਾਰ_ਸ਼ੁੱਕਰਵਾਰ_ਸ਼ਨੀਚਰਵਾਰ'.split('_'),
weekdaysShort: 'ਐਤ_ਸੋਮ_ਮੰਗਲ_ਬੁਧ_ਵੀਰ_ਸ਼ੁਕਰ_ਸ਼ਨੀ'.split('_'),
weekdaysMin: 'ਐਤ_ਸੋਮ_ਮੰਗਲ_ਬੁਧ_ਵੀਰ_ਸ਼ੁਕਰ_ਸ਼ਨੀ'.split('_'),
longDateFormat: {
LT: 'A h:mm ਵਜੇ',
LTS: 'A h:mm:ss ਵਜੇ',
L: 'DD/MM/YYYY',
LL: 'D MMMM YYYY',
LLL: 'D MMMM YYYY, A h:mm ਵਜੇ',
LLLL: 'dddd, D MMMM YYYY, A h:mm ਵਜੇ'
},
calendar: {
sameDay: '[ਅਜ] LT',
nextDay: '[ਕਲ] LT',
nextWeek: 'dddd, LT',
lastDay: '[ਕਲ] LT',
lastWeek: '[ਪਿਛਲੇ] dddd, LT',
sameElse: 'L'
},
relativeTime: {
future: '%s ਵਿੱਚ',
past: '%s ਪਿਛਲੇ',
s: 'ਕੁਝ ਸਕਿੰਟ',
m: 'ਇਕ ਮਿੰਟ',
mm: '%d ਮਿੰਟ',
h: 'ਇੱਕ ਘੰਟਾ',
hh: '%d ਘੰਟੇ',
d: 'ਇੱਕ ਦਿਨ',
dd: '%d ਦਿਨ',
M: 'ਇੱਕ ਮਹੀਨਾ',
MM: '%d ਮਹੀਨੇ',
y: 'ਇੱਕ ਸਾਲ',
yy: '%d ਸਾਲ'
},
preparse: function (string) {
return string.replace(/[੧੨੩੪੫੬੭੮੯੦]/g, function (match) {
return numberMap[match];
});
},
postformat: function (string) {
return string.replace(/\d/g, function (match) {
return symbolMap[match];
});
},
// Punjabi notation for meridiems are quite fuzzy in practice. While there exists
// a rigid notion of a 'Pahar' it is not used as rigidly in modern Punjabi.
meridiemParse: /ਰਾਤ|ਸਵੇਰ|ਦੁਪਹਿਰ|ਸ਼ਾਮ/,
meridiemHour: function (hour, meridiem) {
if (hour === 12) {
hour = 0;
}
if (meridiem === 'ਰਾਤ') {
return hour < 4 ? hour : hour + 12;
} else if (meridiem === 'ਸਵੇਰ') {
return hour;
} else if (meridiem === 'ਦੁਪਹਿਰ') {
return hour >= 10 ? hour : hour + 12;
} else if (meridiem === 'ਸ਼ਾਮ') {
return hour + 12;
}
},
meridiem: function (hour, minute, isLower) {
if (hour < 4) {
return 'ਰਾਤ';
} else if (hour < 10) {
return 'ਸਵੇਰ';
} else if (hour < 17) {
return 'ਦੁਪਹਿਰ';
} else if (hour < 20) {
return 'ਸ਼ਾਮ';
} else {
return 'ਰਾਤ';
}
},
week: {
dow: 0, // Sunday is the first day of the week.
doy: 6 // The week that contains Jan 1st is the first week of the year.
}
});
return paIn;
})));
| mit |
atton16/bluerpc | lib/spec/http.js | 139 | 'use strict';
var BlueRPC = require('../../lib');
describe('HTTP', require('./tests.skip.js')(BlueRPC.Server.HTTP, BlueRPC.Client.HTTP)); | mit |
rubytobi/Design-it-like-Darwin-2.0 | Design-it-like-Darwin-2.0/BpmSolution/App_Start/FilterConfig.cs | 1404 | #region license
// MIT License
//
// Copyright (c) [2017] [Tobias Ruby]
//
// 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.
#endregion
using System.Web.Mvc;
namespace WebApi
{
public class FilterConfig
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
}
}
} | mit |
delete/jira-score | tests/src/auth.test.js | 595 | const auth = require('../../src/auth')
describe('auth method must return login:pass as base64', () => {
test('fellipe.user:123213 must return ZmVsbGlwZS51c2VyOjEyMzIxMw==', () => {
const actual = auth('fellipe.user', '123213')
const expected = 'ZmVsbGlwZS51c2VyOjEyMzIxMw=='
expect( actual ).toBe( expected)
})
test(' fellipe.user:33333 must NOT return ZmVsbGlwZS51c2VyOjEyMzIxMw==', () => {
const actual = auth('fellipe.user', '33333')
const expected = 'ZmVsbGlwZS51c2VyOjEyMzIxMw=='
expect( actual ).not.toBe( expected)
})
}) | mit |
pushbullet/engineer | vendor/github.com/google/martian/har/har.go | 20169 | // Copyright 2015 Google Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Package har collects HTTP requests and responses and stores them in HAR format.
//
// For more information on HAR, see:
// https://w3c.github.io/web-performance/specs/HAR/Overview.html
package har
import (
"bytes"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"mime"
"mime/multipart"
"net/http"
"net/url"
"strings"
"sync"
"time"
"unicode/utf8"
"github.com/google/martian/v3"
"github.com/google/martian/v3/log"
"github.com/google/martian/v3/messageview"
"github.com/google/martian/v3/proxyutil"
)
// Logger maintains request and response log entries.
type Logger struct {
bodyLogging func(*http.Response) bool
postDataLogging func(*http.Request) bool
creator *Creator
mu sync.Mutex
entries map[string]*Entry
tail *Entry
}
// HAR is the top level object of a HAR log.
type HAR struct {
Log *Log `json:"log"`
}
// Log is the HAR HTTP request and response log.
type Log struct {
// Version number of the HAR format.
Version string `json:"version"`
// Creator holds information about the log creator application.
Creator *Creator `json:"creator"`
// Entries is a list containing requests and responses.
Entries []*Entry `json:"entries"`
}
// Creator is the program responsible for generating the log. Martian, in this case.
type Creator struct {
// Name of the log creator application.
Name string `json:"name"`
// Version of the log creator application.
Version string `json:"version"`
}
// Entry is a individual log entry for a request or response.
type Entry struct {
// ID is the unique ID for the entry.
ID string `json:"_id"`
// StartedDateTime is the date and time stamp of the request start (ISO 8601).
StartedDateTime time.Time `json:"startedDateTime"`
// Time is the total elapsed time of the request in milliseconds.
Time int64 `json:"time"`
// Request contains the detailed information about the request.
Request *Request `json:"request"`
// Response contains the detailed information about the response.
Response *Response `json:"response,omitempty"`
// Cache contains information about a request coming from browser cache.
Cache *Cache `json:"cache"`
// Timings describes various phases within request-response round trip. All
// times are specified in milliseconds.
Timings *Timings `json:"timings"`
next *Entry
}
// Request holds data about an individual HTTP request.
type Request struct {
// Method is the request method (GET, POST, ...).
Method string `json:"method"`
// URL is the absolute URL of the request (fragments are not included).
URL string `json:"url"`
// HTTPVersion is the Request HTTP version (HTTP/1.1).
HTTPVersion string `json:"httpVersion"`
// Cookies is a list of cookies.
Cookies []Cookie `json:"cookies"`
// Headers is a list of headers.
Headers []Header `json:"headers"`
// QueryString is a list of query parameters.
QueryString []QueryString `json:"queryString"`
// PostData is the posted data information.
PostData *PostData `json:"postData,omitempty"`
// HeaderSize is the Total number of bytes from the start of the HTTP request
// message until (and including) the double CLRF before the body. Set to -1
// if the info is not available.
HeadersSize int64 `json:"headersSize"`
// BodySize is the size of the request body (POST data payload) in bytes. Set
// to -1 if the info is not available.
BodySize int64 `json:"bodySize"`
}
// Response holds data about an individual HTTP response.
type Response struct {
// Status is the response status code.
Status int `json:"status"`
// StatusText is the response status description.
StatusText string `json:"statusText"`
// HTTPVersion is the Response HTTP version (HTTP/1.1).
HTTPVersion string `json:"httpVersion"`
// Cookies is a list of cookies.
Cookies []Cookie `json:"cookies"`
// Headers is a list of headers.
Headers []Header `json:"headers"`
// Content contains the details of the response body.
Content *Content `json:"content"`
// RedirectURL is the target URL from the Location response header.
RedirectURL string `json:"redirectURL"`
// HeadersSize is the total number of bytes from the start of the HTTP
// request message until (and including) the double CLRF before the body.
// Set to -1 if the info is not available.
HeadersSize int64 `json:"headersSize"`
// BodySize is the size of the request body (POST data payload) in bytes. Set
// to -1 if the info is not available.
BodySize int64 `json:"bodySize"`
}
// Cache contains information about a request coming from browser cache.
type Cache struct {
// Has no fields as they are not supported, but HAR requires the "cache"
// object to exist.
}
// Timings describes various phases within request-response round trip. All
// times are specified in milliseconds
type Timings struct {
// Send is the time required to send HTTP request to the server.
Send int64 `json:"send"`
// Wait is the time spent waiting for a response from the server.
Wait int64 `json:"wait"`
// Receive is the time required to read entire response from server or cache.
Receive int64 `json:"receive"`
}
// Cookie is the data about a cookie on a request or response.
type Cookie struct {
// Name is the cookie name.
Name string `json:"name"`
// Value is the cookie value.
Value string `json:"value"`
// Path is the path pertaining to the cookie.
Path string `json:"path,omitempty"`
// Domain is the host of the cookie.
Domain string `json:"domain,omitempty"`
// Expires contains cookie expiration time.
Expires time.Time `json:"-"`
// Expires8601 contains cookie expiration time in ISO 8601 format.
Expires8601 string `json:"expires,omitempty"`
// HTTPOnly is set to true if the cookie is HTTP only, false otherwise.
HTTPOnly bool `json:"httpOnly,omitempty"`
// Secure is set to true if the cookie was transmitted over SSL, false
// otherwise.
Secure bool `json:"secure,omitempty"`
}
// Header is an HTTP request or response header.
type Header struct {
// Name is the header name.
Name string `json:"name"`
// Value is the header value.
Value string `json:"value"`
}
// QueryString is a query string parameter on a request.
type QueryString struct {
// Name is the query parameter name.
Name string `json:"name"`
// Value is the query parameter value.
Value string `json:"value"`
}
// PostData describes posted data on a request.
type PostData struct {
// MimeType is the MIME type of the posted data.
MimeType string `json:"mimeType"`
// Params is a list of posted parameters (in case of URL encoded parameters).
Params []Param `json:"params"`
// Text contains the posted data. Although its type is string, it may contain
// binary data.
Text string `json:"text"`
}
// pdBinary is the JSON representation of binary PostData.
type pdBinary struct {
MimeType string `json:"mimeType"`
// Params is a list of posted parameters (in case of URL encoded parameters).
Params []Param `json:"params"`
Text []byte `json:"text"`
Encoding string `json:"encoding"`
}
// MarshalJSON returns a JSON representation of binary PostData.
func (p *PostData) MarshalJSON() ([]byte, error) {
if utf8.ValidString(p.Text) {
type noMethod PostData // avoid infinite recursion
return json.Marshal((*noMethod)(p))
}
return json.Marshal(pdBinary{
MimeType: p.MimeType,
Params: p.Params,
Text: []byte(p.Text),
Encoding: "base64",
})
}
// UnmarshalJSON populates PostData based on the []byte representation of
// the binary PostData.
func (p *PostData) UnmarshalJSON(data []byte) error {
if bytes.Equal(data, []byte("null")) { // conform to json.Unmarshaler spec
return nil
}
var enc struct {
Encoding string `json:"encoding"`
}
if err := json.Unmarshal(data, &enc); err != nil {
return err
}
if enc.Encoding != "base64" {
type noMethod PostData // avoid infinite recursion
return json.Unmarshal(data, (*noMethod)(p))
}
var pb pdBinary
if err := json.Unmarshal(data, &pb); err != nil {
return err
}
p.MimeType = pb.MimeType
p.Params = pb.Params
p.Text = string(pb.Text)
return nil
}
// Param describes an individual posted parameter.
type Param struct {
// Name of the posted parameter.
Name string `json:"name"`
// Value of the posted parameter.
Value string `json:"value,omitempty"`
// Filename of a posted file.
Filename string `json:"fileName,omitempty"`
// ContentType is the content type of a posted file.
ContentType string `json:"contentType,omitempty"`
}
// Content describes details about response content.
type Content struct {
// Size is the length of the returned content in bytes. Should be equal to
// response.bodySize if there is no compression and bigger when the content
// has been compressed.
Size int64 `json:"size"`
// MimeType is the MIME type of the response text (value of the Content-Type
// response header).
MimeType string `json:"mimeType"`
// Text contains the response body sent from the server or loaded from the
// browser cache. This field is populated with textual content only. The text
// field is either HTTP decoded text or a encoded (e.g. "base64")
// representation of the response body. Leave out this field if the
// information is not available.
Text []byte `json:"text,omitempty"`
// Encoding used for response text field e.g "base64". Leave out this field
// if the text field is HTTP decoded (decompressed & unchunked), than
// trans-coded from its original character set into UTF-8.
Encoding string `json:"encoding,omitempty"`
}
// Option is a configurable setting for the logger.
type Option func(l *Logger)
// PostDataLogging returns an option that configures request post data logging.
func PostDataLogging(enabled bool) Option {
return func(l *Logger) {
l.postDataLogging = func(*http.Request) bool {
return enabled
}
}
}
// PostDataLoggingForContentTypes returns an option that logs request bodies based
// on opting in to the Content-Type of the request.
func PostDataLoggingForContentTypes(cts ...string) Option {
return func(l *Logger) {
l.postDataLogging = func(req *http.Request) bool {
rct := req.Header.Get("Content-Type")
for _, ct := range cts {
if strings.HasPrefix(strings.ToLower(rct), strings.ToLower(ct)) {
return true
}
}
return false
}
}
}
// SkipPostDataLoggingForContentTypes returns an option that logs request bodies based
// on opting out of the Content-Type of the request.
func SkipPostDataLoggingForContentTypes(cts ...string) Option {
return func(l *Logger) {
l.postDataLogging = func(req *http.Request) bool {
rct := req.Header.Get("Content-Type")
for _, ct := range cts {
if strings.HasPrefix(strings.ToLower(rct), strings.ToLower(ct)) {
return false
}
}
return true
}
}
}
// BodyLogging returns an option that configures response body logging.
func BodyLogging(enabled bool) Option {
return func(l *Logger) {
l.bodyLogging = func(*http.Response) bool {
return enabled
}
}
}
// BodyLoggingForContentTypes returns an option that logs response bodies based
// on opting in to the Content-Type of the response.
func BodyLoggingForContentTypes(cts ...string) Option {
return func(l *Logger) {
l.bodyLogging = func(res *http.Response) bool {
rct := res.Header.Get("Content-Type")
for _, ct := range cts {
if strings.HasPrefix(strings.ToLower(rct), strings.ToLower(ct)) {
return true
}
}
return false
}
}
}
// SkipBodyLoggingForContentTypes returns an option that logs response bodies based
// on opting out of the Content-Type of the response.
func SkipBodyLoggingForContentTypes(cts ...string) Option {
return func(l *Logger) {
l.bodyLogging = func(res *http.Response) bool {
rct := res.Header.Get("Content-Type")
for _, ct := range cts {
if strings.HasPrefix(strings.ToLower(rct), strings.ToLower(ct)) {
return false
}
}
return true
}
}
}
// NewLogger returns a HAR logger. The returned
// logger logs all request post data and response bodies by default.
func NewLogger() *Logger {
l := &Logger{
creator: &Creator{
Name: "martian proxy",
Version: "2.0.0",
},
entries: make(map[string]*Entry),
}
l.SetOption(BodyLogging(true))
l.SetOption(PostDataLogging(true))
return l
}
// SetOption sets configurable options on the logger.
func (l *Logger) SetOption(opts ...Option) {
for _, opt := range opts {
opt(l)
}
}
// ModifyRequest logs requests.
func (l *Logger) ModifyRequest(req *http.Request) error {
ctx := martian.NewContext(req)
if ctx.SkippingLogging() {
return nil
}
id := ctx.ID()
return l.RecordRequest(id, req)
}
// RecordRequest logs the HTTP request with the given ID. The ID should be unique
// per request/response pair.
func (l *Logger) RecordRequest(id string, req *http.Request) error {
hreq, err := NewRequest(req, l.postDataLogging(req))
if err != nil {
return err
}
entry := &Entry{
ID: id,
StartedDateTime: time.Now().UTC(),
Request: hreq,
Cache: &Cache{},
Timings: &Timings{},
}
l.mu.Lock()
defer l.mu.Unlock()
if _, exists := l.entries[id]; exists {
return fmt.Errorf("Duplicate request ID: %s", id)
}
l.entries[id] = entry
if l.tail == nil {
l.tail = entry
}
entry.next = l.tail.next
l.tail.next = entry
l.tail = entry
return nil
}
// NewRequest constructs and returns a Request from req. If withBody is true,
// req.Body is read to EOF and replaced with a copy in a bytes.Buffer. An error
// is returned (and req.Body may be in an intermediate state) if an error is
// returned from req.Body.Read.
func NewRequest(req *http.Request, withBody bool) (*Request, error) {
r := &Request{
Method: req.Method,
URL: req.URL.String(),
HTTPVersion: req.Proto,
HeadersSize: -1,
BodySize: req.ContentLength,
QueryString: []QueryString{},
Headers: headers(proxyutil.RequestHeader(req).Map()),
Cookies: cookies(req.Cookies()),
}
for n, vs := range req.URL.Query() {
for _, v := range vs {
r.QueryString = append(r.QueryString, QueryString{
Name: n,
Value: v,
})
}
}
pd, err := postData(req, withBody)
if err != nil {
return nil, err
}
r.PostData = pd
return r, nil
}
// ModifyResponse logs responses.
func (l *Logger) ModifyResponse(res *http.Response) error {
ctx := martian.NewContext(res.Request)
if ctx.SkippingLogging() {
return nil
}
id := ctx.ID()
return l.RecordResponse(id, res)
}
// RecordResponse logs an HTTP response, associating it with the previously-logged
// HTTP request with the same ID.
func (l *Logger) RecordResponse(id string, res *http.Response) error {
hres, err := NewResponse(res, l.bodyLogging(res))
if err != nil {
return err
}
l.mu.Lock()
defer l.mu.Unlock()
if e, ok := l.entries[id]; ok {
e.Response = hres
e.Time = time.Since(e.StartedDateTime).Nanoseconds() / 1000000
}
return nil
}
// NewResponse constructs and returns a Response from resp. If withBody is true,
// resp.Body is read to EOF and replaced with a copy in a bytes.Buffer. An error
// is returned (and resp.Body may be in an intermediate state) if an error is
// returned from resp.Body.Read.
func NewResponse(res *http.Response, withBody bool) (*Response, error) {
r := &Response{
HTTPVersion: res.Proto,
Status: res.StatusCode,
StatusText: http.StatusText(res.StatusCode),
HeadersSize: -1,
BodySize: res.ContentLength,
Headers: headers(proxyutil.ResponseHeader(res).Map()),
Cookies: cookies(res.Cookies()),
}
if res.StatusCode >= 300 && res.StatusCode < 400 {
r.RedirectURL = res.Header.Get("Location")
}
r.Content = &Content{
Encoding: "base64",
MimeType: res.Header.Get("Content-Type"),
}
if withBody {
mv := messageview.New()
if err := mv.SnapshotResponse(res); err != nil {
return nil, err
}
br, err := mv.BodyReader(messageview.Decode())
if err != nil {
return nil, err
}
body, err := ioutil.ReadAll(br)
if err != nil {
return nil, err
}
r.Content.Text = body
r.Content.Size = int64(len(body))
}
return r, nil
}
// Export returns the in-memory log.
func (l *Logger) Export() *HAR {
l.mu.Lock()
defer l.mu.Unlock()
es := make([]*Entry, 0, len(l.entries))
curr := l.tail
for curr != nil {
curr = curr.next
es = append(es, curr)
if curr == l.tail {
break
}
}
return l.makeHAR(es)
}
// ExportAndReset returns the in-memory log for completed requests, clearing them.
func (l *Logger) ExportAndReset() *HAR {
l.mu.Lock()
defer l.mu.Unlock()
es := make([]*Entry, 0, len(l.entries))
curr := l.tail
prev := l.tail
var first *Entry
for curr != nil {
curr = curr.next
if curr.Response != nil {
es = append(es, curr)
delete(l.entries, curr.ID)
} else {
if first == nil {
first = curr
}
prev.next = curr
prev = curr
}
if curr == l.tail {
break
}
}
if len(l.entries) == 0 {
l.tail = nil
} else {
l.tail = prev
l.tail.next = first
}
return l.makeHAR(es)
}
func (l *Logger) makeHAR(es []*Entry) *HAR {
return &HAR{
Log: &Log{
Version: "1.2",
Creator: l.creator,
Entries: es,
},
}
}
// Reset clears the in-memory log of entries.
func (l *Logger) Reset() {
l.mu.Lock()
defer l.mu.Unlock()
l.entries = make(map[string]*Entry)
l.tail = nil
}
func cookies(cs []*http.Cookie) []Cookie {
hcs := make([]Cookie, 0, len(cs))
for _, c := range cs {
var expires string
if !c.Expires.IsZero() {
expires = c.Expires.Format(time.RFC3339)
}
hcs = append(hcs, Cookie{
Name: c.Name,
Value: c.Value,
Path: c.Path,
Domain: c.Domain,
HTTPOnly: c.HttpOnly,
Secure: c.Secure,
Expires: c.Expires,
Expires8601: expires,
})
}
return hcs
}
func headers(hs http.Header) []Header {
hhs := make([]Header, 0, len(hs))
for n, vs := range hs {
for _, v := range vs {
hhs = append(hhs, Header{
Name: n,
Value: v,
})
}
}
return hhs
}
func postData(req *http.Request, logBody bool) (*PostData, error) {
// If the request has no body (no Content-Length and Transfer-Encoding isn't
// chunked), skip the post data.
if req.ContentLength <= 0 && len(req.TransferEncoding) == 0 {
return nil, nil
}
ct := req.Header.Get("Content-Type")
mt, ps, err := mime.ParseMediaType(ct)
if err != nil {
log.Errorf("har: cannot parse Content-Type header %q: %v", ct, err)
mt = ct
}
pd := &PostData{
MimeType: mt,
Params: []Param{},
}
if !logBody {
return pd, nil
}
mv := messageview.New()
if err := mv.SnapshotRequest(req); err != nil {
return nil, err
}
br, err := mv.BodyReader()
if err != nil {
return nil, err
}
switch mt {
case "multipart/form-data":
mpr := multipart.NewReader(br, ps["boundary"])
for {
p, err := mpr.NextPart()
if err == io.EOF {
break
}
if err != nil {
return nil, err
}
defer p.Close()
body, err := ioutil.ReadAll(p)
if err != nil {
return nil, err
}
pd.Params = append(pd.Params, Param{
Name: p.FormName(),
Filename: p.FileName(),
ContentType: p.Header.Get("Content-Type"),
Value: string(body),
})
}
case "application/x-www-form-urlencoded":
body, err := ioutil.ReadAll(br)
if err != nil {
return nil, err
}
vs, err := url.ParseQuery(string(body))
if err != nil {
return nil, err
}
for n, vs := range vs {
for _, v := range vs {
pd.Params = append(pd.Params, Param{
Name: n,
Value: v,
})
}
}
default:
body, err := ioutil.ReadAll(br)
if err != nil {
return nil, err
}
pd.Text = string(body)
}
return pd, nil
}
| mit |
flumbee/mobiledb | src/MobileDB.Core/Common/ExpressiveAnnotations/Lexer.cs | 5731 | #region Copyright (C) 2014 Dennis Bappert
// The MIT License (MIT)
// Copyright (c) 2014 Dennis Bappert
// 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.
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
namespace MobileDB.Common.ExpressiveAnnotations
{
/// <summary>
/// Performs lexical analysis of provided logical expression.
/// </summary>
public sealed class Lexer
{
/// <summary>
/// Initializes a new instance of the <see cref="Lexer" /> class.
/// </summary>
public Lexer()
{
// special characters (should be escaped if needed): .$^{[(|)*+?\
RegexMap = new Dictionary<TokenType, string>
{
{TokenType.AND, @"&&"},
{TokenType.OR, @"\|\|"},
{TokenType.LEFT_BRACKET, @"\("},
{TokenType.RIGHT_BRACKET, @"\)"},
{TokenType.GE, @">="},
{TokenType.LE, @"<="},
{TokenType.GT, @">"},
{TokenType.LT, @"<"},
{TokenType.EQ, @"=="},
{TokenType.NEQ, @"!="},
{TokenType.NOT, @"!"},
{TokenType.NULL, @"null"},
{TokenType.COMMA, @","},
{TokenType.FLOAT, @"[\+-]?\d*\.\d+(?:[eE][\+-]?\d+)?"},
{TokenType.INT, @"[\+-]?\d+"},
{TokenType.ADD, @"\+"},
{TokenType.SUB, @"-"},
{TokenType.MUL, @"\*"},
{TokenType.DIV, @"/"},
{TokenType.BOOL, @"(?:true|false)"},
{TokenType.STRING, @"([""'])(?:\\\1|.)*?\1"},
{TokenType.FUNC, @"[a-zA-Z_]+(?:(?:\.[a-zA-Z_])?[a-zA-Z0-9_]*)*"}
};
}
private Token Token { get; set; }
private string Expression { get; set; }
private IDictionary<TokenType, string> RegexMap { get; set; }
private IDictionary<TokenType, Regex> CompiledRegexMap { get; set; }
/// <summary>
/// Analyzes the specified logical expression and extracts the array of tokens.
/// </summary>
/// <param name="expression">The logical expression.</param>
/// <returns>
/// Array of extracted tokens.
/// </returns>
/// <exception cref="System.ArgumentNullException">expression;Expression not provided.</exception>
public IEnumerable<Token> Analyze(string expression)
{
if (expression == null)
throw new ArgumentNullException("expression", "Expression not provided.");
Expression = expression;
CompiledRegexMap = RegexMap.ToDictionary(kvp => kvp.Key, kvp => new Regex(string.Format("^{0}", kvp.Value)));
var tokens = new List<Token>();
while (Next())
tokens.Add(Token);
// once we've reached the end of the string, EOF token is returned - thus, parser's lookahead does not have to worry about running out of tokens
tokens.Add(new Token(TokenType.EOF, string.Empty));
return tokens;
}
private bool Next()
{
Expression = Expression.Trim();
if (string.IsNullOrEmpty(Expression))
return false;
foreach (var kvp in CompiledRegexMap)
{
var regex = kvp.Value;
var match = regex.Match(Expression);
var value = match.Value;
if (value.Length > 0)
{
Token = new Token(kvp.Key, ConvertTokenValue(kvp.Key, value));
Expression = Expression.Substring(value.Length);
return true;
}
}
throw new InvalidOperationException(string.Format("Invalid token started at: {0}", Expression));
}
private object ConvertTokenValue(TokenType type, string value)
{
switch (type)
{
case TokenType.NULL:
return null;
case TokenType.INT:
return int.Parse(value);
case TokenType.FLOAT:
return double.Parse(value);
// by default, treat real numeric literals as 64-bit floating binary point values (as C# does, gives better precision than float)
case TokenType.BOOL:
return bool.Parse(value);
case TokenType.STRING:
return value.Substring(1, value.Length - 2);
default:
return value;
}
}
}
} | mit |