repo_name
stringlengths 4
116
| path
stringlengths 4
379
| size
stringlengths 1
7
| content
stringlengths 3
1.05M
| license
stringclasses 15
values |
---|---|---|---|---|
mdchristopher/Protractor | node_modules/lodash/at.js | 765 | var baseAt = require('./_baseAt'),
baseFlatten = require('./_baseFlatten'),
rest = require('./rest');
/**
* Creates an array of values corresponding to `paths` of `object`.
*
* @static
* @memberOf _
* @category Object
* @param {Object} object The object to iterate over.
* @param {...(string|string[])} [paths] The property paths of elements to pick,
* specified individually or in arrays.
* @returns {Array} Returns the new array of picked elements.
* @specs
*
* var object = { 'a': [{ 'b': { 'c': 3 } }, 4] };
*
* _.at(object, ['a[0].b.c', 'a[1]']);
* // => [3, 4]
*
* _.at(['a', 'b', 'c'], 0, 2);
* // => ['a', 'c']
*/
var at = rest(function(object, paths) {
return baseAt(object, baseFlatten(paths, 1));
});
module.exports = at;
| mit |
SlaxWeb/Config | tests/_support/TestConfig/PhpConfig.php | 46 | <?php
$configuration["test.config"] = "test";
| mit |
hkpeprah/television-2.0 | web/sources/television/__init__.py | 7361 | import re
from datetime import datetime
from client import (TelevisionApi, pad)
from common import COUNTRY_CODES as country_codes
API = TelevisionApi()
def list_latest_episodes(*args, **kwargs):
raise NotImplemented
def fetch_episodes_data_for_country(country, date):
"""
Lists the new episodes for the specified country on the specified
date. Expects date to be a datetime object.
"""
if not isinstance(date, datetime):
raise TypeError('Expected date to be a datetime object')
date = '{}-{}-{}'.format(pad(date.year), pad(date.month), pad(date.day))
return API.get_latest(country, date)
def list_latest_episodes_for_country(country, date):
data = fetch_episodes_data_for_country(country, date)
networks, episodes, shows = [], [], []
for episode_metadata in data:
episode_mapping = {
'name': 'name',
'airdate': 'date',
'season': 'season',
'image': 'image',
'number': 'number',
'summary': 'summary',
'airtime': 'time',
'airstamp': 'timestamp',
'runtime': 'runtime'
}
# Populate the episode data from the metadata contained within
# the returned data set
episode = dict()
for (orig_field, new_field) in episode_mapping.iteritems():
episode[new_field] = episode_metadata.get(orig_field, None)
if new_field == 'image' and isinstance(episode[new_field], dict):
episode[new_field] = episode[new_field].get('original', '')
if episode['summary'] is not None:
episode['summary'] = re.sub('<[^>]*>', '', episode['summary'])
# Check if we have metadata to create a show, if so do that.
show_metadata = episode_metadata.get('show', None)
if show_metadata is not None:
show_mapping = {
'genres': 'genres',
'name': 'name',
'summary': 'description',
'runtime': 'runtime'
}
show = dict()
for (orig_field, new_field) in show_mapping.iteritems():
show[new_field] = show_metadata.get(orig_field, None)
if show['description'] is not None:
show['description'] = re.sub('<[^>]*>', '', show['description'])
if 'image' in show_metadata and show_metadata['image'] is not None:
show['image'] = show_metadata['image'].get('original', None)
show['extra_data'] = { 'id': show_metadata.get('id', None) }
# If we dont' haev any genres assigned, then our genres are an
# empty list.
if 'genres' not in show:
show['genres'] = []
# We assume the type of show (e.g. 'Game Show') is also what would be
# considered a genre.
if 'type' in show_metadata and show_metadata['type'] is not None:
show['genres'].append(show_metadata['type'])
# Update the episode with the show information
episode['series_name'] = show['name']
episode['extra_data'] = { 'series_id': show['extra_data']['id'] }
# Check if we have metadata to create the network object.
network_metadata = show_metadata.get('network', None)
if network_metadata is not None:
network = dict()
country = network_metadata.get('country', None)
if country is not None:
network['country_code'] = country.get('code', None)
network['timezone'] = country.get('timezone', None)
network['name'] = network_metadata.get('name', None)
network['extra_data'] = { 'id': network_metadata.get('id', None) }
# Update the show and episode with the network information
episode['network_name'] = network['name']
episode['extra_data']['network_id'] = network['extra_data']['id']
episode['country_code'] = network.get('country_code', None)
show['network_name'] = network['name']
show['extra_data']['network_id'] = network['extra_data']['id']
networks.append(network)
# Push the show into the list
shows.append(show)
# Finally push the episode into the list
episodes.append(episode)
return { 'networks': networks, 'episodes': episodes, 'shows': shows }
def search_for_series(query, allowed_countries=None, limit=None):
if allowed_countries is None:
allowed_countries = API.COUNTRY_CODES
data = API.search(query)
shows, networks = [], []
iteration = 0
for result in data:
if result is None or result.get('show', None) is None:
continue
if limit is not None and iteration >= limit:
break
iteration += 1
show_mapping = {
'genres': 'genres',
'name': 'name',
'summary': 'description',
'runtime': 'runtime'
}
show_metadata = result.get('show')
show = dict()
for (orig_field, new_field) in show_mapping.iteritems():
show[new_field] = show_metadata.get(orig_field, None)
if show['description'] is not None:
show['description'] = re.sub('<[^>]*>', '', show['description'])
if 'image' in show_metadata and show_metadata['image'] is not None:
show['image'] = show_metadata['image'].get('original', None)
show['extra_data'] = { 'id': show_metadata.get('id', None) }
show['extra_data']['url'] = show_metadata.get('url', None)
# If we dont' haev any genres assigned, then our genres are an
# empty list.
if 'genres' not in show:
show['genres'] = []
# We assume the type of show (e.g. 'Game Show') is also what would be
# considered a genre.
if 'type' in show_metadata and show_metadata['type'] is not None:
show['genres'].append(show_metadata['type'])
# Check if we have metadata to create the network object.
network_metadata = show_metadata.get('network', None)
if network_metadata is not None:
network = dict()
country = network_metadata.get('country', None)
country_code = None
if country is not None:
country_code = country.get('code', None)
network['country_code'] = country.get('code', None)
network['timezone'] = country.get('timezone', None)
network['name'] = network_metadata.get('name', None)
network['extra_data'] = { 'id': network_metadata.get('id', None) }
# Update the show with the network information
show['network_name'] = network['name']
show['extra_data']['network_id'] = network['extra_data']['id']
if country_code not in allowed_countries:
continue
networks.append(network)
# Push the show into the list
shows.append(show)
return { 'networks': networks, 'episodes': [], 'shows': shows }
if __name__ == '__main__':
import json
data = search_for_series('Walking Dead')
print json.dumps(data, indent=4, sort_keys=True)
| mit |
richardschneider/club-server | lib/session/resolver.js | 527 | // graphql resolver for a game
import { Game, Board, SessionPair } from '../../data/connectors';
module.exports = {
club(session) {
return session.getClub();
},
boards(session) {
return session.getBoards();
},
games(session) {
return Game.findAll({
include: [{ model: Board, where: { sessionId: session.id } }],
});
},
players(session) {
return session.getSessionPlayers();
},
pairs(session) {
return SessionPair.getAll(session);
},
};
| mit |
Tehelee/Spigot-AdvancedBeacons | src/com/tehelee/beacons/enchantments/Luck.java | 829 | package com.tehelee.beacons.enchantments;
import org.bukkit.Material;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.enchantments.EnchantmentTarget;
import org.bukkit.inventory.ItemStack;
public class Luck extends Enchantment
{
public Luck()
{
super(526);
}
@Override
public boolean canEnchantItem(ItemStack arg0)
{
return (arg0.getType() == Material.BEACON);
}
@Override
public boolean conflictsWith(Enchantment arg0)
{
switch(arg0.hashCode())
{
default:
return false;
}
}
@Override
public EnchantmentTarget getItemTarget()
{
return null;
}
@Override
public int getMaxLevel()
{
return 0;
}
@Override
public String getName()
{
return "Luck";
}
@Override
public int getStartLevel()
{
return 0;
}
}
| mit |
cuckata23/wurfl-data | data/nokia_e71_ver1_sub3_11007127.php | 499 | <?php
return array (
'id' => 'nokia_e71_ver1_sub3_11007127',
'fallback' => 'nokia_e71_ver1',
'capabilities' =>
array (
'model_name' => 'E71-3',
'release_date' => '2009_october',
'columns' => '28',
'rows' => '13',
'max_image_width' => '300',
'resolution_width' => '320',
'resolution_height' => '240',
'colors' => '262144',
'max_deck_size' => '357000',
'mms_max_size' => '307200',
'mms_max_width' => '2048',
'mms_max_height' => '1536',
),
);
| mit |
dyydyydyydyydyy/knowsharing | src/Biz/Like/Dao/Impl/LikeDaoImpl.php | 1050 | <?php
namespace Biz\Like\Dao\Impl;
use Biz\Like\Dao\LikeDao;
use Codeages\Biz\Framework\Dao\GeneralDaoImpl;
class LikeDaoImpl extends GeneralDaoImpl implements LikeDao
{
protected $table = 'user_like';
public function deleteByIdAndUserId($id, $userId)
{
$sql = "DELETE FROM {$this->table} WHERE userId = :userId AND knowledgeId = :knowledgeId";
$stmt = $this->db()->prepare($sql);
$fields = array(
'userId' => $userId,
'knowledgeId' => $id
);
$stmt->execute($fields);
}
public function findByUserId($userId)
{
$sql = "SELECT * FROM {$this->table} WHERE userId =?";
return $this->db()->fetchAll($sql,array($userId));
}
public function declares()
{
return array(
'timestamps' => array('createdTime'),
'serializes' => array(),
'conditions' => array(
'userId = :userId',
'knowledgeId = :knowledgeId'
),
);
}
} | mit |
weissj3/MWTools | Data/LuaFilesFullSkyErrors/params_14.lua | 808 | wedge = 14
background = {
epsilon = 0.997179,
q = 0.619347
}
streams = {
{
epsilon = -1.297424,
mu = 190.545111,
r = 13.878006,
theta = 0.198390,
phi = 3.139994,
sigma = 3.743833
},
{
epsilon = -1.008419,
mu = 199.646461,
r = 39.369932,
theta = 1.119290,
phi = 0.926942,
sigma = 8.875175
},
{
epsilon = -3.069995,
mu = 156.562280,
r = 16.517515,
theta = 0.332154,
phi = 0.588367,
sigma = 1.400307
}
}
area = {
{
r_min = 16,
r_max = 22.5,
r_steps = 700,
mu_min = 135,
mu_max = 235,
mu_steps = 800,
nu_min = -1.25,
nu_max = 1.25,
nu_steps = 320
}
}
| mit |
sidoh/riddlegate | db/db.rb | 288 | require 'data_mapper'
require 'dm-core'
require 'dm-timestamps'
root = File.expand_path(File.join(__FILE__, '../..'))
DataMapper::Logger.new($stdout, :debug)
DataMapper.setup(:default, "sqlite://#{root}/db/sqlite3.db")
require 'db/schema'
DataMapper.finalize
DataMapper.auto_upgrade!
| mit |
TrapKingg/Tescha-books | users/filters.py | 275 | from django.contrib.auth.models import User
import django_filters
class UserFilter(django_filters.FilterSet):
first_name = django_filters.CharFilter(lookup_expr='icontains')
class Meta:
model = User
fields = ['username', 'first_name', 'last_name']
| mit |
laschuet/geometrie_in_react | structure.config.js | 493 | const path = require('path');
const config = {
paths: {
dev: path.resolve(__dirname, 'dev'),
dist: path.resolve(__dirname, 'dist'),
nodeModules: path.resolve(__dirname, 'node_modules'),
source: path.resolve(__dirname, 'src'),
},
filenames: {
dev: {
JS: '[name].js',
},
dist: {
CSS: '[name].css',
JS: '[name].js',
vendorsJS: 'vendors.js',
},
indexJS: 'index.jsx',
indexHTML: 'index.html',
},
};
module.exports = config;
| mit |
rgllm/uminho | 03/DSS/src/BillSplitter/src/visual/conta.java | 17705 |
package visual;
import javax.swing.table.*;
import java.util.ArrayList;
import java.util.Map.*;
import billsplitter.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
public class conta extends javax.swing.JFrame {
Utilizador u;
Casa c;
ArrayList<Despesa> despesasPagas;
ArrayList<Despesa> despesasPorPagar;
public conta(String email) {
BillSplitter bs=new BillSplitter();
u=bs.getUser(email);
c=bs.getCasa(u.getCasa());
initComponents();
jsaldo.setText(String.valueOf(u.getSaldo()));
DefaultTableModel modelT1= (DefaultTableModel)tabela1.getModel();
despesasPagas=new ArrayList<Despesa>();
despesasPorPagar=new ArrayList<Despesa>();
for(Despesa d : new DAODespesa().getDespesasCasa(c.getId()) )
if(d.getEstado()==false)
despesasPorPagar.add(d);
else despesasPagas.add(d);
for(Despesa d : despesasPorPagar)
modelT1.insertRow(modelT1.getRowCount(), new Object []{d.getDescricao(),d.getMontante(),d.getData_limite()});
DefaultTableModel modelT2= (DefaultTableModel)tabela2.getModel();
for(Entry<String,Float> e : u.getSituacoesIrregulares().entrySet()){
modelT2.insertRow(modelT2.getRowCount(), new Object []{e.getKey(),e.getValue().toString()});
}
tabela1.getSelectionModel().addListSelectionListener(new ListSelectionListener(){
public void valueChanged(ListSelectionEvent event) {
for(Despesa d : despesasPorPagar)
if(d.getDescricao().equals(tabela1.getValueAt(tabela1.getSelectedRow(), 0))){
new despesas(email,d).setVisible(true);
setVisible(false);
}
}});
tabela2.getSelectionModel().addListSelectionListener(new ListSelectionListener(){
public void valueChanged(ListSelectionEvent event) {
new transferir(email,(String)tabela2.getValueAt(tabela2.getSelectedRow(), 0)).setVisible(true);
setVisible(false);
}});
jsair.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e){
new home().setVisible(true);
setVisible(false);
}
});
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jMenuItem1 = new javax.swing.JMenuItem();
jMenu1 = new javax.swing.JMenu();
jMenu2 = new javax.swing.JMenu();
jMenu3 = new javax.swing.JMenu();
jLabel1 = new javax.swing.JLabel();
jsair = new javax.swing.JLabel();
jScrollPane1 = new javax.swing.JScrollPane();
tabela1 = new javax.swing.JTable();
jadd_despesa = new javax.swing.JButton();
jdesp_recorrentes = new javax.swing.JButton();
jdesp_liquidadas = new javax.swing.JButton();
jLabel3 = new javax.swing.JLabel();
jsaldo = new javax.swing.JLabel();
jLabel5 = new javax.swing.JLabel();
jdel_morador = new javax.swing.JButton();
jedit_conta = new javax.swing.JButton();
add_morador = new javax.swing.JButton();
jScrollPane3 = new javax.swing.JScrollPane();
tabela2 = new javax.swing.JTable();
jMenuItem1.setText("jMenuItem1");
jMenu1.setText("jMenu1");
jMenu2.setText("jMenu2");
jMenu3.setText("jMenu3");
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jLabel1.setFont(new java.awt.Font("Lucida Grande", 0, 24)); // NOI18N
jLabel1.setText("BillSplitter");
jsair.setText("Sair");
tabela1.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
},
new String [] {
"Descrição", "Valor", "Data Limite"
}
) {
boolean[] canEdit = new boolean [] {
false, false, false
};
public boolean isCellEditable(int rowIndex, int columnIndex) {
return canEdit [columnIndex];
}
});
jScrollPane1.setViewportView(tabela1);
jadd_despesa.setText("Adicionar Despesa");
jadd_despesa.setToolTipText("");
jadd_despesa.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jadd_despesaActionPerformed(evt);
}
});
jdesp_recorrentes.setText("Gerir Despesa Recorrente");
jdesp_recorrentes.setToolTipText("");
jdesp_recorrentes.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jdesp_recorrentesActionPerformed(evt);
}
});
jdesp_liquidadas.setText("Despesas Liquidadas");
jdesp_liquidadas.setToolTipText("");
jdesp_liquidadas.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jdesp_liquidadasActionPerformed(evt);
}
});
jLabel3.setFont(new java.awt.Font("Lucida Grande", 0, 18)); // NOI18N
jLabel3.setText("Conta Corrente:");
jsaldo.setFont(new java.awt.Font("Lucida Grande", 0, 18)); // NOI18N
jLabel5.setText("Compromissos com:");
jdel_morador.setText("Remover Morador");
jdel_morador.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jdel_moradorActionPerformed(evt);
}
});
jedit_conta.setText("Editar Conta");
jedit_conta.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jedit_contaActionPerformed(evt);
}
});
add_morador.setText("Adicionar Morador");
add_morador.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
add_moradorActionPerformed(evt);
}
});
tabela2.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
},
new String [] {
"Morador", "Valor"
}
) {
boolean[] canEdit = new boolean [] {
false, false
};
public boolean isCellEditable(int rowIndex, int columnIndex) {
return canEdit [columnIndex];
}
});
jScrollPane3.setViewportView(tabela2);
if (tabela2.getColumnModel().getColumnCount() > 0) {
tabela2.getColumnModel().getColumn(0).setResizable(false);
tabela2.getColumnModel().getColumn(1).setResizable(false);
}
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jadd_despesa, javax.swing.GroupLayout.PREFERRED_SIZE, 171, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(31, 31, 31)
.addComponent(jdesp_recorrentes, javax.swing.GroupLayout.PREFERRED_SIZE, 171, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(465, 465, 465))
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(add_morador, javax.swing.GroupLayout.PREFERRED_SIZE, 129, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jdesp_liquidadas, javax.swing.GroupLayout.PREFERRED_SIZE, 171, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 372, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(46, 46, 46)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel3)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jsaldo))
.addComponent(jLabel5, javax.swing.GroupLayout.PREFERRED_SIZE, 144, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 227, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addComponent(jdel_morador, javax.swing.GroupLayout.PREFERRED_SIZE, 129, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jedit_conta, javax.swing.GroupLayout.PREFERRED_SIZE, 129, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 122, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(461, 461, 461)
.addComponent(jsair, javax.swing.GroupLayout.PREFERRED_SIZE, 46, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(22, 22, 22)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 69, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jsair, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(94, 94, 94)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel3)
.addComponent(jsaldo))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jLabel5)
.addGap(18, 18, 18)
.addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 165, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jdesp_liquidadas, javax.swing.GroupLayout.PREFERRED_SIZE, 58, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createSequentialGroup()
.addGap(46, 46, 46)
.addComponent(add_morador, javax.swing.GroupLayout.PREFERRED_SIZE, 44, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jdel_morador, javax.swing.GroupLayout.PREFERRED_SIZE, 44, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jedit_conta, javax.swing.GroupLayout.PREFERRED_SIZE, 44, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jadd_despesa, javax.swing.GroupLayout.PREFERRED_SIZE, 58, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jdesp_recorrentes, javax.swing.GroupLayout.PREFERRED_SIZE, 58, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(26, 26, 26))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void jadd_despesaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jadd_despesaActionPerformed
new adicionar_despesa(u.getEmail()).setVisible(true);
setVisible(false);
}//GEN-LAST:event_jadd_despesaActionPerformed
private void jdesp_recorrentesActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jdesp_recorrentesActionPerformed
new despesas_recorrentes(u.getEmail()).setVisible(true);
setVisible(false);
}//GEN-LAST:event_jdesp_recorrentesActionPerformed
private void jdesp_liquidadasActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jdesp_liquidadasActionPerformed
if(jdesp_liquidadas.getText().equals("Despesas Liquidadas"))
jdesp_liquidadas.setText("Despesas por liquidar");
else jdesp_liquidadas.setText("Despesas Liquidadas");
}//GEN-LAST:event_jdesp_liquidadasActionPerformed
private void jdel_moradorActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jdel_moradorActionPerformed
new remover_morador(u.getEmail()).setVisible(true);
setVisible(false);
}//GEN-LAST:event_jdel_moradorActionPerformed
private void jedit_contaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jedit_contaActionPerformed
new editar_conta(u).setVisible(true);
setVisible(false);
}//GEN-LAST:event_jedit_contaActionPerformed
private void add_moradorActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_add_moradorActionPerformed
new adicionar_morador(u.getEmail()).setVisible(true);
setVisible(false);
}//GEN-LAST:event_add_moradorActionPerformed
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(conta.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(conta.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(conta.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(conta.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new conta("email").setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton add_morador;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel5;
private javax.swing.JMenu jMenu1;
private javax.swing.JMenu jMenu2;
private javax.swing.JMenu jMenu3;
private javax.swing.JMenuItem jMenuItem1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JScrollPane jScrollPane3;
private javax.swing.JButton jadd_despesa;
private javax.swing.JButton jdel_morador;
private javax.swing.JButton jdesp_liquidadas;
private javax.swing.JButton jdesp_recorrentes;
private javax.swing.JButton jedit_conta;
private javax.swing.JLabel jsair;
private javax.swing.JLabel jsaldo;
private javax.swing.JTable tabela1;
private javax.swing.JTable tabela2;
// End of variables declaration//GEN-END:variables
}
| mit |
stivalet/PHP-Vulnerability-test-suite | Injection/CWE_98/safe/CWE_98__SESSION__CAST-cast_int_sort_of__include_file_id-sprintf_%d_simple_quote.php | 1174 | <?php
/*
Safe sample
input : get the UserData field of $_SESSION
sanitize : cast via + = 0
construction : use of sprintf via a %d with simple quote
*/
/*Copyright 2015 Bertrand STIVALET
Permission is hereby granted, without written agreement or royalty fee, to
use, copy, modify, and distribute this software and its documentation for
any purpose, provided that the above copyright notice and the following
three paragraphs appear in all copies of this software.
IN NO EVENT SHALL AUTHORS BE LIABLE TO ANY PARTY FOR DIRECT,
INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF AUTHORS HAVE
BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
AUTHORS SPECIFICALLY DISCLAIM ANY WARRANTIES INCLUDING, BUT NOT
LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE, AND NON-INFRINGEMENT.
THE SOFTWARE IS PROVIDED ON AN "AS-IS" BASIS AND AUTHORS HAVE NO
OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR
MODIFICATIONS.*/
$tainted = $_SESSION['UserData'];
$tainted += 0 ;
$var = include(sprintf("pages/'%d'.php", $tainted));
?> | mit |
interdate/dating4disabled | src/D4D/AppBundle/Entity/Income.php | 751 | <?php
namespace D4D\AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Income
*/
class Income
{
/**
* @var integer
*/
private $incomeid;
/**
* @var string
*/
private $incomename;
/**
* Get incomeid
*
* @return integer
*/
public function getIncomeid()
{
return $this->incomeid;
}
/**
* Set incomename
*
* @param string $incomename
* @return Income
*/
public function setIncomename($incomename)
{
$this->incomename = $incomename;
return $this;
}
/**
* Get incomename
*
* @return string
*/
public function getIncomename()
{
return $this->incomename;
}
}
| mit |
IbrahimCode/ReactReduxRouterStarter | src/containers/BookList/reducers.js | 885 | import * as BookActionTypes from './actionTypes'
const initialState = []
const reducer = (state = initialState, action) => {
switch (action.type) {
case BookActionTypes.GET_BOOK_LIST:
return [...action.payload.books]
case BookActionTypes.POST_BOOK:
return [...state, action.payload.book]
case BookActionTypes.POST_BOOK_REJECTED:
return state
case BookActionTypes.DELETE_BOOK:
return state.filter(book => book.id !== action.payload.id)
case BookActionTypes.UPDATE_BOOK_TITLE: {
const bookIndex = state.findIndex(book => book.id === action.payload.id)
return state.map((book, index) => {
if (index === bookIndex) {
return {
...book,
title: action.payload.title
}
}
return book
})
}
default:
return state
}
}
export default reducer
| mit |
kaicataldo/babel | packages/babel-plugin-transform-classes/test/fixtures/get-set/set-semantics-not-defined-on-parent-not-on-obj/output.js | 3766 | "use strict";
function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
function _possibleConstructorReturn(self, call) { if (call && (typeof call === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }
function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
function set(target, property, value, receiver) { if (typeof Reflect !== "undefined" && Reflect.set) { set = Reflect.set; } else { set = function set(target, property, value, receiver) { var base = _superPropBase(target, property); var desc; if (base) { desc = Object.getOwnPropertyDescriptor(base, property); if (desc.set) { desc.set.call(receiver, value); return true; } else if (!desc.writable) { return false; } } desc = Object.getOwnPropertyDescriptor(receiver, property); if (desc) { if (!desc.writable) { return false; } desc.value = value; Object.defineProperty(receiver, property, desc); } else { _defineProperty(receiver, property, value); } return true; }; } return set(target, property, value, receiver); }
function _set(target, property, value, receiver, isStrict) { var s = set(target, property, value, receiver || target); if (!s && isStrict) { throw new Error('failed to set property'); } return value; }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _superPropBase(object, property) { while (!Object.prototype.hasOwnProperty.call(object, property)) { object = _getPrototypeOf(object); if (object === null) break; } return object; }
function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }
function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
let Base = function Base() {
_classCallCheck(this, Base);
};
let Obj = /*#__PURE__*/function (_Base) {
_inherits(Obj, _Base);
function Obj() {
_classCallCheck(this, Obj);
return _possibleConstructorReturn(this, _getPrototypeOf(Obj).apply(this, arguments));
}
_createClass(Obj, [{
key: "set",
value: function set() {
return _set(_getPrototypeOf(Obj.prototype), "test", 3, this, true);
}
}]);
return Obj;
}(Base);
const obj = new Obj();
expect(obj.set()).toBe(3);
expect(Base.prototype.test).toBeUndefined();
expect(Obj.prototype.test).toBeUndefined();
expect(obj.test).toBe(3);
| mit |
facebookarchive/AntennaPod | src/de/danoeh/antennapod/activity/FeedInfoActivity.java | 7137 | package de.danoeh.antennapod.activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.*;
import de.danoeh.antennapod.BuildConfig;
import de.danoeh.antennapod.R;
import de.danoeh.antennapod.asynctask.ImageLoader;
import de.danoeh.antennapod.dialog.DownloadRequestErrorDialogCreator;
import de.danoeh.antennapod.feed.Feed;
import de.danoeh.antennapod.feed.FeedPreferences;
import de.danoeh.antennapod.preferences.UserPreferences;
import de.danoeh.antennapod.storage.DBReader;
import de.danoeh.antennapod.storage.DBWriter;
import de.danoeh.antennapod.storage.DownloadRequestException;
import de.danoeh.antennapod.util.LangUtils;
import de.danoeh.antennapod.util.menuhandler.FeedMenuHandler;
/**
* Displays information about a feed.
*/
public class FeedInfoActivity extends ActionBarActivity {
private static final String TAG = "FeedInfoActivity";
public static final String EXTRA_FEED_ID = "de.danoeh.antennapod.extra.feedId";
private Feed feed;
private ImageView imgvCover;
private TextView txtvTitle;
private TextView txtvDescription;
private TextView txtvLanguage;
private TextView txtvAuthor;
private EditText etxtUsername;
private EditText etxtPassword;
private CheckBox cbxAutoDownload;
@Override
protected void onCreate(Bundle savedInstanceState) {
setTheme(UserPreferences.getTheme());
super.onCreate(savedInstanceState);
setContentView(R.layout.feedinfo);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
long feedId = getIntent().getLongExtra(EXTRA_FEED_ID, -1);
imgvCover = (ImageView) findViewById(R.id.imgvCover);
txtvTitle = (TextView) findViewById(R.id.txtvTitle);
txtvDescription = (TextView) findViewById(R.id.txtvDescription);
txtvLanguage = (TextView) findViewById(R.id.txtvLanguage);
txtvAuthor = (TextView) findViewById(R.id.txtvAuthor);
cbxAutoDownload = (CheckBox) findViewById(R.id.cbxAutoDownload);
etxtUsername = (EditText) findViewById(R.id.etxtUsername);
etxtPassword = (EditText) findViewById(R.id.etxtPassword);
AsyncTask<Long, Void, Feed> loadTask = new AsyncTask<Long, Void, Feed>() {
@Override
protected Feed doInBackground(Long... params) {
return DBReader.getFeed(FeedInfoActivity.this, params[0]);
}
@Override
protected void onPostExecute(Feed result) {
if (result != null) {
feed = result;
if (BuildConfig.DEBUG)
Log.d(TAG, "Language is " + feed.getLanguage());
if (BuildConfig.DEBUG)
Log.d(TAG, "Author is " + feed.getAuthor());
imgvCover.post(new Runnable() {
@Override
public void run() {
ImageLoader.getInstance().loadThumbnailBitmap(
feed.getImage(), imgvCover);
}
});
txtvTitle.setText(feed.getTitle());
txtvDescription.setText(feed.getDescription());
if (feed.getAuthor() != null) {
txtvAuthor.setText(feed.getAuthor());
}
if (feed.getLanguage() != null) {
txtvLanguage.setText(LangUtils
.getLanguageString(feed.getLanguage()));
}
cbxAutoDownload.setEnabled(UserPreferences.isEnableAutodownload());
cbxAutoDownload.setChecked(feed.getPreferences().getAutoDownload());
cbxAutoDownload.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton compoundButton, boolean checked) {
feed.getPreferences().setAutoDownload(checked);
feed.savePreferences(FeedInfoActivity.this);
}
});
etxtUsername.setText(feed.getPreferences().getUsername());
etxtPassword.setText(feed.getPreferences().getPassword());
etxtUsername.addTextChangedListener(authTextWatcher);
etxtPassword.addTextChangedListener(authTextWatcher);
supportInvalidateOptionsMenu();
} else {
Log.e(TAG, "Activity was started with invalid arguments");
}
}
};
loadTask.execute(feedId);
}
private boolean authInfoChanged = false;
private TextWatcher authTextWatcher = new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
authInfoChanged = true;
}
};
@Override
protected void onPause() {
super.onPause();
if (feed != null && authInfoChanged) {
Log.d(TAG, "Auth info changed, saving credentials");
FeedPreferences prefs = feed.getPreferences();
prefs.setUsername(etxtUsername.getText().toString());
prefs.setPassword(etxtPassword.getText().toString());
DBWriter.setFeedPreferences(this, prefs);
authInfoChanged = false;
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.feedinfo, menu);
return true;
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
menu.findItem(R.id.support_item).setVisible(
feed != null && feed.getPaymentLink() != null);
menu.findItem(R.id.share_link_item).setVisible(feed != null &&feed.getLink() != null);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
return true;
default:
try {
return FeedMenuHandler.onOptionsItemClicked(this, item, feed);
} catch (DownloadRequestException e) {
e.printStackTrace();
DownloadRequestErrorDialogCreator.newRequestErrorDialog(this,
e.getMessage());
}
return super.onOptionsItemSelected(item);
}
}
}
| mit |
mathiasbynens/unicode-data | 6.3.0/scripts/Thai-regex.js | 122 | // Regular expression that matches all symbols in the `Thai` script as per Unicode v6.3.0:
/[\u0E01-\u0E3A\u0E40-\u0E5B]/; | mit |
yosuaalvin/sipuskom | application/views/admin/header.php | 5719 | <!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Sistem Informasi Pelatihan UPT Puskom UNDIP</title>
<link rel="shortcut icon" href="<?php echo base_url(); ?>assets/images/gundar.jpg" />
<!-- Bootstrap Styles-->
<link href="<?php echo base_url();?>assets/admin/css/jquery.dataTables.css" rel="stylesheet">
<link href="<?php echo base_url();?>assets/admin/css/bootstrap.css" rel="stylesheet" />
<!-- FontAwesome Styles-->
<link href="<?php echo base_url();?>assets/admin/css/font-awesome.css" rel="stylesheet" />
<!-- Morris Chart Styles-->
<!-- Custom Styles-->
<link href="<?php echo base_url();?>assets/admin/css/custom-styles.css" rel="stylesheet" />
<!-- Google Fonts-->
<!-- TABLE STYLES-->
<link href="<?php echo base_url();?>assets/admin/js/dataTables/dataTables.bootstrap.css" rel="stylesheet" />
</head>
<body>
<div id="wrapper">
<nav class="navbar navbar-default top-navbar" role="navigation">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".sidebar-collapse">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<img style="margin-top:5px" width="250" src="<?php echo base_url(); ?>assets/images/logo-undip.png"></img>
</div>
<ul class="nav navbar-top-links navbar-right">
<li class="dropdown">
<a class="dropdown-toggle" data-toggle="dropdown" href="#">
<i class="fa fa-user fa-fw"></i> <?php echo $pengguna->nama; ?> <i class="fa fa-caret-down"></i>
</a>
<ul class="dropdown-menu dropdown-user">
<li>
<a href="<?php echo base_url().'admin/welcome/logout'?>"><i class="fa fa-sign-out fa-fw"></i> Logout</a>
</li>
<li>
<a href="<?php echo base_url(); ?>admin/welcome/ganti_password"><i class="fa fa-sign-out fa-fw"></i> Ganti Password</a>
</li>
</ul>
<!-- /.dropdown-user -->
</li>
<!-- /.dropdown -->
</ul>
</nav>
<!--/. NAV TOP -->
<nav class="navbar-default navbar-side" role="navigation">
<div class="sidebar-collapse">
<ul class="nav" id="main-menu">
<li>
<a href="<?php echo base_url() ?>admin/welcome"><i class="fa fa-dashboard"></i> Dashboard</a>
</li>
<li>
<a href="<?php echo base_url(); ?>admin/welcome/kursus"><i class="fa fa-sitemap fa-fw"></i> Master<span class="fa arrow"></span></a>
<ul class="nav nav-second-level collapse">
<li>
<a href="<?php echo base_url();?>admin/welcome/laboratorium"><i class="fa fa-sitemap fa-fw"></i> Laboratorium</a>
</li>
<li>
<a href="<?php echo base_url();?>admin/welcome/kursus"><i class="fa fa-sitemap fa-fw"></i> Pelatihan</a>
</li>
<li>
<a href="<?php echo base_url();?>admin/welcome/rekening"><i class="fa fa-sitemap fa-fw"></i> Rekening</a>
</li>
<li>
<a href="<?php echo base_url();?>admin/welcome/akun_sosial"><i class="fa fa-sitemap fa-fw"></i> Akun Sosial</a>
</li>
</ul>
</li>
<li>
<a href="<?php echo base_url(); ?>admin/welcome/peserta"><i class="fa fa-table fa-fw"></i> Data Peserta<span class="fa arrow"></span></a>
<ul class="nav nav-second-level collapse">
<li>
<a href="<?php echo base_url();?>admin/welcome/peserta"><i class="fa fa-sitemap fa-fw"></i> Pelatihan </a>
</li>
<li>
<a href="<?php echo base_url();?>admin/welcome/peserta_custom"><i class="fa fa-sitemap fa-fw"></i> Pelatihan Custom </a>
</li>
<li>
<a href="<?php echo base_url();?>admin/welcome/cek_pembayaran"><i class="fa fa-sitemap fa-fw"></i> Cek Pembayaran </a>
</li>
</ul>
<li>
<a href="<?php echo base_url(); ?>admin/welcome/report"><i class="fa fa-check fa-fw"></i> Report<span class="fa arrow"></span></a>
<ul class="nav nav-second-level collapse">
<li>
<a href="<?php echo base_url();?>admin/welcome/form_report_pemasukan"><i class="fa fa-sitemap fa-fw"></i> Report Pemasukan </a>
</li>
<!--
<li>
<a href="<?php echo base_url();?>admin/welcome/report_pengeluaran"><i class="fa fa-sitemap fa-fw"></i> Report Pengeluaran </a>
</li>
<li>
<a href="<?php echo base_url();?>admin/welcome/report_laba_rugi"><i class="fa fa-sitemap fa-fw"></i> Report Laba Rugi </a>
</li>
-->
</ul>
</div>
</nav>
| mit |
dreamamine/structure_de_recherche | app/cache/dev/twig/30/30db38e01d124f5ae4aeed9b5c10f11b23647acce0d5e4af6b7d02af97a4b98f.php | 4532 | <?php
/* :user:edit.html.twig */
class __TwigTemplate_96be3a8b4cbedd110067f700d362d99888b1d4bf706cd79a65ce1c20b130ff87 extends Twig_Template
{
public function __construct(Twig_Environment $env)
{
parent::__construct($env);
// line 1
$this->parent = $this->loadTemplate("LgmBundle::layout.html.twig", ":user:edit.html.twig", 1);
$this->blocks = array(
'content' => array($this, 'block_content'),
);
}
protected function doGetParent(array $context)
{
return "LgmBundle::layout.html.twig";
}
protected function doDisplay(array $context, array $blocks = array())
{
$__internal_b608ff974cdf8c106acfbd7edeb2e74c2b9689228bdcc699fdd6804aead83abe = $this->env->getExtension("native_profiler");
$__internal_b608ff974cdf8c106acfbd7edeb2e74c2b9689228bdcc699fdd6804aead83abe->enter($__internal_b608ff974cdf8c106acfbd7edeb2e74c2b9689228bdcc699fdd6804aead83abe_prof = new Twig_Profiler_Profile($this->getTemplateName(), "template", ":user:edit.html.twig"));
$this->parent->display($context, array_merge($this->blocks, $blocks));
$__internal_b608ff974cdf8c106acfbd7edeb2e74c2b9689228bdcc699fdd6804aead83abe->leave($__internal_b608ff974cdf8c106acfbd7edeb2e74c2b9689228bdcc699fdd6804aead83abe_prof);
}
// line 3
public function block_content($context, array $blocks = array())
{
$__internal_93c82c4e636510643804e37cf77c2cb5bc68b934c59cd8590d0d2c860afcc289 = $this->env->getExtension("native_profiler");
$__internal_93c82c4e636510643804e37cf77c2cb5bc68b934c59cd8590d0d2c860afcc289->enter($__internal_93c82c4e636510643804e37cf77c2cb5bc68b934c59cd8590d0d2c860afcc289_prof = new Twig_Profiler_Profile($this->getTemplateName(), "block", "content"));
// line 4
echo " <h1>User edit</h1>
";
// line 6
echo $this->env->getExtension('form')->renderer->renderBlock((isset($context["edit_form"]) ? $context["edit_form"] : $this->getContext($context, "edit_form")), 'form_start');
echo "
";
// line 7
echo $this->env->getExtension('form')->renderer->searchAndRenderBlock((isset($context["edit_form"]) ? $context["edit_form"] : $this->getContext($context, "edit_form")), 'widget');
echo "
<input type=\"submit\" value=\"Edit\" />
";
// line 9
echo $this->env->getExtension('form')->renderer->renderBlock((isset($context["edit_form"]) ? $context["edit_form"] : $this->getContext($context, "edit_form")), 'form_end');
echo "
<ul>
<li>
<a href=\"";
// line 13
echo $this->env->getExtension('routing')->getPath("user_index");
echo "\">Back to the list</a>
</li>
<li>
";
// line 16
echo $this->env->getExtension('form')->renderer->renderBlock((isset($context["delete_form"]) ? $context["delete_form"] : $this->getContext($context, "delete_form")), 'form_start');
echo "
<input type=\"submit\" value=\"Delete\">
";
// line 18
echo $this->env->getExtension('form')->renderer->renderBlock((isset($context["delete_form"]) ? $context["delete_form"] : $this->getContext($context, "delete_form")), 'form_end');
echo "
</li>
</ul>
";
$__internal_93c82c4e636510643804e37cf77c2cb5bc68b934c59cd8590d0d2c860afcc289->leave($__internal_93c82c4e636510643804e37cf77c2cb5bc68b934c59cd8590d0d2c860afcc289_prof);
}
public function getTemplateName()
{
return ":user:edit.html.twig";
}
public function isTraitable()
{
return false;
}
public function getDebugInfo()
{
return array ( 71 => 18, 66 => 16, 60 => 13, 53 => 9, 48 => 7, 44 => 6, 40 => 4, 34 => 3, 11 => 1,);
}
}
/* {% extends('LgmBundle::layout.html.twig') %}*/
/* */
/* {% block content %}*/
/* <h1>User edit</h1>*/
/* */
/* {{ form_start(edit_form) }}*/
/* {{ form_widget(edit_form) }}*/
/* <input type="submit" value="Edit" />*/
/* {{ form_end(edit_form) }}*/
/* */
/* <ul>*/
/* <li>*/
/* <a href="{{ path('user_index') }}">Back to the list</a>*/
/* </li>*/
/* <li>*/
/* {{ form_start(delete_form) }}*/
/* <input type="submit" value="Delete">*/
/* {{ form_end(delete_form) }}*/
/* </li>*/
/* </ul>*/
/* {% endblock %}*/
/* */
| mit |
ldahleen54/learn-anything | server/helpers/votes.js | 3270 | const dynamo = require('../utils/dynamoClient');
const cache = require('../utils/cache');
const { cacheKeys } = require('../constants.json');
const { APIError } = require('../utils/errors');
// Possible directions for a vote.
const directions = {
'-1': 'down',
0: 'reset',
1: 'up',
};
// Create or modify a vote, update the score of the voted resource, and update
// the cached map.
async function vote(userID, resourceID, direction) {
const modifiedAt = (new Date()).toString();
let createdAt = (new Date()).toString();
let [vote, resource] = await Promise.all([
dynamo('get', { TableName: 'Votes', Key: { userID, resourceID } }),
dynamo('get', { TableName: 'Resources', Key: { resourceID } }),
]);
vote = vote.Item;
resource = resource.Item;
// Resource doesn't exist, or it was deleted.
if (!resource) {
throw new APIError(404, 'resource not found');
}
// Remove the previous vote if present.
if (vote) {
resource.score[directions[vote.direction]] -= 1;
createdAt = vote.createdAt;
}
// Add the new vote.
resource.score[directions[direction]] += 1;
delete resource.score.reset;
const newVote = {
userID,
resourceID,
direction,
createdAt,
modifiedAt,
mapID: resource.mapID,
};
// Update vote and resource on DynamoDB.
await Promise.all([
dynamo('put', { TableName: 'Votes', Item: newVote }),
dynamo('put', { TableName: 'Resources', Item: resource }),
]);
// Get the cached map, so we can update it and we don't need to make
// additional requests to the DB.
const map = await cache.get(cacheKeys.maps.byID + resource.mapID);
// Map is not cached. Highly improbable as the user that is voting needs to
// have got the map in some way, but not impossible, as we could have finished
// the memory available for memcached and this map could have been deleted
// from the cache.
if (!map) {
return { resource, vote: newVote };
}
console.log(`[MC] Replacing: ${cacheKeys.maps.byID + resource.mapID}`);
const nodeResources = map.resources[resource.parentID];
const oldResource = nodeResources.find(res => (
res.resourceID === resource.resourceID
));
const resourceIndex = nodeResources.indexOf(oldResource);
// Set the new map value on cache.
map.resources[resource.parentID][resourceIndex] = resource;
const cached = await cache.set(cacheKeys.maps.byID + resource.mapID, map);
console.log(`[MC] Cached: ${cached}`);
// Return the updated resource and vote, so the client doesn't need to reload the map.
return { resource, vote: newVote };
}
// Get votes by userID. Returns a promise.
function byUser(userID) {
return dynamo('query', {
TableName: 'Votes',
Select: 'ALL_ATTRIBUTES',
KeyConditionExpression: 'userID = :userID',
ExpressionAttributeValues: { ':userID': userID },
});
}
// Get user votes by mapID. Returns a promise.
function byUserMap(userID, mapID) {
return dynamo('query', {
TableName: 'Votes',
Select: 'ALL_ATTRIBUTES',
IndexName: 'MapIndex',
KeyConditionExpression: 'userID = :user and mapID = :map',
ExpressionAttributeValues: {
':user': userID,
':map': Number(mapID),
},
});
}
module.exports = {
byUser,
byUserMap,
vote,
};
| mit |
chk1/OpenSenseMap | app/scripts/services/validation.js | 908 | 'use strict';
/**
* @ngdoc service
* @name openSenseMapApp.validation
* @description
* # validation
* Factory in the openSenseMapApp.
*/
angular.module('openSenseMapApp')
.factory('Validation', ["$http", "$q", "OpenSenseBoxAPI", function ($http, $q, OpenSenseBoxAPI) {
var service = {};
var validApiKey = function (boxId, apiKey) {
return $http({
method: 'GET',
url: OpenSenseBoxAPI.url+'/users/'+boxId,
headers: {
'X-ApiKey':apiKey
}
});
};
service.checkApiKey = function (boxId, apiKey) {
var http = validApiKey(boxId,apiKey);
var deferred = $q.defer();
http.
success( function (data, status) {
deferred.resolve(status);
}).
error( function (data, status) {
deferred.resolve(status);
});
return deferred.promise;
};
return service;
}]);
| mit |
mjwestcott/chatroulette | twistedchat.py | 6644 | """
twistedchat.py
A TCP chat server in the style of 'Chatroulette' using Twisted.
Part of a study in concurrency and networking in Python:
https://github.com/mjwestcott/chatroulette in which I create versions of this
server using asyncio, gevent, Tornado, and Twisted.
Some 'features':
- on connection, clients are prompted for their name, which will prefix all
of their sent messages;
- the server will notify clients when they are matched with a partner or
their partner disconnects;
- clients whose partner disconnects will be put back in a waiting list to
be matched again;
- clients in the waiting list will periodically be sent a Nietzsche aphorism
to keep them busy;
- clients can issue the following commands:
/help -> describes the service, including the commands below
/quit -> close the connection
/next -> end current chat and wait for a new partner
- the /next command will remember the rejected partners so as not to match
them together again.
Clients are expected to connect via telnet.
"""
from twisted.protocols.basic import LineReceiver
from twisted.internet.protocol import Factory
from twisted.internet import reactor
import random
HOST = 'localhost'
PORT = 12345
with open("nietzsche.txt", "r") as f:
# We'll use these to keep waiting clients busy.
aphorisms = list(filter(bool, f.read().split("\n")))
def main():
reactor.listenTCP(PORT, ChatFactory(), interface=HOST)
reactor.run()
class ChatProtocol(LineReceiver):
delimiter = b'\n'
def __init__(self):
self.name = None
self.partner = None
self.rejected = set()
def connectionMade(self):
# Prompt user for name. Answer will be picked up in lineReceived.
self.sendLine(
b'Server: Welcome to TCP chat roulette! '
b'You will be matched with a partner.')
self.sendLine(b'Server: What is your name?')
def connectionLost(self, exception):
if self.name in self.factory.clients:
del self.factory.clients[self.name]
# Notify the client's partner, if any.
other = self.partner
if other is not None:
other.partnerDisconnected()
def lineReceived(self, data):
if self.name is None: # First interaction with user; data is user's name.
self.handleName(data)
elif data.startswith(b'/'):
self.handleCmd(data)
else:
self.messagePartner(data)
def handleName(self, name):
if name in self.factory.clients:
self.sendLine(b'Server: Sorry, that name is taken. Please choose again.')
else:
self.name = name
self.factory.clients[self.name] = self
self.sendLine(b'Server: Hello, %b. Please wait for a partner.' % self.name)
# Successful onboarding; match client.
reactor.callLater(0, self.match)
def handleCmd(self, cmd):
if cmd.startswith(b'/help'):
self.sendLine(b'Server: Welcome to TCP chat roulette! You will be matched with a partner.')
self.sendLine(b'\t/help -> display this help message')
self.sendLine(b'\t/quit -> close the connection')
self.sendLine(b'\t/next -> end current chat and wait for a new random partner')
elif cmd.startswith(b'/quit'):
self.transport.loseConnection()
elif cmd.startswith(b'/next'):
other = self.partner
if other is None:
# Command issued when not enagaged in chat with a partner.
self.sendLine(b'Server: Sorry, no partner. Please wait.')
else:
self.sendLine(b'Server: Chat over. Please wait for a new partner.')
self.rejected.add(other)
self.partner = None
reactor.callLater(0, self.match)
# Let down the partner gently.
other.partnerDisconnected()
else:
self.sendLine(b'Server: Command not recognised.')
def partnerDisconnected(self):
self.partner = None
self.sendLine(b'Server: Partner disconnected. Please wait.')
reactor.callLater(0, self.match)
def messagePartner(self, msg):
"""Send msg from the sender to their partner. Prefix the message with the
sender's name."""
assert isinstance(msg, bytes)
partner = self.partner
if partner is None:
self.sendLine(b'Server: Sorry, no partner. Please wait.')
else:
partner.sendLine(b'%b: %b' % (self.name, msg))
def match(self, tries=1):
# The global clients dict and waiting set.
waiting = self.factory.waiting
clients = self.factory.clients
# Find any clients who do not have a partner and add them to the
# waiting set.
waiting.update(c for c in clients.values() if c.partner is None)
# Find any clients in the waiting set who have disconnected and remove
# them from the waiting set. (If they are disconnected they will have
# been removed from the client list.)
waiting.intersection_update(clients.values())
if self not in waiting:
# We've been matched by our partner or we've disconnected.
return
if len(waiting) >= 2:
# Attempt to match clients.
A = self
wanted = waiting - A.rejected
partners = [B for B in wanted if A not in B.rejected and A != B]
if partners:
# Match succeeded.
B = partners.pop()
waiting.remove(A)
waiting.remove(B)
A.partner = B
B.partner = A
A.sendLine(b'Server: Partner found! Say hello.')
B.sendLine(b'Server: Partner found! Say hello.')
return
# Match failed. Periodically send something interesting.
if tries % 5 == 0:
aphorism = random.choice(aphorisms)
self.transport.write(
b'Server: Thanks for waiting! Here\'s Nietzsche:\n'
b'\n%b\n\n' % aphorism.encode("utf-8"))
# Exponential backoff up to a maximum sleep of 20 secs.
reactor.callLater(min(20, (tries**2)/4), self.match, tries+1)
class ChatFactory(Factory):
protocol = ChatProtocol
def __init__(self):
self.clients = {} # From names (bytes) to ChatProtocol instances.
self.waiting = set() # Clients without a partner i.e. waiting to chat.
if __name__ == '__main__':
main()
| mit |
Betterment/test_track | app/controllers/api/v1/split_configs_controller.rb | 630 | class Api::V1::SplitConfigsController < AuthenticatedApiController
def create
split_upsert = SplitUpsert.new(create_params.merge(app: current_app))
if split_upsert.save
head :no_content
else
render_errors split_upsert
end
end
def destroy
split = current_app.splits.find_by!(name: params[:id])
split.update!(finished_at: Time.zone.now) unless split.finished?
head :no_content
end
private
def create_params
# rails-sponsored workaround https://github.com/rails/rails/pull/12609
params.permit(:name, weighting_registry: params[:weighting_registry].try(:keys))
end
end
| mit |
clockworkpc/launchschool | notes/preparatory_work/100_programming_and_back-end_prep/100_theory/loops_1/09_thats_odd.rb | 64 | (1..100).each { |i|
# puts i if i % 2 == 1
puts i if i.odd?
}
| mit |
cliffano/swaggy-jenkins | clients/scala-lagom-server/generated/src/main/scala/io/swagger/client/model/Users.scala | 520 | /**
* Swaggy Jenkins
* Jenkins API clients generated from Swagger / Open API specification
*
* OpenAPI spec version: 1.1.1
* Contact: [email protected]
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package io.swagger.client.model
import play.api.libs.json._
import scala.collection.mutable.ListBuffer
case class Users (
)
object Users {
implicit val format: Format[Users] = Json.format
}
| mit |
Geal/MockCA | config/routes.rb | 2372 | MockCA::Application.routes.draw do
get '/certificates', :controller => 'certificate', :action => 'index', :as => 'certificates'
post 'certificates_root', :controller => 'certificate', :action => 'create_root', :as => 'certificates_root'
post 'certificates', :controller => 'certificate', :action => 'create', :as => 'certificates'
get 'certificate/new'
get 'certificate/:id', :controller => 'certificate', :action => 'show', :as => 'certificate'
get 'certificate/root/new', :controller => 'certificate', :action => 'new_root', :as => 'root_certificate'
get "certificate/create"
get "certificate/destroy"
# The priority is based upon order of creation:
# first created -> highest priority.
# Sample of regular route:
# match 'products/:id' => 'catalog#view'
# Keep in mind you can assign values other than :controller and :action
# Sample of named route:
# match 'products/:id/purchase' => 'catalog#purchase', :as => :purchase
# This route can be invoked with purchase_url(:id => product.id)
# Sample resource route (maps HTTP verbs to controller actions automatically):
# resources :products
# Sample resource route with options:
# resources :products do
# member do
# get 'short'
# post 'toggle'
# end
#
# collection do
# get 'sold'
# end
# end
# Sample resource route with sub-resources:
# resources :products do
# resources :comments, :sales
# resource :seller
# end
# Sample resource route with more complex sub-resources
# resources :products do
# resources :comments
# resources :sales do
# get 'recent', :on => :collection
# end
# end
# Sample resource route within a namespace:
# namespace :admin do
# # Directs /admin/products/* to Admin::ProductsController
# # (app/controllers/admin/products_controller.rb)
# resources :products
# end
# You can have the root of your site routed with "root"
# just remember to delete public/index.html.
root :to => "home#index"
# See how all your routes lay out with "rake routes"
# This is a legacy wild controller route that's not recommended for RESTful applications.
# Note: This route will make all actions in every controller accessible via GET requests.
# match ':controller(/:action(/:id(.:format)))'
end
| mit |
Terminus-Project/Terminus-Bot | scripts/gizoogle.rb | 1996 | #
# Terminus-Bot: An IRC bot to solve all of the problems with IRC bots.
#
# Copyright (C) 2010-2015 Kyle Johnson <[email protected]>, Alex Iadicicco
# (http://terminus-bot.net/)
#
# 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.
#
require 'strscan'
need_module! 'http'
register 'Translate text using Gizoogle.'
command 'gizoogle', 'Translate text using Gizoogle' do
argc! 1
uri = URI('http://www.gizoogle.net/textilizer.php')
text = URI.encode @params.first
body = "translatetext=#{text}"
opts = {
:head => {
'Content-Type' => 'application/x-www-form-urlencoded',
'Content-Length' => body.length
},
:body => body
}
http_post(uri, {}, false, opts) do |http|
page = StringScanner.new http.response
page.skip_until(/<textarea[^>]*>/ix)
text = page.scan_until(/<\/textarea[^>]*>/ix)
next if text == nil
text = html_decode text[0..-12]
text = text.gsub(/[[[:cntrl:]]\s]+/, ' ').strip
reply text
end
end
| mit |
Bogh/omckle | main.go | 1789 | package main
import (
"log"
"net/http"
"time"
"github.com/gin-gonic/gin"
)
func main() {
err := Check()
if err != nil {
log.Fatalln("Check method failed: ", err)
}
err = InitClient()
if err != nil {
log.Fatalln("Error initializing torrent client: ", err)
}
router := gin.Default()
router.Static("/static", "./static")
router.LoadHTMLGlob("templates/*")
router.
GET("/", func(c *gin.Context) {
c.HTML(http.StatusOK, "index.gohtml", nil)
}).
POST("/", func(c *gin.Context) {
ctx := gin.H{}
switch c.DefaultPostForm("format", "magnet") {
case "magnet":
magnetLink := c.PostForm("magnet")
if magnetLink == "" {
ctx["Error"] = "Magnet url is required."
}
err := AddMagnetLink(magnetLink)
if err == nil {
ctx["Success"] = true
} else {
ctx["Error"] = err.Error()
}
case "file":
file, header, err := c.Request.FormFile("upload")
if err != nil {
log.Println("Error reading request file: ", err)
ctx["Error"] = "Cannot read uploaded file. Invalid file uploaded."
break
}
filename := header.Filename
log.Println("Uploaded file: ", filename)
if err = AddFromReader(file); err != nil {
ctx["Error"] = "Cannot add torrent from uploaded file."
break
}
}
c.HTML(http.StatusOK, "index.gohtml", ctx)
})
stream := router.Group("/stream")
{
stream.GET("/", func(c *gin.Context) {
if ActivePlayer == nil {
c.String(http.StatusNotFound, "No video found.")
return
}
http.ServeContent(c.Writer, c.Request, ActivePlayer.File.Path(), time.Time{}, ActivePlayer.Reader)
})
}
player := router.Group("/player", gin.ErrorLogger())
{
player.POST("/:action", PlayerAPIAction)
}
router.Run(":8080")
}
func Check() error {
return nil
}
| mit |
stripe/netsuite | spec/netsuite/records/customer_refund_apply_spec.rb | 345 | require 'spec_helper'
describe NetSuite::Records::CustomerRefundApply do
let(:apply) { NetSuite::Records::CustomerRefundApply.new }
it 'has all the right fields' do
[
:amount, :apply, :apply_date, :currency, :doc, :due, :line, :ref_num, :total, :type
].each do |field|
apply.should have_field(field)
end
end
end
| mit |
wenerme/tellets | telletsj-core/src/main/java/me/wener/telletsj/collect/impl/SourceContent.java | 1442 | package me.wener.telletsj.collect.impl;
import com.google.common.base.Throwables;
import java.net.URI;
import lombok.Data;
import me.wener.telletsj.collect.CollectionException;
import me.wener.telletsj.util.IO;
/**
* 收集到的内容<br>
* 对于一些特殊的内容,可以考虑实现子类来做定制
*/
@Data
public class SourceContent
{
/**
* 该源的属性
*/
// private final Map<String, Object> properties = Maps.newConcurrentMap();
private URI uri;
/**
* 文件名
*/
private String filename;
/**
* 源内容
*/
private String content;
/**
* 内容Sha1值
*/
private String sha;
public final String getContent()
{
if (content == null)
try
{
fillContent();
} catch (CollectionException e)
{
Throwables.propagate(e);
}
return content;
}
public final String getSha()
{
// 延迟 hash
if (sha == null)
{
try
{
getSha0();
} catch (CollectionException e)
{
Throwables.propagate(e);
}
}
return sha;
}
protected void getSha0() throws CollectionException
{
this.setSha(IO.sha(getContent()));
}
protected void fillContent() throws CollectionException
{
}
}
| mit |
MDE4CPP/examples | fUMLExamples/Alf/fUMLTest/src-gen/NewModelexec/CoaIsOddExecution.hpp | 862 | #ifndef NEWMODEL_CHECKIFPRIMECOAISODD_EXECUTION_HPP
#define NEWMODEL_CHECKIFPRIMECOAISODD_EXECUTION_HPP
//********************************************************************
//*
//* Warning: This file was generated by Mesapp Generator
//*
//********************************************************************
#include "impl/OpaqueBehaviorExecutionImpl.hpp"
namespace NewModel {
class CoaIsOddExecution : public fUML::OpaqueBehaviorExecutionImpl
{
public:
CoaIsOddExecution(CoaIsOddExecution &obj);
//constructor
CoaIsOddExecution();
//destructor
virtual ~CoaIsOddExecution();
virtual void doBody(QList<fUML::ParameterValue * > * inputParameters,QList<fUML::ParameterValue * > * outputParameters);
virtual ecore::EObject * copy();
};
}
#endif /* end of include guard: NEWMODEL_CHECKIFPRIMECOAISODD_EXECUTION_HPP */
| mit |
DripEmail/drip-dot-net | DripDotNetTests/TagTests.cs | 6305 | /*
The MIT License (MIT)
Copyright (c) 2015 - 2017 Avenue 81 Inc. d/b/a Leadpages, All Rights Reserved
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
using Drip;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using Xunit;
namespace DripDotNetTests
{
public class TagTests : IClassFixture<DripClientFixture>, IClassFixture<SubscriberFactoryFixture>
{
DripClientFixture dripClientFixture;
SubscriberFactoryFixture subscriberFactoryFixture;
public TagTests(DripClientFixture dripClientFixture, SubscriberFactoryFixture subscriberFactoryFixture)
{
this.dripClientFixture = dripClientFixture;
this.subscriberFactoryFixture = subscriberFactoryFixture;
}
[Fact]
public void CanApplyAndRemoveTags()
{
var originalSubscriber = subscriberFactoryFixture.CreateComplexUniqueModifyDripSubscriber();
dripClientFixture.Client.CreateOrUpdateSubscriber(originalSubscriber);
var newTag = Guid.NewGuid().ToString("n");
var result = dripClientFixture.Client.ApplyTagToSubscriber(originalSubscriber.Email, newTag);
DripAssert.Success(result, HttpStatusCode.Created);
var oldTag = originalSubscriber.Tags[0];
result = dripClientFixture.Client.RemoveTagFromSubscriber(originalSubscriber.Email, oldTag);
DripAssert.Success(result, HttpStatusCode.NoContent);
var subscriberResult = dripClientFixture.Client.GetSubscriber(originalSubscriber.Email);
DripAssert.Success(subscriberResult);
var newSubscriber = subscriberResult.Subscribers.First();
Assert.True(newSubscriber.Tags.Contains(newTag));
Assert.False(newSubscriber.Tags.Contains(oldTag));
}
[Fact]
public void ApplyingTagCreatesSubscriber()
{
var email = subscriberFactoryFixture.GetRandomEmailAddress();
var tag = Guid.NewGuid().ToString();
var result = dripClientFixture.Client.ApplyTagToSubscriber(email, tag);
DripAssert.Success(result, HttpStatusCode.Created);
var subscriberResult = dripClientFixture.Client.GetSubscriber(email);
DripAssert.Success(subscriberResult);
var newSubscriber = subscriberResult.Subscribers.First();
Assert.True(newSubscriber.Tags.Contains(tag));
}
[Fact]
public void CanRemoveNonExistantTag()
{
var originalSubscriber = subscriberFactoryFixture.CreateComplexUniqueModifyDripSubscriber();
dripClientFixture.Client.CreateOrUpdateSubscriber(originalSubscriber);
var tag = Guid.NewGuid().ToString();
var result = dripClientFixture.Client.RemoveTagFromSubscriber(originalSubscriber.Email, tag);
DripAssert.Success(result, HttpStatusCode.NoContent);
}
[Fact]
public async Task CanApplyAndRemoveTagsAsync()
{
var originalSubscriber = subscriberFactoryFixture.CreateComplexUniqueModifyDripSubscriber();
await dripClientFixture.Client.CreateOrUpdateSubscriberAsync(originalSubscriber);
var newTag = Guid.NewGuid().ToString("n");
var result = await dripClientFixture.Client.ApplyTagToSubscriberAsync(originalSubscriber.Email, newTag);
DripAssert.Success(result, HttpStatusCode.Created);
var oldTag = originalSubscriber.Tags[0];
result = await dripClientFixture.Client.RemoveTagFromSubscriberAsync(originalSubscriber.Email, oldTag);
DripAssert.Success(result, HttpStatusCode.NoContent);
var subscriberResult = await dripClientFixture.Client.GetSubscriberAsync(originalSubscriber.Email);
DripAssert.Success(subscriberResult);
var newSubscriber = subscriberResult.Subscribers.First();
Assert.True(newSubscriber.Tags.Contains(newTag));
Assert.False(newSubscriber.Tags.Contains(oldTag));
}
[Fact]
public async Task ApplyingTagCreatesSubscriberAsync()
{
var email = subscriberFactoryFixture.GetRandomEmailAddress();
var tag = Guid.NewGuid().ToString();
var result = await dripClientFixture.Client.ApplyTagToSubscriberAsync(email, tag);
DripAssert.Success(result, HttpStatusCode.Created);
var subscriberResult = await dripClientFixture.Client.GetSubscriberAsync(email);
DripAssert.Success(subscriberResult);
var newSubscriber = subscriberResult.Subscribers.First();
Assert.True(newSubscriber.Tags.Contains(tag));
}
[Fact]
public async Task CanRemoveNonExistantTagAsync()
{
var originalSubscriber = subscriberFactoryFixture.CreateComplexUniqueModifyDripSubscriber();
await dripClientFixture.Client.CreateOrUpdateSubscriberAsync(originalSubscriber);
var tag = Guid.NewGuid().ToString();
var result = await dripClientFixture.Client.RemoveTagFromSubscriberAsync(originalSubscriber.Email, tag);
DripAssert.Success(result, HttpStatusCode.NoContent);
}
}
}
| mit |
1tush/reviewboard | reviewboard/webapi/resources/repository_commits.py | 4469 | from __future__ import unicode_literals
from django.core.exceptions import ObjectDoesNotExist
from django.utils import six
from djblets.webapi.decorators import (webapi_response_errors,
webapi_request_fields)
from djblets.webapi.errors import DOES_NOT_EXIST
from reviewboard.reviews.models import ReviewRequest
from reviewboard.webapi.base import WebAPIResource
from reviewboard.webapi.decorators import (webapi_check_login_required,
webapi_check_local_site)
from reviewboard.webapi.errors import REPO_NOT_IMPLEMENTED
from reviewboard.webapi.resources import resources
class RepositoryCommitsResource(WebAPIResource):
"""Provides information on the commits in a repository.
Get a single page of commit history from the repository. This will usually
be 30 items, but the exact count is dependent on the repository type. The
'start' parameter is the id of the most recent commit to start fetching log
information from.
Successive pages of commit history can be fetched by using the 'parent'
field of the last entry as the 'start' parameter for another request.
Returns an array of objects with the following fields:
'author_name' is a string with the author's real name or user name,
depending on the repository type.
'id' is a string representing the revision identifier of the commit,
and the format depends on the repository type (it may contain an
integer, SHA-1 hash, or other type).
'date' is an ISO8601-formatted string.
'message' is a string with the commit message, if any.
'parent' is a string with the id of the parent revision. This may be
the empty string for the first revision in the commit history. The
parent
This is not available for all types of repositories.
"""
name = 'commits'
policy_id = 'repository_commits'
singleton = True
allowed_methods = ('GET',)
mimetype_item_resource_name = 'repository-commits'
@webapi_check_local_site
@webapi_check_login_required
@webapi_response_errors(DOES_NOT_EXIST, REPO_NOT_IMPLEMENTED)
@webapi_request_fields(
optional={
'branch': {
'type': six.text_type,
"description": "The ID of the branch to limit the commits "
"to, as provided by the 'id' field of the "
"repository branches API.",
},
'start': {
'type': six.text_type,
'description': 'A commit ID to start listing from.',
},
}
)
def get(self, request, branch=None, start=None, *args, **kwargs):
"""Retrieves a set of commits from a particular repository.
The ``start`` parameter is a commit ID to use as a starting point. This
allows both pagination and logging of different branches. Successive
pages of commit history can be fetched by using the ``parent`` field of
the last entry as the ``start`` parameter for another request.
"""
try:
repository = resources.repository.get_object(request, *args,
**kwargs)
except ObjectDoesNotExist:
return DOES_NOT_EXIST
try:
items = repository.get_commits(branch=branch, start=start)
except NotImplementedError:
return REPO_NOT_IMPLEMENTED
commits = []
commit_ids = []
for commit in items:
commits.append({
'author_name': commit.author_name,
'id': commit.id,
'date': commit.date,
'message': commit.message,
'parent': commit.parent,
})
commit_ids.append(commit.id)
by_commit_id = {}
for obj in ReviewRequest.objects.filter(commit_id__in=commit_ids):
by_commit_id[obj.commit_id] = obj
for commit in commits:
try:
review_request = by_commit_id[commit['id']]
commit['review_request_url'] = \
review_request.get_absolute_url()
except KeyError:
commit['review_request_url'] = ''
return 200, {
self.item_result_key: commits,
}
repository_commits_resource = RepositoryCommitsResource()
| mit |
kairera0467/TJAP2fPC | FDK17プロジェクト/コード/03.サウンド/ISoundDevice.cs | 899 | using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;
using Un4seen.Bass;
using Un4seen.BassAsio;
using Un4seen.BassWasapi;
using Un4seen.Bass.AddOn.Mix;
namespace FDK
{
public interface ISoundDevice : IDisposable
{
ESoundDeviceType e出力デバイス { get; }
int nMasterVolume { get; set; }
long n実出力遅延ms { get; }
long n実バッファサイズms { get; }
long n経過時間ms { get; }
long n経過時間を更新したシステム時刻ms { get; }
CTimer tmシステムタイマ { get; }
CSound tサウンドを作成する( string strファイル名 );
CSound tサウンドを作成する( byte[] byArrWAVファイルイメージ );
void tサウンドを作成する( string strファイル名, ref CSound sound );
void tサウンドを作成する( byte[] byArrWAVファイルイメージ, ref CSound sound );
}
}
| mit |
Ketouem/py-showcase | tests/test_conf.py | 431 | from nose.tools import assert_is_not_none
from py_showcase import create_app
class TestConf(object):
def setUp(self):
self.app = create_app()
self.client = self.app.test_client()
def test_mandatory_data_exist(self):
assert_is_not_none(self.app.config['SECRET_KEY'])
assert_is_not_none(self.app.config['EMAIL_SUBJECT_PREFIX'])
assert_is_not_none(self.app.config['EMAIL_SENDER'])
| mit |
jjenki11/blaze-chem-rendering | qca_designer/lib/pnetlib-0.8.0/DotGNU.SSL/ISecureSession.cs | 5673 | /*
* ISecureSession.cs - Implementation of the
* "DotGNU.SSL.ISecureSession" class.
*
* Copyright (C) 2003 Southern Storm Software, Pty Ltd.
*
* This program is free software, you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY, without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program, if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
namespace DotGNU.SSL
{
using System;
using System.IO;
/// <summary>
/// <para>The <see cref="T:DotGNU.SSL.ISecureSession"/> interface
/// is implemented by classes that provide secure client or server
/// session functionality to the application program.</para>
/// </summary>
public interface ISecureSession : IDisposable
{
/// <summary>
/// <para>Determines if this session is handling a client.</para>
/// </summary>
///
/// <value>
/// <para>Returns <see langword="true"/> if this session is
/// handling a client, or <see langword="false"/> if this session
/// is handling a server.</para>
/// </value>
bool IsClient { get; }
/// <summary>
/// <para>Get or set the X.509 certificate for the local machine.</para>
/// </summary>
///
/// <value>
/// <para>The ASN.1 form of the certificate.</para>
/// </value>
///
/// <remarks>
/// <para>This property must be set for server sessions, and for
/// client sessions that perform client authentication.</para>
/// </remarks>
///
/// <exception cref="T:System.ArgumentNullException">
/// <para>The supplied value was <see langword="null"/>.</para>
/// </exception>
///
/// <exception cref="T:System.ArgumentException">
/// <para>The supplied value was not a valid certificate.</para>
/// </exception>
///
/// <exception cref="T:System.InvalidOperationException">
/// <para>The certificate was already set previously, or
/// the handshake has already been performed.</para>
/// </exception>
///
/// <exception cref="T:System.ObjectDisposedException">
/// <para>The secure session has been disposed.</para>
/// </exception>
byte[] Certificate { get; set; }
/// <summary>
/// <para>Get or set the private key for the local machine.</para>
/// </summary>
///
/// <value>
/// <para>The ASN.1 form of the RSA private key.</para>
/// </value>
///
/// <remarks>
/// <para>This property must be set for server sessions, and for
/// client sessions that perform client authentication.</para>
/// </remarks>
///
/// <exception cref="T:System.ArgumentNullException">
/// <para>The supplied value was <see langword="null"/>.</para>
/// </exception>
///
/// <exception cref="T:System.ArgumentException">
/// <para>The supplied value was not a valid private key.</para>
/// </exception>
///
/// <exception cref="T:System.InvalidOperationException">
/// <para>The private key was already set previously, or
/// the handshake has already been performed.</para>
/// </exception>
///
/// <exception cref="T:System.ObjectDisposedException">
/// <para>The secure session has been disposed.</para>
/// </exception>
byte[] PrivateKey { get; set; }
/// <summary>
/// <para>Get the certificate of the remote host once the
/// secure connection has been established.</para>
/// </summary>
///
/// <value>
/// <para>The ASN.1 form of the certificate, or <see langword="null"/>
/// if the secure connection has not yet been established.</para>
/// </value>
byte[] RemoteCertificate { get; }
/// <summary>
/// <para>Perform the initial handshake on a
/// <see cref="T:System.Net.Sockets.Socket"/> instance and
/// return a stream that can be used for secure communications.</para>
/// </summary>
///
/// <param name="socket">
/// <para>The socket to use for the underlying communications channel.
/// </para>
/// </param>
///
/// <exception name="T:System.ArgumentNullException">
/// <para>The <paramref name="socket"/> parameter is
/// <see langword="null"/>.</para>
/// </exception>
///
/// <exception name="T:System.ArgumentException">
/// <para>The <paramref name="socket"/> parameter is not a
/// valid socket object.</para>
/// </exception>
///
/// <exception name="T:System.InvalidOperationException">
/// <para>The handshake has already been performed.</para>
/// </exception>
///
/// <exception name="T:System.NotSupportedException">
/// <para>The secure handshake could not be performed because
/// the necessary provider objects could not be created.
/// Usually this is because the provider is out of memory.</para>
/// </exception>
///
/// <exception name="T:System.ObjectDisposedException">
/// <para>The secure session has been disposed.</para>
/// </exception>
///
/// <exception name="T:System.Security.SecurityException">
/// <para>Some kind of security error occurred while attempting
/// to establish the secure connection.</para>
/// </exception>
Stream PerformHandshake(Object socket);
/// <summary>
/// <para>Get the secure communications stream.</para>
/// </summary>
///
/// <value>
/// <para>Returns the secure communications stream, or
/// <see langword="null"/> if the handshake has not yet
/// been performed.</para>
/// </value>
Stream SecureStream { get; }
}; // interface ISecureSession
}; // namespace DotGNU.SSL
| mit |
JohnGrekso/GeckoUBL | src/GeckoUBL.Tests/Ubl21/Documents/OrderResponseSimpleTests.cs | 943 | using GeckoUBL.Ubl21.Documents;
using GeckoUBL.Ubl21.Extensions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace GeckoUBL.Tests.Ubl21.Documents
{
[TestClass]
public class OrderResponseSimpleTests
{
private string _xsdFile;
private OrderResponseSimpleType _document;
[TestInitialize]
public void TestInitialize()
{
_xsdFile = Helpers.XsdFolder + "UBL-OrderResponseSimple-2.1.xsd";
var exampleFile = Helpers.ExampleFolder + "UBL-OrderResponseSimple-2.1-Example.xml";
_document = UblDocumentLoader<OrderResponseSimpleType>.GetDocument(exampleFile);
}
[TestMethod]
public void GivenObject_ThenSchemaIsValid()
{
var actual = _document.Validate(_xsdFile);
Assert.IsTrue(actual.IsValid, actual.Errors);
}
[TestMethod]
public void GivenObject_ThenSchemaIsNotValid()
{
_document.ID = null;
var actual = _document.Validate(_xsdFile);
Assert.IsFalse(actual.IsValid);
}
}
}
| mit |
xenadevel/xenascriptlibs | layer47/python/Info.py | 3372 | #!/usr/bin/python
import os, sys, time, getopt, re, datetime
lib_path = os.path.abspath('testutils')
sys.path.append(lib_path)
from TestUtilsL47 import XenaScriptTools
def helptext():
print
print "Usage: %s ipaddr\n" % (sys.argv[0])
print
print " prints various version and serial numbers."
print
sys.exit(1)
def main(argv):
c_debug = 0
try:
opts, args = getopt.getopt(sys.argv[1:], "dhn")
except getopt.GetoptError:
helptext()
return
for opt, arg in opts:
if opt == '-h':
helptext()
return
elif opt in ("-d"):
c_debug=1
if len(args) != 1:
helptext()
ip_address = args[0]
xm = XenaScriptTools(ip_address)
if c_debug:
xm.debugOn()
xm.haltOn()
xm.Logon("xena")
# Start with CHASSIS
s_serial = xm.Send("C_SERIALNO ?").split()[1]
versionno = xm.Send("C_VERSIONNO ?").split()
s_version1 = versionno[1]
s_version2 = versionno[2]
r_model = re.search( '.*"(.*)"' , xm.Send("C_MODEL ?") )
s_model = r_model.group(1)
# License stuff
res = xm.Send("1 M4_LICENSE_INFO ?")
s_lic_pes = res.split()[2]
s_lic_pes_inuse = res.split()[3]
s_lic_port_type_1 = res.split()[4]
s_lic_port_type_1_inuse = res.split()[5]
s_lic_port_type_2 = res.split()[6]
s_lic_port_type_2_inuse = res.split()[7]
s_lic_port_type_3 = res.split()[8]
s_lic_port_type_3_inuse = res.split()[9]
s_lic_port_type_4 = res.split()[10]
s_lic_port_type_4_inuse = res.split()[11]
# proceed to MODULE
r_m_status = re.search( '.*"(.*)"', xm.Send(" 1 M4_SYSTEM_STATUS ?") )
s_m_status = r_m_status.group(1)
# if module is ok
if (s_m_status == "OK"):
s_m_serial = xm.Send("1 M_SERIALNO ?").split()[2]
s_m_version = xm.Send("1 M_VERSIONNO ?").split()[2]
r_m_version = re.search( '.*"(.*) (.*)"', xm.Send("1 M4_VERSIONNO ?") )
s_m_verstr = r_m_version.group(1)
s_m_build = r_m_version.group(2)
s_m_sysid = xm.Send(" 1 M4_SYSTEMID ?").split()[2]
print
print "Date: %s" % (datetime.datetime.today())
print "Chassis ip address: %s" % (ip_address)
print "Chassis model: %s" % (s_model)
print "Chassis serial number: %s (0x%08x)" % (s_serial, int(s_serial))
print "Chassis server version: %s" % (s_version1)
print "Chassis driver version: %s" % (s_version2)
print "Module serial number: %s (0x%08x)" % (s_m_serial, int(s_m_serial))
print "Module version number: %s" % (s_m_version)
print "Module version string: %s" % (s_m_verstr)
print "Module status: %s" % (s_m_status)
print "Module system id: %s" % (s_m_sysid)
print "Licensed PE's: %s (%s in use)" % (s_lic_pes, s_lic_pes_inuse)
print "Licensed 1G/10G ports: %s (%s in use)" % (s_lic_port_type_1, s_lic_port_type_1_inuse)
print "Licensed 1G/2.5G/5G/10G ports: %s (%s in use)" % (s_lic_port_type_2, s_lic_port_type_2_inuse)
print "Licensed 1G/10G/25G ports: %s (%s in use)" % (s_lic_port_type_3, s_lic_port_type_3_inuse)
print "Licensed 40G ports: %s (%s in use)" % (s_lic_port_type_4, s_lic_port_type_4_inuse)
print "Module build id: %s" % (s_m_build)
print
return 0
if __name__ == '__main__':
sys.exit(main(sys.argv))
| mit |
ajlopez/PLangRe | lib/python.js | 3257 |
if (typeof checker === 'undefined')
var checker = require('./checker');
if (typeof functions === 'undefined')
var functions = require('./functions');
var python = (function () {
var language = 'python';
var whitespace = checker.whitespace;
var newline = checker.newline;
var word = checker.word;
// from http://docs.python.org/release/3.3.2/reference/lexical_analysis.html#keywords
var reserved = [
'False', 'class', 'finally', 'is', 'return',
'None', 'continue', 'for', 'lambda', 'try',
'True', 'def', 'from', 'nonlocal', 'while',
'and', 'del', 'global', 'not', 'with',
'as', 'elif', 'if', 'or', 'yield',
'assert', 'else', 'import', 'pass',
'break', 'except', 'in', 'raise'
];
function reservedWord(text, tokens, position, state) {
var token = tokens[position];
if (token && reserved.indexOf(token.value) >= 0)
return language;
return null;
}
function withColon(text, tokens, position, state) {
for (var k = position + 1; tokens[k]; k++) {
if (tokens[k].newline)
return null;
if (tokens[k].value === ':')
return language;
}
return null;
}
function defSelf(text, tokens, position, state) {
var k;
for (k = position + 1; tokens[k]; k++) {
if (tokens[k].newline)
return null;
if (tokens[k].value === '(')
break;
}
if (!tokens[k])
return null;
k++;
if (!tokens[k])
return null;
if (tokens[k].whitespace)
k++;
if (tokens[k] && tokens[k].value === 'self')
return language;
return null;
}
return {
reservedWord: functions.recognizeWords(language, reserved),
fromImport: functions.recognize(language, ['from', whitespace, word, whitespace, 'import' ]),
importModule: functions.recognize(language, ['import', whitespace, word ]),
shebang: functions.recognize(language, ['#', '!', '/', 'usr', '/', 'bin', '/', 'python' ]),
shebangEnv: functions.recognize(language, ['#', '!', '/', 'usr', '/', 'bin', '/', 'env', whitespace, 'python' ]),
classColon: functions.recognize(withColon, ['class']),
ifColon: functions.recognize(withColon, ['if']),
forColon: functions.recognize(withColon, ['for']),
whileColon: functions.recognize(withColon, ['while']),
defColon: functions.recognize(withColon, ['def']),
tryColon: functions.recognize(language, ['try', ':']),
trySpaceColon: functions.recognize(language, ['try', whitespace, ':']),
exceptColon: functions.recognize(withColon, ['except']),
defSelf: functions.recognize(defSelf, ['def']),
specialName: functions.recognize(language, ['_', '_', word, '_', '_'])
};
})();
if (typeof module !== 'undefined' && module && module.exports)
module.exports = python;
| mit |
kcsl/immutability-benchmark | benchmark-applications/reiminfer-oopsla-2012/source/Xalan/src/org/apache/xalan/xsltc/compiler/util/NumberType.java | 1188 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
*/
/*
* $Id: NumberType.java 468649 2006-10-28 07:00:55Z minchau $
*/
package org.apache.xalan.xsltc.compiler.util;
/**
* @author Jacek Ambroziak
* @author Santiago Pericas-Geertsen
*/
public abstract class NumberType extends Type {
public boolean isNumber() {
return true;
}
public boolean isSimple() {
return true;
}
}
| mit |
iitc/x86 | src/main/java/com/iancaffey/x86/io/X86Visitor.java | 1601 | package com.iancaffey.x86.io;
import com.iancaffey.x86.io.avx.AVXVisitor;
import com.iancaffey.x86.io.crypto.AESVisitor;
import com.iancaffey.x86.io.crypto.SHAVisitor;
import com.iancaffey.x86.io.ext.MemoryProtectionVisitor;
import com.iancaffey.x86.io.ext.SaferModeVisitor;
import com.iancaffey.x86.io.ext.SecurityGuardVisitor;
import com.iancaffey.x86.io.ext.VirtualMachineVisitor;
import com.iancaffey.x86.io.fpu.FPUVisitor;
import com.iancaffey.x86.io.mmx.MMXVisitor;
import com.iancaffey.x86.io.sse.SSEVisitor;
import com.iancaffey.x86.io.sse2.SSE2Visitor;
import com.iancaffey.x86.io.sse3.SSE3Visitor;
import com.iancaffey.x86.io.sse4.SSE4Visitor;
import com.iancaffey.x86.io.tsx.TransactionalSynchronizationVisitor;
/**
* X86Visitor
*
* @author Ian Caffey
* @see <a href="https://software.intel.com/sites/default/files/managed/39/c5/325462-sdm-vol-1-2abcd-3abcd.pdf">Intel Developer's Manual</a>
* @since 1.0
*/
public interface X86Visitor extends
BinaryArithmeticVisitor, BitByteVisitor, BitManipulationVisitor, ControlTransferVisitor, DataTransferVisitor,
DecimalArithmeticVisitor, FlagControlVisitor, IOVisitor, LogicalVisitor, MiscellaneousVisitor, ProcedureVisitor,
QuadwordModeVisitor, RandomNumberVisitor, SaveRestoreVisitor, SegmentRegisterVisitor, ShiftRotateVisitor, StringVisitor,
SystemVisitor, AVXVisitor, AESVisitor, SHAVisitor, MemoryProtectionVisitor, SaferModeVisitor, SecurityGuardVisitor, VirtualMachineVisitor,
FPUVisitor, MMXVisitor, SSEVisitor, SSE2Visitor, SSE3Visitor, SSE4Visitor, TransactionalSynchronizationVisitor {
}
| mit |
SilkStack/Silk.Data.SQL.ORM | Silk.Data.SQL.ORM/Silk.Data/DeferredCollectionExtensions.cs | 1252 | using System.Collections.Generic;
using System.Threading.Tasks;
namespace Silk.Data
{
public static class DeferredCollectionExtensions
{
public static void Execute(this IEnumerable<IDeferred> deferredTasks)
=> deferredTasks.ToExecutor().Execute();
public static Task ExecuteAsync(this IEnumerable<IDeferred> deferredTasks)
=> deferredTasks.ToExecutor().ExecuteAsync();
public static void ExecuteInTransaction(this IEnumerable<IDeferred> deferredTasks)
{
var transaction = new Transaction();
try
{
transaction.Execute(deferredTasks);
transaction.Commit();
}
catch
{
transaction.Rollback();
throw;
}
}
public static async Task ExecuteInTransactionAsync(this IEnumerable<IDeferred> deferredTasks)
{
var transaction = new Transaction();
try
{
await transaction.ExecuteAsync(deferredTasks);
transaction.Commit();
}
catch
{
transaction.Rollback();
throw;
}
}
public static DeferredExecutor ToExecutor(this IEnumerable<IDeferred> deferredTasks)
{
var executor = new DeferredExecutor();
foreach (var task in deferredTasks)
{
executor.Add(task);
}
return executor;
}
}
}
| mit |
phpmob/changmin | src/PhpMob/ChangMinBundle/Factory/TaxonFactory.php | 1421 | <?php
/*
* This file is part of the PhpMob package.
*
* (c) Ishmael Doss <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
declare(strict_types=1);
namespace PhpMob\ChangMinBundle\Factory;
use Sylius\Component\Resource\Factory\FactoryInterface;
use Sylius\Component\Taxonomy\Factory\TaxonFactoryInterface;
use Sylius\Component\Taxonomy\Model\TaxonInterface;
/**
* @author Ishmael Doss <[email protected]>
*/
final class TaxonFactory implements TaxonFactoryInterface
{
/**
* @var FactoryInterface
*/
private $factory;
/**
* @param FactoryInterface $factory
*/
public function __construct(FactoryInterface $factory)
{
$this->factory = $factory;
}
/**
* @return TaxonInterface|object
*/
public function createNew(): TaxonInterface
{
return $this->factory->createNew();
}
/**
* {@inheritdoc}
*/
public function createForParent(TaxonInterface $parent): TaxonInterface
{
$taxon = $this->createNew();
$taxon->setParent($parent);
return $taxon;
}
/**
* {@inheritdoc}
*/
public function createWidthParent(?TaxonInterface $parent): TaxonInterface
{
$taxon = $this->createNew();
$taxon->setParent($parent);
return $taxon;
}
}
| mit |
sibbl/ParkenDD | ParkenDD/Converters/IntGreaterZeroToVisibilityConverter.cs | 670 | using System;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Data;
namespace ParkenDD.Converters
{
public class IntGreaterZeroToVisibilityConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, string language)
{
if (!(value is int))
{
return false;
}
var num = (int) value;
return num > 0 ? Visibility.Visible : Visibility.Collapsed;
}
public object ConvertBack(object value, Type targetType, object parameter, string language)
{
throw new NotImplementedException();
}
}
}
| mit |
pip-benchmark/pip-benchmark-node | obj/src/index.d.ts | 421 | export { Parameter } from './Parameter';
export { IExecutionContext } from './IExecutionContext';
export { Benchmark } from './Benchmark';
export { PassiveBenchmark } from './PassiveBenchmark';
export { DelegatedBenchmark } from './DelegatedBenchmark';
export { BenchmarkSuite } from './BenchmarkSuite';
export * from './runner';
export * from './console';
export * from './standardbenchmarks';
export * from './random';
| mit |
mplessis/navegar | samples/Navegar.WPF.Exemple.CRM/MainWindow.xaml.cs | 288 | using System.Windows;
namespace Navegar.WPF.Exemple
{
/// <summary>
/// Logique d'interaction pour MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
}
}
| mit |
REBELinBLUE/deployer | tests/Unit/View/Composers/ActiveUserComposerTest.php | 870 | <?php
namespace REBELinBLUE\Deployer\Tests\Unit\View\Composers;
use Illuminate\Contracts\Auth\Guard;
use Illuminate\Contracts\View\View;
use Mockery as m;
use REBELinBLUE\Deployer\Tests\TestCase;
use REBELinBLUE\Deployer\View\Composers\ActiveUserComposer;
/**
* @coversDefaultClass \REBELinBLUE\Deployer\View\Composers\ActiveUserComposer
*/
class ActiveUserComposerTest extends TestCase
{
/**
* @covers ::__construct
* @covers ::compose
*/
public function testCompose()
{
$expected_user = 123456;
$view = m::mock(View::class);
$view->shouldReceive('with')->once()->with('logged_in_user', $expected_user);
$auth = m::mock(Guard::class);
$auth->shouldReceive('user')->once()->andReturn($expected_user);
$composer = new ActiveUserComposer($auth);
$composer->compose($view);
}
}
| mit |
yogeshsaroya/new-cdnjs | ajax/libs/mathjax/2.4.0/localization/da/HTML-CSS.js | 129 | version https://git-lfs.github.com/spec/v1
oid sha256:aef1763d9b78abad7495593b2d0ffd425820f3d11fc36a7f8ac57043d71b2053
size 1211
| mit |
thomaswinckell/reactfire-white-board | src/drawing/tool/Circle.js | 1170 | import Tool from './Tool';
export default class Circle extends Tool {
constructor( context ){
super( context , 'Circle');
}
onMouseDown( event ) {
this.isDragging = true;
this.initialPosition = { pageX : event.pageX, pageY : event.pageY };
}
onMouseMove( event, color, backgroundColor, lineWidth ) {
if ( this.isDragging ) {
this.context.clearRect( 0, 0, this.context.canvas.width, this.context.canvas.height );
this.context.beginPath();
const radius = Math.sqrt( Math.pow( this.initialPosition.pageX - event.pageX, 2 ) + Math.pow( this.initialPosition.pageY - event.pageY, 2 ) );
this.context.arc( this.initialPosition.pageX, this.initialPosition.pageY, radius, 0, 2 * Math.PI );
this.context.fillStyle = backgroundColor;
this.context.fill();
this.context.strokeStyle = color;
this.context.lineWidth = lineWidth;
this.context.stroke();
}
}
onMouseUp( event ) {
if ( this.isDragging ) {
this.onMouseMove( event );
this.isDragging = false;
}
}
}
| mit |
TradeMe/tractor | plugins/mock-requests/src/tractor/server/create.js | 290 | // Dependencies:
import { MockRequests } from './mock-requests/mock-requests';
export function create (browser, config) {
let mockRequests = new MockRequests(browser, config.mockRequests);
mockRequests.clear();
return mockRequests;
}
create['@Inject'] = ['browser', 'config'];
| mit |
irmen/Pyro5 | examples/autoproxy/client.py | 466 | import Pyro5.api
uri = input("enter factory server object uri: ").strip()
factory = Pyro5.api.Proxy(uri)
# create several things.
print("Creating things.")
thing1 = factory.createSomething(1)
thing2 = factory.createSomething(2)
thing3 = factory.createSomething(3)
print(repr(thing1))
# interact with them on the server.
print("Speaking stuff (see output on server).")
thing1.speak("I am the first")
thing2.speak("I am second")
thing3.speak("I am last then...")
| mit |
sarariv/phase-0 | week-4/simple-substrings/my_solution.rb | 225 | # Simple Substrings
# I worked on this challenge myself
# Your Solution Below
def welcome (address)
if address.include? 'CA'
return "Welcome to California"
else
return "You should move to California"
end
end | mit |
pearpages/angular-ticketing | www/js/helpdesk/helpdesk.module.js | 1341 | (function() {
'use strict';
angular.module("helpdesk",[])
.config(function($stateProvider, $urlRouterProvider) {
$stateProvider
.state('tab.inbox', {
url: '/helpdesk',
templateUrl: 'js/helpdesk/inbox.html',
controller: 'InboxController',
controllerAs: 'vm'
})
.state('tab.ticket-detail', {
url: '/helpdesk/ticket/:id',
templateUrl: 'js/helpdesk/detail.html',
controller: 'DetailController',
controllerAs: 'vm',
params: {
'id' : -1,
'back' : 'tab.inbox'
}
})
.state('tab.assigned-to-me', {
url: '/helpdesk/assigned-to-me',
templateUrl: 'js/helpdesk/assigned-to-me.html',
controller: 'AssignedToMeController',
controllerAs: 'vm'
})
.state('tab.assign', {
url: '/helpdesk/assign/:id',
templateUrl: 'js/helpdesk/assign.html',
controller: 'AssignController',
controllerAs: 'vm'
})
.state('tab.last-closed', {
url: '/helpdesk/last-closed',
templateUrl: 'js/helpdesk/last-closed.html',
controller: 'ClosedController',
controllerAs: 'vm'
});
});
})(); | mit |
whalenut/winject | src/main/java/com/whalenut/winject/inject/exceptions/WinjectSetterException.java | 304 | package com.whalenut.winject.inject.exceptions;
public class WinjectSetterException extends WinjectException {
public WinjectSetterException(String message) {
super(message);
}
public WinjectSetterException(String message, Throwable cause) {
super(message, cause);
}
}
| mit |
levibostian/myBlanky | googleAppEngine/google/appengine/tools/api_server.py | 33202 | #!/usr/bin/env python
#
# Copyright 2007 Google 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.
#
"""Serves the stub App Engine APIs (e.g. memcache, datastore) over HTTP.
The Remote API protocol is used for communication.
"""
from __future__ import with_statement
import BaseHTTPServer
import httplib
import logging
import os.path
import pickle
import socket
import SocketServer
import subprocess
import sys
import tempfile
import threading
import time
import traceback
import urllib2
import urlparse
import wsgiref.headers
import google
import yaml
from google.appengine.api import mail_stub
from google.appengine.api import request_info
from google.appengine.api import urlfetch_stub
from google.appengine.api import user_service_stub
from google.appengine.api.app_identity import app_identity_stub
from google.appengine.api.blobstore import blobstore_stub
from google.appengine.api.blobstore import file_blob_storage
from google.appengine.api.capabilities import capability_stub
from google.appengine.api.channel import channel_service_stub
from google.appengine.api.files import file_service_stub
from google.appengine.api.logservice import logservice_stub
from google.appengine.api.search import simple_search_stub
from google.appengine.api.taskqueue import taskqueue_stub
from google.appengine.api.prospective_search import prospective_search_stub
from google.appengine.api.memcache import memcache_stub
from google.appengine.api.system import system_stub
from google.appengine.api.xmpp import xmpp_service_stub
from google.appengine.api import datastore_file_stub
from google.appengine.datastore import datastore_sqlite_stub
from google.appengine.datastore import datastore_stub_util
from google.appengine.datastore import datastore_v4_stub
from google.appengine.api import apiproxy_stub_map
from google.appengine.ext.remote_api import remote_api_pb
from google.appengine.ext.remote_api import remote_api_services
from google.appengine.runtime import apiproxy_errors
QUIT_PATH = '/quit'
GLOBAL_API_LOCK = threading.RLock()
class Error(Exception):
pass
def _ClearDatastoreStorage(datastore_path):
"""Delete the datastore storage file at the given path."""
if os.path.lexists(datastore_path):
try:
os.remove(datastore_path)
except OSError, e:
logging.warning('Failed to remove datastore file %r: %s',
datastore_path,
e)
def _ClearProspectiveSearchStorage(prospective_search_path):
"""Delete the perspective search storage file at the given path."""
if os.path.lexists(prospective_search_path):
try:
os.remove(prospective_search_path)
except OSError, e:
logging.warning('Failed to remove prospective search file %r: %s',
prospective_search_path,
e)
THREAD_SAFE_SERVICES = frozenset((
'app_identity_service',
'capability_service',
'channel',
'logservice',
'mail',
'memcache',
'remote_socket',
'urlfetch',
'user',
'xmpp',
))
def _ExecuteRequest(request):
"""Executes an API method call and returns the response object.
Args:
request: A remote_api.Request object representing the API call e.g. a call
to memcache.Get.
Returns:
A ProtocolBuffer.ProtocolMessage representing the API response e.g. a
memcache_service_pb.MemcacheGetResponse.
Raises:
apiproxy_errors.CallNotFoundError: if the requested method doesn't exist.
apiproxy_errors.ApplicationError: if the API method calls fails.
"""
service = request.service_name()
method = request.method()
service_methods = remote_api_services.SERVICE_PB_MAP.get(service, {})
request_class, response_class = service_methods.get(method, (None, None))
if not request_class:
raise apiproxy_errors.CallNotFoundError('%s.%s does not exist' % (service,
method))
request_data = request_class()
request_data.ParseFromString(request.request())
response_data = response_class()
def MakeRequest():
apiproxy_stub_map.MakeSyncCall(service, method, request_data,
response_data)
if service in THREAD_SAFE_SERVICES:
MakeRequest()
else:
with GLOBAL_API_LOCK:
MakeRequest()
return response_data
class APIRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):
"""Handler for all API server HTTP requests."""
def log_message(self, format, *args):
logging.debug(format, *args)
def do_GET(self):
if self.path == QUIT_PATH:
self._HandleShutdown()
else:
params = urlparse.parse_qs(urlparse.urlparse(self.path).query)
rtok = params.get('rtok', ['0'])[0]
self.send_response(httplib.OK)
self.send_header('Content-Type', 'text/plain')
self.end_headers()
self.wfile.write(yaml.dump({
'app_id': self.server.app_id,
'rtok': rtok,
}))
def _HandleShutdown(self):
"""Handles a request for the API Server to exit."""
self.send_response(httplib.OK)
self.send_header('Content-Type', 'text/plain')
self.end_headers()
self.wfile.write('API Server Quitting')
self.server.shutdown()
def do_POST(self):
"""Handles a single API request e.g. memcache.Get()."""
self.send_response(httplib.OK)
self.send_header('Content-Type', 'application/octet-stream')
self.end_headers()
response = remote_api_pb.Response()
try:
request = remote_api_pb.Request()
request.ParseFromString(
self.rfile.read(int(self.headers['content-length'])))
api_response = _ExecuteRequest(request).Encode()
response.set_response(api_response)
except Exception, e:
logging.debug('Exception while handling %s\n%s',
request,
traceback.format_exc())
response.set_exception(pickle.dumps(e))
if isinstance(e, apiproxy_errors.ApplicationError):
application_error = response.mutable_application_error()
application_error.set_code(e.application_error)
application_error.set_detail(e.error_detail)
self.wfile.write(response.Encode())
class APIServer(SocketServer.ThreadingMixIn, BaseHTTPServer.HTTPServer):
"""Serves API calls over HTTP."""
def __init__(self, server_address, app_id):
BaseHTTPServer.HTTPServer.__init__(self, server_address, APIRequestHandler)
self.app_id = app_id
def _SetupStubs(
app_id,
application_root,
appidentity_email_address,
appidentity_private_key_path,
trusted,
blobstore_path,
use_sqlite,
auto_id_policy,
high_replication,
datastore_path,
datastore_require_indexes,
images_host_prefix,
logs_path,
mail_smtp_host,
mail_smtp_port,
mail_smtp_user,
mail_smtp_password,
mail_enable_sendmail,
mail_show_mail_body,
mail_allow_tls,
matcher_prospective_search_path,
taskqueue_auto_run_tasks,
taskqueue_task_retry_seconds,
taskqueue_default_http_server,
user_login_url,
user_logout_url,
default_gcs_bucket_name):
"""Configures the APIs hosted by this server.
Args:
app_id: The str application id e.g. "guestbook".
application_root: The path to the directory containing the user's
application e.g. "/home/bquinlan/myapp".
trusted: A bool indicating if privileged APIs should be made available.
blobstore_path: The path to the file that should be used for blobstore
storage.
use_sqlite: A bool indicating whether DatastoreSqliteStub or
DatastoreFileStub should be used.
auto_id_policy: One of datastore_stub_util.SEQUENTIAL or .SCATTERED,
indicating whether the Datastore stub should assign IDs sequentially
or scattered.
high_replication: A bool indicating whether to use the high replication
consistency model.
datastore_path: The path to the file that should be used for datastore
storage.
datastore_require_indexes: A bool indicating if the same production
datastore indexes requirements should be enforced i.e. if True then
a google.appengine.ext.db.NeedIndexError will be be raised if a query
is executed without the required indexes.
images_host_prefix: The URL prefix (protocol://host:port) to preprend to
image urls on calls to images.GetUrlBase.
logs_path: Path to the file to store the logs data in.
mail_smtp_host: The SMTP hostname that should be used when sending e-mails.
If None then the mail_enable_sendmail argument is considered.
mail_smtp_port: The SMTP port number that should be used when sending
e-mails. If this value is None then mail_smtp_host must also be None.
mail_smtp_user: The username to use when authenticating with the
SMTP server. This value may be None if mail_smtp_host is also None or if
the SMTP server does not require authentication.
mail_smtp_password: The password to use when authenticating with the
SMTP server. This value may be None if mail_smtp_host or mail_smtp_user
is also None.
mail_enable_sendmail: A bool indicating if sendmail should be used when
sending e-mails. This argument is ignored if mail_smtp_host is not None.
mail_show_mail_body: A bool indicating whether the body of sent e-mails
should be written to the logs.
mail_allow_tls: A bool indicating whether to allow TLS support.
matcher_prospective_search_path: The path to the file that should be used to
save prospective search subscriptions.
taskqueue_auto_run_tasks: A bool indicating whether taskqueue tasks should
be run automatically or it the must be manually triggered.
taskqueue_task_retry_seconds: An int representing the number of seconds to
wait before a retrying a failed taskqueue task.
taskqueue_default_http_server: A str containing the address of the http
server that should be used to execute tasks.
user_login_url: A str containing the url that should be used for user login.
user_logout_url: A str containing the url that should be used for user
logout.
default_gcs_bucket_name: A str overriding the usual default bucket name.
"""
os.environ['APPLICATION_ID'] = app_id
tmp_app_identity_stub = app_identity_stub.AppIdentityServiceStub.Create(
email_address=appidentity_email_address,
private_key_path=appidentity_private_key_path)
if default_gcs_bucket_name is not None:
tmp_app_identity_stub.SetDefaultGcsBucketName(default_gcs_bucket_name)
apiproxy_stub_map.apiproxy.RegisterStub(
'app_identity_service', tmp_app_identity_stub)
blob_storage = file_blob_storage.FileBlobStorage(blobstore_path, app_id)
apiproxy_stub_map.apiproxy.RegisterStub(
'blobstore',
blobstore_stub.BlobstoreServiceStub(blob_storage))
apiproxy_stub_map.apiproxy.RegisterStub(
'capability_service',
capability_stub.CapabilityServiceStub())
apiproxy_stub_map.apiproxy.RegisterStub(
'channel',
channel_service_stub.ChannelServiceStub())
if use_sqlite:
datastore = datastore_sqlite_stub.DatastoreSqliteStub(
app_id,
datastore_path,
datastore_require_indexes,
trusted,
root_path=application_root,
auto_id_policy=auto_id_policy)
else:
datastore = datastore_file_stub.DatastoreFileStub(
app_id,
datastore_path,
datastore_require_indexes,
trusted,
root_path=application_root,
auto_id_policy=auto_id_policy)
if high_replication:
datastore.SetConsistencyPolicy(
datastore_stub_util.TimeBasedHRConsistencyPolicy())
apiproxy_stub_map.apiproxy.RegisterStub(
'datastore_v3', datastore)
apiproxy_stub_map.apiproxy.RegisterStub(
'datastore_v4',
datastore_v4_stub.DatastoreV4Stub(app_id))
apiproxy_stub_map.apiproxy.RegisterStub(
'file',
file_service_stub.FileServiceStub(blob_storage))
try:
from google.appengine.api.images import images_stub
except ImportError:
logging.warning('Could not initialize images API; you are likely missing '
'the Python "PIL" module.')
from google.appengine.api.images import images_not_implemented_stub
apiproxy_stub_map.apiproxy.RegisterStub(
'images',
images_not_implemented_stub.ImagesNotImplementedServiceStub())
else:
apiproxy_stub_map.apiproxy.RegisterStub(
'images',
images_stub.ImagesServiceStub(host_prefix=images_host_prefix))
apiproxy_stub_map.apiproxy.RegisterStub(
'logservice',
logservice_stub.LogServiceStub(logs_path=logs_path))
apiproxy_stub_map.apiproxy.RegisterStub(
'mail',
mail_stub.MailServiceStub(mail_smtp_host,
mail_smtp_port,
mail_smtp_user,
mail_smtp_password,
enable_sendmail=mail_enable_sendmail,
show_mail_body=mail_show_mail_body,
allow_tls=mail_allow_tls))
apiproxy_stub_map.apiproxy.RegisterStub(
'memcache',
memcache_stub.MemcacheServiceStub())
apiproxy_stub_map.apiproxy.RegisterStub(
'search',
simple_search_stub.SearchServiceStub())
apiproxy_stub_map.apiproxy.RegisterStub('system',
system_stub.SystemServiceStub())
apiproxy_stub_map.apiproxy.RegisterStub(
'taskqueue',
taskqueue_stub.TaskQueueServiceStub(
root_path=application_root,
auto_task_running=taskqueue_auto_run_tasks,
task_retry_seconds=taskqueue_task_retry_seconds,
default_http_server=taskqueue_default_http_server))
apiproxy_stub_map.apiproxy.GetStub('taskqueue').StartBackgroundExecution()
apiproxy_stub_map.apiproxy.RegisterStub(
'urlfetch',
urlfetch_stub.URLFetchServiceStub())
apiproxy_stub_map.apiproxy.RegisterStub(
'user',
user_service_stub.UserServiceStub(login_url=user_login_url,
logout_url=user_logout_url))
apiproxy_stub_map.apiproxy.RegisterStub(
'xmpp',
xmpp_service_stub.XmppServiceStub())
apiproxy_stub_map.apiproxy.RegisterStub(
'matcher',
prospective_search_stub.ProspectiveSearchStub(
matcher_prospective_search_path,
apiproxy_stub_map.apiproxy.GetStub('taskqueue')))
def _TearDownStubs():
"""Clean up any stubs that need cleanup."""
logging.info('Applying all pending transactions and saving the datastore')
datastore_stub = apiproxy_stub_map.apiproxy.GetStub('datastore_v3')
datastore_stub.Write()
def ParseCommandArguments(args):
"""Parses and the application's command line arguments.
Args:
args: A list of command line arguments *not* including the executable or
script e.g. ['-A' 'myapp', '--api_port=8000'].
Returns:
An object containing the values passed in the commandline as attributes.
Raises:
SystemExit: if the argument parsing fails.
"""
import argparse
from google.appengine.tools import boolean_action
parser = argparse.ArgumentParser()
parser.add_argument('-A', '--application', required=True)
parser.add_argument('--api_host', default='')
parser.add_argument('--api_port', default=8000, type=int)
parser.add_argument('--trusted',
action=boolean_action.BooleanAction,
const=True,
default=False)
parser.add_argument('--appidentity_email_address', default=None)
parser.add_argument('--appidentity_private_key_path', default=None)
parser.add_argument('--application_root', default=None)
parser.add_argument('--application_host', default='localhost')
parser.add_argument('--application_port', default=None)
parser.add_argument('--blobstore_path', default=None)
parser.add_argument('--datastore_path', default=None)
parser.add_argument('--auto_id_policy', default='scattered',
type=lambda s: s.lower(),
choices=(datastore_stub_util.SEQUENTIAL,
datastore_stub_util.SCATTERED))
parser.add_argument('--use_sqlite',
action=boolean_action.BooleanAction,
const=True,
default=False)
parser.add_argument('--high_replication',
action=boolean_action.BooleanAction,
const=True,
default=False)
parser.add_argument('--require_indexes',
action=boolean_action.BooleanAction,
const=True,
default=False)
parser.add_argument('--clear_datastore',
action=boolean_action.BooleanAction,
const=True,
default=False)
parser.add_argument('--logs_path', default=None)
parser.add_argument('--enable_sendmail',
action=boolean_action.BooleanAction,
const=True,
default=False)
parser.add_argument('--smtp_host', default='')
parser.add_argument('--smtp_port', default=25, type=int)
parser.add_argument('--smtp_user', default='')
parser.add_argument('--smtp_password', default='')
parser.add_argument('--show_mail_body',
action=boolean_action.BooleanAction,
const=True,
default=False)
parser.add_argument('--smtp_allow_tls',
action=boolean_action.BooleanAction,
const=True,
default=False)
parser.add_argument('--prospective_search_path', default=None)
parser.add_argument('--clear_prospective_search',
action=boolean_action.BooleanAction,
const=True,
default=False)
parser.add_argument('--enable_task_running',
action=boolean_action.BooleanAction,
const=True,
default=True)
parser.add_argument('--task_retry_seconds', default=30, type=int)
parser.add_argument('--user_login_url', default=None)
parser.add_argument('--user_logout_url', default=None)
return parser.parse_args(args)
class APIServerProcess(object):
"""Manages an API Server running as a seperate process."""
def __init__(self,
executable,
host,
port,
app_id,
script=None,
appidentity_email_address=None,
appidentity_private_key_path=None,
application_host=None,
application_port=None,
application_root=None,
auto_id_policy=None,
blobstore_path=None,
clear_datastore=None,
clear_prospective_search=None,
datastore_path=None,
enable_sendmail=None,
enable_task_running=None,
high_replication=None,
logs_path=None,
prospective_search_path=None,
require_indexes=None,
show_mail_body=None,
smtp_host=None,
smtp_password=None,
smtp_port=None,
smtp_user=None,
smtp_allow_tls=None,
task_retry_seconds=None,
trusted=None,
use_sqlite=None,
default_gcs_bucket_name=None):
"""Configures the APIs hosted by this server.
Args:
executable: The path of the executable to use when running the API Server
e.g. "/usr/bin/python".
host: The host name that should be used by the API Server e.g.
"localhost".
port: The port number that should be used by the API Server e.g. 8080.
app_id: The str application id e.g. "guestbook".
script: The name of the script that should be used, along with the
executable argument, to run the API Server e.g. "api_server.py".
If None then the executable is run without a script argument.
appidentity_email_address: Email address for service account substitute.
appidentity_private_key_path: Private key for service account substitute.
application_host: The name of the host where the development application
server is running e.g. "localhost".
application_port: The port where the application server is running e.g.
8000.
application_root: The path to the directory containing the user's
application e.g. "/home/bquinlan/myapp".
auto_id_policy: One of "sequential" or "scattered", indicating whether
the Datastore stub should assign IDs sequentially or scattered.
blobstore_path: The path to the file that should be used for blobstore
storage.
clear_datastore: Clears the file at datastore_path, emptying the
datastore from previous runs.
clear_prospective_search: Clears the file at prospective_search_path,
emptying the perspective search state from previous runs.
datastore_path: The path to the file that should be used for datastore
storage.
enable_sendmail: A bool indicating if sendmail should be used when sending
e-mails. This argument is ignored if mail_smtp_host is not None.
enable_task_running: A bool indicating whether taskqueue tasks should
be run automatically or it the must be manually triggered.
high_replication: A bool indicating whether to use the high replication
consistency model.
logs_path: Path to the file to store the logs data in.
prospective_search_path: The path to the file that should be used to
save prospective search subscriptions.
require_indexes: A bool indicating if the same production
datastore indexes requirements should be enforced i.e. if True then
a google.appengine.ext.db.NeedIndexError will be be raised if a query
is executed without the required indexes.
show_mail_body: A bool indicating whether the body of sent e-mails
should be written to the logs.
smtp_host: The SMTP hostname that should be used when sending e-mails.
If None then the enable_sendmail argument is considered.
smtp_password: The password to use when authenticating with the
SMTP server. This value may be None if smtp_host or smtp_user
is also None.
smtp_port: The SMTP port number that should be used when sending
e-mails. If this value is None then smtp_host must also be None.
smtp_user: The username to use when authenticating with the
SMTP server. This value may be None if smtp_host is also None or if
the SMTP server does not require authentication.
smtp_allow_tls: A bool indicating whether to enable TLS.
task_retry_seconds: An int representing the number of seconds to
wait before a retrying a failed taskqueue task.
trusted: A bool indicating if privileged APIs should be made available.
use_sqlite: A bool indicating whether DatastoreSqliteStub or
DatastoreFileStub should be used.
default_gcs_bucket_name: A str overriding the normal default bucket name.
"""
self._process = None
self._host = host
self._port = port
if script:
self._args = [executable, script]
else:
self._args = [executable]
self._BindArgument('--api_host', host)
self._BindArgument('--api_port', port)
self._BindArgument('--appidentity_email_address', appidentity_email_address)
self._BindArgument('--appidentity_private_key_path', appidentity_private_key_path)
self._BindArgument('--application_host', application_host)
self._BindArgument('--application_port', application_port)
self._BindArgument('--application_root', application_root)
self._BindArgument('--application', app_id)
self._BindArgument('--auto_id_policy', auto_id_policy)
self._BindArgument('--blobstore_path', blobstore_path)
self._BindArgument('--clear_datastore', clear_datastore)
self._BindArgument('--clear_prospective_search', clear_prospective_search)
self._BindArgument('--datastore_path', datastore_path)
self._BindArgument('--enable_sendmail', enable_sendmail)
self._BindArgument('--enable_task_running', enable_task_running)
self._BindArgument('--high_replication', high_replication)
self._BindArgument('--logs_path', logs_path)
self._BindArgument('--prospective_search_path', prospective_search_path)
self._BindArgument('--require_indexes', require_indexes)
self._BindArgument('--show_mail_body', show_mail_body)
self._BindArgument('--smtp_host', smtp_host)
self._BindArgument('--smtp_password', smtp_password)
self._BindArgument('--smtp_port', smtp_port)
self._BindArgument('--smtp_user', smtp_user)
self._BindArgument('--smtp_allow_tls', smtp_allow_tls)
self._BindArgument('--task_retry_seconds', task_retry_seconds)
self._BindArgument('--trusted', trusted)
self._BindArgument('--use_sqlite', use_sqlite)
self._BindArgument('--default_gcs_bucket_name', default_gcs_bucket_name)
@property
def url(self):
"""Returns the URL that should be used to communicate with the server."""
return 'http://%s:%d' % (self._host, self._port)
def __repr__(self):
return '<APIServerProcess command=%r>' % ' '.join(self._args)
def Start(self):
"""Starts the API Server process."""
assert not self._process, 'Start() can only be called once'
self._process = subprocess.Popen(self._args)
def _CanConnect(self):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
s.connect((self._host, self._port))
except socket.error:
connected = False
else:
connected = True
s.close()
return connected
def WaitUntilServing(self, timeout=30.0):
"""Waits until the API Server is ready to handle requests.
Args:
timeout: The maximum number of seconds to wait for the server to be ready.
Raises:
Error: if the server process exits or is not ready in "timeout" seconds.
"""
assert self._process, 'server was not started'
finish_time = time.time() + timeout
while time.time() < finish_time:
if self._process.poll() is not None:
raise Error('server has already exited with return: %r',
self._process.returncode)
if self._CanConnect():
return
time.sleep(0.2)
raise Error('server did not start after %f seconds', timeout)
def _BindArgument(self, argument, value):
if value is not None:
self._args.append('%s=%s' % (argument, value))
def Quit(self, timeout=5.0):
"""Causes the API Server process to exit.
Args:
timeout: The maximum number of seconds to wait for an orderly shutdown
before forceably killing the process.
"""
assert self._process, 'server was not started'
if self._process.poll() is None:
try:
urllib2.urlopen(self.url + QUIT_PATH)
except urllib2.URLError:
pass
finish_time = time.time() + timeout
while time.time() < finish_time and self._process.poll() is None:
time.sleep(0.2)
if self._process.returncode is None:
logging.warning('api_server did not quit cleanly, killing')
self._process.kill()
class ApiServerDispatcher(request_info._LocalFakeDispatcher):
"""An api_server Dispatcher implementation."""
def add_request(self, method, relative_url, headers, body, source_ip,
server_name=None, version=None, instance_id=None):
"""Process an HTTP request.
Args:
method: A str containing the HTTP method of the request.
relative_url: A str containing path and query string of the request.
headers: A list of (key, value) tuples where key and value are both str.
body: A str containing the request body.
source_ip: The source ip address for the request.
server_name: An optional str containing the server name to service this
request. If unset, the request will be dispatched to the default
server.
version: An optional str containing the version to service this request.
If unset, the request will be dispatched to the default version.
instance_id: An optional str containing the instance_id of the instance to
service this request. If unset, the request will be dispatched to
according to the load-balancing for the server and version.
Returns:
A request_info.ResponseTuple containing the response information for the
HTTP request.
"""
try:
header_dict = wsgiref.headers.Headers(headers)
connection_host = header_dict.get('host')
connection = httplib.HTTPConnection(connection_host)
connection.putrequest(
method, relative_url,
skip_host='host' in header_dict,
skip_accept_encoding='accept-encoding' in header_dict)
for header_key, header_value in headers:
connection.putheader(header_key, header_value)
connection.endheaders()
connection.send(body)
response = connection.getresponse()
response.read()
response.close()
return request_info.ResponseTuple(
'%d %s' % (response.status, response.reason), [], '')
except (httplib.HTTPException, socket.error):
logging.exception(
'An error occured while sending a %s request to "%s%s"',
method, connection_host, relative_url)
return request_info.ResponseTuple('0', [], '')
def main():
logging.basicConfig(
level=logging.INFO,
format='[API Server] [%(filename)s:%(lineno)d] %(levelname)s %(message)s')
args = ParseCommandArguments(sys.argv[1:])
if args.clear_datastore:
_ClearDatastoreStorage(args.datastore_path)
if args.clear_prospective_search:
_ClearProspectiveSearchStorage(args.prospective_search_path)
if args.blobstore_path is None:
_, blobstore_temp_filename = tempfile.mkstemp(prefix='ae-blobstore')
args.blobstore_path = blobstore_temp_filename
if args.datastore_path is None:
_, datastore_temp_filename = tempfile.mkstemp(prefix='ae-datastore')
args.datastore_path = datastore_temp_filename
if args.prospective_search_path is None:
_, prospective_search_temp_filename = tempfile.mkstemp(
prefix='ae-prospective_search')
args.prospective_search_path = prospective_search_temp_filename
if args.application_host:
application_address = args.application_host
if args.application_port and args.application_port != 80:
application_address += ':' + str(args.application_port)
else:
application_address = None
if not hasattr(args, 'default_gcs_bucket_name'):
args.default_gcs_bucket_name = None
request_info._local_dispatcher = ApiServerDispatcher()
_SetupStubs(app_id=args.application,
application_root=args.application_root,
appidentity_email_address=args.appidentity_email_address,
appidentity_private_key_path=args.appidentity_private_key_path,
trusted=args.trusted,
blobstore_path=args.blobstore_path,
datastore_path=args.datastore_path,
use_sqlite=args.use_sqlite,
auto_id_policy=args.auto_id_policy,
high_replication=args.high_replication,
datastore_require_indexes=args.require_indexes,
images_host_prefix=application_address,
logs_path=args.logs_path,
mail_smtp_host=args.smtp_host,
mail_smtp_port=args.smtp_port,
mail_smtp_user=args.smtp_user,
mail_smtp_password=args.smtp_password,
mail_enable_sendmail=args.enable_sendmail,
mail_show_mail_body=args.show_mail_body,
mail_allow_tls=args.smtp_allow_tls,
matcher_prospective_search_path=args.prospective_search_path,
taskqueue_auto_run_tasks=args.enable_task_running,
taskqueue_task_retry_seconds=args.task_retry_seconds,
taskqueue_default_http_server=application_address,
user_login_url=args.user_login_url,
user_logout_url=args.user_logout_url,
default_gcs_bucket_name=args.default_gcs_bucket_name)
server = APIServer((args.api_host, args.api_port), args.application)
try:
server.serve_forever()
finally:
_TearDownStubs()
if __name__ == '__main__':
try:
main()
except KeyboardInterrupt:
pass
| mit |
c0shea/IdParser | IdParser/Parsers/AbstractParser.cs | 3462 | using System;
using System.Globalization;
namespace IdParser.Parsers
{
public abstract class AbstractParser
{
protected IdentificationCard IdCard { get; }
protected DriversLicense License => IdCard as DriversLicense ?? throw new InvalidOperationException("IdCard is of type IdentificationCard and not the expected DriversLicense type.");
protected Version Version { get; }
protected Country? Country { get; }
protected AbstractParser(IdentificationCard idCard, Version version, Country? country)
{
IdCard = idCard;
Version = version;
Country = country;
}
public abstract void ParseAndSet(string input);
protected static bool DateHasNoValue(string input)
{
return string.IsNullOrEmpty(input) || input == "00000000";
}
protected static bool StringHasNoValue(string input)
{
return string.IsNullOrEmpty(input) || input == "NONE" || input == "unavl" || input == "unavail";
}
protected DateTime ParseDate(string input)
{
const string usaFormat = "MMddyyyy";
const string canadaFormat = "yyyyMMdd";
bool tryCanadaFormatFirst = Country.HasValue && Country == IdParser.Country.Canada || Version == Version.Aamva2000;
// Some jurisdictions, like New Hampshire (version 2013), don't follow the standard and have trailing
// characters (like 'M') after the date in the same record. In an attempt to parse the date successfully,
// only try parsing the positions we know should contain a date.
if (input != null && input.Length > usaFormat.Length)
{
input = input.Substring(0, usaFormat.Length);
}
// Some jurisdictions, like Wyoming (version 2009), don't follow the standard and use the wrong date format.
// In an attempt to parse the ID successfully, attempt to parse using both formats if the first attempt fails.
// Hopefully between the two one will work.
if (DateTime.TryParseExact(input, tryCanadaFormatFirst ? canadaFormat : usaFormat, CultureInfo.CurrentCulture, DateTimeStyles.AllowWhiteSpaces, out var firstAttemptResult))
{
return firstAttemptResult;
}
if (DateTime.TryParseExact(input, !tryCanadaFormatFirst ? canadaFormat : usaFormat, CultureInfo.CurrentCulture, DateTimeStyles.AllowWhiteSpaces, out var secondAttemptResult))
{
return secondAttemptResult;
}
throw new ArgumentException($"Failed to parse the date '{input}' for country '{Country}' using version '{Version}'.", nameof(input));
}
protected static bool? ParseBool(string input)
{
switch (input.ToUpper())
{
case "T":
return true;
case "Y":
return true;
case "N":
return false;
case "F":
return false;
case "1":
return true;
case "0":
return false;
case "U":
// Unknown whether truncated
return null;
default:
return null;
}
}
}
}
| mit |
stivalet/PHP-Vulnerability-test-suite | Injection/CWE_78/unsafe/CWE_78__unserialize__func_preg_match-no_filtering__ls-sprintf_%s_simple_quote.php | 1349 | <?php
/*
Unsafe sample
input : Get a serialize string in POST and unserialize it
sanitize : regular expression accepts everything
construction : use of sprintf via a %s with simple quote
*/
/*Copyright 2015 Bertrand STIVALET
Permission is hereby granted, without written agreement or royalty fee, to
use, copy, modify, and distribute this software and its documentation for
any purpose, provided that the above copyright notice and the following
three paragraphs appear in all copies of this software.
IN NO EVENT SHALL AUTHORS BE LIABLE TO ANY PARTY FOR DIRECT,
INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF AUTHORS HAVE
BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
AUTHORS SPECIFICALLY DISCLAIM ANY WARRANTIES INCLUDING, BUT NOT
LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE, AND NON-INFRINGEMENT.
THE SOFTWARE IS PROVIDED ON AN "AS-IS" BASIS AND AUTHORS HAVE NO
OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR
MODIFICATIONS.*/
$string = $_POST['UserData'] ;
$tainted = unserialize($string);
$re = "/^.*$/";
if(preg_match($re, $tainted) == 1){
$tainted = $tainted;
}
else{
$tainted = "";
}
$query = sprintf("ls '%s'", $tainted);
//flaw
$ret = system($query);
?> | mit |
Akamon/oauth2-server | src/Akamon/OAuth2/Server/Infrastructure/SymfonyConsole/CreateClientCommand.php | 1795 | <?php
namespace Akamon\OAuth2\Server\Infrastructure\SymfonyConsole;
use Akamon\OAuth2\Server\Domain\Model\Client\Client;
use Akamon\OAuth2\Server\Domain\Model\Client\ClientRepositoryInterface;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
class CreateClientCommand extends Command
{
private $repository;
public function __construct(ClientRepositoryInterface $repository)
{
$this->repository = $repository;
parent::__construct();
}
protected function configure()
{
$this
->setName('akamon:oauth2-server:client:create')
->setDescription('Creates a new client')
->addArgument('id', InputArgument::REQUIRED)
->addArgument('secret', InputArgument::OPTIONAL)
->addOption('allowed-grant-type', null, InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY)
->addOption('allowed-scope', null, InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY)
->addOption('default-scope', null, InputOption::VALUE_OPTIONAL);
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$client = new Client([
'id' => $input->getArgument('id'),
'secret' => $input->getArgument('secret'),
'allowedGrantTypes' => $input->getOption('allowed-grant-type'),
'allowedScopes' => $input->getOption('allowed-scope'),
'defaultScope' => $input->getOption('default-scope')
]);
$this->repository->add($client);
$output->writeln('Client added.');
}
}
| mit |
xrorox/arelidon | gestion/tresors/modif.php | 2217 | <?php
/*
* Created on 5 mars 2010
*/
echo '<div>';
echo '<form id="form_item" method="post" action="panneauAdmin.php?category=13&update=1&tresor_id='.$_GET['tresor_id'].'">';
echo '<table border="1" class="backgroundBodyNoRadius" cellspacing="0" style="border:solid 1px black;text-align:center;width:800px;">';
echo '<tr class="backgroundMenuNoRadius">';
$arrayStatut = array('id','map','abs','ord','nbobjet','objet','gold','typecle','cle','');
foreach($arrayStatut as $row)
{
$urltri = "gestion/page.php?category=5&orderby=";
if($orderby == $row && $asc == 'ASC')
{
$asca = 'DESC';
}elseif($orderby == $row && $asc == 'DESC'){
$asca = 'ASC';
}
$urltri = $urltri.$row.'&asc='.$asca;
echo '<td onclick="" style="cursor:pointer;">'.$row.' </td>';
}
echo '<td> </td>';
echo '</tr>';
$box = new box($_GET['tresor_id']);
echo '<tr>';
echo '<td>'.$box->getId().'</td>';
echo '<td><input type="text" name="map" value="'.$box->getMap().'" size="3" /></td>';
echo '<td><input type="text" name="abs" value="'.$box->getAbs().'" size="3" /></td>';
echo '<td><input type="text" name="ord" value="'.$box->getOrd().'" size="3" /></td>';
echo '<td><input type="text" name="nbobjet" value="'.$box->getNbObjet().'" size="3" /></td>';
$array_ob = getAutocomplete('item');
$objet = new item($box->getObjet());
$objet_value = $objet->getName();
echo '<td><input id="objet_gagne" value="'.$objet_value.'" onfocus="autoComplete(\'objet_gagne\',\''.$array_ob.'\');autoComplete(\'objet_gagne\',\''.$array_ob.'\');" type="text" name="objet" size="20"></td>';
echo '<td><input type="text" name="gold" value="'.$box->getGold().'" size="3" /></td>';
echo '<td><input type="text" name="typecle" value="'.$box->getTypeCle().'" size="3" /></td>';
$cle = new item($box->getCle());
$cle_value = $cle->getName();
echo '<td><input id="cle" value="'.$cle_value.'" onfocus="autoComplete(\'cle\',\''.$array_ob.'\');autoComplete(\'cle\',\''.$array_ob.'\');" type="text" name="cle" size="20"></td>';
echo '<td> <input class="button" type="submit" value="OK" onclick=""></td>';
echo '</tr>';
echo '</table>';
echo '</form>';
echo '</div><br /><br />';
?>
| mit |
robotbird/Shadowsocks.py | Shadowsocks.py | 746 | import urllib2
import urllib
import re
import os
import json
res= urllib2.urlopen("http://www.ishadowsocks.net/")
con = res.read().decode("utf-8")
pattern = re.compile('<section id="free">(.*?)</section>',re.S)
result = re.search(pattern,con)
items = re.findall("<h4>(.*?)</h4>",result.group(0))
pwdus = items[2][4:12]
pwdhk = items[8][4:12]
pwdjp = items[14][4:12]
print 'init shadowsocks password'
print pwdus,pwdhk,pwdjp
with open('gui-config.json','r') as ff:
d = json.load(ff)
d["configs"][0]["password"]=pwdjp
d["configs"][1]["password"]=pwdus
d["configs"][2]["password"]=pwdhk
with open('gui-config.json','w') as f:
json.dump(d,f)
print "open shadowsocks success , please close this window"
os.popen("Shadowsocks.exe")
exit()
| mit |
mindwind/craft-atom | craft-atom-protocol-rpc/src/test/java/io/craft/atom/protocol/rpc/RpcService.java | 158 | package io.craft.atom.protocol.rpc;
/**
* @author mindwind
* @version 1.0, Jul 22, 2014
*/
public interface RpcService {
void rpc(String s, int i);
}
| mit |
grant/hawk | private/models/trips.js | 234 | var mongoose = require('mongoose');
module.exports = mongoose.model('trips', {
family_id: Number,
vin: String,
start_time: String,
end_time: String,
stats: {
fuel_eff: Number,
fuel_consumed: Number,
distance: Number,
}
}); | mit |
mkwia/jc2atc | scripts/admin/client/guiclass.lua | 6166 | class "GUI"
local sx, sy = Game:GetSetting ( 30 ), Game:GetSetting ( 31 )
local textBoxTypes =
{
[ "text" ] = TextBox,
[ "numeric" ] = TextBoxNumeric,
[ "multiline" ] = TextBoxMultiline,
[ "password" ] = PasswordTextBox
}
local protected = { }
function GUI:Window ( title, pos, size )
local window = Window.Create ( )
window:SetTitle ( title )
window:SetPositionRel ( pos )
window:SetSizeRel ( size )
return window
end
function GUI:Button ( text, pos, size, parent, id )
local button = Button.Create ( )
button:SetText ( text )
button:SetPositionRel ( pos )
button:SetSizeRel ( size )
if ( id ) then
button:SetDataString ( "id", id )
table.insert ( protected, button )
end
if ( parent ) then
button:SetParent ( parent )
end
return button
end
function GUI:Label ( text, pos, size, parent )
local label = Label.Create ( )
label:SetText ( text )
label:SetPositionRel ( pos )
label:SetSizeRel ( size )
if ( parent ) then
label:SetParent ( parent )
end
return label
end
function GUI:SortedList ( pos, size, parent, columns )
local list = SortedList.Create ( )
list:SetPositionRel ( pos )
list:SetSizeRel ( size )
if ( parent ) then
list:SetParent ( parent )
end
if ( type ( columns ) == "table" and #columns > 0 ) then
for _, col in ipairs ( columns ) do
if tonumber ( col.width ) then
list:AddColumn ( tostring ( col.name ), tonumber ( col.width ) )
else
list:AddColumn ( tostring ( col.name ) )
end
end
end
return list
end
function GUI:TextBox ( text, pos, size, type, parent )
local func = textBoxTypes [ type ]
if ( func ) then
local textBox = func.Create ( )
textBox:SetPositionRel ( pos )
textBox:SetSizeRel ( size )
if ( parent ) then
textBox:SetParent ( parent )
end
textBox:SetText ( text )
return textBox
else
return false
end
end
function GUI:ComboBox ( pos, size, parent, items )
local menuItems = { }
local comboBox = ComboBox.Create ( )
comboBox:SetPositionRel ( pos )
comboBox:SetSizeRel ( size )
if ( parent ) then
comboBox:SetParent ( parent )
end
if ( type ( items ) == "table" and #items > 0 ) then
for _, item in ipairs ( items ) do
menuItems [ item ] = comboBox:AddItem ( item )
end
end
return comboBox, menuItems
end
function GUI:ListBox ( pos, size, parent, label )
local list = ListBox.Create ( )
list:SetPositionRel ( pos )
list:SetSizeRel ( size )
if ( parent ) then
list:SetParent ( parent )
end
if ( label ) then
tLabel = Label.Create ( )
if ( parent ) then
tLabel:SetParent ( parent )
end
tLabel:SetText ( label )
tLabel:SetPositionRel ( Vector2 ( pos.x, pos.y - 0.031 ) )
tLabel:SetSizeRel ( size )
tLabel:SetAlignment ( 64 )
end
return list, tLabel
end
function GUI:CollapsibleList ( pos, size, parent, categories )
local cats = { }
local list = CollapsibleList.Create ( )
list:SetPositionRel ( pos )
list:SetSizeRel ( size )
if ( parent ) then
list:SetParent ( parent )
end
if ( type ( categories ) == "table" and #categories > 0 ) then
for _, cat in ipairs ( categories ) do
table.insert ( cats, list:Add ( tostring ( cat ) ) )
end
end
return list, cats
end
function GUI:ScrollControl ( pos, size, parent )
local scroll = ScrollControl.Create ( )
scroll:SetPositionRel ( pos )
scroll:SetSizeRel ( size )
if ( parent ) then
scroll:SetParent ( parent )
end
return scroll
end
function GUI:TabControl ( tabs, pos, size, parent )
local addedTabs = { }
local tabControl = TabControl.Create ( )
tabControl:SetPositionRel ( pos )
tabControl:SetSizeRel ( size )
if ( parent ) then
tabControl:SetParent ( parent )
end
if ( tabs and #tabs > 0 ) then
for _, tab in ipairs ( tabs ) do
local tabName = string.gsub ( tab, "%s", "" ) :lower ( )
addedTabs [ tabName ] = { }
addedTabs [ tabName ].base = BaseWindow.Create ( )
addedTabs [ tabName ].base:SetPositionRel ( pos )
addedTabs [ tabName ].base:SetSizeRel ( size )
if ( parent ) then
addedTabs [ tabName ].base:SetParent ( parent )
end
addedTabs [ tabName ].page = tabControl:AddPage ( tab, addedTabs [ tabName ].base )
addedTabs [ tabName ].page:SetDataString ( "id", "general.tab_".. tab:lower ( ) )
table.insert ( protected, addedTabs [ tabName ].page )
end
end
return tabControl, addedTabs
end
function GUI:ColorPicker ( isHSV, pos, size, parent )
local func = ( isHSV and HSVColorPicker or ColorPicker )
local picker = func.Create ( )
picker:SetPositionRel ( pos )
picker:SetSizeRel ( size )
if ( parent ) then
picker:SetParent ( parent )
end
return picker
end
function GUI:CheckBox ( text, pos, size, parent )
if ( text == "" or not text ) then
checkbox = CheckBox.Create ( )
else
checkbox = LabeledCheckBox.Create ( )
checkbox:GetLabel ( ):SetText ( text )
end
checkbox:SetPositionRel ( pos )
if size ~= "" then
checkbox:SetSizeRel ( size )
end
if ( parent ) then
checkbox:SetParent ( parent )
end
return checkbox
end
function GUI:RadioButtonController ( options, pos, size, parent )
local button = RadioButtonController.Create ( )
button:SetPositionRel ( pos )
button:SetSizeRel ( size )
if ( parent ) then
button:SetParent ( parent )
end
for _, option in ipairs ( options ) do
button:AddOption ( option )
end
return button
end
function GUI:RadioButton ( text, pos, size, parent )
if ( text == "" or not text ) then
button = RadioButton.Create ( )
else
button = LabeledRadioButton.Create ( )
button:GetLabel ( ):SetText ( text )
end
button:SetPositionRel ( pos )
button:SetSizeRel ( size )
if ( parent ) then
button:SetParent ( parent )
end
return button
end
function GUI:Tree ( pos, size, parent )
local tree = Tree.Create ( )
tree:SetPositionRel ( pos )
tree:SetSizeRel ( size )
if ( parent ) then
tree:SetParent ( parent )
end
return tree
end
function GUI:Center ( guiElement )
local size = guiElement:GetSizeRel ( )
local width, height = table.unpack ( tostring ( size ):split ( "," ) )
local size = Vector2 ( ( ( sx / sx ) / 2 - width / 2 ), ( ( sy / sy ) / 2 - height / 2 ) )
guiElement:SetPositionRel ( size )
end
function GUI:GetAllProtected ( )
return protected
end | mit |
danielrohers/bory | lib/types/urlencoded.js | 5152 | /*!
* bory
* Copyright(c) 2017 Daniel Röhers Moura
* MIT Licensed
*/
'use strict';
/**
* Module dependencies.
* @private
*/
const createError = require('http-errors');
const debug = require('debug')('bory:urlencoded');
const deprecate = require('depd')('bory');
const read = require('../read');
const typeis = require('type-is');
const qs = require('qs');
const querystring = require('querystring');
/**
* Helper dependencies.
* @private
*/
const getCharset = require('../helpers/getCharset');
const invalidCharset = require('../helpers/invalidCharset');
const getLimit = require('../helpers/getLimit');
const typeChecker = require('../helpers/typeChecker');
/**
* Module exports.
*/
module.exports = urlencoded;
/**
* Cache of parser modules.
*/
const parsers = Object.create(null);
/**
* Create a middleware to parse urlencoded bodies.
*
* @param {object} [options]
* @return {function}
* @public
*/
function urlencoded(options) {
const opts = options || {};
// notice because option default will flip in next major
if (opts.extended === undefined) {
deprecate('undefined extended: provide extended option');
}
const extended = opts.extended !== false;
const inflate = opts.inflate !== false;
const limit = getLimit(opts);
const type = opts.type || 'application/x-www-form-urlencoded';
const verify = opts.verify || false;
if (verify !== false && typeof verify !== 'function') {
throw new TypeError('option verify must be function');
}
// create the appropriate query parser
const queryparse = extended ? extendedparser(opts) : simpleparser(opts);
// create the appropriate type checking function
const shouldParse = typeof type !== 'function' ? typeChecker(type) : type;
function parse(body) {
return body.length ? queryparse(body) : {};
}
return (req, res, next) => {
if (req._body) {
debug('body already parsed');
return next();
}
req.body = req.body || {};
// skip requests without bodies
if (!typeis.hasBody(req)) {
debug('skip empty body');
return next();
}
debug('content-type %j', req.headers['content-type']);
// determine if request should be parsed
if (!shouldParse(req)) {
debug('skip parsing');
return next();
}
// assert charset
const charset = getCharset(req) || 'utf-8';
if (charset !== 'utf-8') {
return next(invalidCharset(charset));
}
// read
read(req, res, next, parse, debug, {
debug,
encoding: charset,
inflate,
limit,
verify,
});
};
}
/**
* Get the extended query parser.
*
* @param {object} options
*/
function extendedparser(options) {
let parameterLimit = options.parameterLimit !== undefined ? options.parameterLimit : 1000;
const parse = parser('qs');
if (isNaN(parameterLimit) || parameterLimit < 1) {
throw new TypeError('option parameterLimit must be a positive number');
}
if (isFinite(parameterLimit)) {
parameterLimit = Math.floor(parameterLimit);
}
return (body) => {
const paramCount = parameterCount(body, parameterLimit);
if (paramCount === undefined) {
debug('too many parameters');
throw createError(413, 'too many parameters');
}
const arrayLimit = Math.max(100, paramCount);
debug('parse extended urlencoding');
return parse(body, {
allowPrototypes: true,
arrayLimit,
depth: Infinity,
parameterLimit,
});
};
}
/**
* Count the number of parameters, stopping once limit reached
*
* @param {string} body
* @param {number} limit
* @api private
*/
function parameterCount(body, limit) {
let count = 0;
let index = 0;
while ((index = body.indexOf('&', index)) !== -1) {
count += 1;
index += 1;
if (count === limit) {
return undefined;
}
}
return count;
}
/**
* Get parser for module name dynamically.
*
* @param {string} name
* @return {function}
* @api private
*/
function parser(name) {
let mod = parsers[name];
if (mod !== undefined) {
return mod.parse;
}
// this uses a switch for static require analysis
switch (name) {
case 'qs':
mod = qs;
break;
case 'querystring':
mod = querystring;
break;
}
// store to prevent invoking require()
parsers[name] = mod;
return mod.parse;
}
/**
* Get the simple query parser.
*
* @param {object} options
*/
function simpleparser(options) {
let parameterLimit = options.parameterLimit !== undefined ? options.parameterLimit : 1000;
const parse = parser('querystring');
if (isNaN(parameterLimit) || parameterLimit < 1) {
throw new TypeError('option parameterLimit must be a positive number');
}
if (isFinite(parameterLimit)) {
parameterLimit = Math.floor(parameterLimit);
}
return (body) => {
const paramCount = parameterCount(body, parameterLimit);
if (paramCount === undefined) {
debug('too many parameters');
throw createError(413, 'too many parameters');
}
debug('parse urlencoding');
return parse(body, undefined, undefined, { maxKeys: parameterLimit });
};
}
| mit |
ValeriiVasin/angular2-redux-todo | src/app/containers/todos-counter.ts | 498 | import { Component } from '@angular/core';
import { getRemainingTodosCount } from '../reducers/todos';
import { connect } from '../lib';
const mapStateToProps = (state) => {
return {
counter: getRemainingTodosCount(state.todos)
};
};
@Component({
selector: 'todos-counter-container',
template: `
<span id="todo-count">
<strong>{{counter}}</strong> items left
</span>
`,
})
export class TodosCounterContainer {
ngOnInit() {
connect(mapStateToProps)(this);
}
}
| mit |
socomj/Illuminati-Coin | src/qt/bitcoingui.cpp | 30230 | // Copyright (c) 2011-2013 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <QApplication>
#include "bitcoingui.h"
#include "transactiontablemodel.h"
#include "optionsdialog.h"
#include "aboutdialog.h"
#include "clientmodel.h"
#include "walletmodel.h"
#include "walletframe.h"
#include "optionsmodel.h"
#include "transactiondescdialog.h"
#include "bitcoinunits.h"
#include "guiconstants.h"
#include "notificator.h"
#include "guiutil.h"
#include "rpcconsole.h"
#include "ui_interface.h"
#include "wallet.h"
#include "init.h"
#ifdef Q_OS_MAC
#include "macdockiconhandler.h"
#endif
#include <QMenuBar>
#include <QMenu>
#include <QIcon>
#include <QVBoxLayout>
#include <QToolBar>
#include <QStatusBar>
#include <QLabel>
#include <QMessageBox>
#include <QProgressBar>
#include <QStackedWidget>
#include <QDateTime>
#include <QMovie>
#include <QTimer>
#include <QDragEnterEvent>
#if QT_VERSION < 0x050000
#include <QUrl>
#endif
#include <QMimeData>
#include <QStyle>
#include <QSettings>
#include <QDesktopWidget>
#include <QListWidget>
#include <iostream>
const QString BitcoinGUI::DEFAULT_WALLET = "~Default";
BitcoinGUI::BitcoinGUI(QWidget *parent) :
QMainWindow(parent),
clientModel(0),
encryptWalletAction(0),
changePassphraseAction(0),
aboutQtAction(0),
trayIcon(0),
notificator(0),
rpcConsole(0),
prevBlocks(0)
{
restoreWindowGeometry();
setWindowTitle(tr("IlluminatiCoin") + " - " + tr("Wallet"));
#ifndef Q_OS_MAC
QApplication::setWindowIcon(QIcon(":icons/bitcoin"));
setWindowIcon(QIcon(":icons/bitcoin"));
#else
setUnifiedTitleAndToolBarOnMac(true);
QApplication::setAttribute(Qt::AA_DontShowIconsInMenus);
#endif
// Create wallet frame and make it the central widget
walletFrame = new WalletFrame(this);
setCentralWidget(walletFrame);
// Accept D&D of URIs
setAcceptDrops(true);
// Create actions for the toolbar, menu bar and tray/dock icon
// Needs walletFrame to be initialized
createActions();
// Create application menu bar
createMenuBar();
// Create the toolbars
createToolBars();
// Create system tray icon and notification
createTrayIcon();
// Create status bar
statusBar();
// Status bar notification icons
QFrame *frameBlocks = new QFrame();
frameBlocks->setContentsMargins(0,0,0,0);
frameBlocks->setMinimumWidth(56);
frameBlocks->setMaximumWidth(56);
QHBoxLayout *frameBlocksLayout = new QHBoxLayout(frameBlocks);
frameBlocksLayout->setContentsMargins(3,0,3,0);
frameBlocksLayout->setSpacing(3);
labelEncryptionIcon = new QLabel();
labelConnectionsIcon = new QLabel();
labelBlocksIcon = new QLabel();
frameBlocksLayout->addStretch();
frameBlocksLayout->addWidget(labelEncryptionIcon);
frameBlocksLayout->addStretch();
frameBlocksLayout->addWidget(labelConnectionsIcon);
frameBlocksLayout->addStretch();
frameBlocksLayout->addWidget(labelBlocksIcon);
frameBlocksLayout->addStretch();
// Progress bar and label for blocks download
progressBarLabel = new QLabel();
progressBarLabel->setVisible(false);
progressBar = new QProgressBar();
progressBar->setAlignment(Qt::AlignCenter);
progressBar->setVisible(false);
// Override style sheet for progress bar for styles that have a segmented progress bar,
// as they make the text unreadable (workaround for issue #1071)
// See https://qt-project.org/doc/qt-4.8/gallery.html
QString curStyle = QApplication::style()->metaObject()->className();
if(curStyle == "QWindowsStyle" || curStyle == "QWindowsXPStyle")
{
progressBar->setStyleSheet("QProgressBar { background-color: #e8e8e8; border: 1px solid grey; border-radius: 7px; padding: 1px; text-align: center; } QProgressBar::chunk { background: QLinearGradient(x1: 0, y1: 0, x2: 1, y2: 0, stop: 0 #FF8000, stop: 1 orange); border-radius: 7px; margin: 0px; }");
}
statusBar()->addWidget(progressBarLabel);
statusBar()->addWidget(progressBar);
statusBar()->addPermanentWidget(frameBlocks);
syncIconMovie = new QMovie(":/movies/update_spinner", "mng", this);
rpcConsole = new RPCConsole(this);
connect(openRPCConsoleAction, SIGNAL(triggered()), rpcConsole, SLOT(show()));
// prevents an oben debug window from becoming stuck/unusable on client shutdown
connect(quitAction, SIGNAL(triggered()), rpcConsole, SLOT(hide()));
// Install event filter to be able to catch status tip events (QEvent::StatusTip)
this->installEventFilter(this);
// Initially wallet actions should be disabled
setWalletActionsEnabled(false);
}
BitcoinGUI::~BitcoinGUI()
{
saveWindowGeometry();
if(trayIcon) // Hide tray icon, as deleting will let it linger until quit (on Ubuntu)
trayIcon->hide();
#ifdef Q_OS_MAC
delete appMenuBar;
MacDockIconHandler::instance()->setMainWindow(NULL);
#endif
}
void BitcoinGUI::createActions()
{
QActionGroup *tabGroup = new QActionGroup(this);
overviewAction = new QAction(QIcon(":/icons/overview"), tr("&Overview"), this);
overviewAction->setStatusTip(tr("Show general overview of wallet"));
overviewAction->setToolTip(overviewAction->statusTip());
overviewAction->setCheckable(true);
overviewAction->setShortcut(QKeySequence(Qt::ALT + Qt::Key_1));
tabGroup->addAction(overviewAction);
sendCoinsAction = new QAction(QIcon(":/icons/send"), tr("&Send"), this);
sendCoinsAction->setStatusTip(tr("Send coins to a IlluminatiCoin address"));
sendCoinsAction->setToolTip(sendCoinsAction->statusTip());
sendCoinsAction->setCheckable(true);
sendCoinsAction->setShortcut(QKeySequence(Qt::ALT + Qt::Key_2));
tabGroup->addAction(sendCoinsAction);
receiveCoinsAction = new QAction(QIcon(":/icons/receiving_addresses"), tr("&Receive"), this);
receiveCoinsAction->setStatusTip(tr("Show the list of addresses for receiving payments"));
receiveCoinsAction->setToolTip(receiveCoinsAction->statusTip());
receiveCoinsAction->setCheckable(true);
receiveCoinsAction->setShortcut(QKeySequence(Qt::ALT + Qt::Key_3));
tabGroup->addAction(receiveCoinsAction);
historyAction = new QAction(QIcon(":/icons/history"), tr("&Transactions"), this);
historyAction->setStatusTip(tr("Browse transaction history"));
historyAction->setToolTip(historyAction->statusTip());
historyAction->setCheckable(true);
historyAction->setShortcut(QKeySequence(Qt::ALT + Qt::Key_4));
tabGroup->addAction(historyAction);
addressBookAction = new QAction(QIcon(":/icons/address-book"), tr("&Addresses"), this);
addressBookAction->setStatusTip(tr("Edit the list of stored addresses and labels"));
addressBookAction->setToolTip(addressBookAction->statusTip());
addressBookAction->setCheckable(true);
addressBookAction->setShortcut(QKeySequence(Qt::ALT + Qt::Key_5));
tabGroup->addAction(addressBookAction);
connect(overviewAction, SIGNAL(triggered()), this, SLOT(showNormalIfMinimized()));
connect(overviewAction, SIGNAL(triggered()), this, SLOT(gotoOverviewPage()));
connect(sendCoinsAction, SIGNAL(triggered()), this, SLOT(showNormalIfMinimized()));
connect(sendCoinsAction, SIGNAL(triggered()), this, SLOT(gotoSendCoinsPage()));
connect(receiveCoinsAction, SIGNAL(triggered()), this, SLOT(showNormalIfMinimized()));
connect(receiveCoinsAction, SIGNAL(triggered()), this, SLOT(gotoReceiveCoinsPage()));
connect(historyAction, SIGNAL(triggered()), this, SLOT(showNormalIfMinimized()));
connect(historyAction, SIGNAL(triggered()), this, SLOT(gotoHistoryPage()));
connect(addressBookAction, SIGNAL(triggered()), this, SLOT(showNormalIfMinimized()));
connect(addressBookAction, SIGNAL(triggered()), this, SLOT(gotoAddressBookPage()));
quitAction = new QAction(QIcon(":/icons/quit"), tr("E&xit"), this);
quitAction->setStatusTip(tr("Quit application"));
quitAction->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_Q));
quitAction->setMenuRole(QAction::QuitRole);
aboutAction = new QAction(QIcon(":/icons/bitcoin"), tr("&About IlluminatiCoin"), this);
aboutAction->setStatusTip(tr("Show information about IlluminatiCoin"));
aboutAction->setMenuRole(QAction::AboutRole);
aboutQtAction = new QAction(QIcon(":/trolltech/qmessagebox/images/qtlogo-64.png"), tr("About &Qt"), this);
aboutQtAction->setStatusTip(tr("Show information about Qt"));
aboutQtAction->setMenuRole(QAction::AboutQtRole);
optionsAction = new QAction(QIcon(":/icons/options"), tr("&Options..."), this);
optionsAction->setStatusTip(tr("Modify configuration options for IlluminatiCoin"));
optionsAction->setMenuRole(QAction::PreferencesRole);
toggleHideAction = new QAction(QIcon(":/icons/bitcoin"), tr("&Show / Hide"), this);
toggleHideAction->setStatusTip(tr("Show or hide the main Window"));
encryptWalletAction = new QAction(QIcon(":/icons/lock_closed"), tr("&Encrypt Wallet..."), this);
encryptWalletAction->setStatusTip(tr("Encrypt the private keys that belong to your wallet"));
encryptWalletAction->setCheckable(true);
backupWalletAction = new QAction(QIcon(":/icons/filesave"), tr("&Backup Wallet..."), this);
backupWalletAction->setStatusTip(tr("Backup wallet to another location"));
changePassphraseAction = new QAction(QIcon(":/icons/key"), tr("&Change Passphrase..."), this);
changePassphraseAction->setStatusTip(tr("Change the passphrase used for wallet encryption"));
signMessageAction = new QAction(QIcon(":/icons/edit"), tr("Sign &message..."), this);
signMessageAction->setStatusTip(tr("Sign messages with your IlluminatiCoin addresses to prove you own them"));
verifyMessageAction = new QAction(QIcon(":/icons/transaction_0"), tr("&Verify message..."), this);
verifyMessageAction->setStatusTip(tr("Verify messages to ensure they were signed with specified IlluminatiCoin addresses"));
openRPCConsoleAction = new QAction(QIcon(":/icons/debugwindow"), tr("&Debug window"), this);
openRPCConsoleAction->setStatusTip(tr("Open debugging and diagnostic console"));
connect(quitAction, SIGNAL(triggered()), qApp, SLOT(quit()));
connect(aboutAction, SIGNAL(triggered()), this, SLOT(aboutClicked()));
connect(aboutQtAction, SIGNAL(triggered()), qApp, SLOT(aboutQt()));
connect(optionsAction, SIGNAL(triggered()), this, SLOT(optionsClicked()));
connect(toggleHideAction, SIGNAL(triggered()), this, SLOT(toggleHidden()));
connect(encryptWalletAction, SIGNAL(triggered(bool)), walletFrame, SLOT(encryptWallet(bool)));
connect(backupWalletAction, SIGNAL(triggered()), walletFrame, SLOT(backupWallet()));
connect(changePassphraseAction, SIGNAL(triggered()), walletFrame, SLOT(changePassphrase()));
connect(signMessageAction, SIGNAL(triggered()), this, SLOT(gotoSignMessageTab()));
connect(verifyMessageAction, SIGNAL(triggered()), this, SLOT(gotoVerifyMessageTab()));
}
void BitcoinGUI::createMenuBar()
{
#ifdef Q_OS_MAC
// Create a decoupled menu bar on Mac which stays even if the window is closed
appMenuBar = new QMenuBar();
#else
// Get the main window's menu bar on other platforms
appMenuBar = menuBar();
#endif
// Configure the menus
QMenu *file = appMenuBar->addMenu(tr("&File"));
file->addAction(backupWalletAction);
file->addAction(signMessageAction);
file->addAction(verifyMessageAction);
file->addSeparator();
file->addAction(quitAction);
QMenu *settings = appMenuBar->addMenu(tr("&Settings"));
settings->addAction(encryptWalletAction);
settings->addAction(changePassphraseAction);
settings->addSeparator();
settings->addAction(optionsAction);
QMenu *help = appMenuBar->addMenu(tr("&Help"));
help->addAction(openRPCConsoleAction);
help->addSeparator();
help->addAction(aboutAction);
help->addAction(aboutQtAction);
}
void BitcoinGUI::createToolBars()
{
QToolBar *toolbar = addToolBar(tr("Tabs toolbar"));
toolbar->setToolButtonStyle(Qt::ToolButtonTextBesideIcon);
toolbar->addAction(overviewAction);
toolbar->addAction(sendCoinsAction);
toolbar->addAction(receiveCoinsAction);
toolbar->addAction(historyAction);
toolbar->addAction(addressBookAction);
}
void BitcoinGUI::setClientModel(ClientModel *clientModel)
{
this->clientModel = clientModel;
if(clientModel)
{
// Replace some strings and icons, when using the testnet
if(clientModel->isTestNet())
{
setWindowTitle(windowTitle() + QString(" ") + tr("[testnet]"));
#ifndef Q_OS_MAC
QApplication::setWindowIcon(QIcon(":icons/bitcoin_testnet"));
setWindowIcon(QIcon(":icons/bitcoin_testnet"));
#else
MacDockIconHandler::instance()->setIcon(QIcon(":icons/bitcoin_testnet"));
#endif
if(trayIcon)
{
// Just attach " [testnet]" to the existing tooltip
trayIcon->setToolTip(trayIcon->toolTip() + QString(" ") + tr("[testnet]"));
trayIcon->setIcon(QIcon(":/icons/toolbar_testnet"));
}
toggleHideAction->setIcon(QIcon(":/icons/toolbar_testnet"));
aboutAction->setIcon(QIcon(":/icons/toolbar_testnet"));
}
// Create system tray menu (or setup the dock menu) that late to prevent users from calling actions,
// while the client has not yet fully loaded
createTrayIconMenu();
// Keep up to date with client
setNumConnections(clientModel->getNumConnections());
connect(clientModel, SIGNAL(numConnectionsChanged(int)), this, SLOT(setNumConnections(int)));
setNumBlocks(clientModel->getNumBlocks(), clientModel->getNumBlocksOfPeers());
connect(clientModel, SIGNAL(numBlocksChanged(int,int)), this, SLOT(setNumBlocks(int,int)));
// Receive and report messages from network/worker thread
connect(clientModel, SIGNAL(message(QString,QString,unsigned int)), this, SLOT(message(QString,QString,unsigned int)));
rpcConsole->setClientModel(clientModel);
walletFrame->setClientModel(clientModel);
}
}
bool BitcoinGUI::addWallet(const QString& name, WalletModel *walletModel)
{
setWalletActionsEnabled(true);
return walletFrame->addWallet(name, walletModel);
}
bool BitcoinGUI::setCurrentWallet(const QString& name)
{
return walletFrame->setCurrentWallet(name);
}
void BitcoinGUI::removeAllWallets()
{
setWalletActionsEnabled(false);
walletFrame->removeAllWallets();
}
void BitcoinGUI::setWalletActionsEnabled(bool enabled)
{
overviewAction->setEnabled(enabled);
sendCoinsAction->setEnabled(enabled);
receiveCoinsAction->setEnabled(enabled);
historyAction->setEnabled(enabled);
encryptWalletAction->setEnabled(enabled);
backupWalletAction->setEnabled(enabled);
changePassphraseAction->setEnabled(enabled);
signMessageAction->setEnabled(enabled);
verifyMessageAction->setEnabled(enabled);
addressBookAction->setEnabled(enabled);
}
void BitcoinGUI::createTrayIcon()
{
#ifndef Q_OS_MAC
trayIcon = new QSystemTrayIcon(this);
trayIcon->setToolTip(tr("IlluminatiCoin client"));
trayIcon->setIcon(QIcon(":/icons/toolbar"));
trayIcon->show();
#endif
notificator = new Notificator(QApplication::applicationName(), trayIcon);
}
void BitcoinGUI::createTrayIconMenu()
{
QMenu *trayIconMenu;
#ifndef Q_OS_MAC
// return if trayIcon is unset (only on non-Mac OSes)
if (!trayIcon)
return;
trayIconMenu = new QMenu(this);
trayIcon->setContextMenu(trayIconMenu);
connect(trayIcon, SIGNAL(activated(QSystemTrayIcon::ActivationReason)),
this, SLOT(trayIconActivated(QSystemTrayIcon::ActivationReason)));
#else
// Note: On Mac, the dock icon is used to provide the tray's functionality.
MacDockIconHandler *dockIconHandler = MacDockIconHandler::instance();
dockIconHandler->setMainWindow((QMainWindow *)this);
trayIconMenu = dockIconHandler->dockMenu();
#endif
// Configuration of the tray icon (or dock icon) icon menu
trayIconMenu->addAction(toggleHideAction);
trayIconMenu->addSeparator();
trayIconMenu->addAction(sendCoinsAction);
trayIconMenu->addAction(receiveCoinsAction);
trayIconMenu->addSeparator();
trayIconMenu->addAction(signMessageAction);
trayIconMenu->addAction(verifyMessageAction);
trayIconMenu->addSeparator();
trayIconMenu->addAction(optionsAction);
trayIconMenu->addAction(openRPCConsoleAction);
#ifndef Q_OS_MAC // This is built-in on Mac
trayIconMenu->addSeparator();
trayIconMenu->addAction(quitAction);
#endif
}
#ifndef Q_OS_MAC
void BitcoinGUI::trayIconActivated(QSystemTrayIcon::ActivationReason reason)
{
if(reason == QSystemTrayIcon::Trigger)
{
// Click on system tray icon triggers show/hide of the main window
toggleHideAction->trigger();
}
}
#endif
void BitcoinGUI::saveWindowGeometry()
{
QSettings settings;
settings.setValue("nWindowPos", pos());
settings.setValue("nWindowSize", size());
}
void BitcoinGUI::restoreWindowGeometry()
{
QSettings settings;
QPoint pos = settings.value("nWindowPos").toPoint();
QSize size = settings.value("nWindowSize", QSize(850, 550)).toSize();
if (!pos.x() && !pos.y())
{
QRect screen = QApplication::desktop()->screenGeometry();
pos.setX((screen.width()-size.width())/2);
pos.setY((screen.height()-size.height())/2);
}
resize(size);
move(pos);
}
void BitcoinGUI::optionsClicked()
{
if(!clientModel || !clientModel->getOptionsModel())
return;
OptionsDialog dlg;
dlg.setModel(clientModel->getOptionsModel());
dlg.exec();
}
void BitcoinGUI::aboutClicked()
{
AboutDialog dlg;
dlg.setModel(clientModel);
dlg.exec();
}
void BitcoinGUI::gotoOverviewPage()
{
if (walletFrame) walletFrame->gotoOverviewPage();
}
void BitcoinGUI::gotoHistoryPage()
{
if (walletFrame) walletFrame->gotoHistoryPage();
}
void BitcoinGUI::gotoAddressBookPage()
{
if (walletFrame) walletFrame->gotoAddressBookPage();
}
void BitcoinGUI::gotoReceiveCoinsPage()
{
if (walletFrame) walletFrame->gotoReceiveCoinsPage();
}
void BitcoinGUI::gotoSendCoinsPage(QString addr)
{
if (walletFrame) walletFrame->gotoSendCoinsPage(addr);
}
void BitcoinGUI::gotoSignMessageTab(QString addr)
{
if (walletFrame) walletFrame->gotoSignMessageTab(addr);
}
void BitcoinGUI::gotoVerifyMessageTab(QString addr)
{
if (walletFrame) walletFrame->gotoVerifyMessageTab(addr);
}
void BitcoinGUI::setNumConnections(int count)
{
QString icon;
switch(count)
{
case 0: icon = ":/icons/connect_0"; break;
case 1: case 2: case 3: icon = ":/icons/connect_1"; break;
case 4: case 5: case 6: icon = ":/icons/connect_2"; break;
case 7: case 8: case 9: icon = ":/icons/connect_3"; break;
default: icon = ":/icons/connect_4"; break;
}
labelConnectionsIcon->setPixmap(QIcon(icon).pixmap(STATUSBAR_ICONSIZE,STATUSBAR_ICONSIZE));
labelConnectionsIcon->setToolTip(tr("%n active connection(s) to IlluminatiCoin network", "", count));
}
void BitcoinGUI::setNumBlocks(int count, int nTotalBlocks)
{
// Prevent orphan statusbar messages (e.g. hover Quit in main menu, wait until chain-sync starts -> garbelled text)
statusBar()->clearMessage();
// Acquire current block source
enum BlockSource blockSource = clientModel->getBlockSource();
switch (blockSource) {
case BLOCK_SOURCE_NETWORK:
progressBarLabel->setText(tr("Synchronizing with network..."));
break;
case BLOCK_SOURCE_DISK:
progressBarLabel->setText(tr("Importing blocks from disk..."));
break;
case BLOCK_SOURCE_REINDEX:
progressBarLabel->setText(tr("Reindexing blocks on disk..."));
break;
case BLOCK_SOURCE_NONE:
// Case: not Importing, not Reindexing and no network connection
progressBarLabel->setText(tr("No block source available..."));
break;
}
QString tooltip;
QDateTime lastBlockDate = clientModel->getLastBlockDate();
QDateTime currentDate = QDateTime::currentDateTime();
int secs = lastBlockDate.secsTo(currentDate);
if(count < nTotalBlocks)
{
tooltip = tr("Processed %1 of %2 (estimated) blocks of transaction history.").arg(count).arg(nTotalBlocks);
}
else
{
tooltip = tr("Processed %1 blocks of transaction history.").arg(count);
}
// Set icon state: spinning if catching up, tick otherwise
if(secs < 90*60 && count >= nTotalBlocks)
{
tooltip = tr("Up to date") + QString(".<br>") + tooltip;
labelBlocksIcon->setPixmap(QIcon(":/icons/synced").pixmap(STATUSBAR_ICONSIZE, STATUSBAR_ICONSIZE));
walletFrame->showOutOfSyncWarning(false);
progressBarLabel->setVisible(false);
progressBar->setVisible(false);
}
else
{
// Represent time from last generated block in human readable text
QString timeBehindText;
if(secs < 48*60*60)
{
timeBehindText = tr("%n hour(s)","",secs/(60*60));
}
else if(secs < 14*24*60*60)
{
timeBehindText = tr("%n day(s)","",secs/(24*60*60));
}
else
{
timeBehindText = tr("%n week(s)","",secs/(7*24*60*60));
}
progressBarLabel->setVisible(true);
progressBar->setFormat(tr("%1 behind").arg(timeBehindText));
progressBar->setMaximum(1000000000);
progressBar->setValue(clientModel->getVerificationProgress() * 1000000000.0 + 0.5);
progressBar->setVisible(true);
tooltip = tr("Catching up...") + QString("<br>") + tooltip;
labelBlocksIcon->setMovie(syncIconMovie);
if(count != prevBlocks)
syncIconMovie->jumpToNextFrame();
prevBlocks = count;
walletFrame->showOutOfSyncWarning(true);
tooltip += QString("<br>");
tooltip += tr("Last received block was generated %1 ago.").arg(timeBehindText);
tooltip += QString("<br>");
tooltip += tr("Transactions after this will not yet be visible.");
}
// Don't word-wrap this (fixed-width) tooltip
tooltip = QString("<nobr>") + tooltip + QString("</nobr>");
labelBlocksIcon->setToolTip(tooltip);
progressBarLabel->setToolTip(tooltip);
progressBar->setToolTip(tooltip);
}
void BitcoinGUI::message(const QString &title, const QString &message, unsigned int style, bool *ret)
{
QString strTitle = tr("IlluminatiCoin"); // default title
// Default to information icon
int nMBoxIcon = QMessageBox::Information;
int nNotifyIcon = Notificator::Information;
QString msgType;
// Prefer supplied title over style based title
if (!title.isEmpty()) {
msgType = title;
}
else {
switch (style) {
case CClientUIInterface::MSG_ERROR:
msgType = tr("Error");
break;
case CClientUIInterface::MSG_WARNING:
msgType = tr("Warning");
break;
case CClientUIInterface::MSG_INFORMATION:
msgType = tr("Information");
break;
default:
break;
}
}
// Append title to "Bitcoin - "
if (!msgType.isEmpty())
strTitle += " - " + msgType;
// Check for error/warning icon
if (style & CClientUIInterface::ICON_ERROR) {
nMBoxIcon = QMessageBox::Critical;
nNotifyIcon = Notificator::Critical;
}
else if (style & CClientUIInterface::ICON_WARNING) {
nMBoxIcon = QMessageBox::Warning;
nNotifyIcon = Notificator::Warning;
}
// Display message
if (style & CClientUIInterface::MODAL) {
// Check for buttons, use OK as default, if none was supplied
QMessageBox::StandardButton buttons;
if (!(buttons = (QMessageBox::StandardButton)(style & CClientUIInterface::BTN_MASK)))
buttons = QMessageBox::Ok;
// Ensure we get users attention
showNormalIfMinimized();
QMessageBox mBox((QMessageBox::Icon)nMBoxIcon, strTitle, message, buttons, this);
int r = mBox.exec();
if (ret != NULL)
*ret = r == QMessageBox::Ok;
}
else
notificator->notify((Notificator::Class)nNotifyIcon, strTitle, message);
}
void BitcoinGUI::changeEvent(QEvent *e)
{
QMainWindow::changeEvent(e);
#ifndef Q_OS_MAC // Ignored on Mac
if(e->type() == QEvent::WindowStateChange)
{
if(clientModel && clientModel->getOptionsModel()->getMinimizeToTray())
{
QWindowStateChangeEvent *wsevt = static_cast<QWindowStateChangeEvent*>(e);
if(!(wsevt->oldState() & Qt::WindowMinimized) && isMinimized())
{
QTimer::singleShot(0, this, SLOT(hide()));
e->ignore();
}
}
}
#endif
}
void BitcoinGUI::closeEvent(QCloseEvent *event)
{
if(clientModel)
{
#ifndef Q_OS_MAC // Ignored on Mac
if(!clientModel->getOptionsModel()->getMinimizeToTray() &&
!clientModel->getOptionsModel()->getMinimizeOnClose())
{
QApplication::quit();
}
#endif
}
QMainWindow::closeEvent(event);
}
void BitcoinGUI::askFee(qint64 nFeeRequired, bool *payFee)
{
QString strMessage = tr("This transaction is over the size limit. You can still send it for a fee of %1, "
"which goes to the nodes that process your transaction and helps to support the network. "
"Do you want to pay the fee?").arg(BitcoinUnits::formatWithUnit(BitcoinUnits::BTC, nFeeRequired));
QMessageBox::StandardButton retval = QMessageBox::question(this, tr("Confirm transaction fee"), strMessage,
QMessageBox::Yes | QMessageBox::Cancel, QMessageBox::Yes);
*payFee = (retval == QMessageBox::Yes);
}
void BitcoinGUI::incomingTransaction(const QString& date, int unit, qint64 amount, const QString& type, const QString& address)
{
// On new transaction, make an info balloon
message((amount)<0 ? tr("Sent transaction") : tr("Incoming transaction"),
tr("Date: %1\n"
"Amount: %2\n"
"Type: %3\n"
"Address: %4\n")
.arg(date)
.arg(BitcoinUnits::formatWithUnit(unit, amount, true))
.arg(type)
.arg(address), CClientUIInterface::MSG_INFORMATION);
}
void BitcoinGUI::dragEnterEvent(QDragEnterEvent *event)
{
// Accept only URIs
if(event->mimeData()->hasUrls())
event->acceptProposedAction();
}
void BitcoinGUI::dropEvent(QDropEvent *event)
{
if(event->mimeData()->hasUrls())
{
int nValidUrisFound = 0;
QList<QUrl> uris = event->mimeData()->urls();
foreach(const QUrl &uri, uris)
{
if (walletFrame->handleURI(uri.toString()))
nValidUrisFound++;
}
// if valid URIs were found
if (nValidUrisFound)
walletFrame->gotoSendCoinsPage();
else
message(tr("URI handling"), tr("URI can not be parsed! This can be caused by an invalid IlluminatiCoin address or malformed URI parameters."),
CClientUIInterface::ICON_WARNING);
}
event->acceptProposedAction();
}
bool BitcoinGUI::eventFilter(QObject *object, QEvent *event)
{
// Catch status tip events
if (event->type() == QEvent::StatusTip)
{
// Prevent adding text from setStatusTip(), if we currently use the status bar for displaying other stuff
if (progressBarLabel->isVisible() || progressBar->isVisible())
return true;
}
return QMainWindow::eventFilter(object, event);
}
void BitcoinGUI::handleURI(QString strURI)
{
// URI has to be valid
if (!walletFrame->handleURI(strURI))
message(tr("URI handling"), tr("URI can not be parsed! This can be caused by an invalid IlluminatiCoin address or malformed URI parameters."),
CClientUIInterface::ICON_WARNING);
}
void BitcoinGUI::setEncryptionStatus(int status)
{
switch(status)
{
case WalletModel::Unencrypted:
labelEncryptionIcon->hide();
encryptWalletAction->setChecked(false);
changePassphraseAction->setEnabled(false);
encryptWalletAction->setEnabled(true);
break;
case WalletModel::Unlocked:
labelEncryptionIcon->show();
labelEncryptionIcon->setPixmap(QIcon(":/icons/lock_open").pixmap(STATUSBAR_ICONSIZE,STATUSBAR_ICONSIZE));
labelEncryptionIcon->setToolTip(tr("Wallet is <b>encrypted</b> and currently <b>unlocked</b>"));
encryptWalletAction->setChecked(true);
changePassphraseAction->setEnabled(true);
encryptWalletAction->setEnabled(false); // TODO: decrypt currently not supported
break;
case WalletModel::Locked:
labelEncryptionIcon->show();
labelEncryptionIcon->setPixmap(QIcon(":/icons/lock_closed").pixmap(STATUSBAR_ICONSIZE,STATUSBAR_ICONSIZE));
labelEncryptionIcon->setToolTip(tr("Wallet is <b>encrypted</b> and currently <b>locked</b>"));
encryptWalletAction->setChecked(true);
changePassphraseAction->setEnabled(true);
encryptWalletAction->setEnabled(false); // TODO: decrypt currently not supported
break;
}
}
void BitcoinGUI::showNormalIfMinimized(bool fToggleHidden)
{
// activateWindow() (sometimes) helps with keyboard focus on Windows
if (isHidden())
{
show();
activateWindow();
}
else if (isMinimized())
{
showNormal();
activateWindow();
}
else if (GUIUtil::isObscured(this))
{
raise();
activateWindow();
}
else if(fToggleHidden)
hide();
}
void BitcoinGUI::toggleHidden()
{
showNormalIfMinimized(true);
}
void BitcoinGUI::detectShutdown()
{
if (ShutdownRequested())
QMetaObject::invokeMethod(QCoreApplication::instance(), "quit", Qt::QueuedConnection);
}
| mit |
Hellenic/dashboard-frontend | server/core-routes.js | 658 | var React = require('react');
var ReactDOMServer = require('react-dom/server');
var ReactRouter = require('react-router');
var history = require('history');
var routes = require('../app/routes.js');
var RoutingContext = ReactRouter.RoutingContext;
var match = ReactRouter.match;
module.exports = function(app) {
app.get('/', function(req, res) {
var location = history.createLocation(req.url)
match({routes: routes, location: location}, function(error, redirectLocation, renderProps) {
var reactHtml = ReactDOMServer.renderToString(<RoutingContext {...renderProps} />);
res.render('index.html', { reactOutput: reactHtml });
});
});
};
| mit |
Kuree/Faker.Net | Faker.Net/Locales/De.cs | 205804 | namespace Faker.Locales
{
[Locale(LocaleType.de)]
internal class De : En
{
public override string Title { get { return "German"; } }
#region Geography
public override string[] CityPrefix
{
get
{
return new[] {
"Nord",
"Ost",
"West",
"Süd",
"Neu",
"Alt",
"Bad"
};
}
}
public override string[] CitySuffix
{
get
{
return new[] {
"stadt",
"dorf",
"land",
"scheid",
"burg"
};
}
}
public override string[] Country
{
get
{
return new[] {
"Ägypten",
"Äquatorialguinea",
"Äthiopien",
"Österreich",
"Afghanistan",
"Albanien",
"Algerien",
"Amerikanisch-Samoa",
"Amerikanische Jungferninseln",
"Andorra",
"Angola",
"Anguilla",
"Antarktis",
"Antigua und Barbuda",
"Argentinien",
"Armenien",
"Aruba",
"Aserbaidschan",
"Australien",
"Bahamas",
"Bahrain",
"Bangladesch",
"Barbados",
"Belarus",
"Belgien",
"Belize",
"Benin",
"die Bermudas",
"Bhutan",
"Bolivien",
"Bosnien und Herzegowina",
"Botsuana",
"Bouvetinsel",
"Brasilien",
"Britische Jungferninseln",
"Britisches Territorium im Indischen Ozean",
"Brunei Darussalam",
"Bulgarien",
"Burkina Faso",
"Burundi",
"Chile",
"China",
"Cookinseln",
"Costa Rica",
"Dänemark",
"Demokratische Republik Kongo",
"Demokratische Volksrepublik Korea",
"Deutschland",
"Dominica",
"Dominikanische Republik",
"Dschibuti",
"Ecuador",
"El Salvador",
"Eritrea",
"Estland",
"Färöer",
"Falklandinseln",
"Fidschi",
"Finnland",
"Frankreich",
"Französisch-Guayana",
"Französisch-Polynesien",
"Französische Gebiete im südlichen Indischen Ozean",
"Gabun",
"Gambia",
"Georgien",
"Ghana",
"Gibraltar",
"Grönland",
"Grenada",
"Griechenland",
"Guadeloupe",
"Guam",
"Guatemala",
"Guinea",
"Guinea-Bissau",
"Guyana",
"Haiti",
"Heard und McDonaldinseln",
"Honduras",
"Hongkong",
"Indien",
"Indonesien",
"Irak",
"Iran",
"Irland",
"Island",
"Israel",
"Italien",
"Jamaika",
"Japan",
"Jemen",
"Jordanien",
"Jugoslawien",
"Kaimaninseln",
"Kambodscha",
"Kamerun",
"Kanada",
"Kap Verde",
"Kasachstan",
"Katar",
"Kenia",
"Kirgisistan",
"Kiribati",
"Kleinere amerikanische Überseeinseln",
"Kokosinseln",
"Kolumbien",
"Komoren",
"Kongo",
"Kroatien",
"Kuba",
"Kuwait",
"Laos",
"Lesotho",
"Lettland",
"Libanon",
"Liberia",
"Libyen",
"Liechtenstein",
"Litauen",
"Luxemburg",
"Macau",
"Madagaskar",
"Malawi",
"Malaysia",
"Malediven",
"Mali",
"Malta",
"ehemalige jugoslawische Republik Mazedonien",
"Marokko",
"Marshallinseln",
"Martinique",
"Mauretanien",
"Mauritius",
"Mayotte",
"Mexiko",
"Mikronesien",
"Monaco",
"Mongolei",
"Montserrat",
"Mosambik",
"Myanmar",
"Nördliche Marianen",
"Namibia",
"Nauru",
"Nepal",
"Neukaledonien",
"Neuseeland",
"Nicaragua",
"Niederländische Antillen",
"Niederlande",
"Niger",
"Nigeria",
"Niue",
"Norfolkinsel",
"Norwegen",
"Oman",
"Osttimor",
"Pakistan",
"Palau",
"Panama",
"Papua-Neuguinea",
"Paraguay",
"Peru",
"Philippinen",
"Pitcairninseln",
"Polen",
"Portugal",
"Puerto Rico",
"Réunion",
"Republik Korea",
"Republik Moldau",
"Ruanda",
"Rumänien",
"Russische Föderation",
"São Tomé und Príncipe",
"Südafrika",
"Südgeorgien und Südliche Sandwichinseln",
"Salomonen",
"Sambia",
"Samoa",
"San Marino",
"Saudi-Arabien",
"Schweden",
"Schweiz",
"Senegal",
"Seychellen",
"Sierra Leone",
"Simbabwe",
"Singapur",
"Slowakei",
"Slowenien",
"Somalien",
"Spanien",
"Sri Lanka",
"St. Helena",
"St. Kitts und Nevis",
"St. Lucia",
"St. Pierre und Miquelon",
"St. Vincent und die Grenadinen",
"Sudan",
"Surinam",
"Svalbard und Jan Mayen",
"Swasiland",
"Syrien",
"Türkei",
"Tadschikistan",
"Taiwan",
"Tansania",
"Thailand",
"Togo",
"Tokelau",
"Tonga",
"Trinidad und Tobago",
"Tschad",
"Tschechische Republik",
"Tunesien",
"Turkmenistan",
"Turks- und Caicosinseln",
"Tuvalu",
"Uganda",
"Ukraine",
"Ungarn",
"Uruguay",
"Usbekistan",
"Vanuatu",
"Vatikanstadt",
"Venezuela",
"Vereinigte Arabische Emirate",
"Vereinigte Staaten",
"Vereinigtes Königreich",
"Vietnam",
"Wallis und Futuna",
"Weihnachtsinsel",
"Westsahara",
"Zentralafrikanische Republik",
"Zypern"
};
}
}
public string[] StreetRoot
{
get
{
return new[] {
"Ackerweg",
"Adalbert-Stifter-Str.",
"Adalbertstr.",
"Adolf-Baeyer-Str.",
"Adolf-Kaschny-Str.",
"Adolf-Reichwein-Str.",
"Adolfsstr.",
"Ahornweg",
"Ahrstr.",
"Akazienweg",
"Albert-Einstein-Str.",
"Albert-Schweitzer-Str.",
"Albertus-Magnus-Str.",
"Albert-Zarthe-Weg",
"Albin-Edelmann-Str.",
"Albrecht-Haushofer-Str.",
"Aldegundisstr.",
"Alexanderstr.",
"Alfred-Delp-Str.",
"Alfred-Kubin-Str.",
"Alfred-Stock-Str.",
"Alkenrather Str.",
"Allensteiner Str.",
"Alsenstr.",
"Alt Steinbücheler Weg",
"Alte Garten",
"Alte Heide",
"Alte Landstr.",
"Alte Ziegelei",
"Altenberger Str.",
"Altenhof",
"Alter Grenzweg",
"Altstadtstr.",
"Am Alten Gaswerk",
"Am Alten Schafstall",
"Am Arenzberg",
"Am Benthal",
"Am Birkenberg",
"Am Blauen Berg",
"Am Borsberg",
"Am Brungen",
"Am Büchelter Hof",
"Am Buttermarkt",
"Am Ehrenfriedhof",
"Am Eselsdamm",
"Am Falkenberg",
"Am Frankenberg",
"Am Gesundheitspark",
"Am Gierlichshof",
"Am Graben",
"Am Hagelkreuz",
"Am Hang",
"Am Heidkamp",
"Am Hemmelrather Hof",
"Am Hofacker",
"Am Hohen Ufer",
"Am Höllers Eck",
"Am Hühnerberg",
"Am Jägerhof",
"Am Junkernkamp",
"Am Kemperstiegel",
"Am Kettnersbusch",
"Am Kiesberg",
"Am Klösterchen",
"Am Knechtsgraben",
"Am Köllerweg",
"Am Köttersbach",
"Am Kreispark",
"Am Kronefeld",
"Am Küchenhof",
"Am Kühnsbusch",
"Am Lindenfeld",
"Am Märchen",
"Am Mittelberg",
"Am Mönchshof",
"Am Mühlenbach",
"Am Neuenhof",
"Am Nonnenbruch",
"Am Plattenbusch",
"Am Quettinger Feld",
"Am Rosenhügel",
"Am Sandberg",
"Am Scherfenbrand",
"Am Schokker",
"Am Silbersee",
"Am Sonnenhang",
"Am Sportplatz",
"Am Stadtpark",
"Am Steinberg",
"Am Telegraf",
"Am Thelenhof",
"Am Vogelkreuz",
"Am Vogelsang",
"Am Vogelsfeldchen",
"Am Wambacher Hof",
"Am Wasserturm",
"Am Weidenbusch",
"Am Weiher",
"Am Weingarten",
"Am Werth",
"Amselweg",
"An den Irlen",
"An den Rheinauen",
"An der Bergerweide",
"An der Dingbank",
"An der Evangelischen Kirche",
"An der Evgl. Kirche",
"An der Feldgasse",
"An der Fettehenne",
"An der Kante",
"An der Laach",
"An der Lehmkuhle",
"An der Lichtenburg",
"An der Luisenburg",
"An der Robertsburg",
"An der Schmitten",
"An der Schusterinsel",
"An der Steinrütsch",
"An St. Andreas",
"An St. Remigius",
"Andreasstr.",
"Ankerweg",
"Annette-Kolb-Str.",
"Apenrader Str.",
"Arnold-Ohletz-Str.",
"Atzlenbacher Str.",
"Auerweg",
"Auestr.",
"Auf dem Acker",
"Auf dem Blahnenhof",
"Auf dem Bohnbüchel",
"Auf dem Bruch",
"Auf dem End",
"Auf dem Forst",
"Auf dem Herberg",
"Auf dem Lehn",
"Auf dem Stein",
"Auf dem Weierberg",
"Auf dem Weiherhahn",
"Auf den Reien",
"Auf der Donnen",
"Auf der Grieße",
"Auf der Ohmer",
"Auf der Weide",
"Auf'm Berg",
"Auf'm Kamp",
"Augustastr.",
"August-Kekulé-Str.",
"A.-W.-v.-Hofmann-Str.",
"Bahnallee",
"Bahnhofstr.",
"Baltrumstr.",
"Bamberger Str.",
"Baumberger Str.",
"Bebelstr.",
"Beckers Kämpchen",
"Beerenstr.",
"Beethovenstr.",
"Behringstr.",
"Bendenweg",
"Bensberger Str.",
"Benzstr.",
"Bergische Landstr.",
"Bergstr.",
"Berliner Platz",
"Berliner Str.",
"Bernhard-Letterhaus-Str.",
"Bernhard-Lichtenberg-Str.",
"Bernhard-Ridder-Str.",
"Bernsteinstr.",
"Bertha-Middelhauve-Str.",
"Bertha-von-Suttner-Str.",
"Bertolt-Brecht-Str.",
"Berzeliusstr.",
"Bielertstr.",
"Biesenbach",
"Billrothstr.",
"Birkenbergstr.",
"Birkengartenstr.",
"Birkenweg",
"Bismarckstr.",
"Bitterfelder Str.",
"Blankenburg",
"Blaukehlchenweg",
"Blütenstr.",
"Boberstr.",
"Böcklerstr.",
"Bodelschwinghstr.",
"Bodestr.",
"Bogenstr.",
"Bohnenkampsweg",
"Bohofsweg",
"Bonifatiusstr.",
"Bonner Str.",
"Borkumstr.",
"Bornheimer Str.",
"Borsigstr.",
"Borussiastr.",
"Bracknellstr.",
"Brahmsweg",
"Brandenburger Str.",
"Breidenbachstr.",
"Breslauer Str.",
"Bruchhauser Str.",
"Brückenstr.",
"Brucknerstr.",
"Brüder-Bonhoeffer-Str.",
"Buchenweg",
"Bürgerbuschweg",
"Burgloch",
"Burgplatz",
"Burgstr.",
"Burgweg",
"Bürriger Weg",
"Burscheider Str.",
"Buschkämpchen",
"Butterheider Str.",
"Carl-Duisberg-Platz",
"Carl-Duisberg-Str.",
"Carl-Leverkus-Str.",
"Carl-Maria-von-Weber-Platz",
"Carl-Maria-von-Weber-Str.",
"Carlo-Mierendorff-Str.",
"Carl-Rumpff-Str.",
"Carl-von-Ossietzky-Str.",
"Charlottenburger Str.",
"Christian-Heß-Str.",
"Claasbruch",
"Clemens-Winkler-Str.",
"Concordiastr.",
"Cranachstr.",
"Dahlemer Str.",
"Daimlerstr.",
"Damaschkestr.",
"Danziger Str.",
"Debengasse",
"Dechant-Fein-Str.",
"Dechant-Krey-Str.",
"Deichtorstr.",
"Dhünnberg",
"Dhünnstr.",
"Dianastr.",
"Diedenhofener Str.",
"Diepental",
"Diepenthaler Str.",
"Dieselstr.",
"Dillinger Str.",
"Distelkamp",
"Dohrgasse",
"Domblick",
"Dönhoffstr.",
"Dornierstr.",
"Drachenfelsstr.",
"Dr.-August-Blank-Str.",
"Dresdener Str.",
"Driescher Hecke",
"Drosselweg",
"Dudweilerstr.",
"Dünenweg",
"Dünfelder Str.",
"Dünnwalder Grenzweg",
"Düppeler Str.",
"Dürerstr.",
"Dürscheider Weg",
"Düsseldorfer Str.",
"Edelrather Weg",
"Edmund-Husserl-Str.",
"Eduard-Spranger-Str.",
"Ehrlichstr.",
"Eichenkamp",
"Eichenweg",
"Eidechsenweg",
"Eifelstr.",
"Eifgenstr.",
"Eintrachtstr.",
"Elbestr.",
"Elisabeth-Langgässer-Str.",
"Elisabethstr.",
"Elisabeth-von-Thadden-Str.",
"Elisenstr.",
"Elsa-Brändström-Str.",
"Elsbachstr.",
"Else-Lasker-Schüler-Str.",
"Elsterstr.",
"Emil-Fischer-Str.",
"Emil-Nolde-Str.",
"Engelbertstr.",
"Engstenberger Weg",
"Entenpfuhl",
"Erbelegasse",
"Erftstr.",
"Erfurter Str.",
"Erich-Heckel-Str.",
"Erich-Klausener-Str.",
"Erich-Ollenhauer-Str.",
"Erlenweg",
"Ernst-Bloch-Str.",
"Ernst-Ludwig-Kirchner-Str.",
"Erzbergerstr.",
"Eschenallee",
"Eschenweg",
"Esmarchstr.",
"Espenweg",
"Euckenstr.",
"Eulengasse",
"Eulenkamp",
"Ewald-Flamme-Str.",
"Ewald-Röll-Str.",
"Fährstr.",
"Farnweg",
"Fasanenweg",
"Faßbacher Hof",
"Felderstr.",
"Feldkampstr.",
"Feldsiefer Weg",
"Feldsiefer Wiesen",
"Feldstr.",
"Feldtorstr.",
"Felix-von-Roll-Str.",
"Ferdinand-Lassalle-Str.",
"Fester Weg",
"Feuerbachstr.",
"Feuerdornweg",
"Fichtenweg",
"Fichtestr.",
"Finkelsteinstr.",
"Finkenweg",
"Fixheider Str.",
"Flabbenhäuschen",
"Flensburger Str.",
"Fliederweg",
"Florastr.",
"Florianweg",
"Flotowstr.",
"Flurstr.",
"Föhrenweg",
"Fontanestr.",
"Forellental",
"Fortunastr.",
"Franz-Esser-Str.",
"Franz-Hitze-Str.",
"Franz-Kail-Str.",
"Franz-Marc-Str.",
"Freiburger Str.",
"Freiheitstr.",
"Freiherr-vom-Stein-Str.",
"Freudenthal",
"Freudenthaler Weg",
"Fridtjof-Nansen-Str.",
"Friedenberger Str.",
"Friedensstr.",
"Friedhofstr.",
"Friedlandstr.",
"Friedlieb-Ferdinand-Runge-Str.",
"Friedrich-Bayer-Str.",
"Friedrich-Bergius-Platz",
"Friedrich-Ebert-Platz",
"Friedrich-Ebert-Str.",
"Friedrich-Engels-Str.",
"Friedrich-List-Str.",
"Friedrich-Naumann-Str.",
"Friedrich-Sertürner-Str.",
"Friedrichstr.",
"Friedrich-Weskott-Str.",
"Friesenweg",
"Frischenberg",
"Fritz-Erler-Str.",
"Fritz-Henseler-Str.",
"Fröbelstr.",
"Fürstenbergplatz",
"Fürstenbergstr.",
"Gabriele-Münter-Str.",
"Gartenstr.",
"Gebhardstr.",
"Geibelstr.",
"Gellertstr.",
"Georg-von-Vollmar-Str.",
"Gerhard-Domagk-Str.",
"Gerhart-Hauptmann-Str.",
"Gerichtsstr.",
"Geschwister-Scholl-Str.",
"Gezelinallee",
"Gierener Weg",
"Ginsterweg",
"Gisbert-Cremer-Str.",
"Glücksburger Str.",
"Gluckstr.",
"Gneisenaustr.",
"Goetheplatz",
"Goethestr.",
"Golo-Mann-Str.",
"Görlitzer Str.",
"Görresstr.",
"Graebestr.",
"Graf-Galen-Platz",
"Gregor-Mendel-Str.",
"Greifswalder Str.",
"Grillenweg",
"Gronenborner Weg",
"Große Kirchstr.",
"Grunder Wiesen",
"Grundermühle",
"Grundermühlenhof",
"Grundermühlenweg",
"Grüner Weg",
"Grunewaldstr.",
"Grünstr.",
"Günther-Weisenborn-Str.",
"Gustav-Freytag-Str.",
"Gustav-Heinemann-Str.",
"Gustav-Radbruch-Str.",
"Gut Reuschenberg",
"Gutenbergstr.",
"Haberstr.",
"Habichtgasse",
"Hafenstr.",
"Hagenauer Str.",
"Hahnenblecher",
"Halenseestr.",
"Halfenleimbach",
"Hallesche Str.",
"Halligstr.",
"Hamberger Str.",
"Hammerweg",
"Händelstr.",
"Hannah-Höch-Str.",
"Hans-Arp-Str.",
"Hans-Gerhard-Str.",
"Hans-Sachs-Str.",
"Hans-Schlehahn-Str.",
"Hans-von-Dohnanyi-Str.",
"Hardenbergstr.",
"Haselweg",
"Hauptstr.",
"Haus-Vorster-Str.",
"Hauweg",
"Havelstr.",
"Havensteinstr.",
"Haydnstr.",
"Hebbelstr.",
"Heckenweg",
"Heerweg",
"Hegelstr.",
"Heidberg",
"Heidehöhe",
"Heidestr.",
"Heimstättenweg",
"Heinrich-Böll-Str.",
"Heinrich-Brüning-Str.",
"Heinrich-Claes-Str.",
"Heinrich-Heine-Str.",
"Heinrich-Hörlein-Str.",
"Heinrich-Lübke-Str.",
"Heinrich-Lützenkirchen-Weg",
"Heinrichstr.",
"Heinrich-Strerath-Str.",
"Heinrich-von-Kleist-Str.",
"Heinrich-von-Stephan-Str.",
"Heisterbachstr.",
"Helenenstr.",
"Helmestr.",
"Hemmelrather Weg",
"Henry-T.-v.-Böttinger-Str.",
"Herderstr.",
"Heribertstr.",
"Hermann-Ehlers-Str.",
"Hermann-Hesse-Str.",
"Hermann-König-Str.",
"Hermann-Löns-Str.",
"Hermann-Milde-Str.",
"Hermann-Nörrenberg-Str.",
"Hermann-von-Helmholtz-Str.",
"Hermann-Waibel-Str.",
"Herzogstr.",
"Heymannstr.",
"Hindenburgstr.",
"Hirzenberg",
"Hitdorfer Kirchweg",
"Hitdorfer Str.",
"Höfer Mühle",
"Höfer Weg",
"Hohe Str.",
"Höhenstr.",
"Höltgestal",
"Holunderweg",
"Holzer Weg",
"Holzer Wiesen",
"Hornpottweg",
"Hubertusweg",
"Hufelandstr.",
"Hufer Weg",
"Humboldtstr.",
"Hummelsheim",
"Hummelweg",
"Humperdinckstr.",
"Hüscheider Gärten",
"Hüscheider Str.",
"Hütte",
"Ilmstr.",
"Im Bergischen Heim",
"Im Bruch",
"Im Buchenhain",
"Im Bühl",
"Im Burgfeld",
"Im Dorf",
"Im Eisholz",
"Im Friedenstal",
"Im Frohental",
"Im Grunde",
"Im Hederichsfeld",
"Im Jücherfeld",
"Im Kalkfeld",
"Im Kirberg",
"Im Kirchfeld",
"Im Kreuzbruch",
"Im Mühlenfeld",
"Im Nesselrader Kamp",
"Im Oberdorf",
"Im Oberfeld",
"Im Rosengarten",
"Im Rottland",
"Im Scheffengarten",
"Im Staderfeld",
"Im Steinfeld",
"Im Weidenblech",
"Im Winkel",
"Im Ziegelfeld",
"Imbach",
"Imbacher Weg",
"Immenweg",
"In den Blechenhöfen",
"In den Dehlen",
"In der Birkenau",
"In der Dasladen",
"In der Felderhütten",
"In der Hartmannswiese",
"In der Höhle",
"In der Schaafsdellen",
"In der Wasserkuhl",
"In der Wüste",
"In Holzhausen",
"Insterstr.",
"Jacob-Fröhlen-Str.",
"Jägerstr.",
"Jahnstr.",
"Jakob-Eulenberg-Weg",
"Jakobistr.",
"Jakob-Kaiser-Str.",
"Jenaer Str.",
"Johannes-Baptist-Str.",
"Johannes-Dott-Str.",
"Johannes-Popitz-Str.",
"Johannes-Wislicenus-Str.",
"Johannisburger Str.",
"Johann-Janssen-Str.",
"Johann-Wirtz-Weg",
"Josefstr.",
"Jüch",
"Julius-Doms-Str.",
"Julius-Leber-Str.",
"Kaiserplatz",
"Kaiserstr.",
"Kaiser-Wilhelm-Allee",
"Kalkstr.",
"Kämpchenstr.",
"Kämpenwiese",
"Kämper Weg",
"Kamptalweg",
"Kanalstr.",
"Kandinskystr.",
"Kantstr.",
"Kapellenstr.",
"Karl-Arnold-Str.",
"Karl-Bosch-Str.",
"Karl-Bückart-Str.",
"Karl-Carstens-Ring",
"Karl-Friedrich-Goerdeler-Str.",
"Karl-Jaspers-Str.",
"Karl-König-Str.",
"Karl-Krekeler-Str.",
"Karl-Marx-Str.",
"Karlstr.",
"Karl-Ulitzka-Str.",
"Karl-Wichmann-Str.",
"Karl-Wingchen-Str.",
"Käsenbrod",
"Käthe-Kollwitz-Str.",
"Katzbachstr.",
"Kerschensteinerstr.",
"Kiefernweg",
"Kieler Str.",
"Kieselstr.",
"Kiesweg",
"Kinderhausen",
"Kleiberweg",
"Kleine Kirchstr.",
"Kleingansweg",
"Kleinheider Weg",
"Klief",
"Kneippstr.",
"Knochenbergsweg",
"Kochergarten",
"Kocherstr.",
"Kockelsberg",
"Kolberger Str.",
"Kolmarer Str.",
"Kölner Gasse",
"Kölner Str.",
"Kolpingstr.",
"Königsberger Platz",
"Konrad-Adenauer-Platz",
"Köpenicker Str.",
"Kopernikusstr.",
"Körnerstr.",
"Köschenberg",
"Köttershof",
"Kreuzbroicher Str.",
"Kreuzkamp",
"Krummer Weg",
"Kruppstr.",
"Kuhlmannweg",
"Kump",
"Kumper Weg",
"Kunstfeldstr.",
"Küppersteger Str.",
"Kursiefen",
"Kursiefer Weg",
"Kurtekottenweg",
"Kurt-Schumacher-Ring",
"Kyllstr.",
"Langenfelder Str.",
"Längsleimbach",
"Lärchenweg",
"Legienstr.",
"Lehner Mühle",
"Leichlinger Str.",
"Leimbacher Hof",
"Leinestr.",
"Leineweberstr.",
"Leipziger Str.",
"Lerchengasse",
"Lessingstr.",
"Libellenweg",
"Lichstr.",
"Liebigstr.",
"Lindenstr.",
"Lingenfeld",
"Linienstr.",
"Lippe",
"Löchergraben",
"Löfflerstr.",
"Loheweg",
"Lohrbergstr.",
"Lohrstr.",
"Löhstr.",
"Lortzingstr.",
"Lötzener Str.",
"Löwenburgstr.",
"Lucasstr.",
"Ludwig-Erhard-Platz",
"Ludwig-Girtler-Str.",
"Ludwig-Knorr-Str.",
"Luisenstr.",
"Lupinenweg",
"Lurchenweg",
"Lützenkirchener Str.",
"Lycker Str.",
"Maashofstr.",
"Manforter Str.",
"Marc-Chagall-Str.",
"Maria-Dresen-Str.",
"Maria-Terwiel-Str.",
"Marie-Curie-Str.",
"Marienburger Str.",
"Mariendorfer Str.",
"Marienwerderstr.",
"Marie-Schlei-Str.",
"Marktplatz",
"Markusweg",
"Martin-Buber-Str.",
"Martin-Heidegger-Str.",
"Martin-Luther-Str.",
"Masurenstr.",
"Mathildenweg",
"Maurinusstr.",
"Mauspfad",
"Max-Beckmann-Str.",
"Max-Delbrück-Str.",
"Max-Ernst-Str.",
"Max-Holthausen-Platz",
"Max-Horkheimer-Str.",
"Max-Liebermann-Str.",
"Max-Pechstein-Str.",
"Max-Planck-Str.",
"Max-Scheler-Str.",
"Max-Schönenberg-Str.",
"Maybachstr.",
"Meckhofer Feld",
"Meisenweg",
"Memelstr.",
"Menchendahler Str.",
"Mendelssohnstr.",
"Merziger Str.",
"Mettlacher Str.",
"Metzer Str.",
"Michaelsweg",
"Miselohestr.",
"Mittelstr.",
"Mohlenstr.",
"Moltkestr.",
"Monheimer Str.",
"Montanusstr.",
"Montessoriweg",
"Moosweg",
"Morsbroicher Str.",
"Moselstr.",
"Moskauer Str.",
"Mozartstr.",
"Mühlenweg",
"Muhrgasse",
"Muldestr.",
"Mülhausener Str.",
"Mülheimer Str.",
"Münsters Gäßchen",
"Münzstr.",
"Müritzstr.",
"Myliusstr.",
"Nachtigallenweg",
"Nauener Str.",
"Neißestr.",
"Nelly-Sachs-Str.",
"Netzestr.",
"Neuendriesch",
"Neuenhausgasse",
"Neuenkamp",
"Neujudenhof",
"Neukronenberger Str.",
"Neustadtstr.",
"Nicolai-Hartmann-Str.",
"Niederblecher",
"Niederfeldstr.",
"Nietzschestr.",
"Nikolaus-Groß-Str.",
"Nobelstr.",
"Norderneystr.",
"Nordstr.",
"Ober dem Hof",
"Obere Lindenstr.",
"Obere Str.",
"Oberölbach",
"Odenthaler Str.",
"Oderstr.",
"Okerstr.",
"Olof-Palme-Str.",
"Ophovener Str.",
"Opladener Platz",
"Opladener Str.",
"Ortelsburger Str.",
"Oskar-Moll-Str.",
"Oskar-Schlemmer-Str.",
"Oststr.",
"Oswald-Spengler-Str.",
"Otto-Dix-Str.",
"Otto-Grimm-Str.",
"Otto-Hahn-Str.",
"Otto-Müller-Str.",
"Otto-Stange-Str.",
"Ottostr.",
"Otto-Varnhagen-Str.",
"Otto-Wels-Str.",
"Ottweilerstr.",
"Oulustr.",
"Overfeldweg",
"Pappelweg",
"Paracelsusstr.",
"Parkstr.",
"Pastor-Louis-Str.",
"Pastor-Scheibler-Str.",
"Pastorskamp",
"Paul-Klee-Str.",
"Paul-Löbe-Str.",
"Paulstr.",
"Peenestr.",
"Pescher Busch",
"Peschstr.",
"Pestalozzistr.",
"Peter-Grieß-Str.",
"Peter-Joseph-Lenné-Str.",
"Peter-Neuenheuser-Str.",
"Petersbergstr.",
"Peterstr.",
"Pfarrer-Jekel-Str.",
"Pfarrer-Klein-Str.",
"Pfarrer-Röhr-Str.",
"Pfeilshofstr.",
"Philipp-Ott-Str.",
"Piet-Mondrian-Str.",
"Platanenweg",
"Pommernstr.",
"Porschestr.",
"Poststr.",
"Potsdamer Str.",
"Pregelstr.",
"Prießnitzstr.",
"Pützdelle",
"Quarzstr.",
"Quettinger Str.",
"Rat-Deycks-Str.",
"Rathenaustr.",
"Ratherkämp",
"Ratiborer Str.",
"Raushofstr.",
"Regensburger Str.",
"Reinickendorfer Str.",
"Renkgasse",
"Rennbaumplatz",
"Rennbaumstr.",
"Reuschenberger Str.",
"Reusrather Str.",
"Reuterstr.",
"Rheinallee",
"Rheindorfer Str.",
"Rheinstr.",
"Rhein-Wupper-Platz",
"Richard-Wagner-Str.",
"Rilkestr.",
"Ringstr.",
"Robert-Blum-Str.",
"Robert-Koch-Str.",
"Robert-Medenwald-Str.",
"Rolandstr.",
"Romberg",
"Röntgenstr.",
"Roonstr.",
"Ropenstall",
"Ropenstaller Weg",
"Rosenthal",
"Rostocker Str.",
"Rotdornweg",
"Röttgerweg",
"Rückertstr.",
"Rudolf-Breitscheid-Str.",
"Rudolf-Mann-Platz",
"Rudolf-Stracke-Str.",
"Ruhlachplatz",
"Ruhlachstr.",
"Rüttersweg",
"Saalestr.",
"Saarbrücker Str.",
"Saarlauterner Str.",
"Saarstr.",
"Salamanderweg",
"Samlandstr.",
"Sanddornstr.",
"Sandstr.",
"Sauerbruchstr.",
"Schäfershütte",
"Scharnhorststr.",
"Scheffershof",
"Scheidemannstr.",
"Schellingstr.",
"Schenkendorfstr.",
"Schießbergstr.",
"Schillerstr.",
"Schlangenhecke",
"Schlebuscher Heide",
"Schlebuscher Str.",
"Schlebuschrath",
"Schlehdornstr.",
"Schleiermacherstr.",
"Schloßstr.",
"Schmalenbruch",
"Schnepfenflucht",
"Schöffenweg",
"Schöllerstr.",
"Schöne Aussicht",
"Schöneberger Str.",
"Schopenhauerstr.",
"Schubertplatz",
"Schubertstr.",
"Schulberg",
"Schulstr.",
"Schumannstr.",
"Schwalbenweg",
"Schwarzastr.",
"Sebastianusweg",
"Semmelweisstr.",
"Siebelplatz",
"Siemensstr.",
"Solinger Str.",
"Sonderburger Str.",
"Spandauer Str.",
"Speestr.",
"Sperberweg",
"Sperlingsweg",
"Spitzwegstr.",
"Sporrenberger Mühle",
"Spreestr.",
"St. Ingberter Str.",
"Starenweg",
"Stauffenbergstr.",
"Stefan-Zweig-Str.",
"Stegerwaldstr.",
"Steglitzer Str.",
"Steinbücheler Feld",
"Steinbücheler Str.",
"Steinstr.",
"Steinweg",
"Stephan-Lochner-Str.",
"Stephanusstr.",
"Stettiner Str.",
"Stixchesstr.",
"Stöckenstr.",
"Stralsunder Str.",
"Straßburger Str.",
"Stresemannplatz",
"Strombergstr.",
"Stromstr.",
"Stüttekofener Str.",
"Sudestr.",
"Sürderstr.",
"Syltstr.",
"Talstr.",
"Tannenbergstr.",
"Tannenweg",
"Taubenweg",
"Teitscheider Weg",
"Telegrafenstr.",
"Teltower Str.",
"Tempelhofer Str.",
"Theodor-Adorno-Str.",
"Theodor-Fliedner-Str.",
"Theodor-Gierath-Str.",
"Theodor-Haubach-Str.",
"Theodor-Heuss-Ring",
"Theodor-Storm-Str.",
"Theodorstr.",
"Thomas-Dehler-Str.",
"Thomas-Morus-Str.",
"Thomas-von-Aquin-Str.",
"Tönges Feld",
"Torstr.",
"Treptower Str.",
"Treuburger Str.",
"Uhlandstr.",
"Ulmenweg",
"Ulmer Str.",
"Ulrichstr.",
"Ulrich-von-Hassell-Str.",
"Umlag",
"Unstrutstr.",
"Unter dem Schildchen",
"Unterölbach",
"Unterstr.",
"Uppersberg",
"Van\\'t-Hoff-Str.",
"Veit-Stoß-Str.",
"Vereinsstr.",
"Viktor-Meyer-Str.",
"Vincent-van-Gogh-Str.",
"Virchowstr.",
"Voigtslach",
"Volhardstr.",
"Völklinger Str.",
"Von-Brentano-Str.",
"Von-Diergardt-Str.",
"Von-Eichendorff-Str.",
"Von-Ketteler-Str.",
"Von-Knoeringen-Str.",
"Von-Pettenkofer-Str.",
"Von-Siebold-Str.",
"Wacholderweg",
"Waldstr.",
"Walter-Flex-Str.",
"Walter-Hempel-Str.",
"Walter-Hochapfel-Str.",
"Walter-Nernst-Str.",
"Wannseestr.",
"Warnowstr.",
"Warthestr.",
"Weddigenstr.",
"Weichselstr.",
"Weidenstr.",
"Weidfeldstr.",
"Weiherfeld",
"Weiherstr.",
"Weinhäuser Str.",
"Weißdornweg",
"Weißenseestr.",
"Weizkamp",
"Werftstr.",
"Werkstättenstr.",
"Werner-Heisenberg-Str.",
"Werrastr.",
"Weyerweg",
"Widdauener Str.",
"Wiebertshof",
"Wiehbachtal",
"Wiembachallee",
"Wiesdorfer Platz",
"Wiesenstr.",
"Wilhelm-Busch-Str.",
"Wilhelm-Hastrich-Str.",
"Wilhelm-Leuschner-Str.",
"Wilhelm-Liebknecht-Str.",
"Wilhelmsgasse",
"Wilhelmstr.",
"Willi-Baumeister-Str.",
"Willy-Brandt-Ring",
"Winand-Rossi-Str.",
"Windthorststr.",
"Winkelweg",
"Winterberg",
"Wittenbergstr.",
"Wolf-Vostell-Str.",
"Wolkenburgstr.",
"Wupperstr.",
"Wuppertalstr.",
"Wüstenhof",
"Yitzhak-Rabin-Str.",
"Zauberkuhle",
"Zedernweg",
"Zehlendorfer Str.",
"Zehntenweg",
"Zeisigweg",
"Zeppelinstr.",
"Zschopaustr.",
"Zum Claashäuschen",
"Zündhütchenweg",
"Zur Alten Brauerei",
"Zur alten Fabrik"
};
}
}
public override string[] BuildingNumberFormat
{
get
{
return new[] {
"###",
"##",
"#",
"##a",
"##b",
"##c"
};
}
}
public override string[] SecondaryStreetNameFormat
{
get
{
return new[] {
"Apt. ###",
"Zimmer ###",
"# OG"
};
}
}
public override string[] PostCode
{
get
{
return new[] {
"#####"
};
}
}
public override string[] State
{
get
{
return new[] {
"Baden-Württemberg",
"Bayern",
"Berlin",
"Brandenburg",
"Bremen",
"Hamburg",
"Hessen",
"Mecklenburg-Vorpommern",
"Niedersachsen",
"Nordrhein-Westfalen",
"Rheinland-Pfalz",
"Saarland",
"Sachsen",
"Sachsen-Anhalt",
"Schleswig-Holstein",
"Thüringen"
};
}
}
public override string[] StateAbbr
{
get
{
return new[] {
"BW",
"BY",
"BE",
"BB",
"HB",
"HH",
"HE",
"MV",
"NI",
"NW",
"RP",
"SL",
"SN",
"ST",
"SH",
"TH"
};
}
}
public override string[] CityNameFormat
{
get
{
return new[] {
"#{CityPrefix} #{Name.GetFirstName}#{CitySuffix}",
"#{CityPrefix} #{Name.GetFirstName}",
"#{Name.GetFirstName}#{CitySuffix}",
"#{Name.GetLastName}#{CitySuffix}"
};
}
}
public override string[] StreetNameFormat
{
get
{
return new[] {
"#{StreetRoot}"
};
}
}
public override string[] StreetAddressFormat
{
get
{
return new[] { "@{Address.GetStreetName} #{BuildingNumberFormat}" };
}
}
public override bool HasFullStreetAddress
{
get
{
return false;
}
}
#endregion
#region Company
public override string[] CompanySuffix
{
get
{
return new[] {
"GmbH",
"AG",
"Gruppe",
"KG",
"GmbH & Co. KG",
"UG",
"OHG"
};
}
}
public override string[] CompanyNameFormat
{
get
{
return new[] {
"#{Name.GetLastName} #{CompanySuffix}",
"#{Name.GetLastName}-#{Name.GetLastName}",
"#{Name.GetLastName}, #{Name.GetLastName} und #{Name.GetLastName}"
};
}
}
#endregion
#region Internet
public override string[] DomainSuffix
{
get
{
return new[] {
"com",
"info",
"name",
"net",
"org",
"de",
"ch"
};
}
}
#endregion
#region Lorem
public override string[] LoremWord
{
get
{
return new[] {
"alias",
"consequatur",
"aut",
"perferendis",
"sit",
"voluptatem",
"accusantium",
"doloremque",
"aperiam",
"eaque",
"ipsa",
"quae",
"ab",
"illo",
"inventore",
"veritatis",
"et",
"quasi",
"architecto",
"beatae",
"vitae",
"dicta",
"sunt",
"explicabo",
"aspernatur",
"aut",
"odit",
"aut",
"fugit",
"sed",
"quia",
"consequuntur",
"magni",
"dolores",
"eos",
"qui",
"ratione",
"voluptatem",
"sequi",
"nesciunt",
"neque",
"dolorem",
"ipsum",
"quia",
"dolor",
"sit",
"amet",
"consectetur",
"adipisci",
"velit",
"sed",
"quia",
"non",
"numquam",
"eius",
"modi",
"tempora",
"incidunt",
"ut",
"labore",
"et",
"dolore",
"magnam",
"aliquam",
"quaerat",
"voluptatem",
"ut",
"enim",
"ad",
"minima",
"veniam",
"quis",
"nostrum",
"exercitationem",
"ullam",
"corporis",
"nemo",
"enim",
"ipsam",
"voluptatem",
"quia",
"voluptas",
"sit",
"suscipit",
"laboriosam",
"nisi",
"ut",
"aliquid",
"ex",
"ea",
"commodi",
"consequatur",
"quis",
"autem",
"vel",
"eum",
"iure",
"reprehenderit",
"qui",
"in",
"ea",
"voluptate",
"velit",
"esse",
"quam",
"nihil",
"molestiae",
"et",
"iusto",
"odio",
"dignissimos",
"ducimus",
"qui",
"blanditiis",
"praesentium",
"laudantium",
"totam",
"rem",
"voluptatum",
"deleniti",
"atque",
"corrupti",
"quos",
"dolores",
"et",
"quas",
"molestias",
"excepturi",
"sint",
"occaecati",
"cupiditate",
"non",
"provident",
"sed",
"ut",
"perspiciatis",
"unde",
"omnis",
"iste",
"natus",
"error",
"similique",
"sunt",
"in",
"culpa",
"qui",
"officia",
"deserunt",
"mollitia",
"animi",
"id",
"est",
"laborum",
"et",
"dolorum",
"fuga",
"et",
"harum",
"quidem",
"rerum",
"facilis",
"est",
"et",
"expedita",
"distinctio",
"nam",
"libero",
"tempore",
"cum",
"soluta",
"nobis",
"est",
"eligendi",
"optio",
"cumque",
"nihil",
"impedit",
"quo",
"porro",
"quisquam",
"est",
"qui",
"minus",
"id",
"quod",
"maxime",
"placeat",
"facere",
"possimus",
"omnis",
"voluptas",
"assumenda",
"est",
"omnis",
"dolor",
"repellendus",
"temporibus",
"autem",
"quibusdam",
"et",
"aut",
"consequatur",
"vel",
"illum",
"qui",
"dolorem",
"eum",
"fugiat",
"quo",
"voluptas",
"nulla",
"pariatur",
"at",
"vero",
"eos",
"et",
"accusamus",
"officiis",
"debitis",
"aut",
"rerum",
"necessitatibus",
"saepe",
"eveniet",
"ut",
"et",
"voluptates",
"repudiandae",
"sint",
"et",
"molestiae",
"non",
"recusandae",
"itaque",
"earum",
"rerum",
"hic",
"tenetur",
"a",
"sapiente",
"delectus",
"ut",
"aut",
"reiciendis",
"voluptatibus",
"maiores",
"doloribus",
"asperiores",
"repellat"
};
}
}
#endregion
#region Name
public override string[] FirstName
{
get
{
return new[] {
"Aaron",
"Abdul",
"Abdullah",
"Adam",
"Adrian",
"Adriano",
"Ahmad",
"Ahmed",
"Ahmet",
"Alan",
"Albert",
"Alessandro",
"Alessio",
"Alex",
"Alexander",
"Alfred",
"Ali",
"Amar",
"Amir",
"Amon",
"Andre",
"Andreas",
"Andrew",
"Angelo",
"Ansgar",
"Anthony",
"Anton",
"Antonio",
"Arda",
"Arian",
"Armin",
"Arne",
"Arno",
"Arthur",
"Artur",
"Arved",
"Arvid",
"Ayman",
"Baran",
"Baris",
"Bastian",
"Batuhan",
"Bela",
"Ben",
"Benedikt",
"Benjamin",
"Bennet",
"Bennett",
"Benno",
"Bent",
"Berat",
"Berkay",
"Bernd",
"Bilal",
"Bjarne",
"Björn",
"Bo",
"Boris",
"Brandon",
"Brian",
"Bruno",
"Bryan",
"Burak",
"Calvin",
"Can",
"Carl",
"Carlo",
"Carlos",
"Caspar",
"Cedric",
"Cedrik",
"Cem",
"Charlie",
"Chris",
"Christian",
"Christiano",
"Christoph",
"Christopher",
"Claas",
"Clemens",
"Colin",
"Collin",
"Conner",
"Connor",
"Constantin",
"Corvin",
"Curt",
"Damian",
"Damien",
"Daniel",
"Danilo",
"Danny",
"Darian",
"Dario",
"Darius",
"Darren",
"David",
"Davide",
"Davin",
"Dean",
"Deniz",
"Dennis",
"Denny",
"Devin",
"Diego",
"Dion",
"Domenic",
"Domenik",
"Dominic",
"Dominik",
"Dorian",
"Dustin",
"Dylan",
"Ecrin",
"Eddi",
"Eddy",
"Edgar",
"Edwin",
"Efe",
"Ege",
"Elia",
"Eliah",
"Elias",
"Elijah",
"Emanuel",
"Emil",
"Emilian",
"Emilio",
"Emir",
"Emirhan",
"Emre",
"Enes",
"Enno",
"Enrico",
"Eren",
"Eric",
"Erik",
"Etienne",
"Fabian",
"Fabien",
"Fabio",
"Fabrice",
"Falk",
"Felix",
"Ferdinand",
"Fiete",
"Filip",
"Finlay",
"Finley",
"Finn",
"Finnley",
"Florian",
"Francesco",
"Franz",
"Frederic",
"Frederick",
"Frederik",
"Friedrich",
"Fritz",
"Furkan",
"Fynn",
"Gabriel",
"Georg",
"Gerrit",
"Gian",
"Gianluca",
"Gino",
"Giuliano",
"Giuseppe",
"Gregor",
"Gustav",
"Hagen",
"Hamza",
"Hannes",
"Hanno",
"Hans",
"Hasan",
"Hassan",
"Hauke",
"Hendrik",
"Hennes",
"Henning",
"Henri",
"Henrick",
"Henrik",
"Henry",
"Hugo",
"Hussein",
"Ian",
"Ibrahim",
"Ilias",
"Ilja",
"Ilyas",
"Immanuel",
"Ismael",
"Ismail",
"Ivan",
"Iven",
"Jack",
"Jacob",
"Jaden",
"Jakob",
"Jamal",
"James",
"Jamie",
"Jan",
"Janek",
"Janis",
"Janne",
"Jannek",
"Jannes",
"Jannik",
"Jannis",
"Jano",
"Janosch",
"Jared",
"Jari",
"Jarne",
"Jarno",
"Jaron",
"Jason",
"Jasper",
"Jay",
"Jayden",
"Jayson",
"Jean",
"Jens",
"Jeremias",
"Jeremie",
"Jeremy",
"Jermaine",
"Jerome",
"Jesper",
"Jesse",
"Jim",
"Jimmy",
"Joe",
"Joel",
"Joey",
"Johann",
"Johannes",
"John",
"Johnny",
"Jon",
"Jona",
"Jonah",
"Jonas",
"Jonathan",
"Jonte",
"Joost",
"Jordan",
"Joris",
"Joscha",
"Joschua",
"Josef",
"Joseph",
"Josh",
"Joshua",
"Josua",
"Juan",
"Julian",
"Julien",
"Julius",
"Juri",
"Justin",
"Justus",
"Kaan",
"Kai",
"Kalle",
"Karim",
"Karl",
"Karlo",
"Kay",
"Keanu",
"Kenan",
"Kenny",
"Keno",
"Kerem",
"Kerim",
"Kevin",
"Kian",
"Kilian",
"Kim",
"Kimi",
"Kjell",
"Klaas",
"Klemens",
"Konrad",
"Konstantin",
"Koray",
"Korbinian",
"Kurt",
"Lars",
"Lasse",
"Laurence",
"Laurens",
"Laurenz",
"Laurin",
"Lean",
"Leander",
"Leandro",
"Leif",
"Len",
"Lenn",
"Lennard",
"Lennart",
"Lennert",
"Lennie",
"Lennox",
"Lenny",
"Leo",
"Leon",
"Leonard",
"Leonardo",
"Leonhard",
"Leonidas",
"Leopold",
"Leroy",
"Levent",
"Levi",
"Levin",
"Lewin",
"Lewis",
"Liam",
"Lian",
"Lias",
"Lino",
"Linus",
"Lio",
"Lion",
"Lionel",
"Logan",
"Lorenz",
"Lorenzo",
"Loris",
"Louis",
"Luan",
"Luc",
"Luca",
"Lucas",
"Lucian",
"Lucien",
"Ludwig",
"Luis",
"Luiz",
"Luk",
"Luka",
"Lukas",
"Luke",
"Lutz",
"Maddox",
"Mads",
"Magnus",
"Maik",
"Maksim",
"Malik",
"Malte",
"Manuel",
"Marc",
"Marcel",
"Marco",
"Marcus",
"Marek",
"Marian",
"Mario",
"Marius",
"Mark",
"Marko",
"Markus",
"Marlo",
"Marlon",
"Marten",
"Martin",
"Marvin",
"Marwin",
"Mateo",
"Mathis",
"Matis",
"Mats",
"Matteo",
"Mattes",
"Matthias",
"Matthis",
"Matti",
"Mattis",
"Maurice",
"Max",
"Maxim",
"Maximilian",
"Mehmet",
"Meik",
"Melvin",
"Merlin",
"Mert",
"Michael",
"Michel",
"Mick",
"Miguel",
"Mika",
"Mikail",
"Mike",
"Milan",
"Milo",
"Mio",
"Mirac",
"Mirco",
"Mirko",
"Mohamed",
"Mohammad",
"Mohammed",
"Moritz",
"Morten",
"Muhammed",
"Murat",
"Mustafa",
"Nathan",
"Nathanael",
"Nelson",
"Neo",
"Nevio",
"Nick",
"Niclas",
"Nico",
"Nicolai",
"Nicolas",
"Niels",
"Nikita",
"Niklas",
"Niko",
"Nikolai",
"Nikolas",
"Nils",
"Nino",
"Noah",
"Noel",
"Norman",
"Odin",
"Oke",
"Ole",
"Oliver",
"Omar",
"Onur",
"Oscar",
"Oskar",
"Pascal",
"Patrice",
"Patrick",
"Paul",
"Peer",
"Pepe",
"Peter",
"Phil",
"Philip",
"Philipp",
"Pierre",
"Piet",
"Pit",
"Pius",
"Quentin",
"Quirin",
"Rafael",
"Raik",
"Ramon",
"Raphael",
"Rasmus",
"Raul",
"Rayan",
"René",
"Ricardo",
"Riccardo",
"Richard",
"Rick",
"Rico",
"Robert",
"Robin",
"Rocco",
"Roman",
"Romeo",
"Ron",
"Ruben",
"Ryan",
"Said",
"Salih",
"Sam",
"Sami",
"Sammy",
"Samuel",
"Sandro",
"Santino",
"Sascha",
"Sean",
"Sebastian",
"Selim",
"Semih",
"Shawn",
"Silas",
"Simeon",
"Simon",
"Sinan",
"Sky",
"Stefan",
"Steffen",
"Stephan",
"Steve",
"Steven",
"Sven",
"Sönke",
"Sören",
"Taha",
"Tamino",
"Tammo",
"Tarik",
"Tayler",
"Taylor",
"Teo",
"Theo",
"Theodor",
"Thies",
"Thilo",
"Thomas",
"Thorben",
"Thore",
"Thorge",
"Tiago",
"Til",
"Till",
"Tillmann",
"Tim",
"Timm",
"Timo",
"Timon",
"Timothy",
"Tino",
"Titus",
"Tizian",
"Tjark",
"Tobias",
"Tom",
"Tommy",
"Toni",
"Tony",
"Torben",
"Tore",
"Tristan",
"Tyler",
"Tyron",
"Umut",
"Valentin",
"Valentino",
"Veit",
"Victor",
"Viktor",
"Vin",
"Vincent",
"Vito",
"Vitus",
"Wilhelm",
"Willi",
"William",
"Willy",
"Xaver",
"Yannic",
"Yannick",
"Yannik",
"Yannis",
"Yasin",
"Youssef",
"Yunus",
"Yusuf",
"Yven",
"Yves",
"Ömer",
"Aaliyah",
"Abby",
"Abigail",
"Ada",
"Adelina",
"Adriana",
"Aileen",
"Aimee",
"Alana",
"Alea",
"Alena",
"Alessa",
"Alessia",
"Alexa",
"Alexandra",
"Alexia",
"Alexis",
"Aleyna",
"Alia",
"Alica",
"Alice",
"Alicia",
"Alina",
"Alisa",
"Alisha",
"Alissa",
"Aliya",
"Aliyah",
"Allegra",
"Alma",
"Alyssa",
"Amalia",
"Amanda",
"Amelia",
"Amelie",
"Amina",
"Amira",
"Amy",
"Ana",
"Anabel",
"Anastasia",
"Andrea",
"Angela",
"Angelina",
"Angelique",
"Anja",
"Ann",
"Anna",
"Annabel",
"Annabell",
"Annabelle",
"Annalena",
"Anne",
"Anneke",
"Annelie",
"Annemarie",
"Anni",
"Annie",
"Annika",
"Anny",
"Anouk",
"Antonia",
"Arda",
"Ariana",
"Ariane",
"Arwen",
"Ashley",
"Asya",
"Aurelia",
"Aurora",
"Ava",
"Ayleen",
"Aylin",
"Ayse",
"Azra",
"Betty",
"Bianca",
"Bianka",
"Caitlin",
"Cara",
"Carina",
"Carla",
"Carlotta",
"Carmen",
"Carolin",
"Carolina",
"Caroline",
"Cassandra",
"Catharina",
"Catrin",
"Cecile",
"Cecilia",
"Celia",
"Celina",
"Celine",
"Ceyda",
"Ceylin",
"Chantal",
"Charleen",
"Charlotta",
"Charlotte",
"Chayenne",
"Cheyenne",
"Chiara",
"Christin",
"Christina",
"Cindy",
"Claire",
"Clara",
"Clarissa",
"Colleen",
"Collien",
"Cora",
"Corinna",
"Cosima",
"Dana",
"Daniela",
"Daria",
"Darleen",
"Defne",
"Delia",
"Denise",
"Diana",
"Dilara",
"Dina",
"Dorothea",
"Ecrin",
"Eda",
"Eileen",
"Ela",
"Elaine",
"Elanur",
"Elea",
"Elena",
"Eleni",
"Eleonora",
"Eliana",
"Elif",
"Elina",
"Elisa",
"Elisabeth",
"Ella",
"Ellen",
"Elli",
"Elly",
"Elsa",
"Emelie",
"Emely",
"Emilia",
"Emilie",
"Emily",
"Emma",
"Emmely",
"Emmi",
"Emmy",
"Enie",
"Enna",
"Enya",
"Esma",
"Estelle",
"Esther",
"Eva",
"Evelin",
"Evelina",
"Eveline",
"Evelyn",
"Fabienne",
"Fatima",
"Fatma",
"Felicia",
"Felicitas",
"Felina",
"Femke",
"Fenja",
"Fine",
"Finia",
"Finja",
"Finnja",
"Fiona",
"Flora",
"Florentine",
"Francesca",
"Franka",
"Franziska",
"Frederike",
"Freya",
"Frida",
"Frieda",
"Friederike",
"Giada",
"Gina",
"Giulia",
"Giuliana",
"Greta",
"Hailey",
"Hana",
"Hanna",
"Hannah",
"Heidi",
"Helen",
"Helena",
"Helene",
"Helin",
"Henriette",
"Henrike",
"Hermine",
"Ida",
"Ilayda",
"Imke",
"Ina",
"Ines",
"Inga",
"Inka",
"Irem",
"Isa",
"Isabel",
"Isabell",
"Isabella",
"Isabelle",
"Ivonne",
"Jacqueline",
"Jamie",
"Jamila",
"Jana",
"Jane",
"Janin",
"Janina",
"Janine",
"Janna",
"Janne",
"Jara",
"Jasmin",
"Jasmina",
"Jasmine",
"Jella",
"Jenna",
"Jennifer",
"Jenny",
"Jessica",
"Jessy",
"Jette",
"Jil",
"Jill",
"Joana",
"Joanna",
"Joelina",
"Joeline",
"Joelle",
"Johanna",
"Joleen",
"Jolie",
"Jolien",
"Jolin",
"Jolina",
"Joline",
"Jona",
"Jonah",
"Jonna",
"Josefin",
"Josefine",
"Josephin",
"Josephine",
"Josie",
"Josy",
"Joy",
"Joyce",
"Judith",
"Judy",
"Jule",
"Julia",
"Juliana",
"Juliane",
"Julie",
"Julienne",
"Julika",
"Julina",
"Juna",
"Justine",
"Kaja",
"Karina",
"Karla",
"Karlotta",
"Karolina",
"Karoline",
"Kassandra",
"Katarina",
"Katharina",
"Kathrin",
"Katja",
"Katrin",
"Kaya",
"Kayra",
"Kiana",
"Kiara",
"Kim",
"Kimberley",
"Kimberly",
"Kira",
"Klara",
"Korinna",
"Kristin",
"Kyra",
"Laila",
"Lana",
"Lara",
"Larissa",
"Laura",
"Laureen",
"Lavinia",
"Lea",
"Leah",
"Leana",
"Leandra",
"Leann",
"Lee",
"Leila",
"Lena",
"Lene",
"Leni",
"Lenia",
"Lenja",
"Lenya",
"Leona",
"Leoni",
"Leonie",
"Leonora",
"Leticia",
"Letizia",
"Levke",
"Leyla",
"Lia",
"Liah",
"Liana",
"Lili",
"Lilia",
"Lilian",
"Liliana",
"Lilith",
"Lilli",
"Lillian",
"Lilly",
"Lily",
"Lina",
"Linda",
"Lindsay",
"Line",
"Linn",
"Linnea",
"Lisa",
"Lisann",
"Lisanne",
"Liv",
"Livia",
"Liz",
"Lola",
"Loreen",
"Lorena",
"Lotta",
"Lotte",
"Louisa",
"Louise",
"Luana",
"Luca",
"Lucia",
"Lucie",
"Lucienne",
"Lucy",
"Luisa",
"Luise",
"Luka",
"Luna",
"Luzie",
"Lya",
"Lydia",
"Lyn",
"Lynn",
"Madeleine",
"Madita",
"Madleen",
"Madlen",
"Magdalena",
"Maike",
"Mailin",
"Maira",
"Maja",
"Malena",
"Malia",
"Malin",
"Malina",
"Mandy",
"Mara",
"Marah",
"Mareike",
"Maren",
"Maria",
"Mariam",
"Marie",
"Marieke",
"Mariella",
"Marika",
"Marina",
"Marisa",
"Marissa",
"Marit",
"Marla",
"Marleen",
"Marlen",
"Marlena",
"Marlene",
"Marta",
"Martha",
"Mary",
"Maryam",
"Mathilda",
"Mathilde",
"Matilda",
"Maxi",
"Maxima",
"Maxine",
"Maya",
"Mayra",
"Medina",
"Medine",
"Meike",
"Melanie",
"Melek",
"Melike",
"Melina",
"Melinda",
"Melis",
"Melisa",
"Melissa",
"Merle",
"Merve",
"Meryem",
"Mette",
"Mia",
"Michaela",
"Michelle",
"Mieke",
"Mila",
"Milana",
"Milena",
"Milla",
"Mina",
"Mira",
"Miray",
"Miriam",
"Mirja",
"Mona",
"Monique",
"Nadine",
"Nadja",
"Naemi",
"Nancy",
"Naomi",
"Natalia",
"Natalie",
"Nathalie",
"Neele",
"Nela",
"Nele",
"Nelli",
"Nelly",
"Nia",
"Nicole",
"Nika",
"Nike",
"Nikita",
"Nila",
"Nina",
"Nisa",
"Noemi",
"Nora",
"Olivia",
"Patricia",
"Patrizia",
"Paula",
"Paulina",
"Pauline",
"Penelope",
"Philine",
"Phoebe",
"Pia",
"Rahel",
"Rania",
"Rebecca",
"Rebekka",
"Riana",
"Rieke",
"Rike",
"Romina",
"Romy",
"Ronja",
"Rosa",
"Rosalie",
"Ruby",
"Sabrina",
"Sahra",
"Sally",
"Salome",
"Samantha",
"Samia",
"Samira",
"Sandra",
"Sandy",
"Sanja",
"Saphira",
"Sara",
"Sarah",
"Saskia",
"Selin",
"Selina",
"Selma",
"Sena",
"Sidney",
"Sienna",
"Silja",
"Sina",
"Sinja",
"Smilla",
"Sofia",
"Sofie",
"Sonja",
"Sophia",
"Sophie",
"Soraya",
"Stefanie",
"Stella",
"Stephanie",
"Stina",
"Sude",
"Summer",
"Susanne",
"Svea",
"Svenja",
"Sydney",
"Tabea",
"Talea",
"Talia",
"Tamara",
"Tamia",
"Tamina",
"Tanja",
"Tara",
"Tarja",
"Teresa",
"Tessa",
"Thalea",
"Thalia",
"Thea",
"Theresa",
"Tia",
"Tina",
"Tomke",
"Tuana",
"Valentina",
"Valeria",
"Valerie",
"Vanessa",
"Vera",
"Veronika",
"Victoria",
"Viktoria",
"Viola",
"Vivian",
"Vivien",
"Vivienne",
"Wibke",
"Wiebke",
"Xenia",
"Yara",
"Yaren",
"Yasmin",
"Ylvi",
"Ylvie",
"Yvonne",
"Zara",
"Zehra",
"Zeynep",
"Zoe",
"Zoey",
"Zoé"
};
}
}
public override string[] LastName
{
get
{
return new[] {
"Abel",
"Abicht",
"Abraham",
"Abramovic",
"Abt",
"Achilles",
"Achkinadze",
"Ackermann",
"Adam",
"Adams",
"Ade",
"Agostini",
"Ahlke",
"Ahrenberg",
"Ahrens",
"Aigner",
"Albert",
"Albrecht",
"Alexa",
"Alexander",
"Alizadeh",
"Allgeyer",
"Amann",
"Amberg",
"Anding",
"Anggreny",
"Apitz",
"Arendt",
"Arens",
"Arndt",
"Aryee",
"Aschenbroich",
"Assmus",
"Astafei",
"Auer",
"Axmann",
"Baarck",
"Bachmann",
"Badane",
"Bader",
"Baganz",
"Bahl",
"Bak",
"Balcer",
"Balck",
"Balkow",
"Balnuweit",
"Balzer",
"Banse",
"Barr",
"Bartels",
"Barth",
"Barylla",
"Baseda",
"Battke",
"Bauer",
"Bauermeister",
"Baumann",
"Baumeister",
"Bauschinger",
"Bauschke",
"Bayer",
"Beavogui",
"Beck",
"Beckel",
"Becker",
"Beckmann",
"Bedewitz",
"Beele",
"Beer",
"Beggerow",
"Beh",
"Behr",
"Behrenbruch",
"Belz",
"Bender",
"Benecke",
"Benner",
"Benninger",
"Benzing",
"Berends",
"Berger",
"Berner",
"Berning",
"Bertenbreiter",
"Best",
"Bethke",
"Betz",
"Beushausen",
"Beutelspacher",
"Beyer",
"Biba",
"Bichler",
"Bickel",
"Biedermann",
"Bieler",
"Bielert",
"Bienasch",
"Bienias",
"Biesenbach",
"Bigdeli",
"Birkemeyer",
"Bittner",
"Blank",
"Blaschek",
"Blassneck",
"Bloch",
"Blochwitz",
"Blockhaus",
"Blum",
"Blume",
"Bock",
"Bode",
"Bogdashin",
"Bogenrieder",
"Bohge",
"Bolm",
"Borgschulze",
"Bork",
"Bormann",
"Bornscheuer",
"Borrmann",
"Borsch",
"Boruschewski",
"Bos",
"Bosler",
"Bourrouag",
"Bouschen",
"Boxhammer",
"Boyde",
"Bozsik",
"Brand",
"Brandenburg",
"Brandis",
"Brandt",
"Brauer",
"Braun",
"Brehmer",
"Breitenstein",
"Bremer",
"Bremser",
"Brenner",
"Brettschneider",
"Breu",
"Breuer",
"Briesenick",
"Bringmann",
"Brinkmann",
"Brix",
"Broening",
"Brosch",
"Bruckmann",
"Bruder",
"Bruhns",
"Brunner",
"Bruns",
"Bräutigam",
"Brömme",
"Brüggmann",
"Buchholz",
"Buchrucker",
"Buder",
"Bultmann",
"Bunjes",
"Burger",
"Burghagen",
"Burkhard",
"Burkhardt",
"Burmeister",
"Busch",
"Buschbaum",
"Busemann",
"Buss",
"Busse",
"Bussmann",
"Byrd",
"Bäcker",
"Böhm",
"Bönisch",
"Börgeling",
"Börner",
"Böttner",
"Büchele",
"Bühler",
"Büker",
"Büngener",
"Bürger",
"Bürklein",
"Büscher",
"Büttner",
"Camara",
"Carlowitz",
"Carlsohn",
"Caspari",
"Caspers",
"Chapron",
"Christ",
"Cierpinski",
"Clarius",
"Cleem",
"Cleve",
"Co",
"Conrad",
"Cordes",
"Cornelsen",
"Cors",
"Cotthardt",
"Crews",
"Cronjäger",
"Crosskofp",
"Da",
"Dahm",
"Dahmen",
"Daimer",
"Damaske",
"Danneberg",
"Danner",
"Daub",
"Daubner",
"Daudrich",
"Dauer",
"Daum",
"Dauth",
"Dautzenberg",
"De",
"Decker",
"Deckert",
"Deerberg",
"Dehmel",
"Deja",
"Delonge",
"Demut",
"Dengler",
"Denner",
"Denzinger",
"Derr",
"Dertmann",
"Dethloff",
"Deuschle",
"Dieckmann",
"Diedrich",
"Diekmann",
"Dienel",
"Dies",
"Dietrich",
"Dietz",
"Dietzsch",
"Diezel",
"Dilla",
"Dingelstedt",
"Dippl",
"Dittmann",
"Dittmar",
"Dittmer",
"Dix",
"Dobbrunz",
"Dobler",
"Dohring",
"Dolch",
"Dold",
"Dombrowski",
"Donie",
"Doskoczynski",
"Dragu",
"Drechsler",
"Drees",
"Dreher",
"Dreier",
"Dreissigacker",
"Dressler",
"Drews",
"Duma",
"Dutkiewicz",
"Dyett",
"Dylus",
"Dächert",
"Döbel",
"Döring",
"Dörner",
"Dörre",
"Dück",
"Eberhard",
"Eberhardt",
"Ecker",
"Eckhardt",
"Edorh",
"Effler",
"Eggenmueller",
"Ehm",
"Ehmann",
"Ehrig",
"Eich",
"Eichmann",
"Eifert",
"Einert",
"Eisenlauer",
"Ekpo",
"Elbe",
"Eleyth",
"Elss",
"Emert",
"Emmelmann",
"Ender",
"Engel",
"Engelen",
"Engelmann",
"Eplinius",
"Erdmann",
"Erhardt",
"Erlei",
"Erm",
"Ernst",
"Ertl",
"Erwes",
"Esenwein",
"Esser",
"Evers",
"Everts",
"Ewald",
"Fahner",
"Faller",
"Falter",
"Farber",
"Fassbender",
"Faulhaber",
"Fehrig",
"Feld",
"Felke",
"Feller",
"Fenner",
"Fenske",
"Feuerbach",
"Fietz",
"Figl",
"Figura",
"Filipowski",
"Filsinger",
"Fincke",
"Fink",
"Finke",
"Fischer",
"Fitschen",
"Fleischer",
"Fleischmann",
"Floder",
"Florczak",
"Flore",
"Flottmann",
"Forkel",
"Forst",
"Frahmeke",
"Frank",
"Franke",
"Franta",
"Frantz",
"Franz",
"Franzis",
"Franzmann",
"Frauen",
"Frauendorf",
"Freigang",
"Freimann",
"Freimuth",
"Freisen",
"Frenzel",
"Frey",
"Fricke",
"Fried",
"Friedek",
"Friedenberg",
"Friedmann",
"Friedrich",
"Friess",
"Frisch",
"Frohn",
"Frosch",
"Fuchs",
"Fuhlbrügge",
"Fusenig",
"Fust",
"Förster",
"Gaba",
"Gabius",
"Gabler",
"Gadschiew",
"Gakstädter",
"Galander",
"Gamlin",
"Gamper",
"Gangnus",
"Ganzmann",
"Garatva",
"Gast",
"Gastel",
"Gatzka",
"Gauder",
"Gebhardt",
"Geese",
"Gehre",
"Gehrig",
"Gehring",
"Gehrke",
"Geiger",
"Geisler",
"Geissler",
"Gelling",
"Gens",
"Gerbennow",
"Gerdel",
"Gerhardt",
"Gerschler",
"Gerson",
"Gesell",
"Geyer",
"Ghirmai",
"Ghosh",
"Giehl",
"Gierisch",
"Giesa",
"Giesche",
"Gilde",
"Glatting",
"Goebel",
"Goedicke",
"Goldbeck",
"Goldfuss",
"Goldkamp",
"Goldkühle",
"Goller",
"Golling",
"Gollnow",
"Golomski",
"Gombert",
"Gotthardt",
"Gottschalk",
"Gotz",
"Goy",
"Gradzki",
"Graf",
"Grams",
"Grasse",
"Gratzky",
"Grau",
"Greb",
"Green",
"Greger",
"Greithanner",
"Greschner",
"Griem",
"Griese",
"Grimm",
"Gromisch",
"Gross",
"Grosser",
"Grossheim",
"Grosskopf",
"Grothaus",
"Grothkopp",
"Grotke",
"Grube",
"Gruber",
"Grundmann",
"Gruning",
"Gruszecki",
"Gröss",
"Grötzinger",
"Grün",
"Grüner",
"Gummelt",
"Gunkel",
"Gunther",
"Gutjahr",
"Gutowicz",
"Gutschank",
"Göbel",
"Göckeritz",
"Göhler",
"Görlich",
"Görmer",
"Götz",
"Götzelmann",
"Güldemeister",
"Günther",
"Günz",
"Gürbig",
"Haack",
"Haaf",
"Habel",
"Hache",
"Hackbusch",
"Hackelbusch",
"Hadfield",
"Hadwich",
"Haferkamp",
"Hahn",
"Hajek",
"Hallmann",
"Hamann",
"Hanenberger",
"Hannecker",
"Hanniske",
"Hansen",
"Hardy",
"Hargasser",
"Harms",
"Harnapp",
"Harter",
"Harting",
"Hartlieb",
"Hartmann",
"Hartwig",
"Hartz",
"Haschke",
"Hasler",
"Hasse",
"Hassfeld",
"Haug",
"Hauke",
"Haupt",
"Haverney",
"Heberstreit",
"Hechler",
"Hecht",
"Heck",
"Hedermann",
"Hehl",
"Heidelmann",
"Heidler",
"Heinemann",
"Heinig",
"Heinke",
"Heinrich",
"Heinze",
"Heiser",
"Heist",
"Hellmann",
"Helm",
"Helmke",
"Helpling",
"Hengmith",
"Henkel",
"Hennes",
"Henry",
"Hense",
"Hensel",
"Hentel",
"Hentschel",
"Hentschke",
"Hepperle",
"Herberger",
"Herbrand",
"Hering",
"Hermann",
"Hermecke",
"Herms",
"Herold",
"Herrmann",
"Herschmann",
"Hertel",
"Herweg",
"Herwig",
"Herzenberg",
"Hess",
"Hesse",
"Hessek",
"Hessler",
"Hetzler",
"Heuck",
"Heydemüller",
"Hiebl",
"Hildebrand",
"Hildenbrand",
"Hilgendorf",
"Hillard",
"Hiller",
"Hingsen",
"Hingst",
"Hinrichs",
"Hirsch",
"Hirschberg",
"Hirt",
"Hodea",
"Hoffman",
"Hoffmann",
"Hofmann",
"Hohenberger",
"Hohl",
"Hohn",
"Hohnheiser",
"Hold",
"Holdt",
"Holinski",
"Holl",
"Holtfreter",
"Holz",
"Holzdeppe",
"Holzner",
"Hommel",
"Honz",
"Hooss",
"Hoppe",
"Horak",
"Horn",
"Horna",
"Hornung",
"Hort",
"Howard",
"Huber",
"Huckestein",
"Hudak",
"Huebel",
"Hugo",
"Huhn",
"Hujo",
"Huke",
"Huls",
"Humbert",
"Huneke",
"Huth",
"Häber",
"Häfner",
"Höcke",
"Höft",
"Höhne",
"Hönig",
"Hördt",
"Hübenbecker",
"Hübl",
"Hübner",
"Hügel",
"Hüttcher",
"Hütter",
"Ibe",
"Ihly",
"Illing",
"Isak",
"Isekenmeier",
"Itt",
"Jacob",
"Jacobs",
"Jagusch",
"Jahn",
"Jahnke",
"Jakobs",
"Jakubczyk",
"Jambor",
"Jamrozy",
"Jander",
"Janich",
"Janke",
"Jansen",
"Jarets",
"Jaros",
"Jasinski",
"Jasper",
"Jegorov",
"Jellinghaus",
"Jeorga",
"Jerschabek",
"Jess",
"John",
"Jonas",
"Jossa",
"Jucken",
"Jung",
"Jungbluth",
"Jungton",
"Just",
"Jürgens",
"Kaczmarek",
"Kaesmacher",
"Kahl",
"Kahlert",
"Kahles",
"Kahlmeyer",
"Kaiser",
"Kalinowski",
"Kallabis",
"Kallensee",
"Kampf",
"Kampschulte",
"Kappe",
"Kappler",
"Karhoff",
"Karrass",
"Karst",
"Karsten",
"Karus",
"Kass",
"Kasten",
"Kastner",
"Katzinski",
"Kaufmann",
"Kaul",
"Kausemann",
"Kawohl",
"Kazmarek",
"Kedzierski",
"Keil",
"Keiner",
"Keller",
"Kelm",
"Kempe",
"Kemper",
"Kempter",
"Kerl",
"Kern",
"Kesselring",
"Kesselschläger",
"Kette",
"Kettenis",
"Keutel",
"Kick",
"Kiessling",
"Kinadeter",
"Kinzel",
"Kinzy",
"Kirch",
"Kirst",
"Kisabaka",
"Klaas",
"Klabuhn",
"Klapper",
"Klauder",
"Klaus",
"Kleeberg",
"Kleiber",
"Klein",
"Kleinert",
"Kleininger",
"Kleinmann",
"Kleinsteuber",
"Kleiss",
"Klemme",
"Klimczak",
"Klinger",
"Klink",
"Klopsch",
"Klose",
"Kloss",
"Kluge",
"Kluwe",
"Knabe",
"Kneifel",
"Knetsch",
"Knies",
"Knippel",
"Knobel",
"Knoblich",
"Knoll",
"Knorr",
"Knorscheidt",
"Knut",
"Kobs",
"Koch",
"Kochan",
"Kock",
"Koczulla",
"Koderisch",
"Koehl",
"Koehler",
"Koenig",
"Koester",
"Kofferschlager",
"Koha",
"Kohle",
"Kohlmann",
"Kohnle",
"Kohrt",
"Koj",
"Kolb",
"Koleiski",
"Kolokas",
"Komoll",
"Konieczny",
"Konig",
"Konow",
"Konya",
"Koob",
"Kopf",
"Kosenkow",
"Koster",
"Koszewski",
"Koubaa",
"Kovacs",
"Kowalick",
"Kowalinski",
"Kozakiewicz",
"Krabbe",
"Kraft",
"Kral",
"Kramer",
"Krauel",
"Kraus",
"Krause",
"Krauspe",
"Kreb",
"Krebs",
"Kreissig",
"Kresse",
"Kreutz",
"Krieger",
"Krippner",
"Krodinger",
"Krohn",
"Krol",
"Kron",
"Krueger",
"Krug",
"Kruger",
"Krull",
"Kruschinski",
"Krämer",
"Kröckert",
"Kröger",
"Krüger",
"Kubera",
"Kufahl",
"Kuhlee",
"Kuhnen",
"Kulimann",
"Kulma",
"Kumbernuss",
"Kummle",
"Kunz",
"Kupfer",
"Kupprion",
"Kuprion",
"Kurnicki",
"Kurrat",
"Kurschilgen",
"Kuschewitz",
"Kuschmann",
"Kuske",
"Kustermann",
"Kutscherauer",
"Kutzner",
"Kwadwo",
"Kähler",
"Käther",
"Köhler",
"Köhrbrück",
"Köhre",
"Kölotzei",
"König",
"Köpernick",
"Köseoglu",
"Kúhn",
"Kúhnert",
"Kühn",
"Kühnel",
"Kühnemund",
"Kühnert",
"Kühnke",
"Küsters",
"Küter",
"Laack",
"Lack",
"Ladewig",
"Lakomy",
"Lammert",
"Lamos",
"Landmann",
"Lang",
"Lange",
"Langfeld",
"Langhirt",
"Lanig",
"Lauckner",
"Lauinger",
"Laurén",
"Lausecker",
"Laux",
"Laws",
"Lax",
"Leberer",
"Lehmann",
"Lehner",
"Leibold",
"Leide",
"Leimbach",
"Leipold",
"Leist",
"Leiter",
"Leiteritz",
"Leitheim",
"Leiwesmeier",
"Lenfers",
"Lenk",
"Lenz",
"Lenzen",
"Leo",
"Lepthin",
"Lesch",
"Leschnik",
"Letzelter",
"Lewin",
"Lewke",
"Leyckes",
"Lg",
"Lichtenfeld",
"Lichtenhagen",
"Lichtl",
"Liebach",
"Liebe",
"Liebich",
"Liebold",
"Lieder",
"Lienshöft",
"Linden",
"Lindenberg",
"Lindenmayer",
"Lindner",
"Linke",
"Linnenbaum",
"Lippe",
"Lipske",
"Lipus",
"Lischka",
"Lobinger",
"Logsch",
"Lohmann",
"Lohre",
"Lohse",
"Lokar",
"Loogen",
"Lorenz",
"Losch",
"Loska",
"Lott",
"Loy",
"Lubina",
"Ludolf",
"Lufft",
"Lukoschek",
"Lutje",
"Lutz",
"Löser",
"Löwa",
"Lübke",
"Maak",
"Maczey",
"Madetzky",
"Madubuko",
"Mai",
"Maier",
"Maisch",
"Malek",
"Malkus",
"Mallmann",
"Malucha",
"Manns",
"Manz",
"Marahrens",
"Marchewski",
"Margis",
"Markowski",
"Marl",
"Marner",
"Marquart",
"Marschek",
"Martel",
"Marten",
"Martin",
"Marx",
"Marxen",
"Mathes",
"Mathies",
"Mathiszik",
"Matschke",
"Mattern",
"Matthes",
"Matula",
"Mau",
"Maurer",
"Mauroff",
"May",
"Maybach",
"Mayer",
"Mebold",
"Mehl",
"Mehlhorn",
"Mehlorn",
"Meier",
"Meisch",
"Meissner",
"Meloni",
"Melzer",
"Menga",
"Menne",
"Mensah",
"Mensing",
"Merkel",
"Merseburg",
"Mertens",
"Mesloh",
"Metzger",
"Metzner",
"Mewes",
"Meyer",
"Michallek",
"Michel",
"Mielke",
"Mikitenko",
"Milde",
"Minah",
"Mintzlaff",
"Mockenhaupt",
"Moede",
"Moedl",
"Moeller",
"Moguenara",
"Mohr",
"Mohrhard",
"Molitor",
"Moll",
"Moller",
"Molzan",
"Montag",
"Moormann",
"Mordhorst",
"Morgenstern",
"Morhelfer",
"Moritz",
"Moser",
"Motchebon",
"Motzenbbäcker",
"Mrugalla",
"Muckenthaler",
"Mues",
"Muller",
"Mulrain",
"Mächtig",
"Mäder",
"Möcks",
"Mögenburg",
"Möhsner",
"Möldner",
"Möllenbeck",
"Möller",
"Möllinger",
"Mörsch",
"Mühleis",
"Müller",
"Münch",
"Nabein",
"Nabow",
"Nagel",
"Nannen",
"Nastvogel",
"Nau",
"Naubert",
"Naumann",
"Ne",
"Neimke",
"Nerius",
"Neubauer",
"Neubert",
"Neuendorf",
"Neumair",
"Neumann",
"Neupert",
"Neurohr",
"Neuschwander",
"Newton",
"Ney",
"Nicolay",
"Niedermeier",
"Nieklauson",
"Niklaus",
"Nitzsche",
"Noack",
"Nodler",
"Nolte",
"Normann",
"Norris",
"Northoff",
"Nowak",
"Nussbeck",
"Nwachukwu",
"Nytra",
"Nöh",
"Oberem",
"Obergföll",
"Obermaier",
"Ochs",
"Oeser",
"Olbrich",
"Onnen",
"Ophey",
"Oppong",
"Orth",
"Orthmann",
"Oschkenat",
"Osei",
"Osenberg",
"Ostendarp",
"Ostwald",
"Otte",
"Otto",
"Paesler",
"Pajonk",
"Pallentin",
"Panzig",
"Paschke",
"Patzwahl",
"Paukner",
"Peselman",
"Peter",
"Peters",
"Petzold",
"Pfeiffer",
"Pfennig",
"Pfersich",
"Pfingsten",
"Pflieger",
"Pflügner",
"Philipp",
"Pichlmaier",
"Piesker",
"Pietsch",
"Pingpank",
"Pinnock",
"Pippig",
"Pitschugin",
"Plank",
"Plass",
"Platzer",
"Plauk",
"Plautz",
"Pletsch",
"Plotzitzka",
"Poehn",
"Poeschl",
"Pogorzelski",
"Pohl",
"Pohland",
"Pohle",
"Polifka",
"Polizzi",
"Pollmächer",
"Pomp",
"Ponitzsch",
"Porsche",
"Porth",
"Poschmann",
"Poser",
"Pottel",
"Prah",
"Prange",
"Prediger",
"Pressler",
"Preuk",
"Preuss",
"Prey",
"Priemer",
"Proske",
"Pusch",
"Pöche",
"Pöge",
"Raabe",
"Rabenstein",
"Rach",
"Radtke",
"Rahn",
"Ranftl",
"Rangen",
"Ranz",
"Rapp",
"Rath",
"Rau",
"Raubuch",
"Raukuc",
"Rautenkranz",
"Rehwagen",
"Reiber",
"Reichardt",
"Reichel",
"Reichling",
"Reif",
"Reifenrath",
"Reimann",
"Reinberg",
"Reinelt",
"Reinhardt",
"Reinke",
"Reitze",
"Renk",
"Rentz",
"Renz",
"Reppin",
"Restle",
"Restorff",
"Retzke",
"Reuber",
"Reumann",
"Reus",
"Reuss",
"Reusse",
"Rheder",
"Rhoden",
"Richards",
"Richter",
"Riedel",
"Riediger",
"Rieger",
"Riekmann",
"Riepl",
"Riermeier",
"Riester",
"Riethmüller",
"Rietmüller",
"Rietscher",
"Ringel",
"Ringer",
"Rink",
"Ripken",
"Ritosek",
"Ritschel",
"Ritter",
"Rittweg",
"Ritz",
"Roba",
"Rockmeier",
"Rodehau",
"Rodowski",
"Roecker",
"Roggatz",
"Rohländer",
"Rohrer",
"Rokossa",
"Roleder",
"Roloff",
"Roos",
"Rosbach",
"Roschinsky",
"Rose",
"Rosenauer",
"Rosenbauer",
"Rosenthal",
"Rosksch",
"Rossberg",
"Rossler",
"Roth",
"Rother",
"Ruch",
"Ruckdeschel",
"Rumpf",
"Rupprecht",
"Ruth",
"Ryjikh",
"Ryzih",
"Rädler",
"Räntsch",
"Rödiger",
"Röse",
"Röttger",
"Rücker",
"Rüdiger",
"Rüter",
"Sachse",
"Sack",
"Saflanis",
"Sagafe",
"Sagonas",
"Sahner",
"Saile",
"Sailer",
"Salow",
"Salzer",
"Salzmann",
"Sammert",
"Sander",
"Sarvari",
"Sattelmaier",
"Sauer",
"Sauerland",
"Saumweber",
"Savoia",
"Scc",
"Schacht",
"Schaefer",
"Schaffarzik",
"Schahbasian",
"Scharf",
"Schedler",
"Scheer",
"Schelk",
"Schellenbeck",
"Schembera",
"Schenk",
"Scherbarth",
"Scherer",
"Schersing",
"Scherz",
"Scheurer",
"Scheuring",
"Scheytt",
"Schielke",
"Schieskow",
"Schildhauer",
"Schilling",
"Schima",
"Schimmer",
"Schindzielorz",
"Schirmer",
"Schirrmeister",
"Schlachter",
"Schlangen",
"Schlawitz",
"Schlechtweg",
"Schley",
"Schlicht",
"Schlitzer",
"Schmalzle",
"Schmid",
"Schmidt",
"Schmidtchen",
"Schmitt",
"Schmitz",
"Schmuhl",
"Schneider",
"Schnelting",
"Schnieder",
"Schniedermeier",
"Schnürer",
"Schoberg",
"Scholz",
"Schonberg",
"Schondelmaier",
"Schorr",
"Schott",
"Schottmann",
"Schouren",
"Schrader",
"Schramm",
"Schreck",
"Schreiber",
"Schreiner",
"Schreiter",
"Schroder",
"Schröder",
"Schuermann",
"Schuff",
"Schuhaj",
"Schuldt",
"Schult",
"Schulte",
"Schultz",
"Schultze",
"Schulz",
"Schulze",
"Schumacher",
"Schumann",
"Schupp",
"Schuri",
"Schuster",
"Schwab",
"Schwalm",
"Schwanbeck",
"Schwandke",
"Schwanitz",
"Schwarthoff",
"Schwartz",
"Schwarz",
"Schwarzer",
"Schwarzkopf",
"Schwarzmeier",
"Schwatlo",
"Schweisfurth",
"Schwennen",
"Schwerdtner",
"Schwidde",
"Schwirkschlies",
"Schwuchow",
"Schäfer",
"Schäffel",
"Schäffer",
"Schäning",
"Schöckel",
"Schönball",
"Schönbeck",
"Schönberg",
"Schönebeck",
"Schönenberger",
"Schönfeld",
"Schönherr",
"Schönlebe",
"Schötz",
"Schüler",
"Schüppel",
"Schütz",
"Schütze",
"Seeger",
"Seelig",
"Sehls",
"Seibold",
"Seidel",
"Seiders",
"Seigel",
"Seiler",
"Seitz",
"Semisch",
"Senkel",
"Sewald",
"Siebel",
"Siebert",
"Siegling",
"Sielemann",
"Siemon",
"Siener",
"Sievers",
"Siewert",
"Sihler",
"Sillah",
"Simon",
"Sinnhuber",
"Sischka",
"Skibicki",
"Sladek",
"Slotta",
"Smieja",
"Soboll",
"Sokolowski",
"Soller",
"Sollner",
"Sommer",
"Somssich",
"Sonn",
"Sonnabend",
"Spahn",
"Spank",
"Spelmeyer",
"Spiegelburg",
"Spielvogel",
"Spinner",
"Spitzmüller",
"Splinter",
"Sporrer",
"Sprenger",
"Spöttel",
"Stahl",
"Stang",
"Stanger",
"Stauss",
"Steding",
"Steffen",
"Steffny",
"Steidl",
"Steigauf",
"Stein",
"Steinecke",
"Steinert",
"Steinkamp",
"Steinmetz",
"Stelkens",
"Stengel",
"Stengl",
"Stenzel",
"Stepanov",
"Stephan",
"Stern",
"Steuk",
"Stief",
"Stifel",
"Stoll",
"Stolle",
"Stolz",
"Storl",
"Storp",
"Stoutjesdijk",
"Stratmann",
"Straub",
"Strausa",
"Streck",
"Streese",
"Strege",
"Streit",
"Streller",
"Strieder",
"Striezel",
"Strogies",
"Strohschank",
"Strunz",
"Strutz",
"Stube",
"Stöckert",
"Stöppler",
"Stöwer",
"Stürmer",
"Suffa",
"Sujew",
"Sussmann",
"Suthe",
"Sutschet",
"Swillims",
"Szendrei",
"Sören",
"Sürth",
"Tafelmeier",
"Tang",
"Tasche",
"Taufratshofer",
"Tegethof",
"Teichmann",
"Tepper",
"Terheiden",
"Terlecki",
"Teufel",
"Theele",
"Thieke",
"Thimm",
"Thiomas",
"Thomas",
"Thriene",
"Thränhardt",
"Thust",
"Thyssen",
"Thöne",
"Tidow",
"Tiedtke",
"Tietze",
"Tilgner",
"Tillack",
"Timmermann",
"Tischler",
"Tischmann",
"Tittman",
"Tivontschik",
"Tonat",
"Tonn",
"Trampeli",
"Trauth",
"Trautmann",
"Travan",
"Treff",
"Tremmel",
"Tress",
"Tsamonikian",
"Tschiers",
"Tschirch",
"Tuch",
"Tucholke",
"Tudow",
"Tuschmo",
"Tächl",
"Többen",
"Töpfer",
"Uhlemann",
"Uhlig",
"Uhrig",
"Uibel",
"Uliczka",
"Ullmann",
"Ullrich",
"Umbach",
"Umlauft",
"Umminger",
"Unger",
"Unterpaintner",
"Urban",
"Urbaniak",
"Urbansky",
"Urhig",
"Vahlensieck",
"Van",
"Vangermain",
"Vater",
"Venghaus",
"Verniest",
"Verzi",
"Vey",
"Viellehner",
"Vieweg",
"Voelkel",
"Vogel",
"Vogelgsang",
"Vogt",
"Voigt",
"Vokuhl",
"Volk",
"Volker",
"Volkmann",
"Von",
"Vona",
"Vontein",
"Wachenbrunner",
"Wachtel",
"Wagner",
"Waibel",
"Wakan",
"Waldmann",
"Wallner",
"Wallstab",
"Walter",
"Walther",
"Walton",
"Walz",
"Wanner",
"Wartenberg",
"Waschbüsch",
"Wassilew",
"Wassiluk",
"Weber",
"Wehrsen",
"Weidlich",
"Weidner",
"Weigel",
"Weight",
"Weiler",
"Weimer",
"Weis",
"Weiss",
"Weller",
"Welsch",
"Welz",
"Welzel",
"Weniger",
"Wenk",
"Werle",
"Werner",
"Werrmann",
"Wessel",
"Wessinghage",
"Weyel",
"Wezel",
"Wichmann",
"Wickert",
"Wiebe",
"Wiechmann",
"Wiegelmann",
"Wierig",
"Wiese",
"Wieser",
"Wilhelm",
"Wilky",
"Will",
"Willwacher",
"Wilts",
"Wimmer",
"Winkelmann",
"Winkler",
"Winter",
"Wischek",
"Wischer",
"Wissing",
"Wittich",
"Wittl",
"Wolf",
"Wolfarth",
"Wolff",
"Wollenberg",
"Wollmann",
"Woytkowska",
"Wujak",
"Wurm",
"Wyludda",
"Wölpert",
"Wöschler",
"Wühn",
"Wünsche",
"Zach",
"Zaczkiewicz",
"Zahn",
"Zaituc",
"Zandt",
"Zanner",
"Zapletal",
"Zauber",
"Zeidler",
"Zekl",
"Zender",
"Zeuch",
"Zeyen",
"Zeyhle",
"Ziegler",
"Zimanyi",
"Zimmer",
"Zimmermann",
"Zinser",
"Zintl",
"Zipp",
"Zipse",
"Zschunke",
"Zuber",
"Zwiener",
"Zümsande",
"Östringer",
"Überacker"
};
}
}
public override string[] NamePrefix
{
get
{
return new[] {
"Hr.",
"Fr.",
"Dr.",
"Prof. Dr."
};
}
}
public string[] NobilityTitlePrefix
{
get
{
return new[] {
"zu",
"von",
"vom",
"von der"
};
}
}
public override string[] NameFormat
{
get
{
return new[] {
"{0.8}{FirstName} {LastName}",
"#{NamePrefix} @{Name.GetFirstName} @{Name.GetLastName}",
"@{Name.GetFirstName} #{NobilityTitlePrefix} @{Name.GetLastName}"
};
}
}
public override string[] PhoneNumberFormat
{
get
{
return new[] {
"(0###) #########",
"(0####) #######",
"+49-###-#######",
"+49-####-########"
};
}
}
#endregion
}
}
| mit |
alawatthe/MathLib | src/Permutation/init.ts | 610 | /*es6
import {sign} from 'Functn';
import {Matrix} from 'Matrix';
es6*/
/// import Functn, Matrix
/**
* The permutation class for MathLib
*
* @class
* @this {Permutation}
*/
export class Permutation {
type = 'permutation';
length: number;
cycle: any[];
constructor (p) {
var cycle, permutation;
if (Array.isArray(p[0])) {
cycle = p;
permutation = Permutation.cycleToList(cycle);
}
else {
permutation = p;
cycle = Permutation.listToCycle(permutation);
}
permutation.forEach((x, i) => {
this[i] = x;
});
this.length = permutation.length;
this.cycle = cycle;
}
| mit |
LivelyKernel/lively4-core | src/external/event-drops/interval.js | 1025 | import uniqBy from 'src/external/lodash/lodash.js';
export default (config, xScale) => selection => {
const {
interval: {
color,
width,
id,
startDate,
endDate,
onClick,
onMouseOver,
onMouseOut,
},
} = config;
const intervals = selection
.selectAll('.interval')
.data(d => d.intervalData);
//Todo: filter overlapping?
intervals
.enter()
.append('line')
.classed('interval', true)
.on('click', onClick)
.on('mouseover', onMouseOver)
.on('mouseout', onMouseOut)
.merge(intervals)
.attr('id', id)
.attr('x1', d => Math.max(0, xScale(startDate(d))))
.attr('x2', d => xScale(endDate(d)))
.attr('stroke', color)
.attr('stroke-width', width);
intervals
.exit()
.on('click', null)
.on('mouseover', null)
.on('mouseout', null)
.remove();
};
| mit |
meziantou/Meziantou.Framework | common/Range.cs | 11546 | #pragma warning disable
#if NETSTANDARD2_0 || NET45 || NET461|| NET472 || NETCOREAPP2_0 || NETCOREAPP2_1
// https://github.com/dotnet/corefx/blob/1597b894a2e9cac668ce6e484506eca778a85197/src/Common/src/CoreLib/System/Index.cs
// https://github.com/dotnet/corefx/blob/1597b894a2e9cac668ce6e484506eca778a85197/src/Common/src/CoreLib/System/Range.cs
using System.Runtime.CompilerServices;
namespace System
{
/// <summary>Represent a type can be used to index a collection either from the start or the end.</summary>
/// <remarks>
/// Index is used by the C# compiler to support the new index syntax
/// <code>
/// int[] someArray = new int[5] { 1, 2, 3, 4, 5 } ;
/// int lastElement = someArray[^1]; // lastElement = 5
/// </code>
/// </remarks>
[Runtime.InteropServices.StructLayout(Runtime.InteropServices.LayoutKind.Auto)]
internal readonly struct Index : IEquatable<Index>
{
private readonly int _value;
/// <summary>Construct an Index using a value and indicating if the index is from the start or from the end.</summary>
/// <param name="value">The index value. it has to be zero or positive number.</param>
/// <param name="fromEnd">Indicating if the index is from the start or from the end.</param>
/// <remarks>
/// If the Index constructed from the end, index value 1 means pointing at the last element and index value 0 means pointing at beyond last element.
/// </remarks>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public Index(int value, bool fromEnd = false)
{
if (value < 0)
{
throw new ArgumentOutOfRangeException(nameof(value), "value must be non-negative");
}
if (fromEnd)
_value = ~value;
else
_value = value;
}
// The following private constructors mainly created for perf reason to avoid the checks
private Index(int value)
{
_value = value;
}
/// <summary>Create an Index pointing at first element.</summary>
public static Index Start => new Index(0);
/// <summary>Create an Index pointing at beyond last element.</summary>
public static Index End => new Index(~0);
/// <summary>Create an Index from the start at the position indicated by the value.</summary>
/// <param name="value">The index value from the start.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Index FromStart(int value)
{
if (value < 0)
{
throw new ArgumentOutOfRangeException(nameof(value), "value must be non-negative");
}
return new Index(value);
}
/// <summary>Create an Index from the end at the position indicated by the value.</summary>
/// <param name="value">The index value from the end.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Index FromEnd(int value)
{
if (value < 0)
{
throw new ArgumentOutOfRangeException(nameof(value), "value must be non-negative");
}
return new Index(~value);
}
/// <summary>Returns the index value.</summary>
public int Value
{
get
{
if (_value < 0)
{
return ~_value;
}
else
{
return _value;
}
}
}
/// <summary>Indicates whether the index is from the start or the end.</summary>
public bool IsFromEnd => _value < 0;
/// <summary>Calculate the offset from the start using the giving collection length.</summary>
/// <param name="length">The length of the collection that the Index will be used with. length has to be a positive value</param>
/// <remarks>
/// For performance reason, we don't validate the input length parameter and the returned offset value against negative values.
/// we don't validate either the returned offset is greater than the input length.
/// It is expected Index will be used with collections which always have non negative length/count. If the returned offset is negative and
/// then used to index a collection will get out of range exception which will be same affect as the validation.
/// </remarks>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public int GetOffset(int length)
{
var offset = _value;
if (IsFromEnd)
{
// offset = length - (~value)
// offset = length + (~(~value) + 1)
// offset = length + value + 1
offset += length + 1;
}
return offset;
}
/// <summary>Indicates whether the current Index object is equal to another object of the same type.</summary>
/// <param name="value">An object to compare with this object</param>
public override bool Equals(object? value) => value is Index && _value == ((Index)value)._value;
/// <summary>Indicates whether the current Index object is equal to another Index object.</summary>
/// <param name="other">An object to compare with this object</param>
public bool Equals(Index other) => _value == other._value;
/// <summary>Returns the hash code for this instance.</summary>
public override int GetHashCode() => _value;
/// <summary>Converts integer number to an Index.</summary>
public static implicit operator Index(int value) => FromStart(value);
/// <summary>Converts the value of the current Index object to its equivalent string representation.</summary>
public override string ToString()
{
if (IsFromEnd)
return "^" + ((uint)Value).ToString();
return ((uint)Value).ToString();
}
}
/// <summary>Represent a range has start and end indexes.</summary>
/// <remarks>
/// Range is used by the C# compiler to support the range syntax.
/// <code>
/// int[] someArray = new int[5] { 1, 2, 3, 4, 5 };
/// int[] subArray1 = someArray[0..2]; // { 1, 2 }
/// int[] subArray2 = someArray[1..^0]; // { 2, 3, 4, 5 }
/// </code>
/// </remarks>
[Runtime.InteropServices.StructLayout(Runtime.InteropServices.LayoutKind.Auto)]
internal readonly struct Range : IEquatable<Range>
{
/// <summary>Represent the inclusive start index of the Range.</summary>
public Index Start { get; }
/// <summary>Represent the exclusive end index of the Range.</summary>
public Index End { get; }
/// <summary>Construct a Range object using the start and end indexes.</summary>
/// <param name="start">Represent the inclusive start index of the range.</param>
/// <param name="end">Represent the exclusive end index of the range.</param>
public Range(Index start, Index end)
{
Start = start;
End = end;
}
/// <summary>Indicates whether the current Range object is equal to another object of the same type.</summary>
/// <param name="value">An object to compare with this object</param>
public override bool Equals(object? value) =>
value is Range r &&
r.Start.Equals(Start) &&
r.End.Equals(End);
/// <summary>Indicates whether the current Range object is equal to another Range object.</summary>
/// <param name="other">An object to compare with this object</param>
public bool Equals(Range other) => other.Start.Equals(Start) && other.End.Equals(End);
/// <summary>Returns the hash code for this instance.</summary>
public override int GetHashCode()
{
return Start.GetHashCode() * 31 + End.GetHashCode();
}
/// <summary>Converts the value of the current Range object to its equivalent string representation.</summary>
public override string ToString()
{
return Start + ".." + End;
}
/// <summary>Create a Range object starting from start index to the end of the collection.</summary>
public static Range StartAt(Index start) => new Range(start, Index.End);
/// <summary>Create a Range object starting from first element in the collection to the end Index.</summary>
public static Range EndAt(Index end) => new Range(Index.Start, end);
/// <summary>Create a Range object starting from first element to the end.</summary>
public static Range All => new Range(Index.Start, Index.End);
/// <summary>Calculate the start offset and length of range object using a collection length.</summary>
/// <param name="length">The length of the collection that the range will be used with. length has to be a positive value.</param>
/// <remarks>
/// For performance reason, we don't validate the input length parameter against negative values.
/// It is expected Range will be used with collections which always have non negative length/count.
/// We validate the range is inside the length scope though.
/// </remarks>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public (int Offset, int Length) GetOffsetAndLength(int length)
{
int start;
var startIndex = Start;
if (startIndex.IsFromEnd)
start = length - startIndex.Value;
else
start = startIndex.Value;
int end;
var endIndex = End;
if (endIndex.IsFromEnd)
end = length - endIndex.Value;
else
end = endIndex.Value;
if ((uint)end > (uint)length || (uint)start > (uint)end)
{
throw new ArgumentOutOfRangeException(nameof(length));
}
return (start, end - start);
}
}
}
namespace System.Runtime.CompilerServices
{
internal static class RuntimeHelpers
{
/// <summary>
/// Slices the specified array using the specified range.
/// </summary>
public static T[] GetSubArray<T>(T[] array, Range range)
{
if (array == null)
{
throw new ArgumentNullException(nameof(array));
}
(int offset, int length) = range.GetOffsetAndLength(array.Length);
if (default(T)! != null || typeof(T[]) == array.GetType())
{
// We know the type of the array to be exactly T[].
if (length == 0)
{
return Array.Empty<T>();
}
var dest = new T[length];
Array.Copy(array, offset, dest, 0, length);
return dest;
}
else
{
// The array is actually a U[] where U:T.
var dest = (T[])Array.CreateInstance(array.GetType().GetElementType(), length);
Array.Copy(array, offset, dest, 0, length);
return dest;
}
}
}
}
#elif NETSTANDARD2_1 || NETCOREAPP3_0 || NETCOREAPP3_1 || NET5_0 || NET6_0
#else
#error Platform not supported
#endif
| mit |
sudent/symfony | src/Symfony/Component/Routing/Tests/RouteCollectionTest.php | 13079 | <?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\Routing\Tests;
use Symfony\Component\Routing\RouteCollection;
use Symfony\Component\Routing\Route;
use Symfony\Component\Config\Resource\FileResource;
class RouteCollectionTest extends \PHPUnit_Framework_TestCase
{
public function testRoute()
{
$collection = new RouteCollection();
$route = new Route('/foo');
$collection->add('foo', $route);
$this->assertEquals(array('foo' => $route), $collection->all(), '->add() adds a route');
$this->assertEquals($route, $collection->get('foo'), '->get() returns a route by name');
$this->assertNull($collection->get('bar'), '->get() returns null if a route does not exist');
}
/**
* @expectedException \InvalidArgumentException
*/
public function testAddInvalidRoute()
{
$collection = new RouteCollection();
$route = new Route('/foo');
$collection->add('f o o', $route);
}
public function testOverridenRoute()
{
$collection = new RouteCollection();
$collection->add('foo', new Route('/foo'));
$collection->add('foo', new Route('/foo1'));
$this->assertEquals('/foo1', $collection->get('foo')->getPattern());
}
public function testDeepOverridenRoute()
{
$collection = new RouteCollection();
$collection->add('foo', new Route('/foo'));
$collection1 = new RouteCollection();
$collection1->add('foo', new Route('/foo1'));
$collection2 = new RouteCollection();
$collection2->add('foo', new Route('/foo2'));
$collection1->addCollection($collection2);
$collection->addCollection($collection1);
$this->assertEquals('/foo2', $collection1->get('foo')->getPattern());
$this->assertEquals('/foo2', $collection->get('foo')->getPattern());
}
public function testIteratorWithOverridenRoutes()
{
$collection = new RouteCollection();
$collection->add('foo', new Route('/foo'));
$collection1 = new RouteCollection();
$collection->addCollection($collection1);
$collection1->add('foo', new Route('/foo1'));
$this->assertEquals('/foo1', $this->getFirstNamedRoute($collection, 'foo')->getPattern());
}
protected function getFirstNamedRoute(RouteCollection $routeCollection, $name)
{
foreach ($routeCollection as $key => $route) {
if ($route instanceof RouteCollection) {
return $this->getFirstNamedRoute($route, $name);
}
if ($name === $key) {
return $route;
}
}
}
public function testAddCollection()
{
if (!class_exists('Symfony\Component\Config\Resource\FileResource')) {
$this->markTestSkipped('The "Config" component is not available');
}
$collection = new RouteCollection();
$collection->add('foo', $foo = new Route('/foo'));
$collection1 = new RouteCollection();
$collection1->add('foo', $foo1 = new Route('/foo1'));
$collection1->add('bar', $bar1 = new Route('/bar1'));
$collection->addCollection($collection1);
$this->assertEquals(array('foo' => $foo1, 'bar' => $bar1), $collection->all(), '->addCollection() adds routes from another collection');
$collection = new RouteCollection();
$collection->add('foo', $foo = new Route('/foo'));
$collection1 = new RouteCollection();
$collection1->add('foo', $foo1 = new Route('/foo1'));
$collection->addCollection($collection1, '/{foo}', array('foo' => 'foo'), array('foo' => '\d+'), array('foo' => 'bar'));
$this->assertEquals('/{foo}/foo1', $collection->get('foo')->getPattern(), '->addCollection() can add a prefix to all merged routes');
$this->assertEquals(array('foo' => 'foo'), $collection->get('foo')->getDefaults(), '->addCollection() can add a prefix to all merged routes');
$this->assertEquals(array('foo' => '\d+'), $collection->get('foo')->getRequirements(), '->addCollection() can add a prefix to all merged routes');
$this->assertEquals(
array('foo' => 'bar', 'compiler_class' => 'Symfony\\Component\\Routing\\RouteCompiler'),
$collection->get('foo')->getOptions(), '->addCollection() can add an option to all merged routes'
);
$collection = new RouteCollection();
$collection->addResource($foo = new FileResource(__DIR__.'/Fixtures/foo.xml'));
$collection1 = new RouteCollection();
$collection1->addResource($foo1 = new FileResource(__DIR__.'/Fixtures/foo1.xml'));
$collection->addCollection($collection1);
$this->assertEquals(array($foo, $foo1), $collection->getResources(), '->addCollection() merges resources');
}
public function testAddPrefix()
{
$collection = new RouteCollection();
$collection->add('foo', $foo = new Route('/foo'));
$collection->add('bar', $bar = new Route('/bar'));
$collection->addPrefix('/{admin}', array('admin' => 'admin'), array('admin' => '\d+'), array('foo' => 'bar'));
$this->assertEquals('/{admin}/foo', $collection->get('foo')->getPattern(), '->addPrefix() adds a prefix to all routes');
$this->assertEquals('/{admin}/bar', $collection->get('bar')->getPattern(), '->addPrefix() adds a prefix to all routes');
$this->assertEquals(array('admin' => 'admin'), $collection->get('foo')->getDefaults(), '->addPrefix() adds a prefix to all routes');
$this->assertEquals(array('admin' => 'admin'), $collection->get('bar')->getDefaults(), '->addPrefix() adds a prefix to all routes');
$this->assertEquals(array('admin' => '\d+'), $collection->get('foo')->getRequirements(), '->addPrefix() adds a prefix to all routes');
$this->assertEquals(array('admin' => '\d+'), $collection->get('bar')->getRequirements(), '->addPrefix() adds a prefix to all routes');
$this->assertEquals(
array('foo' => 'bar', 'compiler_class' => 'Symfony\\Component\\Routing\\RouteCompiler'),
$collection->get('foo')->getOptions(), '->addPrefix() adds an option to all routes'
);
$this->assertEquals(
array('foo' => 'bar', 'compiler_class' => 'Symfony\\Component\\Routing\\RouteCompiler'),
$collection->get('bar')->getOptions(), '->addPrefix() adds an option to all routes'
);
$collection->addPrefix('0');
$this->assertEquals('/0/{admin}', $collection->getPrefix(), '->addPrefix() ensures a prefix must start with a slash and must not end with a slash');
}
public function testAddPrefixOverridesDefaultsAndRequirements()
{
$collection = new RouteCollection();
$collection->add('foo', $foo = new Route('/foo'));
$collection->add('bar', $bar = new Route('/bar', array(), array('_scheme' => 'http')));
$collection->addPrefix('/admin', array(), array('_scheme' => 'https'));
$this->assertEquals('https', $collection->get('foo')->getRequirement('_scheme'), '->addPrefix() overrides existing requirements');
$this->assertEquals('https', $collection->get('bar')->getRequirement('_scheme'), '->addPrefix() overrides existing requirements');
}
public function testAddCollectionOverridesDefaultsAndRequirements()
{
$imported = new RouteCollection();
$imported->add('foo', $foo = new Route('/foo'));
$imported->add('bar', $bar = new Route('/bar', array(), array('_scheme' => 'http')));
$collection = new RouteCollection();
$collection->addCollection($imported, null, array(), array('_scheme' => 'https'));
$this->assertEquals('https', $collection->get('foo')->getRequirement('_scheme'), '->addCollection() overrides existing requirements');
$this->assertEquals('https', $collection->get('bar')->getRequirement('_scheme'), '->addCollection() overrides existing requirements');
}
public function testResource()
{
if (!class_exists('Symfony\Component\Config\Resource\FileResource')) {
$this->markTestSkipped('The "Config" component is not available');
}
$collection = new RouteCollection();
$collection->addResource($foo = new FileResource(__DIR__.'/Fixtures/foo.xml'));
$this->assertEquals(array($foo), $collection->getResources(), '->addResources() adds a resource');
}
public function testUniqueRouteWithGivenName()
{
$collection1 = new RouteCollection();
$collection1->add('foo', new Route('/old'));
$collection2 = new RouteCollection();
$collection3 = new RouteCollection();
$collection3->add('foo', $new = new Route('/new'));
$collection1->addCollection($collection2);
$collection2->addCollection($collection3);
$collection1->add('stay', new Route('/stay'));
$iterator = $collection1->getIterator();
$this->assertSame($new, $collection1->get('foo'), '->get() returns new route that overrode previous one');
// size of 2 because collection1 contains collection2 and /stay but not /old anymore
$this->assertCount(2, $iterator, '->addCollection() removes previous routes when adding new routes with the same name');
$this->assertInstanceOf('Symfony\Component\Routing\RouteCollection', $iterator->current(), '->getIterator returns both Routes and RouteCollections');
$iterator->next();
$this->assertInstanceOf('Symfony\Component\Routing\Route', $iterator->current(), '->getIterator returns both Routes and RouteCollections');
}
public function testGet()
{
$collection1 = new RouteCollection();
$collection1->add('a', $a = new Route('/a'));
$collection2 = new RouteCollection();
$collection2->add('b', $b = new Route('/b'));
$collection1->addCollection($collection2);
$this->assertSame($b, $collection1->get('b'), '->get() returns correct route in child collection');
$this->assertNull($collection2->get('a'), '->get() does not return the route defined in parent collection');
$this->assertNull($collection1->get('non-existent'), '->get() returns null when route does not exist');
$this->assertNull($collection1->get(0), '->get() does not disclose internal child RouteCollection');
}
/**
* @expectedException \InvalidArgumentException
*/
public function testCannotSelfJoinCollection()
{
$collection = new RouteCollection();
$collection->addCollection($collection);
}
/**
* @expectedException \InvalidArgumentException
*/
public function testCannotAddExistingCollectionToTree()
{
$collection1 = new RouteCollection();
$collection2 = new RouteCollection();
$collection3 = new RouteCollection();
$collection1->addCollection($collection2);
$collection1->addCollection($collection3);
$collection2->addCollection($collection3);
}
public function testPatternDoesNotChangeWhenDefinitionOrderChanges()
{
$collection1 = new RouteCollection();
$collection1->add('a', new Route('/a...'));
$collection2 = new RouteCollection();
$collection2->add('b', new Route('/b...'));
$collection3 = new RouteCollection();
$collection3->add('c', new Route('/c...'));
$rootCollection_A = new RouteCollection();
$collection2->addCollection($collection3, '/c');
$collection1->addCollection($collection2, '/b');
$rootCollection_A->addCollection($collection1, '/a');
// above should mean the same as below
$collection1 = new RouteCollection();
$collection1->add('a', new Route('/a...'));
$collection2 = new RouteCollection();
$collection2->add('b', new Route('/b...'));
$collection3 = new RouteCollection();
$collection3->add('c', new Route('/c...'));
$rootCollection_B = new RouteCollection();
$collection1->addCollection($collection2, '/b');
$collection2->addCollection($collection3, '/c');
$rootCollection_B->addCollection($collection1, '/a');
// test it now
$this->assertEquals($rootCollection_A, $rootCollection_B);
}
public function testSetHostnamePattern()
{
$collection = new RouteCollection();
$routea = new Route('/a');
$routeb = new Route('/b', array(), array(), array(), '{locale}.example.net');
$collection->add('a', $routea);
$collection->add('b', $routeb);
$collection->setHostnamePattern('{locale}.example.com');
$this->assertEquals('{locale}.example.com', $routea->getHostnamePattern());
$this->assertEquals('{locale}.example.net', $routeb->getHostnamePattern());
}
}
| mit |
olivierlizotte/Proteomics.Utilities | PolynomialRegression.cs | 2866 | /*
* Copyright 2013 Olivier Caron-Lizotte
* [email protected]
* Licensed under the MIT license: <http://www.opensource.org/licenses/mit-license.php>
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MathNet.Numerics.LinearAlgebra.Generic;
using MathNet.Numerics.LinearAlgebra;
using MathNet.Numerics.LinearAlgebra.Double;
using MathNet.Numerics.LinearAlgebra.Double.Factorization;
namespace Proteomics.Utilities
{
/// <summary>
/// Implementation of a Polynomial Regression method (based on Math.NET)
/// Maps a dataset to a quadratic curve
/// </summary>
public class PolynominalRegression
{
private int _order;
private Vector<double> _coefs;
public PolynominalRegression(List<double> observedValues, List<double> theoricalValues, int order)
{
DenseVector xData = DenseVector.OfEnumerable(observedValues);
DenseVector yData = DenseVector.OfEnumerable(theoricalValues);
Initialize(xData, yData, order);
}
public PolynominalRegression(DenseVector xData, DenseVector yData, int order)
{
Initialize(xData, yData, order);
}
private void Initialize(DenseVector xData, DenseVector yData, int order)
{
_order = order;
int n = xData.Count;
var vandMatrix = new DenseMatrix(xData.Count, order + 1);
for (int i = 0; i < n; i++)
vandMatrix.SetRow(i, VandermondeRow(xData[i]));
// var vandMatrixT = vandMatrix.Transpose();
// 1 variant:
//_coefs = (vandMatrixT * vandMatrix).Inverse() * vandMatrixT * yData;
// 2 variant:
//_coefs = (vandMatrixT * vandMatrix).LU().Solve(vandMatrixT * yData);
// 3 variant (most fast I think. Possible LU decomposion also can be replaced with one triangular matrix):
_coefs = vandMatrix.TransposeThisAndMultiply(vandMatrix).LU().Solve(TransposeAndMult(vandMatrix, yData));
}
private Vector<double> VandermondeRow(double x)
{
double[] result = new double[_order + 1];
double mult = 1;
for (int i = 0; i <= _order; i++)
{
result[i] = mult;
mult *= x;
}
return new DenseVector(result);
}
private static DenseVector TransposeAndMult(Matrix m, Vector v)
{
var result = new DenseVector(m.ColumnCount);
for (int j = 0; j < m.RowCount; j++)
for (int i = 0; i < m.ColumnCount; i++)
result[i] += m[j, i] * v[j];
return result;
}
public double Calculate(double x)
{
return VandermondeRow(x) * _coefs;
}
}
}
| mit |
zcoinofficial/zcoin | src/coins.cpp | 10628 | // Copyright (c) 2012-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 "coins.h"
#include "util.h"
#include "consensus/consensus.h"
#include "memusage.h"
#include "random.h"
#include <assert.h>
bool CCoinsView::GetCoin(const COutPoint &outpoint, Coin &coin) const { return false; }
bool CCoinsView::HaveCoin(const COutPoint &outpoint) const { return false; }
uint256 CCoinsView::GetBestBlock() const { return uint256(); }
bool CCoinsView::BatchWrite(CCoinsMap &mapCoins, const uint256 &hashBlock) { return false; }
CCoinsViewCursor *CCoinsView::Cursor() const { return 0; }
CCoinsViewBacked::CCoinsViewBacked(CCoinsView *viewIn) : base(viewIn) { }
bool CCoinsViewBacked::GetCoin(const COutPoint &outpoint, Coin &coin) const { return base->GetCoin(outpoint, coin); }
bool CCoinsViewBacked::HaveCoin(const COutPoint &outpoint) const { return base->HaveCoin(outpoint); }
uint256 CCoinsViewBacked::GetBestBlock() const { return base->GetBestBlock(); }
void CCoinsViewBacked::SetBackend(CCoinsView &viewIn) { base = &viewIn; }
bool CCoinsViewBacked::BatchWrite(CCoinsMap &mapCoins, const uint256 &hashBlock) { return base->BatchWrite(mapCoins, hashBlock); }
CCoinsViewCursor *CCoinsViewBacked::Cursor() const { return base->Cursor(); }
size_t CCoinsViewBacked::EstimateSize() const { return base->EstimateSize(); }
SaltedOutpointHasher::SaltedOutpointHasher() : k0(GetRand(std::numeric_limits<uint64_t>::max())), k1(GetRand(std::numeric_limits<uint64_t>::max())) {}
CCoinsViewCache::CCoinsViewCache(CCoinsView *baseIn) : CCoinsViewBacked(baseIn), cachedCoinsUsage(0) {}
size_t CCoinsViewCache::DynamicMemoryUsage() const {
return memusage::DynamicUsage(cacheCoins) + cachedCoinsUsage;
}
CCoinsMap::iterator CCoinsViewCache::FetchCoin(const COutPoint &outpoint) const {
CCoinsMap::iterator it = cacheCoins.find(outpoint);
if (it != cacheCoins.end())
return it;
Coin tmp;
if (!base->GetCoin(outpoint, tmp))
return cacheCoins.end();
CCoinsMap::iterator ret = cacheCoins.emplace(std::piecewise_construct, std::forward_as_tuple(outpoint), std::forward_as_tuple(std::move(tmp))).first;
if (ret->second.coin.IsSpent()) {
// The parent only has an empty entry for this outpoint; we can consider our
// version as fresh.
ret->second.flags = CCoinsCacheEntry::FRESH;
}
cachedCoinsUsage += ret->second.coin.DynamicMemoryUsage();
return ret;
}
bool CCoinsViewCache::GetCoin(const COutPoint &outpoint, Coin &coin) const {
CCoinsMap::const_iterator it = FetchCoin(outpoint);
if (it != cacheCoins.end()) {
coin = it->second.coin;
return true;
}
return false;
}
void CCoinsViewCache::AddCoin(const COutPoint &outpoint, Coin&& coin, bool possible_overwrite) {
assert(!coin.IsSpent());
if (coin.out.scriptPubKey.IsUnspendable()) return;
CCoinsMap::iterator it;
bool inserted;
std::tie(it, inserted) = cacheCoins.emplace(std::piecewise_construct, std::forward_as_tuple(outpoint), std::tuple<>());
bool fresh = false;
if (!inserted) {
cachedCoinsUsage -= it->second.coin.DynamicMemoryUsage();
}
if (!possible_overwrite) {
if (!it->second.coin.IsSpent()) {
throw std::logic_error("Adding new coin that replaces non-pruned entry");
}
fresh = !(it->second.flags & CCoinsCacheEntry::DIRTY);
}
it->second.coin = std::move(coin);
it->second.flags |= CCoinsCacheEntry::DIRTY | (fresh ? CCoinsCacheEntry::FRESH : 0);
cachedCoinsUsage += it->second.coin.DynamicMemoryUsage();
}
void AddCoins(CCoinsViewCache& cache, const CTransaction &tx, int nHeight) {
bool fCoinbase = tx.IsCoinBase();
const uint256& txid = tx.GetHash();
for (size_t i = 0; i < tx.vout.size(); ++i) {
// Pass fCoinbase as the possible_overwrite flag to AddCoin, in order to correctly
// deal with the pre-BIP30 occurrances of duplicate coinbase transactions.
cache.AddCoin(COutPoint(txid, i), Coin(tx.vout[i], nHeight, fCoinbase), fCoinbase);
}
}
void CCoinsViewCache::SpendCoin(const COutPoint &outpoint, Coin* moveout) {
CCoinsMap::iterator it = FetchCoin(outpoint);
if (it == cacheCoins.end()) return;
cachedCoinsUsage -= it->second.coin.DynamicMemoryUsage();
if (moveout) {
*moveout = std::move(it->second.coin);
}
if (it->second.flags & CCoinsCacheEntry::FRESH) {
cacheCoins.erase(it);
} else {
it->second.flags |= CCoinsCacheEntry::DIRTY;
it->second.coin.Clear();
}
}
static const Coin coinEmpty;
const Coin& CCoinsViewCache::AccessCoin(const COutPoint &outpoint) const {
CCoinsMap::const_iterator it = FetchCoin(outpoint);
if (it == cacheCoins.end()) {
return coinEmpty;
} else {
return it->second.coin;
}
}
bool CCoinsViewCache::HaveCoin(const COutPoint &outpoint) const {
CCoinsMap::const_iterator it = FetchCoin(outpoint);
return (it != cacheCoins.end() && !it->second.coin.IsSpent());
}
bool CCoinsViewCache::HaveCoinInCache(const COutPoint &outpoint) const {
CCoinsMap::const_iterator it = cacheCoins.find(outpoint);
return it != cacheCoins.end();
}
uint256 CCoinsViewCache::GetBestBlock() const {
if (hashBlock.IsNull())
hashBlock = base->GetBestBlock();
return hashBlock;
}
void CCoinsViewCache::SetBestBlock(const uint256 &hashBlockIn) {
hashBlock = hashBlockIn;
}
bool CCoinsViewCache::BatchWrite(CCoinsMap &mapCoins, const uint256 &hashBlockIn) {
for (CCoinsMap::iterator it = mapCoins.begin(); it != mapCoins.end();) {
if (it->second.flags & CCoinsCacheEntry::DIRTY) { // Ignore non-dirty entries (optimization).
CCoinsMap::iterator itUs = cacheCoins.find(it->first);
if (itUs == cacheCoins.end()) {
// The parent cache does not have an entry, while the child does
// We can ignore it if it's both FRESH and pruned in the child
if (!(it->second.flags & CCoinsCacheEntry::FRESH && it->second.coin.IsSpent())) {
// Otherwise we will need to create it in the parent
// and move the data up and mark it as dirty
CCoinsCacheEntry& entry = cacheCoins[it->first];
entry.coin = std::move(it->second.coin);
cachedCoinsUsage += entry.coin.DynamicMemoryUsage();
entry.flags = CCoinsCacheEntry::DIRTY;
// We can mark it FRESH in the parent if it was FRESH in the child
// Otherwise it might have just been flushed from the parent's cache
// and already exist in the grandparent
if (it->second.flags & CCoinsCacheEntry::FRESH)
entry.flags |= CCoinsCacheEntry::FRESH;
}
} else {
// Assert that the child cache entry was not marked FRESH if the
// parent cache entry has unspent outputs. If this ever happens,
// it means the FRESH flag was misapplied and there is a logic
// error in the calling code.
if ((it->second.flags & CCoinsCacheEntry::FRESH) && !itUs->second.coin.IsSpent())
throw std::logic_error("FRESH flag misapplied to cache entry for base transaction with spendable outputs");
// Found the entry in the parent cache
if ((itUs->second.flags & CCoinsCacheEntry::FRESH) && it->second.coin.IsSpent()) {
// The grandparent does not have an entry, and the child is
// modified and being pruned. This means we can just delete
// it from the parent.
cachedCoinsUsage -= itUs->second.coin.DynamicMemoryUsage();
cacheCoins.erase(itUs);
} else {
// A normal modification.
cachedCoinsUsage -= itUs->second.coin.DynamicMemoryUsage();
itUs->second.coin = std::move(it->second.coin);
cachedCoinsUsage += itUs->second.coin.DynamicMemoryUsage();
itUs->second.flags |= CCoinsCacheEntry::DIRTY;
// NOTE: It is possible the child has a FRESH flag here in
// the event the entry we found in the parent is pruned. But
// we must not copy that FRESH flag to the parent as that
// pruned state likely still needs to be communicated to the
// grandparent.
}
}
}
CCoinsMap::iterator itOld = it++;
mapCoins.erase(itOld);
}
hashBlock = hashBlockIn;
return true;
}
bool CCoinsViewCache::Flush() {
bool fOk = base->BatchWrite(cacheCoins, hashBlock);
cacheCoins.clear();
cachedCoinsUsage = 0;
return fOk;
}
void CCoinsViewCache::Uncache(const COutPoint& hash)
{
CCoinsMap::iterator it = cacheCoins.find(hash);
if (it != cacheCoins.end() && it->second.flags == 0) {
cachedCoinsUsage -= it->second.coin.DynamicMemoryUsage();
cacheCoins.erase(it);
}
}
unsigned int CCoinsViewCache::GetCacheSize() const {
return cacheCoins.size();
}
CAmount CCoinsViewCache::GetValueIn(const CTransaction& tx) const
{
if (tx.IsCoinBase() || tx.IsZerocoinSpend() || tx.IsSigmaSpend() || tx.IsZerocoinRemint() || tx.IsLelantusJoinSplit())
return 0;
CAmount nResult = 0;
for (unsigned int i = 0; i < tx.vin.size(); i++)
nResult += AccessCoin(tx.vin[i].prevout).out.nValue;
return nResult;
}
bool CCoinsViewCache::HaveInputs(const CTransaction& tx) const
{
if (!tx.IsCoinBase() && !tx.IsZerocoinSpend() && !tx.IsSigmaSpend() && !tx.IsZerocoinRemint() && !tx.IsLelantusJoinSplit()) {
for (unsigned int i = 0; i < tx.vin.size(); i++) {
if (!HaveCoin(tx.vin[i].prevout)) {
return false;
}
}
}
return true;
}
static const size_t MAX_OUTPUTS_PER_BLOCK = MAX_BLOCK_BASE_SIZE / ::GetSerializeSize(CTxOut(), SER_NETWORK, PROTOCOL_VERSION); // TODO: merge with similar definition in undo.h.
const Coin& AccessByTxid(const CCoinsViewCache& view, const uint256& txid)
{
COutPoint iter(txid, 0);
while (iter.n < MAX_OUTPUTS_PER_BLOCK) {
const Coin& alternate = view.AccessCoin(iter);
if (!alternate.IsSpent()) return alternate;
++iter.n;
}
return coinEmpty;
}
| mit |
milesj/boost | packages/pipeline/src/ConcurrentPipeline.ts | 854 | import { Context } from './Context';
import { debug } from './debug';
import { ParallelPipeline } from './ParallelPipeline';
export class ConcurrentPipeline<
Ctx extends Context,
Input = unknown,
Output = Input,
> extends ParallelPipeline<{}, Ctx, Input, Output> {
/**
* Execute all work units in parallel with a value being passed to each work unit.
* If an error occurs, the pipeline will abort early, otherwise return a list of all results.
*/
async run(): Promise<Output[]> {
const { context, value } = this;
const work = this.getWorkUnits();
debug('Running %d in parallel', work.length);
this.onBeforeRun.emit([value]);
const result = await Promise.all(
work.map((unit) => {
this.onRunWorkUnit.emit([unit, value]);
return unit.run(context, value);
}),
);
this.onAfterRun.emit([]);
return result;
}
}
| mit |
Tao-Oak/LeetCodeProblems | Problems/Array/hard/45_jump_game_ii/JumpGameTwo.java | 3926 | //
// Created by Joshua.Cao, 2018/12/02
//
// https://leetcode.com/problems/jump-game-ii/
//
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;
/*
* Given an array of non-negative integers, you are initially positioned at the
* first index of the array.
*
* Each element in the array represents your maximum jump length at that position.
*
* Your goal is to reach the last index in the minimum number of jumps.
*
* Example:
* Input: [2,3,1,1,4]
* Output: 2
* Explanation: The minimum number of jumps to reach the last index is 2.
* Jump 1 step from index 0 to 1, then 3 steps to the last index.
*
* Note:
* You can assume that you can always reach the last index.
*/
public class JumpGameTwo {
public int jump(int[] nums) {
int steps = 0, fastIdx = 0, curIdx = 0;
for (int i = 0; i < nums.length - 1; i++) {
fastIdx = Math.max(fastIdx, i + nums[i]);
if (i == curIdx) {
steps++;
curIdx = fastIdx;
}
}
return steps;
}
// Accepted, beats 75.65%
public int jump_1(int[] nums) {
if (nums.length <= 1) return 0;
int index = 0, steps = 0;
int left = 0, right = nums[0];
int tgrIdx = nums.length - 1;
while (true) {
steps++;
if (nums[index] + index >= tgrIdx) {
break;
}
int max = 0;
for (int i = left + 1; i <= right; i++) {
int nextIndex = i + nums[i];
if (nextIndex > max) {
index = i;
max = nextIndex;
}
}
left = right;
right = max;
}
return steps;
}
// Time Limit Exceeded
public int jump_2(int[] nums) {
int tgrIdx = nums.length - 1;
Map<Integer, Integer> stepsMap = new HashMap<>();
stepsMap.put(tgrIdx, 0);
for (int i = tgrIdx - 1; i >= 0; i--) {
if (i + nums[i] >= tgrIdx) {
stepsMap.put(i, 1);
} else {
int minStep = tgrIdx;
for (int j = 1; j <= nums[i]; j++) {
if (stepsMap.get(i + j) < minStep) {
minStep = stepsMap.get(i + j);
}
}
stepsMap.put(i, 1 + minStep);
}
}
return stepsMap.get(0);
}
// Time Limit Exceeded
public int jump_3(int[] nums) {
return traceHelper(nums, nums.length - 1, 0, 0);
}
public int traceHelper(int[] nums, int tgrIdx, int curIdx, int steps) {
if (curIdx == tgrIdx) {
return steps;
}
if (curIdx + nums[curIdx] > tgrIdx) {
return steps + 1;
}
int minStep = tgrIdx;
for (int i = 1; i <= nums[curIdx]; i++) {
int step = traceHelper(nums, tgrIdx, curIdx + i, steps + 1);
if (step < minStep) minStep = step;
}
return minStep;
}
public int[] readInputFromFile() {
try {
FileInputStream fi = new FileInputStream("./LargeInput.txt");
InputStreamReader isr = new InputStreamReader(fi, "UTF-8");
BufferedReader br = new BufferedReader(isr);
String currentLine;
StringBuilder builder = new StringBuilder();
while ((currentLine = br.readLine()) != null) {
builder.append(currentLine);
}
br.close();
String[] strArr = builder.toString().split(",");
int[] input = new int[strArr.length];
for (int i = 0; i < strArr.length; i++) {
input[i] = Integer.parseInt(strArr[i]);
}
return input;
} catch (Exception e) {
System.out.println(" ...error:" + e);
return new int[]{};
}
}
public void test(int[] nums) {
System.out.println(jump(nums));
}
public static void main(String[] args) {
JumpGameTwo obj = new JumpGameTwo();
obj.test(new int[]{0});
obj.test(new int[]{2,3,1,1,4});
obj.test(obj.readInputFromFile());
obj.test(new int[]{
5,6,4,4,6,9,4,4,7,4,4,8,2,6,8,1,5,9,6,
5,2,7,9,7,9,6,9,4,1,6,8,8,4,4,2,0,3,8,5
});
}
}
| mit |
hpolthof/php-mt940 | src/Parser/Banking/Mt940/Engine/Ing.php | 3703 | <?php
namespace Kingsquare\Parser\Banking\Mt940\Engine;
use Kingsquare\Parser\Banking\Mt940\Engine;
/**
* @package Kingsquare\Parser\Banking\Mt940\Engine
* @author Kingsquare ([email protected])
* @license http://opensource.org/licenses/MIT MIT
*/
class Ing extends Engine
{
/**
* returns the name of the bank
* @return string
*/
protected function parseStatementBank()
{
return 'ING';
}
/**
* Overloaded: Added simple IBAN transaction handling
* @inheritdoc
*/
protected function parseTransactionAccount()
{
$account = parent::parseTransactionAccount();
if ($account !== '') {
return $account;
}
// IBAN
$transactionData = str_replace('Europese Incasso, doorlopend ', '', $this->getCurrentTransactionData());
$transactionData = preg_replace('![\r\n]+!', '', $transactionData);
if (preg_match('#/CNTP/(.*?)/#', $transactionData, $results)) {
$account = trim($results[1]);
if (!empty($account)) {
return $this->sanitizeAccount($account);
}
}
if (preg_match('#:86:([A-Z]{2}[0-9]{2}[A-Z]{4}[\d]+?) [A-Z]{6}[A-Z0-9]{0,4} #', $transactionData, $results)) {
$account = trim($results[1]);
if (!empty($account)) {
return $this->sanitizeAccount($account);
}
}
return '';
}
/**
* Overloaded: Added simple IBAN transaction handling
* @inheritdoc
*/
protected function parseTransactionAccountName()
{
$name = parent::parseTransactionAccountName();
if ($name !== '') {
return $name;
}
// IBAN
$transactionData = str_replace('Europese Incasso, doorlopend ', '', $this->getCurrentTransactionData());
$transactionData = preg_replace('![\r\n]+!', '', $transactionData);
if (preg_match('#/CNTP/[^/]*/[^/]*/(.*?)/#', $transactionData, $results)) {
$name = trim($results[1]);
if (!empty($name)) {
return $this->sanitizeAccountName($name);
}
}
if (preg_match('#:86:.*? [^ ]+ (.*)#', $transactionData, $results) !== 1) {
return '';
}
return $this->parseNameFromTransactionData($results[1]);
}
/**
* @param $transactionData
*
* @return string
*/
private function parseNameFromTransactionData($transactionData)
{
if (preg_match('#(.*) (Not-Provided|NOTPROVIDED)#', $transactionData, $results) === 1) {
$name = trim($results[1]);
if (!empty($name)) {
return $this->sanitizeAccountName($name);
}
}
if (preg_match('#\D+#', $transactionData, $results)) {
$name = trim($results[0]);
if (!empty($name)) {
return $this->sanitizeAccountName($name);
}
}
return '';
}
/**
* Overloaded: ING encapsulates the description with /REMI/ for SEPA
* @inheritdoc
*/
protected function sanitizeDescription($string)
{
$description = parent::sanitizeDescription($string);
if (strpos($description, '/REMI/USTD//') !== false
&& preg_match('#/REMI/USTD//(.*?)/#s', $description, $results) && !empty($results[1])
) {
return $results[1];
}
if (strpos($description, '/REMI/STRD/CUR/') !== false
&& preg_match('#/REMI/STRD/CUR/(.*?)/#s', $description, $results) && !empty($results[1])
) {
return $results[1];
}
return $description;
}
}
| mit |
cezarsa/was_tracer | benchmark/benchmark.rb | 393 | $:.unshift File.expand_path('../../lib', __FILE__)
require "was_tracer"
require "fileutils"
require "benchmark"
tmp_name = 'tmp_dkjsady83hai'
t = nil
Benchmark.bmbm do |x|
x.report("Parsing") {
t = WasTracer::Trace.new(File.expand_path('../trace.log', __FILE__))
}
x.report("Rendering") {
t.render_html_frames(tmp_name)
}
end
FileUtils.rm_r "./#{tmp_name}", :force => true
| mit |
bluewitch/Code-Blue-Python | HR_solveMeFirst.py | 303 | #HR_solveMeFirst.py
def solveMeFirst(a,b)
#Hint: Type return a+b below
return a+b
#Gotcha!
#You must cast your parameters as int
#or else they will concatenate as defult
#string instead of defult integer add sum
num1 = int(input())
num2 = int(input())
res = solveMeFirst(num1, num2)
print(res)
| mit |
jacobsalmela/AdminLTE | scripts/pi-hole/js/groups.js | 7980 | /* Pi-hole: A black hole for Internet advertisements
* (c) 2017 Pi-hole, LLC (https://pi-hole.net)
* Network-wide ad blocking via your own hardware.
*
* This file is copyright under the latest version of the EUPL.
* Please see LICENSE file for your rights under this license. */
/* global utils:false */
var table;
var token = $("#token").text();
$(function () {
$("#btnAdd").on("click", addGroup);
table = $("#groupsTable").DataTable({
ajax: {
url: "scripts/pi-hole/php/groups.php",
data: { action: "get_groups", token: token },
type: "POST"
},
order: [[0, "asc"]],
columns: [
{ data: "id", visible: false },
{ data: "name" },
{ data: "enabled", searchable: false },
{ data: "description" },
{ data: null, width: "60px", orderable: false }
],
drawCallback: function () {
$('button[id^="deleteGroup_"]').on("click", deleteGroup);
},
rowCallback: function (row, data) {
$(row).attr("data-id", data.id);
var tooltip =
"Added: " +
utils.datetime(data.date_added, false) +
"\nLast modified: " +
utils.datetime(data.date_modified, false) +
"\nDatabase ID: " +
data.id;
$("td:eq(0)", row).html(
'<input id="name_' + data.id + '" title="' + tooltip + '" class="form-control">'
);
var nameEl = $("#name_" + data.id, row);
nameEl.val(utils.unescapeHtml(data.name));
nameEl.on("change", editGroup);
var disabled = data.enabled === 0;
$("td:eq(1)", row).html(
'<input type="checkbox" id="status_' + data.id + '"' + (disabled ? "" : " checked") + ">"
);
var statusEl = $("#status_" + data.id, row);
statusEl.bootstrapToggle({
on: "Enabled",
off: "Disabled",
size: "small",
onstyle: "success",
width: "80px"
});
statusEl.on("change", editGroup);
$("td:eq(2)", row).html('<input id="desc_' + data.id + '" class="form-control">');
var desc = data.description !== null ? data.description : "";
var descEl = $("#desc_" + data.id, row);
descEl.val(utils.unescapeHtml(desc));
descEl.on("change", editGroup);
$("td:eq(3)", row).empty();
if (data.id !== 0) {
var button =
'<button type="button" class="btn btn-danger btn-xs" id="deleteGroup_' +
data.id +
'">' +
'<span class="far fa-trash-alt"></span>' +
"</button>";
$("td:eq(3)", row).html(button);
}
},
dom:
"<'row'<'col-sm-4'l><'col-sm-8'f>>" +
"<'row'<'col-sm-12'<'table-responsive'tr>>>" +
"<'row'<'col-sm-5'i><'col-sm-7'p>>",
lengthMenu: [
[10, 25, 50, 100, -1],
[10, 25, 50, 100, "All"]
],
stateSave: true,
stateSaveCallback: function (settings, data) {
utils.stateSaveCallback("groups-table", data);
},
stateLoadCallback: function () {
var data = utils.stateLoadCallback("groups-table");
// Return if not available
if (data === null) {
return null;
}
// Reset visibility of ID column
data.columns[0].visible = false;
// Apply loaded state to table
return data;
}
});
// Disable autocorrect in the search box
var input = document.querySelector("input[type=search]");
if (input !== null) {
input.setAttribute("autocomplete", "off");
input.setAttribute("autocorrect", "off");
input.setAttribute("autocapitalize", "off");
input.setAttribute("spellcheck", false);
}
table.on("order.dt", function () {
var order = table.order();
if (order[0][0] !== 0 || order[0][1] !== "asc") {
$("#resetButton").removeClass("hidden");
} else {
$("#resetButton").addClass("hidden");
}
});
$("#resetButton").on("click", function () {
table.order([[0, "asc"]]).draw();
$("#resetButton").addClass("hidden");
});
});
function addGroup() {
var name = utils.escapeHtml($("#new_name").val());
var desc = utils.escapeHtml($("#new_desc").val());
utils.disableAll();
utils.showAlert("info", "", "Adding group...", name);
if (name.length === 0) {
// enable the ui elements again
utils.enableAll();
utils.showAlert("warning", "", "Warning", "Please specify a group name");
return;
}
$.ajax({
url: "scripts/pi-hole/php/groups.php",
method: "post",
dataType: "json",
data: { action: "add_group", name: name, desc: desc, token: token },
success: function (response) {
utils.enableAll();
if (response.success) {
utils.showAlert("success", "fas fa-plus", "Successfully added group", name);
$("#new_name").val("");
$("#new_desc").val("");
table.ajax.reload();
} else {
utils.showAlert("error", "", "Error while adding new group", response.message);
}
},
error: function (jqXHR, exception) {
utils.enableAll();
utils.showAlert("error", "", "Error while adding new group", jqXHR.responseText);
console.log(exception); // eslint-disable-line no-console
}
});
}
function editGroup() {
var elem = $(this).attr("id");
var tr = $(this).closest("tr");
var id = tr.attr("data-id");
var name = utils.escapeHtml(tr.find("#name_" + id).val());
var status = tr.find("#status_" + id).is(":checked") ? 1 : 0;
var desc = utils.escapeHtml(tr.find("#desc_" + id).val());
var done = "edited";
var notDone = "editing";
switch (elem) {
case "status_" + id:
if (status === 0) {
done = "disabled";
notDone = "disabling";
} else if (status === 1) {
done = "enabled";
notDone = "enabling";
}
break;
case "name_" + id:
done = "edited name of";
notDone = "editing name of";
break;
case "desc_" + id:
done = "edited description of";
notDone = "editing description of";
break;
default:
alert("bad element or invalid data-id!");
return;
}
utils.disableAll();
utils.showAlert("info", "", "Editing group...", name);
$.ajax({
url: "scripts/pi-hole/php/groups.php",
method: "post",
dataType: "json",
data: {
action: "edit_group",
id: id,
name: name,
desc: desc,
status: status,
token: token
},
success: function (response) {
utils.enableAll();
if (response.success) {
utils.showAlert("success", "fas fa-pencil-alt", "Successfully " + done + " group", name);
} else {
utils.showAlert(
"error",
"",
"Error while " + notDone + " group with ID " + id,
response.message
);
}
},
error: function (jqXHR, exception) {
utils.enableAll();
utils.showAlert(
"error",
"",
"Error while " + notDone + " group with ID " + id,
jqXHR.responseText
);
console.log(exception); // eslint-disable-line no-console
}
});
}
function deleteGroup() {
var tr = $(this).closest("tr");
var id = tr.attr("data-id");
var name = utils.escapeHtml(tr.find("#name_" + id).val());
utils.disableAll();
utils.showAlert("info", "", "Deleting group...", name);
$.ajax({
url: "scripts/pi-hole/php/groups.php",
method: "post",
dataType: "json",
data: { action: "delete_group", id: id, token: token },
success: function (response) {
utils.enableAll();
if (response.success) {
utils.showAlert("success", "far fa-trash-alt", "Successfully deleted group ", name);
table.row(tr).remove().draw(false);
} else {
utils.showAlert("error", "", "Error while deleting group with ID " + id, response.message);
}
},
error: function (jqXHR, exception) {
utils.enableAll();
utils.showAlert("error", "", "Error while deleting group with ID " + id, jqXHR.responseText);
console.log(exception); // eslint-disable-line no-console
}
});
}
| mit |
holoed/AwesomeProject | node_modules/Prelude.Unsafe/index.js | 242 | // Generated by psc-make version 0.6.9.5
"use strict";
var Prelude = require("Prelude");
function unsafeIndex(xs) {
return function(n) {
return xs[n];
};
}
;
module.exports = {
unsafeIndex: unsafeIndex
};
| mit |
Adeynack/finances | app/models/book_role.rb | 587 | # frozen_string_literal: true
# == Schema Information
#
# Table name: book_roles
#
# id :bigint not null, primary key
# created_at :datetime not null
# updated_at :datetime not null
# book_id :bigint not null, indexed, indexed => [user_id, role]
# user_id :bigint not null, indexed => [book_id, role], indexed
# role :enum not null, indexed => [book_id, user_id]
#
class BookRole < ApplicationRecord
belongs_to :book
belongs_to :user
enum role: [:admin, :writer, :reader].index_with(&:to_s)
end
| mit |
iiling/ywt | ThinkPHP/Extend/Engine/Sae/Common/functions.php | 24955 | <?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2012 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <[email protected]>
// +----------------------------------------------------------------------
/**
* Think 标准模式公共函数库
* @category Think
* @package Common
* @author liu21st <[email protected]>
*/
/**
* 错误输出
* @param mixed $error 错误
* @return void
*/
function halt($error) {
$e = array();
if (APP_DEBUG) {
//调试模式下输出错误信息
if (!is_array($error)) {
$trace = debug_backtrace();
$e['message'] = $error;
$e['file'] = $trace[0]['file'];
$e['class'] = isset($trace[0]['class'])?$trace[0]['class']:'';
$e['function'] = isset($trace[0]['function'])?$trace[0]['function']:'';
$e['line'] = $trace[0]['line'];
$traceInfo = '';
$time = date('y-m-d H:i:m');
foreach ($trace as $t) {
$traceInfo .= '[' . $time . '] ' . $t['file'] . ' (' . $t['line'] . ') ';
$traceInfo .= $t['class'] . $t['type'] . $t['function'] . '(';
$traceInfo .= implode(', ', $t['args']);
$traceInfo .=')<br/>';
}
$e['trace'] = $traceInfo;
} else {
$e = $error;
}
} else {
//否则定向到错误页面
$error_page = C('ERROR_PAGE');
if (!empty($error_page)) {
redirect($error_page);
} else {
if (C('SHOW_ERROR_MSG'))
$e['message'] = is_array($error) ? $error['message'] : $error;
else
$e['message'] = C('ERROR_MESSAGE');
}
}
// 包含异常页面模板
include C('TMPL_EXCEPTION_FILE');
exit;
}
/**
* 自定义异常处理
* @param string $msg 异常消息
* @param string $type 异常类型 默认为ThinkException
* @param integer $code 异常代码 默认为0
* @return void
*/
function throw_exception($msg, $type='ThinkException', $code=0) {
if (class_exists($type, false))
throw new $type($msg, $code, true);
else
halt($msg); // 异常类型不存在则输出错误信息字串
}
/**
* 浏览器友好的变量输出
* @param mixed $var 变量
* @param boolean $echo 是否输出 默认为True 如果为false 则返回输出字符串
* @param string $label 标签 默认为空
* @param boolean $strict 是否严谨 默认为true
* @return void|string
*/
function dump($var, $echo=true, $label=null, $strict=true) {
$label = ($label === null) ? '' : rtrim($label) . ' ';
if (!$strict) {
if (ini_get('html_errors')) {
$output = print_r($var, true);
$output = '<pre>' . $label . htmlspecialchars($output, ENT_QUOTES) . '</pre>';
} else {
$output = $label . print_r($var, true);
}
} else {
ob_start();
var_dump($var);
$output = ob_get_clean();
if (!extension_loaded('xdebug')) {
$output = preg_replace("/\]\=\>\n(\s+)/m", '] => ', $output);
$output = '<pre>' . $label . htmlspecialchars($output, ENT_QUOTES) . '</pre>';
}
}
if ($echo) {
echo($output);
return null;
}else
return $output;
}
/**
* 404处理
* 调试模式会抛异常
* 部署模式下面传入url参数可以指定跳转页面,否则发送404信息
* @param string $msg 提示信息
* @param string $url 跳转URL地址
* @return void
*/
function _404($msg='',$url='') {
APP_DEBUG && throw_exception($msg);
if($msg && C('LOG_EXCEPTION_RECORD')) Log::write($msg);
if(empty($url) && C('URL_404_REDIRECT')) {
$url = C('URL_404_REDIRECT');
}
if($url) {
redirect($url);
}else{
send_http_status(404);
exit;
}
}
/**
* 设置当前页面的布局
* @param string|false $layout 布局名称 为false的时候表示关闭布局
* @return void
*/
function layout($layout) {
if(false !== $layout) {
// 开启布局
C('LAYOUT_ON',true);
if(is_string($layout)) { // 设置新的布局模板
C('LAYOUT_NAME',$layout);
}
}else{// 临时关闭布局
C('LAYOUT_ON',false);
}
}
/**
* URL组装 支持不同URL模式
* @param string $url URL表达式,格式:'[分组/模块/操作@域名]?参数1=值1&参数2=值2...'
* @param string|array $vars 传入的参数,支持数组和字符串
* @param string $suffix 伪静态后缀,默认为true表示获取配置值
* @param boolean $redirect 是否跳转,如果设置为true则表示跳转到该URL地址
* @param boolean $domain 是否显示域名
* @return string
*/
function U($url='',$vars='',$suffix=true,$redirect=false,$domain=false) {
// 解析URL
$info = parse_url($url);
$url = !empty($info['path'])?$info['path']:ACTION_NAME;
if(false !== strpos($url,'@')) { // 解析域名
list($url,$host) = explode('@',$info['path'], 2);
}
// 解析子域名
if(isset($host)) {
$domain = $host.(strpos($host,'.')?'':strstr($_SERVER['HTTP_HOST'],'.'));
}elseif($domain===true){
$domain = $_SERVER['HTTP_HOST'];
if(C('APP_SUB_DOMAIN_DEPLOY') ) { // 开启子域名部署
$domain = $domain=='localhost'?'localhost':'www'.strstr($_SERVER['HTTP_HOST'],'.');
// '子域名'=>array('项目[/分组]');
foreach (C('APP_SUB_DOMAIN_RULES') as $key => $rule) {
if(false === strpos($key,'*') && 0=== strpos($url,$rule[0])) {
$domain = $key.strstr($domain,'.'); // 生成对应子域名
$url = substr_replace($url,'',0,strlen($rule[0]));
break;
}
}
}
}
// 解析参数
if(is_string($vars)) { // aaa=1&bbb=2 转换成数组
parse_str($vars,$vars);
}elseif(!is_array($vars)){
$vars = array();
}
if(isset($info['query'])) { // 解析地址里面参数 合并到vars
parse_str($info['query'],$params);
$vars = array_merge($params,$vars);
}
// URL组装
$depr = C('URL_PATHINFO_DEPR');
if($url) {
if(0=== strpos($url,'/')) {// 定义路由
$route = true;
$url = substr($url,1);
if('/' != $depr) {
$url = str_replace('/',$depr,$url);
}
}else{
if('/' != $depr) { // 安全替换
$url = str_replace('/',$depr,$url);
}
// 解析分组、模块和操作
$url = trim($url,$depr);
$path = explode($depr,$url);
$var = array();
$var[C('VAR_ACTION')] = !empty($path)?array_pop($path):ACTION_NAME;
$var[C('VAR_MODULE')] = !empty($path)?array_pop($path):MODULE_NAME;
if(C('URL_CASE_INSENSITIVE')) {
$var[C('VAR_MODULE')] = parse_name($var[C('VAR_MODULE')]);
}
if(!C('APP_SUB_DOMAIN_DEPLOY') && C('APP_GROUP_LIST')) {
if(!empty($path)) {
$group = array_pop($path);
$var[C('VAR_GROUP')] = $group;
}else{
if(GROUP_NAME != C('DEFAULT_GROUP')) {
$var[C('VAR_GROUP')]= GROUP_NAME;
}
}
if(C('URL_CASE_INSENSITIVE') && isset($var[C('VAR_GROUP')])) {
$var[C('VAR_GROUP')] = strtolower($var[C('VAR_GROUP')]);
}
}
}
}
if(C('URL_MODEL') == 0) { // 普通模式URL转换
$url = __APP__.'?'.http_build_query(array_reverse($var));
if(!empty($vars)) {
$vars = urldecode(http_build_query($vars));
$url .= '&'.$vars;
}
}else{ // PATHINFO模式或者兼容URL模式
if(isset($route)) {
$url = __APP__.'/'.rtrim($url,$depr);
}else{
$url = __APP__.'/'.implode($depr,array_reverse($var));
}
if(!empty($vars)) { // 添加参数
foreach ($vars as $var => $val)
$url .= $depr.$var . $depr . $val;
}
if($suffix) {
$suffix = $suffix===true?C('URL_HTML_SUFFIX'):$suffix;
if($pos = strpos($suffix, '|')){
$suffix = substr($suffix, 0, $pos);
}
if($suffix && $url[1]){
$url .= '.'.ltrim($suffix,'.');
}
}
}
if($domain) {
$url = (is_ssl()?'https://':'http://').$domain.$url;
}
if($redirect) // 直接跳转URL
redirect($url);
else
return $url;
}
/**
* 判断是否SSL协议
* @return boolean
*/
function is_ssl() {
if(isset($_SERVER['HTTPS']) && ('1' == $_SERVER['HTTPS'] || 'on' == strtolower($_SERVER['HTTPS']))){
return true;
}elseif(isset($_SERVER['SERVER_PORT']) && ('443' == $_SERVER['SERVER_PORT'] )) {
return true;
}
return false;
}
/**
* URL重定向
* @param string $url 重定向的URL地址
* @param integer $time 重定向的等待时间(秒)
* @param string $msg 重定向前的提示信息
* @return void
*/
function redirect($url, $time=0, $msg='') {
//多行URL地址支持
$url = str_replace(array("\n", "\r"), '', $url);
if (empty($msg))
$msg = "系统将在{$time}秒之后自动跳转到{$url}!";
if (!headers_sent()) {
// redirect
if (0 === $time) {
header('Location: ' . $url);
} else {
header("refresh:{$time};url={$url}");
echo($msg);
}
exit();
} else {
$str = "<meta http-equiv='Refresh' content='{$time};URL={$url}'>";
if ($time != 0)
$str .= $msg;
exit($str);
}
}
/**
* 缓存管理
* @param string|array $name 缓存名称,如果为数组表示进行缓存设置
* @param mixed $value 缓存值
* @param integer $expire 缓存有效期(秒)
* @return mixed
*/
function cache($name,$value='',$expire=0) {
static $cache = '';
if(is_array($name)) { // 缓存初始化
$type = 'Memcache';//[sae],SAE下是否要设置DATA_CACHE_TYPE的默认值
unset($name['type']);
$cache = Cache::getInstance($type,$name);
return $cache;
}
if(empty($cache)) { // 自动初始化
$cache = Cache::getInstance();
}
if(''=== $value){ // 获取缓存值
// 获取缓存数据
return $cache->get($name);
}elseif(is_null($value)) { // 删除缓存
return $cache->rm($name);
}else { // 缓存数据
return $cache->set($name, $value, $expire);
}
}
/**
* 全局缓存设置和读取
* @param string $name 缓存名称
* @param mixed $value 缓存值
* @param integer $expire 缓存有效期(秒)
* @param string $type 缓存类型
* @param array $options 缓存参数
* @return mixed
*/
//[sae] 在sae下S缓存固定用memcache实现。
function S($name, $value='', $expire=0, $type='', $options=null) {
static $_cache = array();
static $mc;
//取得缓存对象实例
if (!is_object($mc)) {
$mc = memcache_init();
}
if ('' !== $value) {
if (is_null($value)) {
// 删除缓存
$result = $mc->delete($_SERVER['HTTP_APPVERSION'] . '/' . $name);
if ($result)
unset($_cache[$name]);
return $result;
}else {
// 缓存数据
$mc->set($_SERVER['HTTP_APPVERSION'] . '/' . $name, $value, MEMCACHE_COMPRESSED, $expire);
$_cache[$name] = $value;
//[sae] 实现列队
if (!is_null($options['length']) && $options['length'] > 0) {
$queue = F('think_queue');
if (!$queue) {
$queue = array();
}
array_push($queue, $name);
if (count($queue) > $options['length']) {
$key = array_shift($queue);
$mc->delete($key);
//[sae] 在调试模式下,统计出队次数
if (APP_DEBUG) {
$counter = Think::instance('SaeCounter');
if ($counter->exists('think_queue_out_times'))
$counter->incr('think_queue_out_times');
else
$counter->create('think_queue_out_times', 1);
}
}
F('think_queue', $queue);
}
}
return;
}
if (isset($_cache[$name]))
return $_cache[$name];
// 获取缓存数据
$value = $mc->get($_SERVER['HTTP_APPVERSION'] . '/' . $name);
$_cache[$name] = $value;
return $value;
}
/**
* 快速文件数据读取和保存 针对简单类型数据 字符串、数组
* @param string $name 缓存名称
* @param mixed $value 缓存值
* @param string $path 缓存路径
* @return mixed
*/
//[sae] 在sae下F缓存使用KVDB实现
function F($name, $value='', $path=DATA_PATH) {
//sae使用KVDB实现F缓存
static $_cache = array();
static $kv;
if (!is_object($kv)) {
$kv = Think::instance('SaeKVClient');
if(!$kv->init()) halt('您没有初始化KVDB,请在SAE平台进行初始化');
}
if ('' !== $value) {
if (is_null($value)) {
// 删除缓存
return $kv->delete($_SERVER['HTTP_APPVERSION'] . '/' . $name);
} else {
return $kv->set($_SERVER['HTTP_APPVERSION'] . '/' . $name, $value);
}
}
if (isset($_cache[$name]))
return $_cache[$name];
// 获取缓存数据
$value = $kv->get($_SERVER['HTTP_APPVERSION'] . '/' . $name);
return $value;
}
/**
* 取得对象实例 支持调用类的静态方法
* @param string $name 类名
* @param string $method 方法名,如果为空则返回实例化对象
* @param array $args 调用参数
* @return object
*/
function get_instance_of($name, $method='', $args=array()) {
static $_instance = array();
$identify = empty($args) ? $name . $method : $name . $method . to_guid_string($args);
if (!isset($_instance[$identify])) {
if (class_exists($name)) {
$o = new $name();
if (method_exists($o, $method)) {
if (!empty($args)) {
$_instance[$identify] = call_user_func_array(array(&$o, $method), $args);
} else {
$_instance[$identify] = $o->$method();
}
}
else
$_instance[$identify] = $o;
}
else
halt(L('_CLASS_NOT_EXIST_') . ':' . $name);
}
return $_instance[$identify];
}
/**
* 根据PHP各种类型变量生成唯一标识号
* @param mixed $mix 变量
* @return string
*/
function to_guid_string($mix) {
if (is_object($mix) && function_exists('spl_object_hash')) {
return spl_object_hash($mix);
} elseif (is_resource($mix)) {
$mix = get_resource_type($mix) . strval($mix);
} else {
$mix = serialize($mix);
}
return md5($mix);
}
/**
* XML编码
* @param mixed $data 数据
* @param string $encoding 数据编码
* @param string $root 根节点名
* @return string
*/
function xml_encode($data, $encoding='utf-8', $root='think') {
$xml = '<?xml version="1.0" encoding="' . $encoding . '"?>';
$xml .= '<' . $root . '>';
$xml .= data_to_xml($data);
$xml .= '</' . $root . '>';
return $xml;
}
/**
* 数据XML编码
* @param mixed $data 数据
* @return string
*/
function data_to_xml($data) {
$xml = '';
foreach ($data as $key => $val) {
is_numeric($key) && $key = "item id=\"$key\"";
$xml .= "<$key>";
$xml .= ( is_array($val) || is_object($val)) ? data_to_xml($val) : $val;
list($key, ) = explode(' ', $key);
$xml .= "</$key>";
}
return $xml;
}
/**
* session管理函数
* @param string|array $name session名称 如果为数组则表示进行session设置
* @param mixed $value session值
* @return mixed
*/
function session($name,$value='') {
$prefix = C('SESSION_PREFIX');
if(is_array($name)) { // session初始化 在session_start 之前调用
if(isset($name['prefix'])) C('SESSION_PREFIX',$name['prefix']);
if(C('VAR_SESSION_ID') && isset($_REQUEST[C('VAR_SESSION_ID')])){
session_id($_REQUEST[C('VAR_SESSION_ID')]);
}elseif(isset($name['id'])) {
session_id($name['id']);
}
//ini_set('session.auto_start', 0);//[sae] 在sae平台不用设置
if(isset($name['name'])) session_name($name['name']);
if(isset($name['path'])) session_save_path($name['path']);
if(isset($name['domain'])) ini_set('session.cookie_domain', $name['domain']);
if(isset($name['expire'])) ini_set('session.gc_maxlifetime', $name['expire']);
if(isset($name['use_trans_sid'])) ini_set('session.use_trans_sid', $name['use_trans_sid']?1:0);
if(isset($name['use_cookies'])) ini_set('session.use_cookies', $name['use_cookies']?1:0);
if(isset($name['cache_limiter'])) session_cache_limiter($name['cache_limiter']);
if(isset($name['cache_expire'])) session_cache_expire($name['cache_expire']);
if(isset($name['type'])) C('SESSION_TYPE',$name['type']);
if(C('SESSION_TYPE')) { // 读取session驱动
$class = 'Session'. ucwords(strtolower(C('SESSION_TYPE')));
// 检查驱动类
if(require_cache(EXTEND_PATH.'Driver/Session/'.$class.'.class.php')) {
$hander = new $class();
$hander->execute();
}else {
// 类没有定义
throw_exception(L('_CLASS_NOT_EXIST_').': ' . $class);
}
}
// 启动session
if(C('SESSION_AUTO_START')) session_start();
}elseif('' === $value){
if(0===strpos($name,'[')) { // session 操作
if('[pause]'==$name){ // 暂停session
session_write_close();
}elseif('[start]'==$name){ // 启动session
session_start();
}elseif('[destroy]'==$name){ // 销毁session
$_SESSION = array();
session_unset();
session_destroy();
}elseif('[regenerate]'==$name){ // 重新生成id
session_regenerate_id();
}
}elseif(0===strpos($name,'?')){ // 检查session
$name = substr($name,1);
if($prefix) {
return isset($_SESSION[$prefix][$name]);
}else{
return isset($_SESSION[$name]);
}
}elseif(is_null($name)){ // 清空session
if($prefix) {
unset($_SESSION[$prefix]);
}else{
$_SESSION = array();
}
}elseif($prefix){ // 获取session
return isset($_SESSION[$prefix][$name])?$_SESSION[$prefix][$name]:null;
}else{
return isset($_SESSION[$name])?$_SESSION[$name]:null;
}
}elseif(is_null($value)){ // 删除session
if($prefix){
unset($_SESSION[$prefix][$name]);
}else{
unset($_SESSION[$name]);
}
}else{ // 设置session
if($prefix){
if (!is_array($_SESSION[$prefix])) {
$_SESSION[$prefix] = array();
}
$_SESSION[$prefix][$name] = $value;
}else{
$_SESSION[$name] = $value;
}
}
}
/**
* Cookie 设置、获取、删除
* @param string $name cookie名称
* @param mixed $value cookie值
* @param mixed $options cookie参数
* @return mixed
*/
function cookie($name, $value='', $option=null) {
// 默认设置
$config = array(
'prefix' => C('COOKIE_PREFIX'), // cookie 名称前缀
'expire' => C('COOKIE_EXPIRE'), // cookie 保存时间
'path' => C('COOKIE_PATH'), // cookie 保存路径
'domain' => C('COOKIE_DOMAIN'), // cookie 有效域名
);
// 参数设置(会覆盖黙认设置)
if (!empty($option)) {
if (is_numeric($option))
$option = array('expire' => $option);
elseif (is_string($option))
parse_str($option, $option);
$config = array_merge($config, array_change_key_case($option));
}
// 清除指定前缀的所有cookie
if (is_null($name)) {
if (empty($_COOKIE))
return;
// 要删除的cookie前缀,不指定则删除config设置的指定前缀
$prefix = empty($value) ? $config['prefix'] : $value;
if (!empty($prefix)) {// 如果前缀为空字符串将不作处理直接返回
foreach ($_COOKIE as $key => $val) {
if (0 === stripos($key, $prefix)) {
setcookie($key, '', time() - 3600, $config['path'], $config['domain']);
unset($_COOKIE[$key]);
}
}
}
return;
}
$name = $config['prefix'] . $name;
if ('' === $value) {
return isset($_COOKIE[$name]) ? json_decode(MAGIC_QUOTES_GPC?stripslashes($_COOKIE[$name]):$_COOKIE[$name]) : null; // 获取指定Cookie
} else {
if (is_null($value)) {
setcookie($name, '', time() - 3600, $config['path'], $config['domain']);
unset($_COOKIE[$name]); // 删除指定cookie
} else {
// 设置cookie
$value = json_encode($value);
$expire = !empty($config['expire']) ? time() + intval($config['expire']) : 0;
setcookie($name, $value, $expire, $config['path'], $config['domain']);
$_COOKIE[$name] = $value;
}
}
}
/**
* 加载动态扩展文件
* @return void
*/
function load_ext_file() {
// 加载自定义外部文件
if(C('LOAD_EXT_FILE')) {
$files = explode(',',C('LOAD_EXT_FILE'));
foreach ($files as $file){
$file = COMMON_PATH.$file.'.php';
if(is_file($file)) include $file;
}
}
// 加载自定义的动态配置文件
if(C('LOAD_EXT_CONFIG')) {
$configs = C('LOAD_EXT_CONFIG');
if(is_string($configs)) $configs = explode(',',$configs);
foreach ($configs as $key=>$config){
$file = CONF_PATH.$config.'.php';
if(is_file($file)) {
is_numeric($key)?C(include $file):C($key,include $file);
}
}
}
}
/**
* 获取客户端IP地址
* @param integer $type 返回类型 0 返回IP地址 1 返回IPV4地址数字
* @return mixed
*/
function get_client_ip($type = 0) {
$type = $type ? 1 : 0;
static $ip = NULL;
if ($ip !== NULL) return $ip[$type];
if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
$arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
$pos = array_search('unknown',$arr);
if(false !== $pos) unset($arr[$pos]);
$ip = trim($arr[0]);
}elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
$ip = $_SERVER['HTTP_CLIENT_IP'];
}elseif (isset($_SERVER['REMOTE_ADDR'])) {
$ip = $_SERVER['REMOTE_ADDR'];
}
// IP地址合法验证
$long = ip2long($ip);
$ip = $long ? array($ip, $long) : array('0.0.0.0', 0);
return $ip[$type];
}
/**
* 发送HTTP状态
* @param integer $code 状态码
* @return void
*/
function send_http_status($code) {
static $_status = array(
// Success 2xx
200 => 'OK',
// Redirection 3xx
301 => 'Moved Permanently',
302 => 'Moved Temporarily ', // 1.1
// Client Error 4xx
400 => 'Bad Request',
403 => 'Forbidden',
404 => 'Not Found',
// Server Error 5xx
500 => 'Internal Server Error',
503 => 'Service Unavailable',
);
if(isset($_status[$code])) {
header('HTTP/1.1 '.$code.' '.$_status[$code]);
// 确保FastCGI模式下正常
header('Status:'.$code.' '.$_status[$code]);
}
} | mit |
TryGhost/Ghost-Admin | app/components/modal-delete-member.js | 1499 | import ModalComponent from 'ghost-admin/components/modal-base';
import {alias} from '@ember/object/computed';
import {computed} from '@ember/object';
import {reads} from '@ember/object/computed';
import {inject as service} from '@ember/service';
import {task} from 'ember-concurrency';
export default ModalComponent.extend({
membersStats: service(),
shouldCancelSubscriptions: false,
// Allowed actions
confirm: () => {},
member: alias('model'),
cancelSubscriptions: reads('shouldCancelSubscriptions'),
hasActiveStripeSubscriptions: computed('member', function () {
let subscriptions = this.member.get('subscriptions');
if (!subscriptions || subscriptions.length === 0) {
return false;
}
let firstActiveStripeSubscription = subscriptions.find((subscription) => {
return ['active', 'trialing', 'unpaid', 'past_due'].includes(subscription.status);
});
return firstActiveStripeSubscription !== undefined;
}),
actions: {
confirm() {
this.deleteMember.perform();
},
toggleShouldCancelSubscriptions() {
this.set('shouldCancelSubscriptions', !this.shouldCancelSubscriptions);
}
},
deleteMember: task(function* () {
try {
yield this.confirm(this.shouldCancelSubscriptions);
this.membersStats.invalidate();
} finally {
this.send('closeModal');
}
}).drop()
});
| mit |
5monkeys/zoomenhance | jquery.zoomenhance.js | 4828 | (function($) {
// zoomenhance: Image zoomer
$.fn.extend({
zoomenhance: function(userOpts) {
var defaults = { width: 200,
height: 200,
hitboxPadding: 5,
zoomFactor: undefined,
manualCss: false,
css: { cursor: 'none',
backgroundRepeat: 'no-repeat',
backgroundColor: '#ccc',
cursor: 'none',
border: '2px solid white',
boxShadow: '0 0 10px #777, 0 0 8px black inset, 0 0 20px white inset',
position: 'absolute'
}
};
var opts = $.extend(defaults, (userOpts !== undefined) ? userOpts : {});
return this.each(function() {
var el = $(this);
var src = el.attr('src');
var overlay = $(document.createElement('div'));
var overlayVisible = false;
overlay.addClass('zoomenhance-overlay');
if (!opts.manualCss) {
var vec2dLength2 = function(x,y) { return Math.pow(x,2) + Math.pow(y,2); };
var vec2dLength = function(x,y) { return Math.sqrt(vec2dLength2(x,y)); };
overlay.css({ borderRadius: vec2dLength(opts.width/2,
opts.height/2) + 'px',
width: opts.width + 'px',
height: opts.height + 'px'
});
overlay.css(opts.css);
}
overlay.appendTo(document.body);
var imageWidth;
var imageHeight;
var updateImage = function(src, width, height) {
overlay.css('backgroundImage', 'url(' + src + ')');
if (opts.zoomFactor) {
imageWidth = el.width()*opts.zoomFactor;
imageHeight = el.height()*opts.zoomFactor;
var bgSize = imageWidth + 'px '
+ imageHeight + 'px';
overlay.css({ 'background-size': bgSize,
'-webkit-background-size': bgSize,
'-moz-background-size': bgSize,
'-o-background-size': bgSize });
} else {
imageWidth = width;
imageHeight = height;
}
};
var loadImageSize = function() {
var src = el.attr('src');
var sizeEl = $(document.createElement('img'));
sizeEl.bind('load', function(ev) {
if (ev.target.width*ev.target.height == 0) {
return;
}
updateImage(src, ev.target.width, ev.target.height);
$(this).remove();
});
sizeEl.attr('src', src);
sizeEl.load();
};
var imageReloaded = function() {
imageWidth = imageHeight = undefined;
overlay.css('display', 'none');
if (el.naturalWidth) {
updateImage(el.attr('src'), el.naturalWidth, el.naturalHeight);
}
else {
console.warn('getting image dimensions with unreliable method');
loadImageSize();
}
};
el.bind('load', imageReloaded);
el.bind('error', imageReloaded);
el.load();
var mouseX;
var mouseY;
var relocate = function(ev) {
if (imageWidth === undefined) {
return;
}
if ((mouseX !== undefined) && mouseX == ev.pageX && mouseY == ev.pageY) {
return;
}
mouseX = ev.pageX;
mouseY = ev.pageY;
var offset = el.offset();
var elWidth = el.width();
var elHeight = el.height();
var elX = mouseX - offset.left;
var elY = mouseY - offset.top;
var overlayX = mouseX - opts.width/2;
var overlayY = mouseY - opts.height/2;
var x = Math.min(Math.max(elX / elWidth, 0), 1);
var y = Math.min(Math.max(elY / elHeight, 0), 1);
var zoomX = x*imageWidth - opts.width/2;
var zoomY = y*imageHeight - opts.height/2;
var outOfBounds = (Math.abs(elX - elWidth/2) > (elWidth/2 + opts.hitboxPadding))
|| (Math.abs(elY - elHeight/2) > (elHeight/2 + opts.hitboxPadding));
overlay.css({backgroundPosition: (-zoomX) + 'px ' + (-zoomY) + 'px',
display: outOfBounds ? 'none' : 'block',
left: overlayX + 'px',
top: overlayY + 'px'});
};
$(document.body).bind('mousemove', relocate);
el.bind('mousemove', relocate);
overlay.bind('mousemove', relocate);
});
}
});
})(jQuery || django.jQuery);
| mit |
Dryra/SosAnimauxWeb | app/cache/prod/doctrine/orm/Proxies/__CG__SosAnimauxBackOfficeBundleEntityRendezVous.php | 6400 | <?php
namespace Proxies\__CG__\SosAnimaux\BackOfficeBundle\Entity;
/**
* DO NOT EDIT THIS FILE - IT WAS CREATED BY DOCTRINE'S PROXY GENERATOR
*/
class RendezVous extends \SosAnimaux\BackOfficeBundle\Entity\RendezVous implements \Doctrine\ORM\Proxy\Proxy
{
/**
* @var \Closure the callback responsible for loading properties in the proxy object. This callback is called with
* three parameters, being respectively the proxy object to be initialized, the method that triggered the
* initialization process and an array of ordered parameters that were passed to that method.
*
* @see \Doctrine\Common\Persistence\Proxy::__setInitializer
*/
public $__initializer__;
/**
* @var \Closure the callback responsible of loading properties that need to be copied in the cloned object
*
* @see \Doctrine\Common\Persistence\Proxy::__setCloner
*/
public $__cloner__;
/**
* @var boolean flag indicating if this object was already initialized
*
* @see \Doctrine\Common\Persistence\Proxy::__isInitialized
*/
public $__isInitialized__ = false;
/**
* @var array properties to be lazy loaded, with keys being the property
* names and values being their default values
*
* @see \Doctrine\Common\Persistence\Proxy::__getLazyProperties
*/
public static $lazyPropertiesDefaults = array();
/**
* @param \Closure $initializer
* @param \Closure $cloner
*/
public function __construct($initializer = null, $cloner = null)
{
$this->__initializer__ = $initializer;
$this->__cloner__ = $cloner;
}
/**
*
* @return array
*/
public function __sleep()
{
if ($this->__isInitialized__) {
return array('__isInitialized__', 'idRdv', 'date', 'idAdh', 'idPens');
}
return array('__isInitialized__', 'idRdv', 'date', 'idAdh', 'idPens');
}
/**
*
*/
public function __wakeup()
{
if ( ! $this->__isInitialized__) {
$this->__initializer__ = function (RendezVous $proxy) {
$proxy->__setInitializer(null);
$proxy->__setCloner(null);
$existingProperties = get_object_vars($proxy);
foreach ($proxy->__getLazyProperties() as $property => $defaultValue) {
if ( ! array_key_exists($property, $existingProperties)) {
$proxy->$property = $defaultValue;
}
}
};
}
}
/**
*
*/
public function __clone()
{
$this->__cloner__ && $this->__cloner__->__invoke($this, '__clone', array());
}
/**
* Forces initialization of the proxy
*/
public function __load()
{
$this->__initializer__ && $this->__initializer__->__invoke($this, '__load', array());
}
/**
* {@inheritDoc}
* @internal generated method: use only when explicitly handling proxy specific loading logic
*/
public function __isInitialized()
{
return $this->__isInitialized__;
}
/**
* {@inheritDoc}
* @internal generated method: use only when explicitly handling proxy specific loading logic
*/
public function __setInitialized($initialized)
{
$this->__isInitialized__ = $initialized;
}
/**
* {@inheritDoc}
* @internal generated method: use only when explicitly handling proxy specific loading logic
*/
public function __setInitializer(\Closure $initializer = null)
{
$this->__initializer__ = $initializer;
}
/**
* {@inheritDoc}
* @internal generated method: use only when explicitly handling proxy specific loading logic
*/
public function __getInitializer()
{
return $this->__initializer__;
}
/**
* {@inheritDoc}
* @internal generated method: use only when explicitly handling proxy specific loading logic
*/
public function __setCloner(\Closure $cloner = null)
{
$this->__cloner__ = $cloner;
}
/**
* {@inheritDoc}
* @internal generated method: use only when explicitly handling proxy specific cloning logic
*/
public function __getCloner()
{
return $this->__cloner__;
}
/**
* {@inheritDoc}
* @internal generated method: use only when explicitly handling proxy specific loading logic
* @static
*/
public function __getLazyProperties()
{
return self::$lazyPropertiesDefaults;
}
/**
* {@inheritDoc}
*/
public function getIdRdv()
{
if ($this->__isInitialized__ === false) {
return (int) parent::getIdRdv();
}
$this->__initializer__ && $this->__initializer__->__invoke($this, 'getIdRdv', array());
return parent::getIdRdv();
}
/**
* {@inheritDoc}
*/
public function setDate($date)
{
$this->__initializer__ && $this->__initializer__->__invoke($this, 'setDate', array($date));
return parent::setDate($date);
}
/**
* {@inheritDoc}
*/
public function getDate()
{
$this->__initializer__ && $this->__initializer__->__invoke($this, 'getDate', array());
return parent::getDate();
}
/**
* {@inheritDoc}
*/
public function setIdAdh(\SosAnimaux\BackOfficeBundle\Entity\Adherant $idAdh = NULL)
{
$this->__initializer__ && $this->__initializer__->__invoke($this, 'setIdAdh', array($idAdh));
return parent::setIdAdh($idAdh);
}
/**
* {@inheritDoc}
*/
public function getIdAdh()
{
$this->__initializer__ && $this->__initializer__->__invoke($this, 'getIdAdh', array());
return parent::getIdAdh();
}
/**
* {@inheritDoc}
*/
public function setIdPens(\SosAnimaux\BackOfficeBundle\Entity\Pensions $idPens = NULL)
{
$this->__initializer__ && $this->__initializer__->__invoke($this, 'setIdPens', array($idPens));
return parent::setIdPens($idPens);
}
/**
* {@inheritDoc}
*/
public function getIdPens()
{
$this->__initializer__ && $this->__initializer__->__invoke($this, 'getIdPens', array());
return parent::getIdPens();
}
}
| mit |
bkahlert/seqan-research | raw/workshop13/workshop2013-data-20130926/sources/kpj5j5z3lqazq2d2/31/sandbox/lkuchenb/apps/rnaseq/rnaseq.cpp | 3265 | #include <iostream>
#include <seqan/store.h>
#include <seqan/arg_parse.h>
#include <seqan/misc/misc_interval_tree.h>
#include <seqan/parallel.h>
using namespace seqan;
// define used types
typedef FragmentStore<> TStore;
typedef Value<TStore::TAnnotationStore>::Type TAnnotation;
typedef TAnnotation::TId TId;
typedef TAnnotation::TId TPos;
typedef IntervalAndCargo<TPos, TId> TInterval;
// define options
struct Options
{
std::string annotationFileName;
std::string alignmentFileName;
};
//
// 1. Parse command line and fill Options object
//
ArgumentParser::ParseResult parseOptions(Options & options, int argc, char const * argv[])
{
ArgumentParser parser("gene_quant");
setShortDescription(parser, "A simple gene quantification tool");
setVersion(parser, "1.0");
setDate(parser, "Sep 2012");
addArgument(parser, ArgParseArgument(ArgParseArgument::INPUTFILE));
addArgument(parser, ArgParseArgument(ArgParseArgument::INPUTFILE));
addUsageLine(parser, "[\\fIOPTIONS\\fP] <\\fIANNOTATION FILE\\fP> <\\fIREAD ALIGNMENT FILE\\fP>");
// Parse command line
ArgumentParser::ParseResult res = parse(parser, argc, argv);
if (res == ArgumentParser::PARSE_OK)
{
// Extract option values
getArgumentValue(options.annotationFileName, parser, 0);
getArgumentValue(options.alignmentFileName, parser, 1);
}
return res;
}
//
// 2. Load annotations and alignments from files
//
bool loadFiles(TStore & store, Options const & options)
{
std::ifstream alignStream(toCString(options.alignmentFileName));
std::ifstream annoStream(toCString(options.annotationFileName));
if (!alignStream.good()) {
std::cerr << "Could not open the specified SAM file " << options.annotationFileName << std::endl;
return false;
}
read(alignStream, store, Sam());
std::cout << "read " << length(store.alignedReadStore) << " aligned reads" << std::endl;
if (!annoStream.good()) {
std::cerr << "Could not open the specified GFF file " << options.annotationFileName << std::endl;
return false;
}
read(annoStream, store, Gtf());
std::cout << "read " << length(store.annotationStore) << " annotations" << std::endl;
return true;
}
//
// 3. Extract intervals from gene annotations (grouped by contigId)
//
void extractGeneIntervals(String<String<TInterval> > & intervals, TStore const & store)
{
Iterator<TStore const, AnnotationTree<> >::Type it = begin(store, AnnotationTree<>());
if (!goDown(it)) {
// err
}
if (atEnd(it))
return;
do {
TPos beginPos = getAnnotation(it).beginPos;
TPos endPos = getAnnotation(it).endPos;
TId contigId = getAnnotation(it).contigId;
if (endPos < beginPos)
std::swap(beginPos, endPos);
appendValue(intervals[contigId], TInterval(beginPos, endPos, value(*it)));
} while (goRight(it));
}
int main(int argc, char const * argv[])
{
Options options;
TStore store;
String<String<TInterval> > intervals;
ArgumentParser::ParseResult res = parseOptions(options, argc, argv);
if (res != ArgumentParser::PARSE_OK)
return res == ArgumentParser::PARSE_ERROR;
if (!loadFiles(store, options))
return 1;
extractGeneIntervals(intervals, store);
return 0;
} | mit |
backpaper0/sandbox | servlet3-java6/src/test/java/com/example/FooServlet.java | 1152 | package com.example;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Set;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet(urlPatterns = "/foo")
public class FooServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
final List<Class<?>> classes = new ArrayList<Class<?>>(
(Set<Class<?>>) req.getServletContext()
.getAttribute(Foo.class.getName()));
Collections.sort(classes, new Comparator<Class<?>>() {
@Override
public int compare(Class<?> o1, Class<?> o2) {
return o1.getName().compareTo(o2.getName());
}
});
resp.setContentType("text/plain");
final PrintWriter out = resp.getWriter();
for (final Class<?> clazz : classes) {
out.println(clazz.getName());
}
out.flush();
out.close();
}
}
| mit |
camilolopes/nodejs-examples | firstappnode/hello_server_refactored.js | 356 | var http = require('http');
var atendeRequisicao = function(request,response){
response.writeHead(200,{"Content-Type":"text/html"});
response.write("<h1>Hello world NodeJS</h1>");
response.end();
}
var server = http.createServer(atendeRequisicao);
var servidorUp = function(){
console.log("Servidor node rodando");
}
server.listen(3000,servidorUp);
| mit |
botstory/todo-bot | todo/conftest.py | 9475 | import botstory
from botstory import di
from botstory.integrations import fb, mongodb, mockhttp
import datetime
import emoji
import logging
import os
import pytest
from todo import lists, stories, tasks
from todo.test_helpers import env
logger = logging.getLogger(__name__)
def all_emoji(text):
return emoji.emojize(emoji.emojize(text), use_aliases=True)
@pytest.fixture
def build_context():
class AsyncContext:
def __init__(self, use_app_stories=True):
self.use_app_stories = use_app_stories
async def __aenter__(self):
self.story = botstory.Story()
logger.debug('di.injector.root')
logger.debug(di.injector.root)
logger.debug('after create story')
self.fb_interface = self.story.use(
fb.FBInterface(page_access_token='qwerty'))
logger.debug('after use fb')
self.db_interface = self.story.use(mongodb.MongodbInterface(
uri=os.environ.get('MONGODB_URI', 'mongo'),
db_name=os.environ.get('MONGODB_TEST_DB', 'test'),
))
logger.debug('after use db')
self.http_interface = self.story.use(mockhttp.MockHttpInterface())
logger.debug('after use http')
if self.use_app_stories:
stories.setup(self.story)
logger.debug('after setup stories')
await self.story.start()
logger.debug('after stadsrt stories')
self.user = await self.db_interface.new_user(
facebook_user_id='facebook_user_id',
)
self.session = await self.db_interface.new_session(
user=self.user,
)
logger.debug('after create new user')
lists.lists_document.setup(self.db_interface.db)
self.lists_document = self.db_interface.db.get_collection('lists')
await self.lists_document.drop()
tasks.tasks_document.setup(self.db_interface.db)
self.tasks_collection = self.db_interface.db.get_collection('tasks')
await self.tasks_collection.drop()
return self
async def add_test_tasks(self, last_task_state='open', props=None):
if props is None:
props = [{}, {}, {}]
else:
props += [{}] * (3 - len(props))
props = [p if p is not None else {} for p in props]
return await self.add_tasks([{
'description': 'coffee with friends',
'user_id': self.user['_id'],
'state': props[0].get('state', 'done'),
'created_at': datetime.datetime(2017, 1, 1),
'updated_at': datetime.datetime(2017, 1, 1),
}, {
'description': 'go to gym',
'user_id': self.user['_id'],
'state': props[1].get('state', 'in progress'),
'created_at': datetime.datetime(2017, 1, 2),
'updated_at': datetime.datetime(2017, 1, 2),
}, {
'description': 'go to work',
'user_id': self.user['_id'],
'state': props[2].get('state', last_task_state),
'created_at': datetime.datetime(2017, 1, 3),
'updated_at': datetime.datetime(2017, 1, 3),
},
])
async def __aexit__(self, exc_type, exc_val, exc_tb):
await self.db_interface.clear_collections()
if hasattr(self, 'tasks_collection'):
await self.lists_document.drop()
await self.tasks_collection.drop()
await self.db_interface.db.get_collection('lists').drop()
await self.story.stop()
self.story.clear()
self.db_interface = None
async def add_tasks(self, new_tasks):
added_tasks = []
for t in new_tasks:
assert 'description' in t
assert 'user_id' in t
_id = await self.tasks_collection.insert(t)
task = await tasks.TaskDocument.objects.find_one({'_id': _id})
added_tasks.append(task)
return added_tasks
async def add_lists(self, new_lists):
for l in new_lists:
assert 'name' in l
assert 'user_id' in l
await self.lists_document.insert(l)
async def ask(self, data):
await self.fb_interface.handle(env.build_message(data))
async def dialog(self, dialog_sequence):
# even if it is only one phrase we add empty answer to get dialog
if len(dialog_sequence) == 1:
dialog_sequence.append(None)
for q_a in zip(
dialog_sequence[:-1][::2],
dialog_sequence[1:][::2],
):
question = q_a[0]
if question:
if isinstance(question, str):
question = {'text': all_emoji(
question
)}
if 'entry' in question:
await self.fb_interface.handle(question)
else:
await self.ask(question)
answer = q_a[1]
if answer:
self.receive_answer(answer)
def was_asked_with_quick_replies(self, options):
assert self.http_interface.post.call_count > 0
_, obj = self.http_interface.post.call_args
assert obj['json']['message']['quick_replies'] == options
def was_asked_with_without_quick_replies(self):
assert self.http_interface.post.call_count > 0
_, obj = self.http_interface.post.call_args
assert 'quick_replies' not in obj['json']['message']
def receive_answer(self, message, **kwargs):
assert self.http_interface.post.call_count > 0
_, obj = self.http_interface.post.call_args
assert 'json' in obj
assert obj['json']['recipient']['id'] == self.user['facebook_user_id']
assert 'message' in obj['json']
if 'text' in message:
assert obj['json']['message']['text'] == all_emoji(message['text'])
if 'quick_replies' in message:
assert 'quick_replies' in obj['json']['message']
logger.debug("obj['json']['message']['quick_replies']")
logger.debug(obj['json']['message']['quick_replies'])
for should_reply_action in message['quick_replies']:
logger.debug('check `{}`'.format(should_reply_action))
if isinstance(should_reply_action, str):
assert any(
reply['title'] == should_reply_action for reply in obj['json']['message']['quick_replies'])
elif isinstance(should_reply_action, dict):
assert any(
reply['title'] == should_reply_action['title'] and
reply['payload'] == should_reply_action['payload'] for reply in
obj['json']['message']['quick_replies'])
return
if isinstance(message, list):
list_of_messages = message
posted_list = obj['json']['message']['attachment']['payload']['elements']
for idx, message in enumerate(list_of_messages):
if isinstance(message, str):
assert posted_list[idx]['title'] == all_emoji(message)
else:
if 'title' in message:
assert posted_list[idx]['title'] == all_emoji(message['title'])
if 'subtitle' in message:
assert posted_list[idx]['subtitle'] == all_emoji(message['subtitle'])
if 'next_button' in kwargs:
next_button_title = kwargs['next_button']
if next_button_title is None:
assert 'buttons' not in obj['json']['message']['attachment']['payload'] or \
obj['json']['message']['attachment']['payload']['buttons'] == []
else:
assert obj['json']['message']['attachment']['payload']['buttons'][0][
'title'] == next_button_title
elif 'template_type' in message:
assert 'attachment' in obj['json']['message']
assert 'payload' in obj['json']['message']['attachment']
assert 'type' in obj['json']['message']['attachment']
assert obj['json']['message']['attachment']['type'] == 'template'
template_payload = obj['json']['message']['attachment']['payload']
assert template_payload['template_type'] == message['template_type']
template_elements = template_payload['elements']
assert template_elements[0]['title'] == message['title']
assert template_elements[0]['subtitle'] == message['subtitle']
assert template_elements[0]['buttons'] == message['buttons']
elif isinstance(message, str):
assert obj['json']['message']['text'] == all_emoji(message)
return AsyncContext
| mit |
kib357/osdusshorAwards | app.js | 374 | /**
* Created by kib357 on 04.03.2015.
*/
var express = require('express');
var compression = require('compression');
var app = express();
app.use(compression());
app.use(express.static(__dirname + '/dist'));
app.set('port', process.env.Port || 4000);
var server = app.listen(app.get('port'));
console.log("app.js up and running on port " + app.get('port'));
| mit |
guzzle/command | tests/ServiceClientTest.php | 5461 | <?php
namespace GuzzleHttp\Tests\Command\Guzzle;
use PHPUnit\Framework\TestCase;
use GuzzleHttp\Client as HttpClient;
use GuzzleHttp\Command\Command;
use GuzzleHttp\Command\CommandInterface;
use GuzzleHttp\Command\Exception\CommandException;
use GuzzleHttp\Command\Result;
use GuzzleHttp\Command\ServiceClient;
use GuzzleHttp\Exception\BadResponseException;
use GuzzleHttp\Handler\MockHandler;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Psr7\Response;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
use GuzzleHttp\Psr7\Request;
/**
* @covers \GuzzleHttp\Command\ServiceClient
*/
class ServiceClientTest extends TestCase
{
private function getServiceClient(array $responses)
{
return new ServiceClient(
new HttpClient([
'handler' => new MockHandler($responses)
]),
function (CommandInterface $command) {
$data = $command->toArray();
$data['action'] = $command->getName();
return new Request('POST', '/', [], http_build_query($data));
},
function (ResponseInterface $response, RequestInterface $request) {
$data = json_decode($response->getBody(), true);
parse_str($request->getBody(), $data['_request']);
return new Result($data);
}
);
}
public function testCanGetHttpClientAndHandlers()
{
$httpClient = new HttpClient();
$handlers = new HandlerStack();
$fn = function () {};
$serviceClient = new ServiceClient($httpClient, $fn, $fn, $handlers);
$this->assertSame($httpClient, $serviceClient->getHttpClient());
$this->assertSame($handlers, $serviceClient->getHandlerStack());
}
public function testExecuteCommandViaMagicMethod()
{
$client = $this->getServiceClient([
new Response(200, [], '{"foo":"bar"}'),
new Response(200, [], '{"foofoo":"barbar"}'),
]);
// Synchronous
$result1 = $client->doThatThingYouDo(['fizz' => 'buzz']);
$this->assertEquals('bar', $result1['foo']);
$this->assertEquals('buzz', $result1['_request']['fizz']);
$this->assertEquals('doThatThingYouDo', $result1['_request']['action']);
// Asynchronous
$result2 = $client->doThatThingOtherYouDoAsync(['fizz' => 'buzz'])->wait();
$this->assertEquals('barbar', $result2['foofoo']);
$this->assertEquals('doThatThingOtherYouDo', $result2['_request']['action']);
}
public function testCommandExceptionIsThrownWhenAnErrorOccurs()
{
$client = $this->getServiceClient([
new BadResponseException(
'Bad Response',
$this->getMockForAbstractClass(RequestInterface::class),
$this->getMockForAbstractClass(ResponseInterface::class)
),
]);
$this->expectException(CommandException::class);
$client->execute($client->getCommand('foo'));
}
public function testExecuteMultipleCommands()
{
// Set up commands to execute concurrently.
$generateCommands = function () {
yield new Command('capitalize', ['letter' => 'a']);
yield new Command('capitalize', ['letter' => '2']);
yield new Command('capitalize', ['letter' => 'z']);
};
// Setup a client with mock responses for the commands.
// Note: the second one will be a failed request.
$client = $this->getServiceClient([
new Response(200, [], '{"letter":"A"}'),
new BadResponseException(
'Bad Response',
$this->getMockForAbstractClass(RequestInterface::class),
new Response(200, [], '{"error":"Not a letter"}')
),
new Response(200, [], '{"letter":"Z"}'),
]);
// Setup fulfilled/rejected callbacks, just to confirm they are called.
$fulfilledFnCalled = false;
$rejectedFnCalled = false;
$options = [
'fulfilled' => function () use (&$fulfilledFnCalled) {
$fulfilledFnCalled = true;
},
'rejected' => function () use (&$rejectedFnCalled) {
$rejectedFnCalled = true;
},
];
// Execute multiple commands.
$results = $client->executeAll($generateCommands(), $options);
// Make sure the callbacks were called
$this->assertTrue($fulfilledFnCalled);
$this->assertTrue($rejectedFnCalled);
// Validate that the results are as expected.
$this->assertCount(3, $results);
$this->assertInstanceOf(Result::class, $results[0]);
$this->assertEquals('A', $results[0]['letter']);
$this->assertInstanceOf(CommandException::class, $results[1]);
$this->assertStringContainsString(
'Not a letter',
(string) $results[1]->getResponse()->getBody()
);
$this->assertInstanceOf(Result::class, $results[2]);
$this->assertEquals('Z', $results[2]['letter']);
}
public function testMultipleCommandsFailsForNonCommands()
{
$generateCommands = function () {
yield 'foo';
};
$this->expectException(\InvalidArgumentException::class);
$client = $this->getServiceClient([]);
$client->executeAll($generateCommands());
}
}
| mit |
ip28/ProductService | ProductService/ProductsRepository/Properties/AssemblyInfo.cs | 1407 | 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("ProductsRepository")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("ProductsRepository")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[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("b6761c2c-552f-4583-ba29-618e41caeb8d")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| mit |
Logiks/Logiks-TestKit | comps/rightSidebar.php | 3883 | <div id="right-sidebar" class="">
<div class="slimScrollDiv" style="position: relative; overflow: hidden; width: auto; height: 100%;">
<div class="sidebar-container" style="overflow: auto; width: auto; height: 100%;">
<ul class="nav nav-tabs navs-2">
<li class="active"><a data-toggle="tab" href="#tab-1" aria-expanded="true">
Active Queue
</a></li>
<li class=""><a data-toggle="tab" href="#tab-2" aria-expanded="false">
History
</a></li>
</ul>
<div class="tab-content">
<div id="tab-1" class="tab-pane active">
<div class="sidebar-title">
<h3> <i class="fa fa-tasks"></i> Test Queue</h3>
<small><i class="fa fa-tim"></i>You have 14 tests. 4 are completed.</small>
</div>
<ul class='sidebar-list'>
<li>
<a href="#">
<div class="small pull-right m-t-xs">9 hours ago</div>
<h4>Business valuation</h4>
It is a long established fact that a reader will be distracted.
</a>
</li>
<li>
<a href="#">
<div class="small pull-right m-t-xs">9 hours ago</div>
<h4>Business valuation</h4>
It is a long established fact that a reader will be distracted.
</a>
</li>
<li>
<a href="#">
<div class="small pull-right m-t-xs">9 hours ago</div>
<h4>Business valuation</h4>
It is a long established fact that a reader will be distracted.
</a>
</li>
</ul>
</div>
<div id="tab-2" class="tab-pane">
<div class="sidebar-title">
<h3> <i class="fa fa-cube"></i> Test History</h3>
<small><i class="fa fa-tim"></i>14 tests completed.</small>
</div>
<ul class='sidebar-list'>
<li>
<a href="#">
<span class="label label-success pull-right">SUCCESS</span><h4>Business valuation</h4>
It is a long established fact that a reader will be distracted.
<div class="small pull-right m-t-xs">9 hours ago</div>
</a>
</li>
<li>
<a href="#">
<span class="label label-danger pull-right">Failed</span><h4>Business valuation</h4>
It is a long established fact that a reader will be distracted.
<div class="small pull-right m-t-xs">9 hours ago</div>
</a>
</li>
<li>
<a href="#">
<span class="label label-warning pull-right">Warning</span><h4>Business valuation</h4>
It is a long established fact that a reader will be distracted.
<div class="small pull-right m-t-xs">9 hours ago</div>
</a>
</li>
</ul>
</div>
</div>
</div>
</div>
</div> | mit |
pombredanne/metamorphosys-desktop | metamorphosys/META/externals/HCDDES/src/FRODO/src/arch/win32/highres_timing.cpp | 5493 | /*** Included Header Files ***/
#include <Windows.h>
#include <assert.h>
#include <math.h>
#include <stdio.h>
#include "scheduler.h"
#ifdef __cplusplus
extern "C" {
#endif
/*****************************************************************************/
#define HRT_MAXOFFSETS 8
#define HRT_OFFSETGAIN 0.5
// Static Variables
static bool _hrtInitialized = false;
static bool _hrtFirstHyperperiod = true;
static LARGE_INTEGER _startAT = {0,0};
static LARGE_INTEGER _initAT = {0,0};
static LARGE_INTEGER _frequencyMS = {0,0};
static double _hrtOffsets[HRT_MAXOFFSETS];
static uint8_t _hrtNumOffsets = 0;
static double _hrtGain = 1.00;
/*** Externall Defined Variables and Functions ***/
extern SchedSchedulable *_nextTask;
extern void (*_SchedErrorHandler)(ErrorCode,void*,pfloat_t);
/*****************************************************************************/
/* Initialize the high resolution timer system */
void InitializeTime( void ) {
// Get the frequency - quit if there is an error
assert( ::QueryPerformanceFrequency( &_frequencyMS ) != 0 );
// Adjust frequency to milliseconds
_frequencyMS.QuadPart /= 1000;
// Also, make sure Windows time resolution is set the finest possible
TIMECAPS timeCaps;
timeGetDevCaps( &timeCaps, sizeof(TIMECAPS) );
timeBeginPeriod( timeCaps.wPeriodMin );
// Initialize the init and start times
::QueryPerformanceCounter( &_startAT );
_initAT = _startAT;
// Set the initialization flag
_hrtInitialized = true;
// Also set the first hyperperiod flag
_hrtFirstHyperperiod = true;
}
/* Reset the high resolution timer */
void ZeroTime( double desiredMS ) {
// Make sure clock has been initialized
assert( _hrtInitialized );
// Is this the first hyperperiod
if ( _hrtFirstHyperperiod ) {
// Just set the startAT clock
::QueryPerformanceCounter( &_startAT );
// Mark as no longer first hyperperiod
_hrtFirstHyperperiod = false;
}
// Otherwise...
else {
// Are there offsets to work with (avoid div by zero)
if ( _hrtNumOffsets != 0 ) {
// What is the average offset
uint8_t i = 0;
double offsetAvgMS = 0.0;
for ( ; i < _hrtNumOffsets; i++ ) offsetAvgMS += _hrtOffsets[i];
// Look out for div by zero
offsetAvgMS /= (double)_hrtNumOffsets;
// printf( "Average offset: %4.3f.\n", offsetAvgMS );
// Set the HRT Gain factor
desiredMS -= ( offsetAvgMS * HRT_OFFSETGAIN );
// Clear the offsets
_hrtNumOffsets = 0;
}
}
// Just increment Start clock by desiredMS
LONGLONG diffNS = (LONGLONG)( desiredMS * _frequencyMS.QuadPart );
_startAT.QuadPart += (LONGLONG)diffNS;
}
/* Get the amount of time (in ms) since the timer was last reset */
double GetTimeMS( void ) {
LARGE_INTEGER stop;
// Make sure clock has been initialized
assert( _hrtInitialized );
::QueryPerformanceCounter( &stop );
// Determine how much time has elapsed (take the Gain into account)
double time = (double)(stop.QuadPart - _startAT.QuadPart) / (double)_frequencyMS.QuadPart * _hrtGain;
// Convert to float and return
return time;
}
/* Return the time (in ms) since the last call to InitializeTime() */
double AbsoluteTimeMS( void ) {
LARGE_INTEGER stop;
// Make sure clock has been initialized
assert( _hrtInitialized );
::QueryPerformanceCounter( &stop );
double time = (double)(stop.QuadPart - _initAT.QuadPart) / (double)_frequencyMS.QuadPart;
// Convert to float and return
return time;
}
/* Let the timing system know that an event occured at a slightly different time than expected */
void SuggestOffset( double deltaMS ) {
// Make sure the is room for an additional offset
if ( _hrtNumOffsets == HRT_MAXOFFSETS - 1 ) return;
// Add the offset to the list
_hrtOffsets[_hrtNumOffsets++] = deltaMS;
}
/* Sleep until the specified amount of time has elapsed (measured using _startAT) */
double NanoSleep( double deadlineMS ) {
// Make sure clock has been initialized
assert( _hrtInitialized );
assert( deadlineMS >= 0.0 );
// Get the current time and determine sleep duration
double currentTimeMS = GetTimeMS();
// Make sure we are not calling this too late
if ( currentTimeMS > deadlineMS + SCHEDULER_RESOLUTION_MS ) {
// Signal an error has occured
_SchedErrorHandler( FS_ERR_SLEEPDEADLINEMISS, NULL, deadlineMS );
return currentTimeMS;
}
// Try sleeping that long - will not be accurate ( make sure differnce is positive )
DWORD sleepDuration = DWORD( floor( abs( deadlineMS - currentTimeMS ) ) );
DWORD retVal = SleepEx( sleepDuration, TRUE );
// See what the time is now and busy wait until the time is up
do {
currentTimeMS = GetTimeMS();
} while ( currentTimeMS < deadlineMS );
// Return the current time
return currentTimeMS;
}
/* Occupy this thread until the desired amount of time has elapsed */
double BusyWait( double durationMS ) {
double stopTimeMS = GetTimeMS() + durationMS;
double timeMS;
// Make sure clock has been initialized
assert( _hrtInitialized );
// Loop until desired duration has been reached
do {
// Get the current time
timeMS = GetTimeMS();
// Loop until timeMS is reached
} while ( timeMS < stopTimeMS );
// Return the current time
return timeMS;
}
/*****************************************************************************/
#ifdef __cplusplus
}
#endif
| mit |
gaoxiang12/slambook | ch4/useSophus/useSophus.cpp | 2642 | #include <iostream>
#include <cmath>
using namespace std;
#include <Eigen/Core>
#include <Eigen/Geometry>
#include "sophus/so3.h"
#include "sophus/se3.h"
int main( int argc, char** argv )
{
// 沿Z轴转90度的旋转矩阵
Eigen::Matrix3d R = Eigen::AngleAxisd(M_PI/2, Eigen::Vector3d(0,0,1)).toRotationMatrix();
Sophus::SO3 SO3_R(R); // Sophus::SO(3)可以直接从旋转矩阵构造
Sophus::SO3 SO3_v( 0, 0, M_PI/2 ); // 亦可从旋转向量构造
Eigen::Quaterniond q(R); // 或者四元数
Sophus::SO3 SO3_q( q );
// 上述表达方式都是等价的
// 输出SO(3)时,以so(3)形式输出
cout<<"SO(3) from matrix: "<<SO3_R<<endl;
cout<<"SO(3) from vector: "<<SO3_v<<endl;
cout<<"SO(3) from quaternion :"<<SO3_q<<endl;
// 使用对数映射获得它的李代数
Eigen::Vector3d so3 = SO3_R.log();
cout<<"so3 = "<<so3.transpose()<<endl;
// hat 为向量到反对称矩阵
cout<<"so3 hat=\n"<<Sophus::SO3::hat(so3)<<endl;
// 相对的,vee为反对称到向量
cout<<"so3 hat vee= "<<Sophus::SO3::vee( Sophus::SO3::hat(so3) ).transpose()<<endl; // transpose纯粹是为了输出美观一些
// 增量扰动模型的更新
Eigen::Vector3d update_so3(1e-4, 0, 0); //假设更新量为这么多
Sophus::SO3 SO3_updated = Sophus::SO3::exp(update_so3)*SO3_R;
cout<<"SO3 updated = "<<SO3_updated<<endl;
/********************萌萌的分割线*****************************/
cout<<"************我是分割线*************"<<endl;
// 对SE(3)操作大同小异
Eigen::Vector3d t(1,0,0); // 沿X轴平移1
Sophus::SE3 SE3_Rt(R, t); // 从R,t构造SE(3)
Sophus::SE3 SE3_qt(q,t); // 从q,t构造SE(3)
cout<<"SE3 from R,t= "<<endl<<SE3_Rt<<endl;
cout<<"SE3 from q,t= "<<endl<<SE3_qt<<endl;
// 李代数se(3) 是一个六维向量,方便起见先typedef一下
typedef Eigen::Matrix<double,6,1> Vector6d;
Vector6d se3 = SE3_Rt.log();
cout<<"se3 = "<<se3.transpose()<<endl;
// 观察输出,会发现在Sophus中,se(3)的平移在前,旋转在后.
// 同样的,有hat和vee两个算符
cout<<"se3 hat = "<<endl<<Sophus::SE3::hat(se3)<<endl;
cout<<"se3 hat vee = "<<Sophus::SE3::vee( Sophus::SE3::hat(se3) ).transpose()<<endl;
// 最后,演示一下更新
Vector6d update_se3; //更新量
update_se3.setZero();
update_se3(0,0) = 1e-4d;
Sophus::SE3 SE3_updated = Sophus::SE3::exp(update_se3)*SE3_Rt;
cout<<"SE3 updated = "<<endl<<SE3_updated.matrix()<<endl;
return 0;
} | mit |
openaq/openaq-fetch | adapters/slovenia.js | 3724 | 'use strict';
import { REQUEST_TIMEOUT } from '../lib/constants';
import { default as baseRequest } from 'request';
import { cloneDeep } from 'lodash';
import { default as moment } from 'moment-timezone';
import { convertUnits } from '../lib/utils';
import cheerio from 'cheerio';
const request = baseRequest.defaults({timeout: REQUEST_TIMEOUT});
exports.name = 'slovenia';
exports.fetchData = function (source, cb) {
request(source.url, function (err, res, body) {
if (err || res.statusCode !== 200) {
return cb({message: 'Failure to load data url.'});
}
// Wrap everything in a try/catch in case something goes wrong
try {
// Format the data
var data = formatData(body, source);
// Make sure the data is valid
if (data === undefined) {
return cb({message: 'Failure to parse data.'});
}
cb(null, data);
} catch (e) {
return cb({message: 'Unknown adapter error.'});
}
});
};
var formatData = function (data, source) {
var getDate = function (dateString) {
var date = moment.tz(dateString, 'YYYY-MM-DD HH:mm', 'Europe/Ljubljana');
return {utc: date.toDate(), local: date.format()};
};
var getUnit = function (parameter) {
var units = {
'so2': 'µg/m³',
'co': 'mg/m³',
'o3': 'µg/m³',
'no2': 'µg/m³',
'pm10': 'µg/m³'
};
return units[parameter];
};
// Load all the XML
var $ = cheerio.load(data, {xmlMode: true});
// Create measurements array
var measurements = [];
// There are a number of "postaja" elements in this XML.
// This is described (in Slovene) here: http://www.arso.gov.si/zrak/kakovost%20zraka/podatki/opis_ones_zrak_urni_xml.pdf
// Summarized below:
// <postaja> element contains:
// attributes: ge_dolzina=longitude ge_sirina=latitude
// elements:
// <merilno_mesto> - name of location
// <datum_od> - time of measurement start
// <datum_do> - time of measurement end
// <so2 > - hourly concentration of SO2 in µg/m³
// <co> - hourly concentration of CO in mg/m³
// <o3> - hourly concentration of O3 in µg/m³
// <no2> - hourly concentration of NO2 in µg/m³
// <pm10> - hourly concentration of PM10 in µg/m³
var baseObj = {
averagingPeriod: {'value': 1, 'unit': 'hours'},
attribution: [{
name: source.name,
url: source.sourceURL
}]
};
// Loop over each item and save the object
$('postaja').each(function (i, elem) {
var coordinates = {
latitude: parseFloat($(elem).attr('ge_sirina')),
longitude: parseFloat($(elem).attr('ge_dolzina'))
};
var date = getDate($(elem).children('datum_do').text());
var location = $(elem).children('merilno_mesto').text();
$(elem).children().each(function (i, e) {
// Currently only storing PM10 as the other measurements
// should be picked up by EEA.
if (this.tagName !== 'pm10') {
return;
}
var obj = cloneDeep(baseObj);
var unit = getUnit(this.tagName);
var value = parseFloat($(this).text());
if (unit === 'mg/m³') {
value = value * 1000;
}
if (unit && value) {
// Since there is limited information, both city &
// location will be set to same value.
obj.city = location;
obj.location = location;
obj.parameter = this.tagName;
obj.unit = 'µg/m³';
obj.value = value;
obj.coordinates = coordinates;
obj.date = date;
measurements.push(obj);
}
});
});
// Convert units to platform standard
measurements = convertUnits(measurements);
return {
name: source.name,
measurements: measurements
};
};
| mit |
investonline/adwords-api | src/Exceptions/TooManyKeywordsException.php | 224 | <?php
namespace InvestOnlineAdWordsApi\Exceptions;
use RuntimeException;
/**
* Class TooManyKeywordsException
* @package InvestOnlineAdWordsApi\Exceptions
*/
class TooManyKeywordsException extends RuntimeException
{
} | mit |
bartbastings/school | periode-6-2012/PTM32/prototype/stratumseindv2/includes/fbconnect.php | 97 | <?php
$app_id = "Your App ID/API Key goes here";
$app_secret = "Your App secret goes here";
?> | mit |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.