code
stringlengths 3
1.05M
| repo_name
stringlengths 4
116
| path
stringlengths 3
942
| language
stringclasses 30
values | license
stringclasses 15
values | size
int32 3
1.05M
|
---|---|---|---|---|---|
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;
/**
* Randomly generates Secret Santa assignments for a given group.
* <p>
* All valid possible assignments are equally likely to be generated (uniform distribution).
*
* @author Michael Zaccardo ([email protected])
*/
public class SecretSanta {
private static final Random random = new Random();
private static final String[] DEFAULT_NAMES = { "Rob", "Ally", "Angus", "Mike", "Shannon", "Greg", "Lewis", "Isabel" };
public static void main(final String[] args) {
final String[] names = getNamesToUse(args);
final List<Integer> assignments = generateAssignments(names.length);
printAssignmentsWithNames(assignments, names);
}
private static String[] getNamesToUse(final String[] args) {
if (args.length >= 2) {
return args;
} else {
System.out.println("Two or more names were not provided -- using default names.\n");
return DEFAULT_NAMES;
}
}
private static List<Integer> generateAssignments(final int size) {
final List<Integer> assignments = generateShuffledList(size);
while (!areValidAssignments(assignments)) {
Collections.shuffle(assignments, random);
}
return assignments;
}
private static List<Integer> generateShuffledList(final int size) {
final List<Integer> list = new ArrayList<>(size);
for (int i = 0; i < size; i++) {
list.add(i);
}
Collections.shuffle(list, random);
return list;
}
private static boolean areValidAssignments(final List<Integer> assignments) {
for (int i = 0; i < assignments.size(); i++) {
if (i == assignments.get(i)) {
return false;
}
}
return true;
}
private static void printAssignmentsWithNames(final List<Integer> assignments, final String[] names) {
for (int i = 0; i < assignments.size(); i++) {
System.out.println(names[i] + " --> " + names[assignments.get(i)]);
}
}
} | AetherWorks/SecretSanta | java/SecretSanta.java | Java | unlicense | 2,008 |
#include "fat.h"
#include "disk.h"
#include "malloc.h"
void read_fs(struct fat_fs *b) {
read_sector((unsigned char *) &(b->bpb), 0, 0);
b->total_sectors = b->bpb.n_sectors;
b->fat_size = b->bpb.spf;
b->root_size = ((b->bpb.n_dirents * 32)
+ (b->bpb.bps - 1)) / b->bpb.bps;
b->first_data = b->bpb.n_hidden
+ (b->bpb.n_fats * b->fat_size)
+ b->root_size;
b->first_fat = b->bpb.n_hidden;
b->total_data = b->total_sectors
- (b->bpb.n_hidden
+ (b->bpb.n_fats * b->fat_size)
+ b->root_size);
b->total_clusters = b->total_data / b->bpb.spc;
}
struct fat_dirent *read_root_directory(struct fat_fs *b) {
struct fat_dirent *r = malloc(sizeof(struct fat_dirent) * b->bpb.n_dirents);
unsigned char *data = (unsigned char *) r;
unsigned int sector = b->first_data - b->root_size + 1;
unsigned int i;
for(i = 0; i < b->root_size; i++)
read_sector(data + (i * 512), 0, sector + i);
return r;
}
void parse_filename(char fname[11], char name[9], char ext[4]) {
int i;
for(i = 0; i < 8; i++) {
name[i] = fname[i];
if(fname[i] == ' ') {
name[i] = 0;
break;
}
}
for(i = 0; i < 3; i++)
ext[i] = fname[i + 8];
name[8] = ext[3] = 0;
}
unsigned int sector_from_fat(struct fat_fs *b, unsigned short fat_offset) {
unsigned char *fat = malloc(b->fat_size * b->bpb.bps);
unsigned short cluster;
unsigned int r;
cluster = fat[fat_offset];
cluster |= fat[fat_offset + 1];
if(cluster >= 0xFFF8) r = -1;
else r = cluster * b->bpb.spc;
free(fat);
return r;
}
| Firewiz/fireOS | fat.c | C | unlicense | 1,548 |
<?php
include '../test/connect.php';
$conn = mysql_connect($dbhost,$dbuser,$dbpass)
or die ('Error connecting to mysql');
mysql_select_db($dbname);
if(isset($_GET['query'])) { $query = $_GET['query']; } else { $query = ""; }
if(isset($_GET['type'])) { $type = $_GET['type']; } else { $query = "count"; }
if($type == "count"){
$sql = mysql_query("SELECT count(gameid) FROM arcade_games WHERE MATCH(shortname, description, title) AGAINST('$query*' IN BOOLEAN MODE)");
$total = mysql_fetch_array($sql);
$num = $total[0];
echo $num;
}
?>
<table width="300px">
<?php
if($type == "results"){
$sql = mysql_query("SELECT shortname, title, description FROM arcade_games WHERE MATCH(shortname, title, description) AGAINST('$query*' IN BOOLEAN MODE)");
while($result_ar = mysql_fetch_array($sql)) {
$id = $result_ar['gameid'];
$squery = sprintf("SELECT * FROM arcade_highscores WHERE gamename = ('%s') ORDER by score DESC",
$id);
$sresult = mysql_query($squery);
$sresult_ar = mysql_fetch_assoc($sresult);
$image = $result_ar['stdimage'];
$name = $result_ar['shortname'];
$file = $result_ar['file'];
$width = $result_ar['width'];
$height = $result_ar['height'];
$champ = $sresult_ar['username'];
$cscore = $sresult_ar['score'];
?>
<tr>
<td><?php echo "<img src='http://www.12daysoffun.com/hustle/arcade/images/$image' />";?></td>
<td><?php echo ucwords($name);
echo "<br />";
echo"<a href='#' onClick=\"parent.location.href='gamescreen.php?game=$file&width=$width&height=$height'\">PLAY</a>";
?></td>
<td><?php
if ($result_ar['gameid'] = $sresult_ar['gamename']){
echo "<b>Champion: </b>";
echo $champ;
echo "<br />";
echo "High Score: ";
echo $cscore;
}else{
$champ = "None";
$cscore = 0;
echo "<b>Champion: </b>";
echo "none";
echo "<br />";
echo "High Score: ";
echo 0;
}
?> </td>
</tr>
<?php
$i+=1;
} //while
?>
</table>
<?
}
mysql_close($conn);
?> | dvelle/The-hustle-game-on-facebook-c.2010 | hustle/hustle/arcade/search.php | PHP | unlicense | 2,075 |
/* Taken from bootstrap: https://github.com/twitter/bootstrap/blob/master/less/tooltip.less */
.fade {
opacity: 0;
-webkit-transition: opacity 0.15s linear;
-moz-transition: opacity 0.15s linear;
-ms-transition: opacity 0.15s linear;
-o-transition: opacity 0.15s linear;
transition: opacity 0.15s linear;
}
.fade.in {
opacity: 1;
}
.tooltip {
position: absolute;
z-index: 1020;
display: block;
padding: 5px;
font-size: 11px;
opacity: 0;
filter: alpha(opacity=0);
visibility: visible;
}
.tooltip.in {
opacity: 0.8;
filter: alpha(opacity=80);
}
.tooltip.top {
margin-top: -2px;
}
.tooltip.right {
margin-left: 2px;
}
.tooltip.bottom {
margin-top: 2px;
}
.tooltip.left {
margin-left: -2px;
}
.tooltip.top .arrow {
bottom: 0;
left: 50%;
margin-left: -5px;
border-top: 5px solid #000000;
border-right: 5px solid transparent;
border-left: 5px solid transparent;
}
.tooltip.left .arrow {
top: 50%;
right: 0;
margin-top: -5px;
border-top: 5px solid transparent;
border-bottom: 5px solid transparent;
border-left: 5px solid #000000;
}
.tooltip.bottom .arrow {
top: 0;
left: 50%;
margin-left: -5px;
border-right: 5px solid transparent;
border-bottom: 5px solid #000000;
border-left: 5px solid transparent;
}
.tooltip.right .arrow {
top: 50%;
left: 0;
margin-top: -5px;
border-top: 5px solid transparent;
border-right: 5px solid #000000;
border-bottom: 5px solid transparent;
}
.tooltip-inner {
max-width: 200px;
padding: 3px 8px;
color: #ffffff;
text-align: center;
text-decoration: none;
background-color: #000000;
-webkit-border-radius: 4px;
-moz-border-radius: 4px;
border-radius: 4px;
}
.arrow {
position: absolute;
width: 0;
height: 0;
}
.popover {
position: absolute;
top: 0;
left: 0;
z-index: 1010;
display: none;
padding: 5px;
}
.popover.top {
margin-top: -5px;
}
.popover.right {
margin-left: 5px;
}
.popover.bottom {
margin-top: 5px;
}
.popover.left {
margin-left: -5px;
}
.popover.top .arrow {
bottom: 0;
left: 50%;
margin-left: -5px;
border-top: 5px solid #000000;
border-right: 5px solid transparent;
border-left: 5px solid transparent;
}
.popover.right .arrow {
top: 50%;
left: 0;
margin-top: -5px;
border-top: 5px solid transparent;
border-right: 5px solid #000000;
border-bottom: 5px solid transparent;
}
.popover.bottom .arrow {
top: 0;
left: 50%;
margin-left: -5px;
border-right: 5px solid transparent;
border-bottom: 5px solid #000000;
border-left: 5px solid transparent;
}
.popover.left .arrow {
top: 50%;
right: 0;
margin-top: -5px;
border-top: 5px solid transparent;
border-bottom: 5px solid transparent;
border-left: 5px solid #000000;
}
.popover-inner {
width: 280px;
padding: 3px;
overflow: hidden;
background: #000000;
background: rgba(0, 0, 0, 0.8);
-webkit-border-radius: 6px;
-moz-border-radius: 6px;
border-radius: 6px;
-webkit-box-shadow: 0 3px 7px rgba(0, 0, 0, 0.3);
-moz-box-shadow: 0 3px 7px rgba(0, 0, 0, 0.3);
box-shadow: 0 3px 7px rgba(0, 0, 0, 0.3);
}
.popover-title {
padding: 5px 10px 0px;
line-height: 1;
background-color: #f5f5f5;
border-bottom: 1px solid #eee;
-webkit-border-radius: 3px 3px 0 0;
-moz-border-radius: 3px 3px 0 0;
border-radius: 3px 3px 0 0;
margin: 0;
}
.popover-content {
padding: 5px 10px;
line-height: 1;
background-color: #ffffff;
-webkit-border-radius: 0 0 3px 3px;
-moz-border-radius: 0 0 3px 3px;
border-radius: 0 0 3px 3px;
-webkit-background-clip: padding-box;
-moz-background-clip: padding-box;
background-clip: padding-box;
}
.popover-content p,
.popover-content ul,
.popover-content ol {
margin-bottom: 0;
}
| solring/TWCompanyTree | website/static/lib/css/d3-bootstrap-plugins.css | CSS | unlicense | 3,823 |
package com.google.gson;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
class Gson$FutureTypeAdapter<T> extends TypeAdapter<T>
{
private TypeAdapter<T> delegate;
public T read(JsonReader paramJsonReader)
{
if (this.delegate == null)
throw new IllegalStateException();
return this.delegate.read(paramJsonReader);
}
public void setDelegate(TypeAdapter<T> paramTypeAdapter)
{
if (this.delegate != null)
throw new AssertionError();
this.delegate = paramTypeAdapter;
}
public void write(JsonWriter paramJsonWriter, T paramT)
{
if (this.delegate == null)
throw new IllegalStateException();
this.delegate.write(paramJsonWriter, paramT);
}
}
/* Location: E:\Progs\Dev\Android\Decompile\apktool\zssq\zssq-dex2jar.jar
* Qualified Name: com.google.gson.Gson.FutureTypeAdapter
* JD-Core Version: 0.6.0
*/ | clilystudio/NetBook | allsrc/com/google/gson/Gson$FutureTypeAdapter.java | Java | unlicense | 917 |
<?php
class EtendardVideo extends WP_Widget{
private $error = false;
private $novideo = false;
public function __construct(){
parent::__construct(
'EtendardVideo',
__('Etendard - Video', 'etendard'),
array('description'=>__('Add a video from Youtube, Dailymotion or Vimeo.', 'etendard'))
);
}
public function widget($args, $instance){
echo $args['before_widget'];
?>
<?php if (isset($instance['title']) && !empty($instance['title'])){
echo $args['before_title'] . apply_filters( 'widget_title', $instance['title'] ) . $args['after_title'];
} ?>
<?php if (isset($instance['video_link']) && $instance['video_link']!=""){ ?>
<div class="widget-video">
<?php echo wp_oembed_get($instance['video_link'], array('width'=>287)); ?>
</div>
<?php }else{ ?>
<p><?php _e('To display a video, please add a Youtube, Dailymotion or Vimeo URL in the widget settings.', 'etendard'); ?></p>
<?php } ?>
<?php
echo $args['after_widget'];
}
public function form($instance){
if ($this->error){
echo '<div class="error">';
_e('Please enter a valid url', 'etendard');
echo '</div>';
}
if ($this->novideo){
echo '<div class="error">';
_e('This video url doesn\'t seem to exist.', 'etendard');
echo '</div>';
}
$fields = array("title" => "", "video_link" => "");
if ( isset( $instance[ 'title' ] ) ) {
$fields['title'] = $instance[ 'title' ];
}
if ( isset( $instance[ 'video_link' ] ) ) {
$fields['video_link'] = $instance[ 'video_link' ];
}
?>
<p>
<label for="<?php echo $this->get_field_id( 'title' ); ?>"><?php _e( 'Title:', 'etendard' ); ?></label>
<input class="widefat" id="<?php echo $this->get_field_id( 'title' ); ?>" name="<?php echo $this->get_field_name( 'title' ); ?>" type="text" value="<?php echo esc_attr( $fields['title'] ); ?>">
</p>
<p>
<label for="<?php echo $this->get_field_id( 'video_link' ); ?>"><?php _e( 'Video URL (Youtube, Dailymotion or Vimeo):', 'etendard' ); ?></label>
<input class="widefat" id="<?php echo $this->get_field_id( 'video_link' ); ?>" name="<?php echo $this->get_field_name( 'video_link' ); ?>" type="url" value="<?php echo esc_attr( $fields['video_link'] ); ?>">
</p>
<?php
}
public function update($new_instance, $old_instance){
$new_instance['title'] = ( ! empty( $new_instance['title'] ) ) ? strip_tags( $new_instance['title'] ) : '';
// Check the video link
if(isset($new_instance['video_link']) && !empty($new_instance['video_link']) && !filter_var($new_instance['video_link'], FILTER_VALIDATE_URL)){
$new_instance['video_link'] = $old_instance['video_link'];
$this->error = true;
}else{
if(!wp_oembed_get($new_instance['video_link'])){
$new_instance['video_link'] = $old_instance['video_link'];
$this->novideo = true;
}else{
$new_instance['video_link'] = ( ! empty( $new_instance['video_link'] ) ) ? strip_tags( $new_instance['video_link'] ) : '';
}
}
return $new_instance;
}
}
if (!function_exists('etendard_video_widget_init')){
function etendard_video_widget_init(){
register_widget('EtendardVideo');
}
}
add_action('widgets_init', 'etendard_video_widget_init');
| Offirmo/base-wordpress | backupbuddy_backup/wp-content/themes/Etendard/admin/widgets/video.php | PHP | unlicense | 3,281 |
<?php $canon_options_frame = get_option('canon_options_frame'); ?>
<div class="outter-wrapper post-footer feature">
<div class="wrapper">
<div class="clearfix">
<div class="foot left"><?php echo $canon_options_frame['footer_text'] ?></div>
<div class="foot right">
<?php
if ($canon_options_frame['show_social_icons'] == "checked") {
get_template_part('inc/templates/header/template_header_element_social');
}
?>
</div>
</div>
</div>
</div>
| jameymcelveen/com.flyingtigersrc.www | wp-content/themes/sport/inc/templates/footer/template_footer_post.php | PHP | unlicense | 841 |
<!DOCTYPE html>
<html lang="en-ca">
<head>
<meta charset="utf-8">
<title>Mars · Planets of the Universe</title>
<link href="/css/main.css" rel="stylesheet">
<meta name="description" content="Mars is the fourth planet from the Sun and the second smallest planet in the Solar System.">
</head>
<body>
<header class="masthead ">
<h1>Planets of the Universe</h1>
<nav>
<ul class="nav nav-top">
<li><a href="/" class="">Home</a></li>
<li><a href="/planets/" class="current">Planets</a></li>
<li><a href="/news/" class="">News</a></li>
</ul>
</nav>
</header>
<strong>Planets</strong>
<nav>
<ul>
<li>
<a href="/planets/dwarf/" class="">Dwarf</a>
</li>
<li>
<a href="/planets/terrestrial/" class="current">Terrestrial</a>
</li>
<li>
<a href="/planets/gas-giant/" class="">Gas Giant</a>
</li>
</ul>
</nav>
<h1>Mars</h1>
<img src="/img/planets/mars.jpg" alt="Photo of Mars">
<dl>
<dt>Discoverer:</dt><dd>Galileo Galilei</dd>
<dt>Discovered:</dt><dd>1610</dd>
<dt>Orbital Period:</dt><dd>686 days</dd>
<dt>Mean Radius:</dt><dd>3396 km</dd>
<dt>Axial Tilt:</dt><dd>25°</dd>
</dl>
<p><em>Mars</em> is the fourth planet from the Sun and the second smallest planet in the Solar System. Mars is a terrestrial planet with a thin atmosphere, having surface features reminiscent both of the impact craters of the Moon and the volcanoes, valleys, deserts, and polar ice caps of Earth.</p>
<footer>
<nav>
<ul class="nav nav-bottom">
<li><a href="/" class="">Home</a></li>
<li><a href="/planets/" class="current">Planets</a></li>
<li><a href="/news/" class="">News</a></li>
</ul>
</nav>
<p>© 2013 Planets of the Universe</p>
</footer>
</body>
</html>
| anish7/anish7.github.io | _site/planets/terrestrial/mars.html | HTML | unlicense | 1,788 |
package com.smartgwt.mobile.client.widgets;
import com.google.gwt.resources.client.ImageResource;
public abstract class Action {
private ImageResource icon;
private int iconSize;
private String title;
private String tooltip;
public Action(String title) {
this.title = title;
}
public Action(ImageResource icon) {
this.icon = icon;
}
public Action(String title, ImageResource icon) {
this(title);
this.icon = icon;
}
public Action(String title, ImageResource icon, int iconSize) {
this(title, icon);
this.iconSize = iconSize;
}
public Action(String title, ImageResource icon, int iconSize, String tooltip) {
this(title, icon, iconSize);
this.tooltip = tooltip;
}
public final ImageResource getIcon() {
return icon;
}
public final int getIconSize() {
return iconSize;
}
public final String getTitle() {
return title;
}
public final String getTooltip() {
return tooltip;
}
public abstract void execute(ActionContext context);
}
| will-gilbert/SmartGWT-Mobile | mobile/src/main/java/com/smartgwt/mobile/client/widgets/Action.java | Java | unlicense | 1,126 |
class Enrollment < ActiveRecord::Base
belongs_to :student
belongs_to :course
end
| TSwimson/GA | week4/tue/active_record_associations/college/app/models/enrollment.rb | Ruby | unlicense | 85 |
import os
import sys
import string
import random
import math
#################################################
# State
balance = 0
def deposit(amount):
global balance
balance += amount
return balance
def withdraw(amount):
global balance
balance -= amount
return balance
#################################################
# Dict like
def make_account():
return {'balance': 0}
def deposit(account, amount):
account['balance'] += amount
return account['balance']
def withdraw(account, amount):
account['balance'] -= amount
return account['balance']
# >>> a = make_account()
# >>> b = make_account()
# >>> deposit(a, 100)
# 100
# >>> deposit(b, 50)
# 50
# >>> withdraw(b, 10)
# 40
# >>> withdraw(a, 10)
# 90
#################################################
# Class
class BankAccount:
def __init__(self, balance=0):
self.balance = balance
def withdraw(self, amount):
self.balance -= amount
return self.balance
def deposit(self, amount):
self.balance += amount
return self.balance
# >>> a = BankAccount()
# >>> b = BankAccount()
# >>> a.deposit(100)
# 100
# >>> b.deposit(50)
# 50
# >>> b.withdraw(10)
# 40
# >>> a.withdraw(10)
# 90
#################################################
# Inheritance
class MinimumBalanceAccount(BankAccount):
def __init__(self, minimum_balance):
BankAccount.__init__(self)
self.minimum_balance = minimum_balance
def withdraw(self, amount):
if self.balance - amount < self.minimum_balance:
print('Sorry, minimum balance must be maintained.')
else:
BankAccount.withdraw(self, amount)
# >>> a = MinimumBalanceAccount(0)
# >>> a.deposit(100)
# 100
# >>> b.withdraw(101)
# 'Sorry, minimum balance must be maintained.'
########################################
# Mangling, Exceptions
def generate_id(n=16):
alphabet = string.ascii_letters + string.digits
return ''.join(random.choice(alphabet) for _ in range(n))
class WithdrawError(Exception):
"""Not enough money"""
def __init__(self, amount):
super().__init__()
self.amount = amount
class AdvancedBankAccount:
MAX_BALANCE = 2 ** 64
def __init__(self):
self._balance = 0
self.__id = generate_id()
def withdraw(self, amount):
if not isinstance(amount, int):
raise ValueError
if self._balance < amount:
raise WithdrawError(amount)
self._balance -= amount
return self._balance
def deposit(self, amount):
self._balance += amount
return self._balance
def get_max_balance():
return AdvancedBankAccount.MAX_BALANCE
if __name__ == '__main__':
a = AdvancedBankAccount()
b = a
c = AdvancedBankAccount()
a.deposit(10)
# AdvancedBankAccount.deposit(a, 10) # the same
print('UNACCEPTABLE! b balance:', b._balance)
# print(b.__id) # error, name mangling
a.get_id = lambda self: self.__id
# print(a.get_id()) # TypeError
# print(a.get_id(a)) # AttributeError
################################################
# UNACCEPTABLE!
print("UNACCEPTABLE! b id:", b._AdvancedBankAccount__id) # name unmangling
# static
AdvancedBankAccount.MAX_BALANCE = 2 ** 32
print('max balance:', AdvancedBankAccount.get_max_balance())
a.MAX_BALANCE = 2 ** 64
print('a max: {}, c max: {}'.format(a.MAX_BALANCE,
c.MAX_BALANCE))
################################################
# Exceptions
# in module import
try:
a.withdraw("100")
except:
pass
# UNACCEPTIBLE!
try:
a.withdraw(100)
except WithdrawError as e:
pass
try:
a.withdraw(100)
except (ValueError, WithdrawError) as e:
print('exception raised')
else:
print('no exception')
finally:
print('Finally')
def tricky():
try:
print('Tricky called')
return 1
finally:
print('Tricky finally called')
return 42
return 0
print(tricky())
# how about with statement?
# module is object -> import
class Shape:
def area(self):
raise NotImplementedError
class Circle(Shape):
def __init__(self, radius):
self.radius = radius
def area(self):
return math.pi * self.radius ** 2
class Square(Shape):
def __init__(self, side):
self.side = side
def area(self):
return self.side ** 2
if __name__ == "__main__":
a = [Square(10), Circle(2)]
s = sum(s.area() for s in a)
print(s)
| SPbAU-ProgrammingParadigms/materials | python_2/common_objects.py | Python | unlicense | 4,690 |
//------------------------------------------------------------------------------
// <auto-generated>
// 此代码由工具生成。
// 运行时版本: 2.0.50727.42
//
// 对此文件的更改可能会导致不正确的行为,并且如果
// 重新生成代码,这些更改将丢失。
// </auto-generated>
//------------------------------------------------------------------------------
namespace Maticsoft.Web
{
public partial class ValidateCode
{
/// <summary>
/// form1 控件。
/// </summary>
/// <remarks>
/// 自动生成的字段。
/// 若要进行修改,请将字段声明从设计器文件移到代码隐藏文件。
/// </remarks>
protected global::System.Web.UI.HtmlControls.HtmlForm form1;
}
}
| nature-track/wenCollege-CSharp | Web/ValidateCode.aspx.designer.cs | C# | unlicense | 814 |
'use strict';
var app = angular.module('App', ['App.controller']);
| mirzadelic/django-social-example | django_social_example/django_app/public/js/app/app.js | JavaScript | unlicense | 68 |
{% extends "base.html" %}
{% block content %}
<div class="row" ng-controller="HomepageController">
<div class="posts">
<ul>
<div class="post" ng-repeat="post in posts">
<heading ng-bind="post.title"></heading>
<content ng-bind="post.content"></content>
</div>
<div class="navbar-form">
<input type="text" ng-model="input_post.title">
<input type="text" ng-model="input_post.content">
<button ng-click="createPost(input_post.title, input_post.content)" type="submit" class="btn">Create Post</button>
</div>
</ul>
</div>
<aside class="subreddits">
<uib-tabset vertical="true" type="pills">
<uib-tab heading="global" select="refreshPosts('global')"></uib-tab>
<uib-tab heading="{[{subreddit.title}]}" select="refreshPosts(subreddit.id)" ng-repeat="subreddit in subreddits">{[{ subreddit.description }]}</uib-tab>
</uib-tabset>
<div class="navbar-form">
<input type="text" ng-model="input_sub.title">
<input type="text" ng-model="input_sub.description">
<button ng-click="createSubreddit(input_sub.title, input_sub.description)" type="submit" class="btn">Create Subreddit</button>
</div>
</aside>
</div>
{% endblock content %}
| agile-course/news_feed | news_feed/templates/pages/home.html | HTML | unlicense | 1,377 |
/* **********************************************************************
/*
* NOTE: This copyright does *not* cover user programs that use Hyperic
* program services by normal system calls through the application
* program interfaces provided as part of the Hyperic Plug-in Development
* Kit or the Hyperic Client Development Kit - this is merely considered
* normal use of the program, and does *not* fall under the heading of
* "derived work".
*
* Copyright (C) [2004-2012], VMware, Inc.
* This file is part of Hyperic.
*
* Hyperic is free software; you can redistribute it and/or modify
* it under the terms version 2 of the GNU General Public License as
* published by the Free Software Foundation. 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.
*/
package org.hyperic.tools.ant;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class PropertiesFileMergerTask extends Properties{
private static Method saveConvertMethod ;
private String fileContent ;
private Map<String,String[]> delta ;
private boolean isLoaded ;
static {
try{
saveConvertMethod = Properties.class.getDeclaredMethod("saveConvert", String.class, boolean.class, boolean.class) ;
saveConvertMethod.setAccessible(true) ;
}catch(Throwable t) {
throw (t instanceof RuntimeException ? (RuntimeException) t: new RuntimeException(t)) ;
}//EO catch block
}//EO static block
public PropertiesFileMergerTask() {
this.delta = new HashMap<String, String[]>() ;
}//EOM
@Override
public synchronized Object put(Object key, Object value) {
Object oPrevious = null ;
try{
oPrevious = super.put(key, value);
if(this.isLoaded && !value.equals(oPrevious)) this.delta.put(key.toString(), new String[] { value.toString(), (String) oPrevious}) ;
return oPrevious ;
}catch(Throwable t) {
t.printStackTrace() ;
throw new RuntimeException(t) ;
}//EO catch block
}//EOM
@Override
public final synchronized Object remove(Object key) {
final Object oExisting = super.remove(key);
this.delta.remove(key) ;
return oExisting ;
}//EOM
public static final PropertiesFileMergerTask load(final File file) throws IOException {
InputStream fis = null, fis1 = null ;
try{
if(!file.exists()) throw new IOException(file + " does not exist or is not readable") ;
//else
final PropertiesFileMergerTask properties = new PropertiesFileMergerTask() ;
fis = new FileInputStream(file) ;
//first read the content into a string
final byte[] arrFileContent = new byte[(int)fis.available()] ;
fis.read(arrFileContent) ;
properties.fileContent = new String(arrFileContent) ;
fis1 = new ByteArrayInputStream(arrFileContent) ;
properties.load(fis1);
// System.out.println(properties.fileContent);
return properties ;
}catch(Throwable t) {
throw (t instanceof IOException ? (IOException)t : new IOException(t)) ;
}finally{
if(fis != null) fis.close() ;
if(fis1 != null) fis1.close() ;
}//EO catch block
}//EOM
@Override
public synchronized void load(InputStream inStream) throws IOException {
try{
super.load(inStream);
}finally{
this.isLoaded = true ;
}//EO catch block
}//EOm
public final void store(final File outputFile, final String comments) throws IOException {
if(this.delta.isEmpty()) return ;
FileOutputStream fos = null ;
String key = null, value = null ;
Pattern pattern = null ;
Matcher matcher = null ;
String[] arrValues = null;
try{
for(Map.Entry<String,String[]> entry : this.delta.entrySet()) {
key = (String) saveConvertMethod.invoke(this, entry.getKey(), true/*escapeSpace*/, true /*escUnicode*/);
arrValues = entry.getValue() ;
value = (String) saveConvertMethod.invoke(this, arrValues[0], false/*escapeSpace*/, true /*escUnicode*/);
//if the arrValues[1] == null then this is a new property
if(arrValues[1] == null) {
this.fileContent = this.fileContent + "\n" + key + "=" + value ;
}else {
//pattern = Pattern.compile(key+"\\s*=(\\s*.*\\s*)"+ arrValues[1].replaceAll("\\s+", "(\\\\s*.*\\\\s*)") , Pattern.MULTILINE) ;
pattern = Pattern.compile(key+"\\s*=.*\n", Pattern.MULTILINE) ;
matcher = pattern.matcher(this.fileContent) ;
this.fileContent = matcher.replaceAll(key + "=" + value) ;
}//EO else if existing property
System.out.println("Adding/Replacing " + key + "-->" + arrValues[1] + " with: " + value) ;
}//EO while there are more entries ;
fos = new FileOutputStream(outputFile) ;
fos.write(this.fileContent.getBytes()) ;
}catch(Throwable t) {
throw (t instanceof IOException ? (IOException)t : new IOException(t)) ;
}finally{
if(fos != null) {
fos.flush() ;
fos.close() ;
}//EO if bw was initialized
}//EO catch block
}//EOM
public static void main(String[] args) throws Throwable {
///FOR DEBUG
String s = " 1 2 4 sdf \\\\\nsdfsd" ;
final Pattern pattern = Pattern.compile("test.prop2\\s*=.*(?:\\\\?\\s*)(\n)" , Pattern.MULTILINE) ;
final Matcher matcher = pattern.matcher("test.prop2="+s) ;
System.out.println(matcher.replaceAll("test.prop2=" + "newvalue$1")) ;
///FOR DEBUG
if(true) return ;
final String path = "/tmp/confs/hq-server-46.conf" ;
final File file = new File(path) ;
final PropertiesFileMergerTask properties = PropertiesFileMergerTask.load(file) ;
/* final Pattern pattern = Pattern.compile("test.prop1\\s*=this(\\s*.*\\s*)is(\\s*.*\\s*)the(\\s*.*\\s*)value" ,
Pattern.MULTILINE) ;
final Matcher matcher = pattern.matcher(properties.fileContent) ;
System.out.println( matcher.replaceAll("test.prop1=new value") ) ;
System.out.println("\n\n--> " + properties.get("test.prop1")) ;*/
final String overridingConfPath = "/tmp/confs/hq-server-5.conf" ;
//final Properties overrdingProperties = new Properties() ;
final FileInputStream fis = new FileInputStream(overridingConfPath) ;
properties.load(fis) ;
fis.close() ;
///properties.putAll(overrdingProperties) ;
final String outputPath = "/tmp/confs/output-hq-server.conf" ;
final File outputFile = new File(outputPath) ;
final String comments = "" ;
properties.store(outputFile, comments) ;
}//EOM
}//EOC
| cc14514/hq6 | hq-installer/src/main/java/org/hyperic/tools/ant/PropertiesFileMergerTask.java | Java | unlicense | 8,153 |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.3.1"/>
<title>wf: login_dlg Class Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="dynsections.js"></script>
<link href="navtree.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="resize.js"></script>
<script type="text/javascript" src="navtree.js"></script>
<script type="text/javascript">
$(document).ready(initResizable);
$(window).load(resizeHeight);
</script>
<link href="search/search.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="search/search.js"></script>
<script type="text/javascript">
$(document).ready(function() { searchBox.OnSelectItem(0); });
</script>
<link href="doxygen.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="top"><!-- do not remove this div, it is closed by doxygen! -->
<div id="titlearea">
<table cellspacing="0" cellpadding="0">
<tbody>
<tr style="height: 56px;">
<td style="padding-left: 0.5em;">
<div id="projectname">wf
</div>
</td>
</tr>
</tbody>
</table>
</div>
<!-- end header part -->
<!-- Generated by Doxygen 1.8.3.1 -->
<script type="text/javascript">
var searchBox = new SearchBox("searchBox", "search",false,'Search');
</script>
<div id="navrow1" class="tabs">
<ul class="tablist">
<li><a href="index.html"><span>Main Page</span></a></li>
<li class="current"><a href="annotated.html"><span>Classes</span></a></li>
<li><a href="files.html"><span>Files</span></a></li>
<li>
<div id="MSearchBox" class="MSearchBoxInactive">
<span class="left">
<img id="MSearchSelect" src="search/mag_sel.png"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
alt=""/>
<input type="text" id="MSearchField" value="Search" accesskey="S"
onfocus="searchBox.OnSearchFieldFocus(true)"
onblur="searchBox.OnSearchFieldFocus(false)"
onkeyup="searchBox.OnSearchFieldChange(event)"/>
</span><span class="right">
<a id="MSearchClose" href="javascript:searchBox.CloseResultsWindow()"><img id="MSearchCloseImg" border="0" src="search/close.png" alt=""/></a>
</span>
</div>
</li>
</ul>
</div>
<div id="navrow2" class="tabs2">
<ul class="tablist">
<li><a href="annotated.html"><span>Class List</span></a></li>
<li><a href="classes.html"><span>Class Index</span></a></li>
<li><a href="hierarchy.html"><span>Class Hierarchy</span></a></li>
<li><a href="functions.html"><span>Class Members</span></a></li>
</ul>
</div>
</div><!-- top -->
<div id="side-nav" class="ui-resizable side-nav-resizable">
<div id="nav-tree">
<div id="nav-tree-contents">
<div id="nav-sync" class="sync"></div>
</div>
</div>
<div id="splitbar" style="-moz-user-select:none;"
class="ui-resizable-handle">
</div>
</div>
<script type="text/javascript">
$(document).ready(function(){initNavTree('classlogin__dlg.html','');});
</script>
<div id="doc-content">
<!-- window showing the filter options -->
<div id="MSearchSelectWindow"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
onkeydown="return searchBox.OnSearchSelectKey(event)">
<a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(0)"><span class="SelectionMark"> </span>All</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(1)"><span class="SelectionMark"> </span>Classes</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(2)"><span class="SelectionMark"> </span>Functions</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(3)"><span class="SelectionMark"> </span>Variables</a></div>
<!-- iframe showing the search results (closed by default) -->
<div id="MSearchResultsWindow">
<iframe src="javascript:void(0)" frameborder="0"
name="MSearchResults" id="MSearchResults">
</iframe>
</div>
<div class="header">
<div class="summary">
<a href="#pub-methods">Public Member Functions</a> |
<a href="#pub-attribs">Public Attributes</a> |
<a href="#pro-static-attribs">Static Protected Attributes</a> |
<a href="classlogin__dlg-members.html">List of all members</a> </div>
<div class="headertitle">
<div class="title">login_dlg Class Reference</div> </div>
</div><!--header-->
<div class="contents">
<p>Inherits wxDialog.</p>
<table class="memberdecls">
<tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="pub-methods"></a>
Public Member Functions</h2></td></tr>
<tr class="memitem:add5ed4d04d17a6682e52dc7c945537a6"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="add5ed4d04d17a6682e52dc7c945537a6"></a>
 </td><td class="memItemRight" valign="bottom"><b>login_dlg</b> (wxWindow *parent=0, wxWindowID id=wxID_ANY, const wxPoint &pos=wxDefaultPosition, const wxSize &size=wxDefaultSize)</td></tr>
<tr class="separator:add5ed4d04d17a6682e52dc7c945537a6"><td class="memSeparator" colspan="2"> </td></tr>
</table><table class="memberdecls">
<tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="pub-attribs"></a>
Public Attributes</h2></td></tr>
<tr class="memitem:a493dfba34a083a868b73b1ab792652c6"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a493dfba34a083a868b73b1ab792652c6"></a>
wxStaticText * </td><td class="memItemRight" valign="bottom"><b>st_message</b></td></tr>
<tr class="separator:a493dfba34a083a868b73b1ab792652c6"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:af488e56655cbe86da7c8ff99da85e416"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="af488e56655cbe86da7c8ff99da85e416"></a>
wxCheckBox * </td><td class="memItemRight" valign="bottom"><b>cb_save</b></td></tr>
<tr class="separator:af488e56655cbe86da7c8ff99da85e416"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a75ac77e66704c675eeeebb02367c0906"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a75ac77e66704c675eeeebb02367c0906"></a>
wxStaticText * </td><td class="memItemRight" valign="bottom"><b>StaticText2</b></td></tr>
<tr class="separator:a75ac77e66704c675eeeebb02367c0906"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:aefe2d280e7d21736f6ce91d804dc8705"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="aefe2d280e7d21736f6ce91d804dc8705"></a>
wxButton * </td><td class="memItemRight" valign="bottom"><b>Button1</b></td></tr>
<tr class="separator:aefe2d280e7d21736f6ce91d804dc8705"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:ab489b0475d1ce8b138619f861b4b2894"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="ab489b0475d1ce8b138619f861b4b2894"></a>
wxTextCtrl * </td><td class="memItemRight" valign="bottom"><b>tc_user</b></td></tr>
<tr class="separator:ab489b0475d1ce8b138619f861b4b2894"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:aa8a177968c530e105fcd846b3d69d62f"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="aa8a177968c530e105fcd846b3d69d62f"></a>
wxStaticText * </td><td class="memItemRight" valign="bottom"><b>StaticText1</b></td></tr>
<tr class="separator:aa8a177968c530e105fcd846b3d69d62f"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a9c5cb50ae85eb958d8a9e9390b1b6308"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a9c5cb50ae85eb958d8a9e9390b1b6308"></a>
wxButton * </td><td class="memItemRight" valign="bottom"><b>Button2</b></td></tr>
<tr class="separator:a9c5cb50ae85eb958d8a9e9390b1b6308"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a5df1d07c40d7a23f82fda07a6cd97325"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a5df1d07c40d7a23f82fda07a6cd97325"></a>
wxTextCtrl * </td><td class="memItemRight" valign="bottom"><b>tc_pwd</b></td></tr>
<tr class="separator:a5df1d07c40d7a23f82fda07a6cd97325"><td class="memSeparator" colspan="2"> </td></tr>
</table><table class="memberdecls">
<tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="pro-static-attribs"></a>
Static Protected Attributes</h2></td></tr>
<tr class="memitem:a4d73ea73d0699260873bc77116456b4d"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a4d73ea73d0699260873bc77116456b4d"></a>
static const long </td><td class="memItemRight" valign="bottom"><b>ID_STATICTEXT1</b> = wxNewId()</td></tr>
<tr class="separator:a4d73ea73d0699260873bc77116456b4d"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a546f4161b9dab01b809e733122ad97df"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a546f4161b9dab01b809e733122ad97df"></a>
static const long </td><td class="memItemRight" valign="bottom"><b>ID_STATICTEXT2</b> = wxNewId()</td></tr>
<tr class="separator:a546f4161b9dab01b809e733122ad97df"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a429cdbcca129440ba6d6a301a27293da"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a429cdbcca129440ba6d6a301a27293da"></a>
static const long </td><td class="memItemRight" valign="bottom"><b>ID_TEXTCTRL_USER</b> = wxNewId()</td></tr>
<tr class="separator:a429cdbcca129440ba6d6a301a27293da"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:acd6bf048bfbfa405da257b03789ede42"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="acd6bf048bfbfa405da257b03789ede42"></a>
static const long </td><td class="memItemRight" valign="bottom"><b>ID_TEXTCTRL_PWD</b> = wxNewId()</td></tr>
<tr class="separator:acd6bf048bfbfa405da257b03789ede42"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:abfc72bf4a0140e5741916cfd85df96c9"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="abfc72bf4a0140e5741916cfd85df96c9"></a>
static const long </td><td class="memItemRight" valign="bottom"><b>ID_CHECKBOX_SAVE</b> = wxNewId()</td></tr>
<tr class="separator:abfc72bf4a0140e5741916cfd85df96c9"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:ad484da6409488c8a4e1151ef9d1174c0"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="ad484da6409488c8a4e1151ef9d1174c0"></a>
static const long </td><td class="memItemRight" valign="bottom"><b>ID_BUTTON1</b> = wxNewId()</td></tr>
<tr class="separator:ad484da6409488c8a4e1151ef9d1174c0"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a8f805bf6bce5f2ecc340bf2103dd68a4"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a8f805bf6bce5f2ecc340bf2103dd68a4"></a>
static const long </td><td class="memItemRight" valign="bottom"><b>ID_BUTTON2</b> = wxNewId()</td></tr>
<tr class="separator:a8f805bf6bce5f2ecc340bf2103dd68a4"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a2e2f7ead14f6e24e32782fdcfcf25b61"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a2e2f7ead14f6e24e32782fdcfcf25b61"></a>
static const long </td><td class="memItemRight" valign="bottom"><b>ID_STATICTEXT3</b> = wxNewId()</td></tr>
<tr class="separator:a2e2f7ead14f6e24e32782fdcfcf25b61"><td class="memSeparator" colspan="2"> </td></tr>
</table>
<hr/>The documentation for this class was generated from the following files:<ul>
<li><a class="el" href="login__dlg_8h_source.html">login_dlg.h</a></li>
<li>login_dlg.cpp</li>
</ul>
</div><!-- contents -->
</div><!-- doc-content -->
<!-- start footer part -->
<div id="nav-path" class="navpath"><!-- id is needed for treeview function! -->
<ul>
<li class="navelem"><a class="el" href="classlogin__dlg.html">login_dlg</a></li>
<li class="footer">Generated on Tue Nov 24 2015 14:16:31 for wf by
<a href="http://www.doxygen.org/index.html">
<img class="footer" src="doxygen.png" alt="doxygen"/></a> 1.8.3.1 </li>
</ul>
</div>
</body>
</html>
| mikewolfli/workflow | doxygen/html/classlogin__dlg.html | HTML | unlicense | 12,693 |
package com.sochat.client;
import java.math.BigInteger;
import java.security.GeneralSecurityException;
import java.security.KeyFactory;
import java.security.PublicKey;
import java.security.spec.RSAPublicKeySpec;
public class ServerPublicKey {
public static PublicKey getServerPublicKey(String publicKeyModulus, String publicKeyExponent)
throws GeneralSecurityException {
BigInteger modulus = new BigInteger(publicKeyModulus, 16);
BigInteger exponent = new BigInteger(publicKeyExponent, 16);
RSAPublicKeySpec pubKeySpec = new RSAPublicKeySpec(modulus, exponent);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
return keyFactory.generatePublic(pubKeySpec);
}
}
| ovaskevich/sochat | src/com/sochat/client/ServerPublicKey.java | Java | unlicense | 732 |
package main
type FluxConfig struct {
Iam string `toml:"iam"`
Url string `toml:"url"`
Port int `toml:"port"`
Logdir string `toml:"logdir"`
Balancer FluxCluster `toml:"cluster"`
//Jwts []JwtAuth `toml:"jwt"`
}
type JwtAuth struct {
RequiredClaims []JwtClaim `toml:"claim"`
DecryptionSecret string `toml:"secret"`
}
type JwtClaim struct {
Key string `toml:"key"`
Value string `toml:"value"`
}
type FluxCluster struct {
Name string `toml:"name"`
BalancerAddress string `toml:"address"`
BalancerPort int `toml:"port"`
Scramble bool `toml:"scramble"`
}
| zerocruft/flux | config.go | GO | unlicense | 645 |
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using BeatManagement;
public class InitialBuildingEntryAnimation : Task
{
private TaskManager subtaskManager;
private float baseStaggerTime;
private float structStaggerTime;
private float terrainStaggerTime;
private bool run_tasks = false;
protected override void Init()
{
baseStaggerTime = Services.Clock.EighthLength();
structStaggerTime = Services.Clock.SixteenthLength();
terrainStaggerTime = Services.Clock.ThirtySecondLength();
subtaskManager = new TaskManager();
for (int i = 0; i < 2; i++)
{
Task dropTask = new Wait(baseStaggerTime * i);
dropTask.Then(new BuildingDropAnimation(Services.GameManager.Players[i].mainBase));
subtaskManager.Do(dropTask);
}
for (int i = 0; i < Services.MapManager.structuresOnMap.Count; i++)
{
Task dropTask = new Wait((structStaggerTime * i) + (baseStaggerTime * 2));
dropTask.Then(new BuildingDropAnimation(Services.MapManager.structuresOnMap[i]));
subtaskManager.Do(dropTask);
}
for (int i = 0; i < Services.MapManager.terrainOnMap.Count; i++)
{
Task dropTask = new Wait((terrainStaggerTime * i) + (baseStaggerTime * 2));
dropTask.Then(new BuildingDropAnimation(Services.MapManager.terrainOnMap[i]));
subtaskManager.Do(dropTask);
}
// Task waitTask = new Wait((structStaggerTime * Services.MapManager.structuresOnMap.Count) + (baseStaggerTime * 2));
// waitTask.Then(new ActionTask(() => { SetStatus(TaskStatus.Success); }));
//subtaskManager.Do(waitTask);
Services.Clock.SyncFunction(() => { run_tasks = true; }, Clock.BeatValue.Quarter);
}
internal override void Update()
{
if (run_tasks)
{
subtaskManager.Update();
if (subtaskManager.tasksInProcessCount == 0)
SetStatus(TaskStatus.Success);
}
}
}
| chrsjwilliams/RTS_Blokus | Assets/Scripts/Pieces/Tasks/InitialBuildingEntryAnimation.cs | C# | unlicense | 2,097 |
<h3>Public products 1</h3> | dekloni/MarketPlace | MarketPlaceUI/public-products.html | HTML | unlicense | 29 |
// https://github.com/KubaO/stackoverflown/tree/master/questions/html-get-24965972
#include <QtNetwork>
#include <functional>
void htmlGet(const QUrl &url, const std::function<void(const QString&)> &fun) {
QScopedPointer<QNetworkAccessManager> manager(new QNetworkAccessManager);
QNetworkReply *response = manager->get(QNetworkRequest(QUrl(url)));
QObject::connect(response, &QNetworkReply::finished, [response, fun]{
response->deleteLater();
response->manager()->deleteLater();
if (response->error() != QNetworkReply::NoError) return;
auto const contentType =
response->header(QNetworkRequest::ContentTypeHeader).toString();
static QRegularExpression re("charset=([!-~]+)");
auto const match = re.match(contentType);
if (!match.hasMatch() || 0 != match.captured(1).compare("utf-8", Qt::CaseInsensitive)) {
qWarning() << "Content charsets other than utf-8 are not implemented yet:" << contentType;
return;
}
auto const html = QString::fromUtf8(response->readAll());
fun(html); // do something with the data
}) && manager.take();
}
int main(int argc, char *argv[])
{
QCoreApplication app(argc, argv);
htmlGet({"http://www.google.com"}, [](const QString &body){ qDebug() << body; qApp->quit(); });
return app.exec();
}
| KubaO/stackoverflown | questions/html-get-24965972/main.cpp | C++ | unlicense | 1,330 |
using System;
using System.Collections.Generic;
using System.Linq;
namespace NetGore
{
/// <summary>
/// Provides helper functions for parsing command-line switches and the arguments that go with
/// each of those switches.
/// </summary>
public static class CommandLineSwitchHelper
{
/// <summary>
/// The name of the primary key. This is the key used for arguments that come before any switches.
/// This key is only present if it has any arguments.
/// </summary>
public const string PrimaryKeyName = "Main";
/// <summary>
/// The prefix used to denote a switch. Any word after a word with this prefix that does not
/// have this prefix will be considered as an argument to the switch. For example:
/// -switch1 arg1 arg2 -switch2 -switch3 arg1
/// </summary>
public const string SwitchPrefix = "-";
/// <summary>
/// Gets the switches and their arguments from the given string array.
/// </summary>
/// <param name="args">The array of strings.</param>
/// <returns>The switches and their arguments from the given string array.</returns>
public static IEnumerable<KeyValuePair<string, string[]>> GetCommands(string[] args)
{
return GroupValuesToSwitches(args);
}
/// <summary>
/// Gets the switches and their arguments from the given string array. Only switches that can be parsed to
/// type <typeparamref name="T"/> will be returned.
/// </summary>
/// <typeparam name="T">The Type of Enum to use as the key.</typeparam>
/// <param name="args">The array of strings.</param>
/// <returns>The switches and their arguments from the given string array.</returns>
/// <exception cref="MethodAccessException">Generic type <typeparamref name="T"/> must be an Enum.</exception>
public static IEnumerable<KeyValuePair<T, string[]>> GetCommandsUsingEnum<T>(string[] args)
where T : struct, IComparable, IConvertible, IFormattable
{
if (!typeof(T).IsEnum)
{
const string errmsg = "Generic type T (type: {0}) must be an Enum.";
throw new MethodAccessException(string.Format(errmsg, typeof(T)));
}
var items = GetCommands(args);
foreach (var item in items)
{
T parsed;
if (EnumHelper<T>.TryParse(item.Key, true, out parsed))
yield return new KeyValuePair<T, string[]>(parsed, item.Value);
}
}
/// <summary>
/// Groups the values after a switch to a switch.
/// </summary>
/// <param name="args">The array of strings.</param>
/// <returns>The switches grouped with their values.</returns>
static IEnumerable<KeyValuePair<string, string[]>> GroupValuesToSwitches(IList<string> args)
{
if (args == null || args.Count == 0)
return Enumerable.Empty<KeyValuePair<string, string[]>>();
var switchPrefixAsCharArray = SwitchPrefix.ToCharArray();
var ret = new List<KeyValuePair<string, string[]>>(args.Count);
var currentKey = PrimaryKeyName;
var currentArgs = new List<string>(args.Count);
// Iterate through all the strings
for (var i = 0; i < args.Count; i++)
{
var currentArg = args[i];
var currentArgTrimmed = args[i].Trim();
if (currentArgTrimmed.StartsWith(SwitchPrefix, StringComparison.OrdinalIgnoreCase))
{
// Empty out the current switch
if (currentKey != PrimaryKeyName || currentArgs.Count > 0)
ret.Add(new KeyValuePair<string, string[]>(currentKey, currentArgs.ToArray()));
// Remove the switch prefix and set as the new key
currentKey = currentArgTrimmed.TrimStart(switchPrefixAsCharArray);
currentArgs.Clear();
}
else
{
// Add the argument only if its an actual string
if (currentArg.Length > 0)
currentArgs.Add(currentArg);
}
}
// Empty out the remainder
if (currentKey != PrimaryKeyName || currentArgs.Count > 0)
ret.Add(new KeyValuePair<string, string[]>(currentKey, currentArgs.ToArray()));
return ret;
}
}
} | LAGIdiot/NetGore | NetGore/Core/CommandLineSwitchHelper.cs | C# | unlicense | 4,642 |
#include<stdio.h>
void heap_sort(int[], int);
void build_max_heap(int[], int);
void max_heapify(int[],int,int);
void swap(int*, int*);
void display(int[],int);
int main(){
int n = 11;
int a[] = {55,3,2,5,77,44,65,53,88,31,9};
display(a,n);
heap_sort(a,n);
display(a,n);
return 0;
}
void heap_sort(int a[], int n){
int i;
int heap_size = n;
build_max_heap(a,n);
for(i = n-1; i > 0; i--){
swap(&a[0], &a[i]);
heap_size--;
max_heapify(a,0,heap_size);
}
}
void build_max_heap(int a[], int n){
int i;
int loop = (n-1)/2;
for(i = loop; i >= 0; i--){
max_heapify(a,i,n);
}
}
void max_heapify(int a[], int i, int heap_size){
int left = 2*i + 1;
int right = 2*i + 2;
int largest;
if(left < heap_size && a[left] > a[i]){
largest = left;
}
else{
largest = i;
}
if((right < heap_size) && (a[right] > a[largest])){
largest = right;
}
if(largest != i){
swap(&a[largest], &a[i]);
max_heapify(a, largest, heap_size);
}
}
void swap(int *a,int *b){
int temp;
temp = *a;
*a = *b;
*b = temp;
}
void display(int a[],int n){
int i;
printf("\n");
for(i = 0;i<n;i++){
printf("%d\t",a[i]);
}
}
| miansari/sorting-programs-in-C | heapsort.c | C | unlicense | 1,129 |
#include "alfe/main.h"
#ifndef INCLUDED_PARSER_H
#define INCLUDED_PARSER_H
#include "alfe/code.h"
#include "alfe/space.h"
class Parser : Uncopyable
{
public:
CodeList parseFromFile(File file)
{
CodeList c;
parseFromFile(c, file);
return c;
}
void parseFromString(Code code, String s)
{
CharacterSource source(s);
do {
CharacterSource s2 = source;
if (s2.get() == -1)
return;
parseStatementOrFail(code, &source);
} while (true);
}
private:
void parseFromFile(Code code, File file)
{
parseFromString(code, file.contents());
}
bool parseStatement(Code code, CharacterSource* source)
{
if (parseExpressionStatement(code, source))
return true;
if (parseFunctionDefinitionStatement(code, source))
return true;
if (parseAssignment(code, source))
return true;
if (parseCompoundStatement(code, source))
return true;
if (parseTycoDefinitionStatement(code, source))
return true;
if (parseNothingStatement(source))
return true;
if (parseIncrementDecrementStatement(code, source))
return true;
if (parseConditionalStatement(code, source))
return true;
if (parseSwitchStatement(code, source))
return true;
if (parseReturnStatement(code, source))
return true;
if (parseIncludeStatement(code, source))
return true;
if (parseBreakOrContinueStatement(code, source))
return true;
if (parseForeverStatement(code, source))
return true;
if (parseWhileStatement(code, source))
return true;
if (parseForStatement(code, source))
return true;
if (parseLabelStatement(code, source))
return true;
if (parseGotoStatement(code, source))
return true;
return false;
}
void parseStatementOrFail(Code code, CharacterSource* source)
{
if (!parseStatement(code, source))
source->location().throwError("Expected statement");
}
bool parseExpressionStatement(Code code, CharacterSource* source)
{
CharacterSource s = *source;
Expression expression = Expression::parse(&s);
if (!expression.valid())
return false;
Span span;
if (!Space::parseCharacter(&s, ';', &span))
return false;
_lastSpan = span;
*source = s;
if (!expression.mightHaveSideEffect())
source->location().throwError("Statement has no effect");
code.insert<ExpressionStatement>(expression, expression.span() + span);
return true;
}
bool parseAssignment(Code code, CharacterSource* source)
{
CharacterSource s = *source;
Expression left = Expression::parse(&s);
Location operatorLocation = s.location();
if (!left.valid())
return false;
Span span;
static const Operator ops[] = {
OperatorAssignment(), OperatorAddAssignment(),
OperatorSubtractAssignment(), OperatorMultiplyAssignment(),
OperatorDivideAssignment(), OperatorModuloAssignment(),
OperatorShiftLeftAssignment(), OperatorShiftRightAssignment(),
OperatorBitwiseAndAssignment(), OperatorBitwiseOrAssignment(),
OperatorBitwiseXorAssignment(), OperatorPowerAssignment(),
Operator() };
const Operator* op;
for (op = ops; op->valid(); ++op)
if (Space::parseOperator(&s, op->toString(), &span))
break;
if (!op->valid())
return false;
*source = s;
Expression right = Expression::parseOrFail(source);
Space::assertCharacter(source, ';', &span);
_lastSpan = span;
code.insert<ExpressionStatement>(FunctionCallExpression::binary(*op,
span,
FunctionCallExpression::unary(OperatorAmpersand(), Span(), left),
right), left.span() + span);
return true;
}
List<VariableDefinition> parseParameterList(CharacterSource* source)
{
List<VariableDefinition> list;
VariableDefinition parameter = VariableDefinition::parse(source);
if (!parameter.valid())
return list;
list.add(parameter);
Span span;
while (Space::parseCharacter(source, ',', &span)) {
VariableDefinition parameter = VariableDefinition::parse(source);
if (!parameter.valid())
source->location().throwError("Expected parameter");
list.add(parameter);
}
return list;
}
bool parseFunctionDefinitionStatement(Code code, CharacterSource* source)
{
CharacterSource s = *source;
TycoSpecifier returnTypeSpecifier = TycoSpecifier::parse(&s);
if (!returnTypeSpecifier.valid())
return false;
Identifier name = Identifier::parse(&s);
if (!name.valid())
return false;
Span span;
if (!Space::parseCharacter(&s, '('))
return false;
*source = s;
List<VariableDefinition> parameterList = parseParameterList(source);
Space::assertCharacter(source, ')');
Span span;
if (Space::parseKeyword(source, "from", &span)) {
Expression dll = Expression::parseOrFail(source);
Space::assertCharacter(source, ';', &span);
_lastSpan = span;
code.insert<FunctionDefinitionFromStatement>(returnTypeSpecifier,
name, parameterList, dll, returnTypeSpecifier.span() + span);
return true;
}
CodeList body;
parseStatementOrFail(body, source);
code.insert<FunctionDefinitionCodeStatement>(returnTypeSpecifier,
name, parameterList, body, returnTypeSpecifier.span() + _lastSpan);
return true;
}
void parseStatementSequence(Code code, CharacterSource* source)
{
do {
if (!parseStatement(code, source))
return;
} while (true);
}
bool parseCompoundStatement(Code code, CharacterSource* source)
{
Span span;
if (!Space::parseCharacter(source, '{', &span))
return false;
parseStatementSequence(code, source);
Space::assertCharacter(source, '}', &span);
_lastSpan = span;
return true;
}
// TycoDefinitionStatement := TycoSignifier "=" TycoSpecifier ";"
bool parseTycoDefinitionStatement(Code code, CharacterSource* source)
{
CharacterSource s = *source;
CharacterSource s2 = s;
TycoSignifier tycoSignifier = TycoSignifier::parse(&s);
if (!tycoSignifier.valid())
return false;
if (!Space::parseCharacter(&s, '='))
return false;
*source = s;
TycoSpecifier tycoSpecifier = TycoSpecifier::parse(source);
Span span;
Space::assertCharacter(source, ';', &span);
_lastSpan = span;
code.insert<TycoDefinitionStatement>(tycoSignifier, tycoSpecifier,
tycoSignifier.span() + span);
return true;
}
bool parseNothingStatement(CharacterSource* source)
{
Span span;
if (!Space::parseKeyword(source, "nothing", &span))
return false;
Space::assertCharacter(source, ';', &span);
_lastSpan = span;
return true;
}
bool parseIncrementDecrementStatement(Code code, CharacterSource* source)
{
Span span;
Operator o = OperatorIncrement().parse(source, &span);
if (!o.valid())
o = OperatorDecrement().parse(source, &span);
if (!o.valid())
return false;
Expression lValue = Expression::parse(source);
Span span2;
Space::assertCharacter(source, ';', &span2);
_lastSpan = span2;
code.insert<ExpressionStatement>(FunctionCallExpression::unary(o, span,
FunctionCallExpression::unary(
OperatorAmpersand(), Span(), lValue)),
span + span2);
return true;
}
void parseConditionalStatement2(Code code, CharacterSource* source,
Span span, bool unlessStatement)
{
Space::assertCharacter(source, '(');
Expression condition = Expression::parseOrFail(source);
Space::assertCharacter(source, ')');
CodeList conditionalCode;
parseStatementOrFail(conditionalCode, source);
span += _lastSpan;
CodeList elseCode;
if (Space::parseKeyword(source, "else"))
parseStatementOrFail(elseCode, source);
else {
if (Space::parseKeyword(source, "elseIf"))
parseConditionalStatement2(elseCode, source, span, false);
else {
if (Space::parseKeyword(source, "elseUnless"))
parseConditionalStatement2(elseCode, source, span, true);
}
}
if (unlessStatement)
condition = !condition;
code.insert<ConditionalStatement>(condition, conditionalCode, elseCode,
span + _lastSpan);
}
// ConditionalStatement = (`if` | `unless`) ConditionedStatement
// ((`elseIf` | `elseUnless`) ConditionedStatement)* [`else` Statement];
// ConditionedStatement = "(" Expression ")" Statement;
bool parseConditionalStatement(Code code, CharacterSource* source)
{
Span span;
if (Space::parseKeyword(source, "if", &span)) {
parseConditionalStatement2(code, source, span, false);
return true;
}
if (Space::parseKeyword(source, "unless", &span)) {
parseConditionalStatement2(code, source, span, true);
return true;
}
return false;
}
SwitchStatement::Case parseCase(CharacterSource* source)
{
List<Expression> expressions;
bool defaultType;
Span span;
if (Space::parseKeyword(source, "case", &span)) {
defaultType = false;
do {
Expression expression = Expression::parseOrFail(source);
expressions.add(expression);
if (!Space::parseCharacter(source, ','))
break;
} while (true);
}
else {
defaultType = true;
if (!Space::parseKeyword(source, "default", &span))
source->location().throwError("Expected case or default");
}
Space::assertCharacter(source, ':');
CodeList code;
parseStatementOrFail(code, source);
span += _lastSpan;
if (defaultType)
return SwitchStatement::Case(code, span);
return SwitchStatement::Case(expressions, code, span);
}
bool parseSwitchStatement(Code code, CharacterSource* source)
{
Span span;
if (!Space::parseKeyword(source, "switch", &span))
return false;
Space::assertCharacter(source, '(');
Expression expression = Expression::parseOrFail(source);
Space::assertCharacter(source, ')');
Space::assertCharacter(source, '{');
SwitchStatement::Case defaultCase;
CharacterSource s = *source;
List<SwitchStatement::Case> cases;
do {
SwitchStatement::Case c = parseCase(source);
if (!c.valid())
break;
if (c.isDefault()) {
if (defaultCase.valid())
s.location().throwError(
"This switch statement already has a default case");
defaultCase = c;
}
else
cases.add(c);
} while (true);
Space::assertCharacter(source, '}', &span);
_lastSpan = span;
code.insert<SwitchStatement>(expression, defaultCase, cases, span);
return true;
}
bool parseReturnStatement(Code code, CharacterSource* source)
{
Span span;
if (!Space::parseKeyword(source, "return", &span))
return false;
Expression expression = Expression::parseOrFail(source);
Space::assertCharacter(source, ';', &span);
_lastSpan = span;
code.insert<ReturnStatement>(expression, span);
return true;
}
bool parseIncludeStatement(Code code, CharacterSource* source)
{
Span span;
if (!Space::parseKeyword(source, "include", &span))
return false;
Expression expression = parseExpression(source);
StringLiteralExpression s(expression);
if (!s.valid()) {
expression.span().throwError("Argument to include must be a "
"simple string");
}
String path = s.string();
//Resolver resolver;
//resolver.resolve(expression);
//Evaluator evaluator;
//Value value = evaluator.evaluate(expression).convertTo(StringType());
//String path = value.value<String>();
File lastFile = _currentFile;
_currentFile = File(path, _currentFile.parent());
parseFromFile(code, _currentFile);
_currentFile = lastFile;
}
bool parseBreakOrContinueStatement(Code code, CharacterSource* source)
{
int breakCount = 0;
bool hasContinue = false;
Span span;
do {
if (Space::parseKeyword(source, "break", &span))
++breakCount;
else
break;
} while (true);
if (Space::parseKeyword(source, "continue", &span))
hasContinue = true;
if (breakCount == 0 && !hasContinue)
return false;
Space::assertCharacter(source, ';', &span);
_lastSpan = span;
code.insert<BreakOrContinueStatement>(span, breakCount, hasContinue);
return true;
}
bool parseForeverStatement(Code code, CharacterSource* source)
{
Span span;
if (!Space::parseKeyword(source, "forever", &span))
return false;
CodeList body;
parseStatementOrFail(body, source);
code.insert<ForeverStatement>(body, span);
return true;
}
bool parseWhileStatement(Code code, CharacterSource* source)
{
Span span;
CodeList doCode;
bool foundDo = false;
if (Space::parseKeyword(source, "do", &span)) {
foundDo = true;
parseStatementOrFail(doCode, source);
}
bool foundWhile = false;
bool foundUntil = false;
if (Space::parseKeyword(source, "while", &span))
foundWhile = true;
else
if (Space::parseKeyword(source, "until", &span))
foundUntil = true;
if (!foundWhile && !foundUntil) {
if (foundDo)
source->location().throwError("Expected while or until");
return false;
}
Space::assertCharacter(source, '(');
Expression condition = Expression::parse(source);
Space::assertCharacter(source, ')');
CodeList body;
parseStatementOrFail(body, source);
CodeList doneCode;
if (Space::parseKeyword(source, "done"))
parseStatementOrFail(doneCode, source);
span += _lastSpan;
if (foundUntil)
condition = !condition;
code.insert<WhileStatement>(doCode, condition, body, doneCode, span);
return true;
}
bool parseForStatement(Code code, CharacterSource* source)
{
Span span;
if (!Space::parseKeyword(source, "for", &span))
return false;
Space::assertCharacter(source, '(');
CodeList preCode;
if (!parseStatement(preCode, source))
Space::assertCharacter(source, ';');
Expression expression = Expression::parse(source);
Space::assertCharacter(source, ';');
CodeList postCode;
parseStatement(postCode, source);
Space::parseCharacter(source, ')');
CodeList body;
parseStatement(body, source);
span += _lastSpan;
CodeList doneCode;
if (Space::parseKeyword(source, "done")) {
parseStatementOrFail(doneCode, source);
span += _lastSpan;
}
code.insert<ForStatement>(preCode, expression, postCode, body,
doneCode, span);
return true;
}
bool parseLabelStatement(Code code, CharacterSource* source)
{
CharacterSource s2 = *source;
Identifier identifier = Identifier::parse(&s2);
if (!identifier.valid())
return false;
Span span;
if (!Space::parseCharacter(&s2, ':', &span))
return false;
_lastSpan = span;
code.insert<LabelStatement>(identifier, identifier.span() + span);
return true;
}
bool parseGotoStatement(Code code, CharacterSource* source)
{
Span span;
if (!Space::parseKeyword(source, "goto", &span))
return false;
Expression expression = Expression::parseOrFail(source);
Span span2;
Space::parseCharacter(source, ';', &span);
code.insert<GotoStatement>(expression, span);
return true;
}
Span _lastSpan;
File _currentFile;
};
#endif // INCLUDED_PARSER_H | reenigne/reenigne | include/alfe/parser.h | C | unlicense | 17,446 |
// vi: nu:noai:ts=4:sw=4
//
// c_defs
//
// Created by bob on 1/14/19.
//
/*
This is free and unencumbered software released into the public domain.
Anyone is free to copy, modify, publish, use, compile, sell, or
distribute this software, either in source code form or as a compiled
binary, for any purpose, commercial or non-commercial, and by any
means.
In jurisdictions that recognize copyright laws, the author or authors
of this software dedicate any and all copyright interest in the
software to the public domain. We make this dedication for the benefit
of the public at large and to the detriment of our heirs and
successors. We intend this dedication to be an overt act of
relinquishment in perpetuity of all present and future rights to this
software under copyright law.
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 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.
For more information, please refer to <http://unlicense.org/>
*/
#include <cmn_defs.h>
#include <AStr.h>
#include <CsvFile.h>
#include <Path.h>
#include <trace.h>
#include <uuid/uuid.h>
//===============================================================
// M a i n
//===============================================================
int main(
int argc,
const
char * argv[]
)
{
//bool fRc;
uint8_t uuid[16];
uint32_t i;
char *pUUID = "A63EA833-7B46-45DD-B63D-4B9446ED845A";
int iRc;
uuid_t uuid2 = { 0xA6, 0x3E, 0xA8, 0x33, 0x7B, 0x46, 0x45,
0xDD, 0xB6, 0x3D, 0x4B, 0x94, 0x46, 0xED,
0x84, 0x5A
};
uuid_string_t uuid2str; // Internally seems to be char [37]
fprintf(stdout, "size of ptr: %d\n", (int)sizeof(long *));
fprintf(stdout, "size of long: %d\n", (int)sizeof(long));
fprintf(stdout, "size of int: %d\n", (int)sizeof(int));
fprintf(stdout, "size of short: %d\n", (int)sizeof(short));
fprintf(stdout, "size of uint64_t: %d\n", (int)sizeof(uint64_t));
fprintf(stdout, "size of uint32_t: %d\n", (int)sizeof(uint32_t));
fprintf(stdout, "size of uint16_t: %d\n", (int)sizeof(uint16_t));
// This is MacOS's way of dealing with UUIDs/GUIDs.
iRc = uuid_parse(pUUID, uuid);
fprintf(stdout, "parse ret=%d\n", iRc);
fprintf(stdout, "%s -> ", pUUID);
for (i=0; i<16; i++) {
fprintf(stdout, "0x%02X, ", uuid[i]);
}
fprintf(stdout, "\n");
uuid_unparse(uuid, uuid2str);
fprintf(stdout, "uuid: %s\n", uuid2str);
uuid_unparse(uuid2, uuid2str);
fprintf(stdout, "uuid2: %s\n", uuid2str);
fprintf(stdout, "\n\n\n");
return 0;
}
| 2kranki/libCmn | programs/c_defs/src/c_defs.c | C | unlicense | 3,011 |
---
title: 'Wolf Creek National Fish Hatchery Open House'
start: 2019-12-14T10:00:00.000Z
end: 2019-12-14T14:00:00.000Z
description: 'Come celebrate with our holiday open house and nature ornament workshop. Light refreshments and holiday entertainment with be provided. Make a nature themed ornament for our Christmas tree and take home another for your own. Event sponsored by the Friends of Wolf Creek National Fish Hatchery.'
hero:
name: wolf-creek-nfh-holiday-table.jpg
alt: 'A table with a sign that reads Wolf Creek NFH Holiday Open House with craft making supplies'
caption: 'Wolf Creek National Fish Hatchery Open House. Photo by USFWS.'
position: '10% 55%'
timezone: CDT
tags:
- Kentucky
- 'Wolf Creek National Fish Hatchery'
updated: 'December 4th, 2019'
---
## Description
Come celebrate with our holiday open house and nature ornament workshop. Light refreshments and holiday entertainment with be provided. Make a nature themed ornament for our Christmas tree and take home another for your own. Event sponsored by the Friends of Wolf Creek National Fish Hatchery.
- Open house: 10:00 a.m - 2:00 p.m. CST
- Craft stations open: 10:00 a.m. - 1:30 p.m. CST
## Location
Wolf Creek National Fish Hatchery
50 Kendall Road Jamestown, KY 42629
## Contact
Moria Painter, Environmental education and interpretation specialist
[[email protected]](mailto:[email protected]), (270) 343-3797
## Flyer
{{< figure class="photo-center" src="/images/pages/2019-wolf-creek-nfh-openhouse.jpg" alt="A flyer for this event; information above" >}} | USFWS/southeast | site/content/events/2019-wolf-creek-national-fish-hatchery-open-house.md | Markdown | unlicense | 1,583 |
#include_next <cxxabi.h>
| automeka/automeka | lib/std/include/cxxabi.h | C | unlicense | 25 |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Get Twemoji!</title>
<link rel="stylesheet" href="http://ellekasai.github.io/twemoji-awesome/twemoji-awesome.css">
</head>
<body>
<i class="twa twa-chilli" style="-webkit-font-smoothing : none; font-size:200px; font-smooth: never; filter: contrast(1);" title=":heart:"></i>
<i class="twa twa-chili-pepper" style="-webkit-font-smoothing : none; font-size:200px; font-smooth: never; filter: contrast(1);" title=":heart:"></i>
</body>
</html>
| voec/melonpoop | get twemoji.html | HTML | unlicense | 518 |
package com.elionhaxhi.ribbit.ui;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.app.AlertDialog;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.NavUtils;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.elionhaxhi.ribbit.R;
import com.elionhaxhi.ribbit.adapters.UserAdapter;
import com.elionhaxhi.ribbit.utils.FileHelper;
import com.elionhaxhi.ribbit.utils.ParseConstants;
import com.parse.FindCallback;
import com.parse.ParseException;
import com.parse.ParseFile;
import com.parse.ParseInstallation;
import com.parse.ParseObject;
import com.parse.ParsePush;
import com.parse.ParseQuery;
import com.parse.ParseRelation;
import com.parse.ParseUser;
import com.parse.SaveCallback;
public class RecipientsActivity extends Activity {
public static final String TAG=RecipientsActivity.class.getSimpleName();
protected List<ParseUser> mFriends;
protected ParseRelation<ParseUser> mFriendsRelation;
protected ParseUser mCurrentUser;
protected MenuItem mSendMenuItem;
protected Uri mMediaUri;
protected String mFileType;
protected GridView mGridView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
setContentView(R.layout.user_grid);
//setupActionBar();
mGridView =(GridView)findViewById(R.id.friendsGrid);
mGridView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
mGridView.setOnItemClickListener(mOnItemClickListener);
TextView emptyTextView = (TextView)findViewById(android.R.id.empty);
mGridView.setEmptyView(emptyTextView);
mMediaUri = getIntent().getData();
mFileType = getIntent().getExtras().getString(ParseConstants.KEY_FILE_TYPE);
}
@Override
public void onResume(){
super.onResume();
mCurrentUser = ParseUser.getCurrentUser();
mFriendsRelation = mCurrentUser.getRelation(ParseConstants.KEY_FRIENDS_RELATION);
setProgressBarIndeterminateVisibility(true);
ParseQuery<ParseUser> query = mFriendsRelation.getQuery();
query.addAscendingOrder(ParseConstants.KEY_USERNAME);
query.findInBackground(new FindCallback<ParseUser>(){
@Override
public void done(List<ParseUser> friends, ParseException e){
setProgressBarIndeterminateVisibility(false);
if(e == null){
mFriends = friends;
String [] usernames = new String[mFriends.size()];
int i =0;
for(ParseUser user : mFriends){
usernames[i]=user.getUsername();
i++;
}
if(mGridView.getAdapter() == null){
UserAdapter adapter = new UserAdapter(RecipientsActivity.this, mFriends);
mGridView.setAdapter(adapter);
}
else{
((UserAdapter)mGridView.getAdapter()).refill(mFriends);
}
}
else{
Log.e(TAG, e.getMessage());
AlertDialog.Builder builder= new AlertDialog.Builder(RecipientsActivity.this);
builder.setMessage(e.getMessage())
.setTitle(R.string.error_title)
.setPositiveButton(android.R.string.ok, null);
AlertDialog dialog = builder.create();
dialog.show();
}
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.reciptient, menu);
mSendMenuItem = menu.getItem(0);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
switch(item.getItemId()){
case android.R.id.home:
NavUtils.navigateUpFromSameTask(this);
return true;
case R.id.action_send:
ParseObject message = createMessage();
if(message == null){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(R.string.error_selecting_file)
.setTitle(R.string.error_selection_file_title)
.setPositiveButton(android.R.string.ok, null);
AlertDialog dialog = builder.create();
dialog.show();
}
else
{
send(message);
finish();
}
return true;
}
return super.onOptionsItemSelected(item);
}
protected ParseObject createMessage(){
ParseObject message = new ParseObject(ParseConstants.CLASS_MESSAGE);
message.put(ParseConstants.KEY_SENDER_ID, ParseUser.getCurrentUser().getObjectId());
message.put(ParseConstants.KEY_SENDER_NAME, ParseUser.getCurrentUser().getUsername());
message.put(ParseConstants.KEY_RECIPIENT_IDS, getRecipientIds());
message.put(ParseConstants.KEY_FILE_TYPE, mFileType);
byte[] fileBytes = FileHelper.getByteArrayFromFile(this, mMediaUri);
if(fileBytes == null){
return null;
}
else{
if(mFileType.equalsIgnoreCase(ParseConstants.TYPE_IMAGE)){
fileBytes = FileHelper.reduceImageForUpload(fileBytes);
}
String fileName = FileHelper.getFileName(this, mMediaUri, mFileType);
ParseFile file = new ParseFile(fileName, fileBytes);
message.put(ParseConstants.KEY_FILE, file);
return message;
}
}
protected ArrayList<String> getRecipientIds(){
ArrayList<String> recipientIds = new ArrayList<String>();
for(int i=0; i< mGridView.getCount(); i++){
if(mGridView.isItemChecked(i)){
recipientIds.add(mFriends.get(i).getObjectId());
}
}
return recipientIds;
}
protected void send(ParseObject message){
message.saveInBackground(new SaveCallback(){
@Override
public void done(ParseException e){
if(e == null){
//success
Toast.makeText(RecipientsActivity.this, R.string.success_message, Toast.LENGTH_LONG).show();
sendPushNotifications();
}
else{
AlertDialog.Builder builder = new AlertDialog.Builder(RecipientsActivity.this);
builder.setMessage(R.string.error_sending_message)
.setTitle(R.string.error_selection_file_title)
.setPositiveButton(android.R.string.ok, null);
AlertDialog dialog = builder.create();
dialog.show();
}
}
});
}
protected OnItemClickListener mOnItemClickListener = new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
if(mGridView.getCheckedItemCount() > 0)
{
mSendMenuItem.setVisible(true);
}
else{
mSendMenuItem.setVisible(false);
}
ImageView checkImageView =(ImageView)findViewById(R.id.checkImageView);
if(mGridView.isItemChecked(position)){
//add recipient
checkImageView.setVisibility(View.VISIBLE);
}
else{
//remove the recipient
checkImageView.setVisibility(View.INVISIBLE);
}
}
};
protected void sendPushNotifications(){
ParseQuery<ParseInstallation> query = ParseInstallation.getQuery();
query.whereContainedIn(ParseConstants.KEY_USER_ID, getRecipientIds());
//send a push notificaton
ParsePush push = new ParsePush();
push.setQuery(query);
push.setMessage(getString(R.string.push_message, ParseUser.getCurrentUser().getUsername()));
push.sendInBackground();
}
}
| ElionHaxhi/Ribbit | src/com/elionhaxhi/ribbit/ui/RecipientsActivity.java | Java | unlicense | 7,505 |
<!DOCTYPE html>
<html>
<head>
<title>Henlo World</title>
<meta charset="UTF-8">
<style>
body {
font-family: helvetica, sans serif;
text-align: center;
background-color: #fceed4;
padding-top: 20%;
}
</style>
</head>
<body>
<div>
<a href="https://twitter.com/ChristenNguyen">😸</a> |
<a href="https://www.instagram.com/deathbypuppies/">📷</a> |
<a href="https://www.youtube.com/watch?v=JaPf-MRKITg">🎼</a>
</div>
<p>Hello World, I'm Christen! Here's a link to my <a href="https://github.com/christennguyen">Github</a>!</p>
</body>
</html> | muan/hello-world | humans/christennguyen.html | HTML | unlicense | 681 |
---
ID: 122673
post_title: Rules
author: Mark
post_excerpt: ""
layout: page
permalink: https://philoserf.com/rules/
published: true
post_date: 2020-01-01 00:06:55
---
<h2>level one</h2>
<ul><li>if it has a name do not give it another name</li>
<li>if you have given it a name do not give it another name</li>
<li>start with one file until you need^ another file</li>
<li>start with one folder until you need^ another folder</li>
<li>adapt to the default configuration</li>
<li>after a sincere effort to adapt fails, change the default configuration</li>
<li>don't think about lint and style, use tools for that</li>
</ul>
<h2>level two</h2>
<ul><li>test everything^</li>
<li>deploy every merge request that passes the tests</li>
<li>test everything^</li>
<li>release master after every merge</li>
</ul>
<h2>level three</h2>
<ul><li>rebase to reorganize before you offer a pull request</li>
<li>rebase again to squash before you merge to master</li>
</ul>
<h2>todo</h2>
<ul><li>add why</li>
<li>provide examples</li>
<li>^define <em>need</em></li>
<li>^define <em>everything</em></li>
</ul>
| philoserf/wp-sync | _pages/rules.md | Markdown | unlicense | 1,091 |
<?php
/**
* Pizza E96
*
* @author: Paul Melekhov
*/
namespace App\Http;
/**
* Поднятие этого исключения служит сигналом для FrontController о том,
* что нужно отобразить страницу с ошибкой HTTP/1.1 400 Bad Request
*/
class BadRequestException extends Exception
{
public function __construct($message = "", $code = 0, Exception $previous = null) {
parent::__construct($message, $code, $previous);
$this->_httpStatusCode = 400;
$this->_httpStatusMessage = "Bad Request";
}
}
| gugglegum/pizza | app/library/Http/BadRequestException.php | PHP | unlicense | 592 |
# ambuttu.sh
ambuttu
| Rat-S/ambuttu.sh | README.md | Markdown | unlicense | 21 |
class PermissionRequired(Exception):
"""
Exception to be thrown by views which check permissions internally.
Takes a single C{perm} argument which defines the permission that caused
the exception.
"""
def __init__(self, perm):
self.perm = perm
def require_permissions(user, *permissions):
for perm in permissions:
if not user.has_perm(perm):
raise PermissionRequired(perm)
class checks_permissions(object):
"""
Decorator for views which handle C{PermissionRequired} errors and renders
the given error view if necessary.
The original request and arguments are passed to the error with the
additional C{_perm} and C{_view} keyword arguments.
"""
def __init__(self, view_or_error=None):
self.wrapped = callable(view_or_error)
error_view = None
if self.wrapped:
self.view = view_or_error
else:
error_view = view_or_error
if not error_view:
from django.conf import settings
error_view = settings.PERMISSIONS_VIEW
from django.core.urlresolvers import get_callable
self.error_view = get_callable(error_view)
def __call__(self, view_or_request, *args, **kwargs):
if not self.wrapped:
self.view = view_or_request
def dec(*args, **kwargs):
try:
return self.view(*args, **kwargs)
except PermissionRequired as e:
kwargs['_perm'] = e.perm
kwargs['_view'] = self.view
return self.error_view(*args, **kwargs)
return dec(view_or_request, *args, **kwargs) if self.wrapped else dec
class permission_required(object):
"""
Decorator which builds upon the C{checks_permission} decorator to offer
the same functionality as the built-in
C{django.contrib.auth.decorators.permission_required} decorator but which
renders an error view insted of redirecting to the login page.
"""
def __init__(self, perm, error_view=None):
self.perm = perm
self.error_view = error_view
def __call__(self, view_func):
def decorator(request, *args, **kwargs):
if not request.user.has_perm(self.perm):
raise PermissionRequired(self.perm)
return view_func(request, *args, **kwargs)
return checks_permissions(self.error_view)(decorator)
| AnimeDB/adb-browser-frontend | adb/frontend/auth/decorators.py | Python | unlicense | 2,476 |
package com.intershop.adapter.payment.partnerpay.internal.service.capture;
import javax.inject.Inject;
import com.google.inject.Injector;
import com.intershop.adapter.payment.partnerpay.capi.service.capture.CaptureFactory;
import com.intershop.api.service.payment.v1.capability.Capture;
public class CaptureFactoryImpl implements CaptureFactory
{
@Inject
private Injector injector;
@Override
public Capture createCapture()
{
Capture ret = new CaptureImpl();
injector.injectMembers(ret);
return ret;
}
}
| IntershopCommunicationsAG/partnerpay-example | s_payment_partnerpay/ac_payment_partnerpay/javasource/com/intershop/adapter/payment/partnerpay/internal/service/capture/CaptureFactoryImpl.java | Java | unlicense | 578 |
#ifndef REGTEST
#include <threads.h>
#include <windows.h>
int mtx_lock(mtx_t *mtx)
{
DWORD myId = GetCurrentThreadId();
if(mtx->_ThreadId == (long) myId) {
mtx->_NestCount++;
return thrd_success;
}
for(;;) {
LONG prev = InterlockedCompareExchange(&mtx->_ThreadId, myId, 0);
if(prev == 0)
return thrd_success;
DWORD rv = WaitForSingleObject(mtx->_WaitEvHandle, INFINITE);
if(rv != WAIT_OBJECT_0)
return thrd_error;
}
}
#endif
#ifdef TEST
#include "_PDCLIB_test.h"
int main( void )
{
return TEST_RESULTS;
}
#endif | cartman300/Kernel | 3rdParty/PDCLib/platform/win32/functions/threads/mtx_lock.c | C | unlicense | 614 |
// This Source Code is in the Public Domain per: http://unlicense.org
package org.litesoft.commonfoundation.charstreams;
/**
* A CharSource is like a powerful version of a "char" based Iterator.
*/
public interface CharSource {
/**
* Report if there are any more characters available to get().
* <p/>
* Similar to Iterator's hasNext().
*/
public boolean anyRemaining();
/**
* Get the next character (consume it from the stream) or -1 if there are no more characters available.
*/
public int get();
/**
* Get the next character (consume it from the stream) or throw an exception if there are no more characters available.
*/
public char getRequired();
/**
* Return the next character (without consuming it) or -1 if there are no more characters available.
*/
public int peek();
/**
* Return the Next Offset (from the stream) that the peek/get/getRequired would read from (it may be beyond the stream end).
*/
public int getNextOffset();
/**
* Return the Last Offset (from the stream), which the previous get/getRequired read from (it may be -1 if stream has not been successfully read from).
*/
public int getLastOffset();
/**
* Return a string (and consume the characters) from the current position up to (but not including) the position of the 'c' character. OR "" if 'c' is not found (nothing consumed).
*/
public String getUpTo( char c );
/**
* Consume all the spaces (NOT white space) until either there are no more characters or a non space is encountered (NOT consumed).
*
* @return true if there are more characters.
*/
public boolean consumeSpaces();
/**
* Return a string (and consume the characters) from the current position thru the end of the characters OR up to (but not including) a character that is not a visible 7-bit ascii character (' ' < c <= 126).
*/
public String getUpToNonVisible7BitAscii();
/**
* Consume all the non-visible 7-bit ascii characters (visible c == ' ' < c <= 126) until either there are no more characters or a visible 7-bit ascii character is encountered (NOT consumed).
*
* @return true if there are more characters.
*/
public boolean consumeNonVisible7BitAscii();
}
| litesoft/LiteSoftCommonFoundation | src/org/litesoft/commonfoundation/charstreams/CharSource.java | Java | unlicense | 2,332 |
package net.simpvp.Jail;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;
import org.bukkit.Location;
/**
* Class representing the stored information about a jailed player
*/
public class JailedPlayer {
public UUID uuid;
public String playername;
public String reason;
public String jailer;
public Location location;
public int jailed_time;
public boolean to_be_released;
public boolean online;
public JailedPlayer(UUID uuid, String playername, String reason, String jailer, Location location, int jailed_time, boolean to_be_released, boolean online) {
this.uuid = uuid;
this.playername = playername;
this.reason = reason;
this.jailer = jailer;
this.location = location;
this.jailed_time = jailed_time;
this.to_be_released = to_be_released;
this.online = online;
}
public void add() {
Jail.jailed_players.add(this.uuid);
}
public void insert() {
SQLite.insert_player_info(this);
}
public int get_to_be_released() {
int ret = 0;
if (this.to_be_released)
ret ^= 1;
if (!this.online)
ret ^= 2;
return ret;
}
/**
* Returns a text description of this jailed player.
*/
public String get_info() {
SimpleDateFormat sdf = new SimpleDateFormat("d MMMM yyyy, H:m:s");
String msg = this.playername + " (" + this.uuid + ")"
+ " was jailed on " + sdf.format(new Date(this.jailed_time * 1000L))
+ " by " + this.jailer
+ " for" + this.reason + ".";
if (this.to_be_released) {
msg += "\nThis player is set to be released";
}
return msg;
}
}
| C4K3/Jail | src/main/java/net/simpvp/Jail/JailedPlayer.java | Java | unlicense | 1,551 |
/*
* NOTE: This copyright does *not* cover user programs that use HQ
* program services by normal system calls through the application
* program interfaces provided as part of the Hyperic Plug-in Development
* Kit or the Hyperic Client Development Kit - this is merely considered
* normal use of the program, and does *not* fall under the heading of
* "derived work".
*
* Copyright (C) [2004, 2005, 2006], Hyperic, Inc.
* This file is part of HQ.
*
* HQ is free software; you can redistribute it and/or modify
* it under the terms version 2 of the GNU General Public License as
* published by the Free Software Foundation. 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.
*/
package org.hyperic.hq.ui.action.portlet.autoDisc;
import org.hyperic.hq.appdef.shared.AIPlatformValue;
import org.hyperic.hq.autoinventory.ScanStateCore;
import org.hyperic.hq.autoinventory.ScanMethodState;
public class AIPlatformWithStatus
extends AIPlatformValue {
private ScanStateCore state = null;
public AIPlatformWithStatus(AIPlatformValue aip, ScanStateCore state) {
super(aip);
this.state = state;
}
public boolean getIsAgentReachable() {
return state != null;
}
public boolean getIsScanning() {
return state != null && !state.getIsDone();
}
public String getStatus() {
if (state == null)
return "Agent is not responding";
if (state.getGlobalException() != null) {
return state.getGlobalException().getMessage();
}
ScanMethodState[] methstates = state.getScanMethodStates();
String rval = "";
String status;
for (int i = 0; i < methstates.length; i++) {
status = methstates[i].getStatus();
if (status != null)
rval += status.trim();
}
rval = rval.trim();
if (rval.length() == 0) {
rval = "Scan starting...";
}
return rval;
}
}
| cc14514/hq6 | hq-web/src/main/java/org/hyperic/hq/ui/action/portlet/autoDisc/AIPlatformWithStatus.java | Java | unlicense | 2,391 |
#ifndef HAVE_spiral_io_hpp
#define HAVE_spiral_io_hpp
#include <cstdio>
#include "spiral/core.hpp"
#include "spiral/string.hpp"
namespace spiral {
struct IoObj {
const ObjTable* otable;
std::FILE* stdio;
bool close_on_drop;
};
auto io_from_val(Bg* bg, Val val) -> IoObj*;
auto io_from_obj_ptr(void* obj_ptr) -> IoObj*;
auto io_new_from_stdio(Bg* bg, void* sp, std::FILE* stdio, bool close_on_drop) -> IoObj*;
void io_stringify(Bg* bg, Buffer* buf, void* obj_ptr);
auto io_length(void* obj_ptr) -> uint32_t;
auto io_evacuate(GcCtx* gc_ctx, void* obj_ptr) -> Val;
void io_scavenge(GcCtx* gc_ctx, void* obj_ptr);
void io_drop(Bg* bg, void* obj_ptr);
auto io_eqv(Bg* bg, void* l_ptr, void* r_ptr) -> bool;
extern const ObjTable io_otable;
auto io_open_file(Bg* bg, void* sp, StrObj* path, const char* mode) -> Val;
extern "C" {
auto spiral_std_io_file_open(Bg* bg, void* sp, uint32_t path) -> uint32_t;
auto spiral_std_io_file_create(Bg* bg, void* sp, uint32_t path) -> uint32_t;
auto spiral_std_io_file_append(Bg* bg, void* sp, uint32_t path) -> uint32_t;
auto spiral_std_io_close(Bg* bg, void* sp, uint32_t io) -> uint32_t;
auto spiral_std_io_flush(Bg* bg, void* sp, uint32_t io) -> uint32_t;
auto spiral_std_is_io(Bg* bg, void* sp, uint32_t io) -> uint32_t;
auto spiral_std_io_is_eof(Bg* bg, void* sp, uint32_t io) -> uint32_t;
auto spiral_std_io_is_error(Bg* bg, void* sp, uint32_t io) -> uint32_t;
auto spiral_std_io_stdin(Bg* bg, void* sp) -> uint32_t;
auto spiral_std_io_stdout(Bg* bg, void* sp) -> uint32_t;
auto spiral_std_io_stderr(Bg* bg, void* sp) -> uint32_t;
auto spiral_std_io_write_byte(Bg* bg, void* sp, uint32_t io, uint32_t byte) -> uint32_t;
auto spiral_std_io_write(Bg* bg, void* sp, uint32_t io, uint32_t str) -> uint32_t;
auto spiral_std_io_write_line(Bg* bg, void* sp, uint32_t io, uint32_t str) -> uint32_t;
auto spiral_std_io_read_byte(Bg* bg, void* sp, uint32_t io) -> uint32_t;
auto spiral_std_io_read_str(Bg* bg, void* sp, uint32_t io, uint32_t len) -> uint32_t;
auto spiral_std_io_read_all_str(Bg* bg, void* sp, uint32_t io) -> uint32_t;
auto spiral_std_io_read_line(Bg* bg, void* sp, uint32_t io) -> uint32_t;
auto spiral_std_io_read_word(Bg* bg, void* sp, uint32_t io) -> uint32_t;
auto spiral_std_io_read_int(Bg* bg, void* sp, uint32_t io) -> uint32_t;
auto spiral_std_io_read_number(Bg* bg, void* sp, uint32_t io) -> uint32_t;
}
}
#endif
| honzasp/spiral | rt/include/spiral/io.hpp | C++ | unlicense | 2,505 |
package generics.p19;
import java.util.Random;
import utils.Generator;
public class Good {
private final int id;
private String description;
public Good(int id, String description) {
this.id = id;
this.description = description;
}
public static Generator<Good> generator = new Generator<Good>() {
Random random = new Random();
@Override
public Good next() {
return new Good(random.nextInt(1000), "");
}
};
@Override
public String toString() {
return "Good: " + id + " " + description;
}
}
| bodydomelight/tij-problems | src/generics/p19/Good.java | Java | unlicense | 619 |
var Theme = (function() {
var Theme = function() {
};
return Theme;
})();
module.exports = Theme;
| frostney/dropoff | lib/theme/index.js | JavaScript | unlicense | 119 |
lcasecbl
========
C99 utility to convert COBOL to lowercase or uppercase.
The following are excluded from being converted to the target case:
comment lines
sequence area (columns 1-6)
indicator area (column 7)
comment area (column 73 through end of line)
alphanumeric literals
hexadecimal literals
pseudo-text
Everything else is converted to the target case. This is not necessarily valid.
Options
===========
A few options are supported. Options may start with either a hyphen (-) or a slash (/).
-h Help. Show the usage statement.
-u Uppercase. Convert code to uppercase rather than to lowercase.
Assumptions
===========
The COBOL source code is assumed to be in ANSI format (a.k.a. reference format).
The only exception is that the comment area is allowed to be arbitrarily long.
This is done to prevent truncation of overlong comments.
The code is assumed to compile, so that unexpected conditions like unterminated
alphanumeric literals and unterminated pseudo-text will not occur. Continuation
lines are supported.
Alphanumeric and hex literals are assumed to be delimited in the following ways:
"abcdef"
'abcdef'
Pseudo-text is assumed to be delimited as follows:
==some text goes here==
Alphanumeric literals, hex literals, and pseudo-text may continue across line
breaks. Continuation lines have a hyphen in the indicator area.
Normal lines have a space in the indicator area.
Conditional debugging lines have a 'D' or 'd' in the indicator area, and are
treated here like normal lines.
Comment lines have one of the following in the indicator area: an asterisk (*),
a slash (/), or a dollar sign ($).
Lines may continue beyond the comment area, which starts in column 73 and ends
in column 80. Everything past column 72 is considered to be a comment.
Caveats
=======
Areas where I suspect that breakage may occur in at least some dialects of
COBOL are:
case-sensitive picture clauses
space-delimited literals
| ps8v9/lcasecbl | README.md | Markdown | unlicense | 2,008 |
#!/bin/bash
#
# ++++ Raspberry Pi Temperature script ++++
#
# By woftor (GitHub)
#
# This script shows the temperature of the ARM CPU of you Raspberry Pi: current, mean, lowest and highest.
# You can choose between Celcius of Fahrenheit.
# It uses three text files to store data:
# - pitemps_file for the last temperatures
# - pitemps_data_file_mean to calculate a mean temperature
# - pitemps_data_file_plot for plotting/arhiving
#
# You can tweak the update interval and the number of hours to use for the mean.
# Other variables are in the first part of this script.
#
# To make a plot, see the configuration file 'pitemps-gnuplot.conf'
#
# ---- ---- ---- ---- ---- Change variables below this line ---- ---- ---- ---- ----
# Update time in seconds
# Note: the script will finish the whole duration of update time at exit. Make it too long and the waiting time on exit can be long
# CTRL-C is disabled ny default. You can enable it by commenting out "trap '' 2" below
# Doing a CTRL-C will disable output to the file with last temperatures however
update_interval=4
# Number of hours to use for the mean.
no_hours_mean=1
# Number of hours to store for plotting/archiving (the data older than this will be deleted)
no_hours_plot=168
# Which directory to use to store the files (must be writable, will be created if necessary)
pitemps_dir=~/pitemps
# Name of the file containing the last temperatures (mean, high and low)
pitemps_file=pitemps-last.txt
# Name of the data file containing the temperatures used for the mean
pitemps_data_file_mean=pitemps-data-mean.txt
# Name of the data file containing the temperatures for plotting/archiving
pitemps_data_file_plot=pitemps-data-plot.txt
# Make backups of data files if they exist? 1 for Yes and 2 for No
make_backups=1
# Date format (see 'man date' for help). Default %d-%m-%Y %H:%M:%S - 14-05-2017 20:48:23
date_format="%d-%m-%Y %H:%M:%S"
# Temperature scale: 1 for degree Celcius, 2 for degree Fahrenheit
temp_scale=1
# Trap 'signal 2' to disable CTRL-C
# CTRL-C is disabled ny default. You can enable it by commenting out this variable
# Doing a "CTRL-C" will disable output to the file with last temperatures however
trap '' 2
# ---- ---- ---- ---- ---- Change variables above this line ---- ---- ---- ---- ----
# Official version. Please don't change.
version=2.2.1
# ---- ---- ---- ---- ---- Begin of variable check section ---- ---- ---- ---- ----
# Check if 'bc' installed? (required)
command -v bc >/dev/null 2>&1 || { echo; echo >&2 "Error: program 'bc' is not installed, please install it ('sudo apt install bc')"; echo; exit 1; }
# Check if the update time is valid (must be an integer)
re='^[0-9]+$'
if ! [[ $update_interval =~ $re ]]
then
echo
echo "Error: Number of seconds update time must be an integer (1,2,3 etc.). It is now set to '$update_interval'. Please check variables in pitemps file."
echo
exit 1
fi
# Check if the number of hours for the mean is valid (must be an integer)
if ! [[ $no_hours_mean =~ $re ]]
then
echo
echo "Error: Number of hours to use for mean must be an integer (1,2,3 etc.). It is now set to '$no_hours_mean'. Please check variables in pitemps file."
echo
exit 1
fi
# Check if the option to make backups is valid
if [[ $make_backups != 1 && $make_backups != 2 ]]
then
echo
echo "Error: Option to make backups must be 1 (Yes) or 2 (No). It is now set to '$make_backups'. Please check variables in pitemps file."
echo
exit 1
fi
# Check if the temperature scale is valid
if [[ $temp_scale != 1 && $temp_scale != 2 ]]
then
echo
echo "Error: Temperature scale must be 1 (Celcius) or 2 (Fahrenheit). It is now set to '$temp_scale'. Please check variables in pitemps file."
echo
exit 1
fi
# Check if the directory to store the files exists and if it's writable
if [[ ! -d $pitemps_dir ]]
then
if [[ -w $(dirname "$pitemps_dir") ]]
then
mkdir $pitemps_dir
else
echo
echo "Error: Cannot create pitemps directory '$pitemps_dir' - No write permission. Please check variables in pitemps file."
echo
exit 1
fi
else
if [[ ! -w $pitemps_dir ]]
then
echo
echo "Error: No write permissions in pitemps directory '$pitemps_dir'. Please check variables in pitemps file."
echo
exit 1
fi
fi
# Max hours 9999
if [[ $no_hours_mean -gt 9999 ]]
then
echo
echo "Error: Too many hours for calculation mean (max 9999). It is now set to '$no_hours_mean'. Please check variables in pitemps file."
echo
exit 1
fi
# ---- ---- ---- ---- ---- End of variable check section ---- ---- ---- ---- ----
# This is to make sure the file containing the last variables looks pretty (adds spaces if appropriate)
if [[ $no_hours_mean -gt 999 ]]
then
spaces=" "
elif [[ $no_hours_mean -gt 99 ]]
then
spaces=" "
elif [[ $no_hours_mean -gt 9 ]]
then
spaces=" "
else
spaces=""
fi
# Define function to make the temperatures read by the script human readable and do Fahrenheit converion if appropriate
if [[ $temp_scale = 1 ]]
then
function convert_temp {
bc <<< "scale=1; $1/1000"
}
else
function convert_temp {
bc <<< "scale=1; $1 * 1.8 / 1000 + 32"
}
fi
# Celcius or Fahrenheit symbol
if [[ $temp_scale = 1 ]]
then
deg=$'\xc2\xb0'C
else
deg=$'\xc2\xb0'F
fi
# Some variables to format the output on the screen
noform=$(tput sgr0)
form1=$(tput setaf 6)
form2=$(tput bold)$(tput setaf 3)
form3=$(tput bold)$(tput setaf 2)
form4=$(tput bold)$(tput setaf 1)
# Set the path of the files
pitemps_file_P=$pitemps_dir/$pitemps_file
pitemps_data_file_mean_P=$pitemps_dir/$pitemps_data_file_mean
pitemps_data_file_plot_P=$pitemps_dir/$pitemps_data_file_plot
# Initial (bogus) temperatures, will not be stored
if [[ $temp_scale = 1 ]]
then
low_temp=100.0
high_temp=0.0
else
low_temp=212.0
high_temp=32.0
fi
# Initialize the text files (make backups if appropriate)
if [[ -f $pitemps_file_P ]]
then
if [[ $make_backups = 1 ]]
then
if ! [[ -d $pitemps_dir/backups ]]
then
mkdir $pitemps_dir/backups
cp --backup=t $pitemps_file_P $pitemps_dir/backups/$pitemps_file
else
cp --backup=t $pitemps_file_P $pitemps_dir/backups/$pitemps_file
fi
fi
> $pitemps_file_P
else
touch $pitemps_file_P
fi
if [[ -f $pitemps_data_file_mean_P ]]
then
if [[ $make_backups = 1 ]]
then
if ! [[ -d $pitemps_dir/backups ]]
then
mkdir $pitemps_dir/backups
cp --backup=t $pitemps_data_file_mean_P $pitemps_dir/backups/$pitemps_data_file_mean
else
cp --backup=t $pitemps_data_file_mean_P $pitemps_dir/backups/$pitemps_data_file_mean
fi
fi
> $pitemps_data_file_mean_P
else
touch $pitemps_data_file_mean_P
fi
if [[ -f $pitemps_data_file_plot_P ]]
then
if [[ $make_backups = 1 ]]
then
if ! [[ -d $pitemps_dir/backups ]]
then
mkdir $pitemps_dir/backups
cp --backup=t $pitemps_data_file_plot_P $pitemps_dir/backups/$pitemps_data_file_plot
else
cp --backup=t $pitemps_data_file_plot_P $pitemps_dir/backups/$pitemps_data_file_plot
fi
fi
> $pitemps_data_file_plot_P
else
touch $pitemps_data_file_plot_P
fi
# The time this script was started for the statistics
start_time_script=$(date +"$date_format")
# The time at beginning of the loop to calculate running time and when to truncate data file for mean and plotting/archiving
start_time_loop=$(date "+%s")
# Calculate when the data file for the mean and for plotting/archiving should be truncated
trunc_temp_data_mean=$(( $no_hours_mean * 3600 + $start_time_loop + $update_interval))
trunc_temp_data_plot=$(( $no_hours_plot * 3600 + $start_time_loop + $update_interval))
# Set stty for catching keys
if [[ -t 0 ]]
then
stty -echo -icanon -icrnl time 0 min 0
fi
# Beginning of a loop to update temperatures and times
while true
do
# Read the actual temperature from the sensor, make it human readable and do conversion to Fahrenheir if appropriate
temp=$(convert_temp $(cat /sys/class/thermal/thermal_zone0/temp))
# Check if the temperature is lower than the lowest recorded and change the variable if appropriate
if (( $(bc <<< "$temp < $low_temp") ))
then
low_temp_time=$(date +"$date_format")
low_temp=$temp
fi
# Check if the temperature is higher than the highest recorded and change the variable if appropriate
if (( $(bc <<< "$temp > $high_temp") ))
then
high_temp_time=$(date +"$date_format")
high_temp=$temp
fi
# The current time
current_time=$(date +"$date_format")
# The time during the loop to calculate running time
current_time_loop=$(date "+%s")
# Calculate the time the loop is running in seconds
running_time=$(($current_time_loop-$start_time_loop))
# Convert the running time of the script to human readable format
running_time=$(echo "$((running_time / 86400)) day(s) $((($running_time % 86400) / 3600 )) hour(s) $((($running_time % 3600) / 60)) minute(s) $(($running_time % 60)) second(s)")
# Write temperature and date/time to the data file for the mean and for plotting/archiving
echo $current_time $temp | tee -a $pitemps_data_file_mean_P >> $pitemps_data_file_plot_P
# Truncate the data file for the mean and for plotting/archiving if appropriate (from the top)
if [[ $current_time_loop -gt $trunc_temp_data_mean ]]
then
sed -i '1d' $pitemps_data_file_mean_P
fi
if [[ $current_time_loop -gt $trunc_temp_data_plot ]]
then
sed -i '1d' $pitemps_data_file_plot_P
fi
# Calculate the mean temperature from the data file for the mean
mean_temp=$(awk '{ total += $3 } END { printf"%.1f",total/NR }' $pitemps_data_file_mean_P)
# Clear the screen
clear
# Present the temperatures / times
echo "$(tput cup 2 6)$form1 ---- Raspberry Pi CPU Temperature ----$(tput cup 2 60)$noform v$version"
echo "$(tput cup 4 2)$noform Current temperature:$(tput cup 4 40)| $form2$temp$noform $deg |"
echo "$(tput cup 5 2)$noform Mean temperature - $no_hours_mean hour(s):$(tput cup 5 40)| $form2$mean_temp$noform $deg |"
echo "$(tput cup 7 2)$noform Lowest temperature:$(tput cup 7 40)| $form3$low_temp$noform $deg | $form1($low_temp_time)"
echo "$(tput cup 8 2)$noform Highest temperature:$(tput cup 8 40)| $form4$high_temp$noform $deg | $form1($high_temp_time)"
echo "$(tput cup 10 6)$noform Update interval:$(tput cup 10 40)$form1$update_interval sec."
echo "$(tput cup 11 6)$noform Script was started:$(tput cup 11 40)$form1$start_time_script"
echo "$(tput cup 12 6)$noform Current date/time:$(tput cup 12 40)$form1$current_time"
echo "$(tput cup 13 6)$noform Script is running:$(tput cup 13 40)$form1$running_time"
echo "$(tput cup 16 2)$noform Press $form4'q'$noform to quit/exit..."
echo "$(tput cup 18 5)$noform (Note: exit after max.$form1 $update_interval sec.$noform pressing 'q')"
# Catch 'q' to quit. Then position cursur below the lowest line and break the loop
read input
if [[ "$input" = "q" ]]
then
tput cup 20 0
break
fi
# Sleep for the duration of the update interval
sleep $update_interval
done
# Set stty to normal again
if [[ -t 0 ]]
then
stty sane
fi
# The time this script was stopped for the statistics
stop_time_script=$(date +"$date_format")
# Write the mean temperature to the file with the last temperatures
echo "Mean temperature - $no_hours_mean hour(s): $mean_temp $deg" >> $pitemps_file_P
# Write the lowest temperature to the file with the last temperatures
echo "Lowest temperature: $spaces $low_temp $deg ($low_temp_time)" >> $pitemps_file_P
# Write the highest temperature to the file with the last temperatures
echo "Highest temperature: $spaces $high_temp $deg ($high_temp_time)" >> $pitemps_file_P
# Write the update interval, running time, start and stop times to the file with last temperatures
echo >> $pitemps_file_P
echo "Update interval: $update_interval" >> $pitemps_file_P "sec."
echo "Script started: $start_time_script" >> $pitemps_file_P
echo "Script stopped: $stop_time_script" >> $pitemps_file_P
echo "Script was running: $running_time" >> $pitemps_file_P
# End signal 2 (CTRL-C) trap
trap 2
| woftor/pitemps | pitemps.sh | Shell | unlicense | 12,490 |
# mentat-example
Example app for the hapi.js microframework mentat
| alivesay/mentat-example | README.md | Markdown | unlicense | 67 |
# -*- coding: utf-8 -*-
"""
Created on Fri Nov 15 15:55:28 2013
@author: dyanna
"""
import numpy as np
from sklearn.svm import SVC
def getSample(pointA, pointB, numberOfPoints):
pointList = list(zip(np.random.uniform(-1,1.00,numberOfPoints),np.random.uniform(-1,1.00,numberOfPoints)))
sample = np.array([(i[0], i[1], isLeft(pointA, pointB, i)) for i in pointList])
y = sample[:,2]
breakpoint = False
while not breakpoint:
if(len(y[y==-1]) == 0 or len(y[y==1]) == 0):
pointList = list(zip(np.random.uniform(-1,1.00,numberOfPoints),np.random.uniform(-1,1.00,numberOfPoints)))
sample = np.array([(i[0], i[1], isLeft(pointA, pointB, i)) for i in pointList])
y = sample[:,2]
else:
breakpoint = True
return sample
def getRandomLine():
return list(zip(np.random.uniform(-1,1.00,2),np.random.uniform(-1,1.00,2)))
def getPoints(numberOfPoints):
pointList = list(zip(np.random.uniform(-1,1.00,numberOfPoints),np.random.uniform(-1,1.00,numberOfPoints)))
return pointList
def isLeft(a, b, c):
return 1 if ((b[0] - a[0])*(c[1] - a[1]) - (b[1] - a[1])*(c[0] - a[0])) > 0 else -1;
def sign(x):
return 1 if x > 0 else -1
def getMisMatchesQP(data, clf):
#print(data)
data_x = np.c_[data[:,0], data[:,1]]
results = clf.predict(data_x)
#print(np.sign(results))
print("mismatch ", float(len(data) - np.sum(np.sign(results) == np.sign(data[:,2])))/len(data))
print("score ", clf.score(data_x, data[:,2]))
return float(len(data) - np.sum(np.sign(results) == np.sign(data[:,2])))/len(data)
def doMonteCarloQP(pointa, pointb, clf, nopoint):
#print "weights ", weight
points = [(np.random.uniform(-1,1), np.random.uniform(-1,1)) for i in range(nopoint)]
#print points
dataset_Monte = np.array([(i[0],i[1], isLeft(pointa,pointb,i)) for i in points])
#print dataset_Monte
return getMisMatchesQP(dataset_Monte, clf)
def doPLA(sample):
w = np.array([0,0,0])
iteration = 0
it = 0
while True:#(it < 10):
iteration = iteration + 1
it = it + 1
mismatch = list()
for i in sample:
#print("point in question ", i , " weight ", w)
yy = w[0] + w[1] * i[0] + w[2] * i[1]
#print("this is after applying weight to a point ",yy)
point = [i[0], i[1], sign(yy)]
if any(np.equal(sample, point).all(1)):
#print "point not in sample"
if(point[2] == -1):
mismatch.append((1, (i[0]), (i[1])))
else:
mismatch.append((-1, -(i[0]), -(i[1])))
#print " length ", len(mismatch), " mismatch list ",mismatch
if(len(mismatch) > 0):
#find a random point and update w
choiceIndex = np.random.randint(0, len(mismatch))
choice = mismatch[choiceIndex]
#print("choice ", choice)
w = w + choice
#print "new weight ", w
else:
break
#print("this is the iteration ", iteration)
#print("this is the weight ", w)
#montelist = [monetcarlo((x1,y1),(x2,y2),w,10000) for i in range(5)]
#print("Montelist " , montelist)
#monteavg = sum([i for i in montelist])/10
return w, iteration
def getMisMatches(data, weights):
#print data
list1 = np.empty(len(data))
list1.fill(weights[0])
results = list1+ weights[1]*data[:,0]+weights[2]*data[:,1]
results = -1 * results
return float(len(data) - np.sum(np.sign(results) == np.sign(data[:,2])))/len(data)
def doMonteCarloNP(pointa, pointb, weights, nopoint):
#print "weights ", weight
points = [(np.random.uniform(-1,1), np.random.uniform(-1,1)) for i in range(nopoint)]
#print points
dataset_Monte = np.array([(i[0],i[1], isLeft(pointa,pointb,i)) for i in points])
#print dataset_Monte
return getMisMatches(dataset_Monte, weights)
if __name__ == "__main__":
'''X = np.array([[-1,-1],[-2,-1], [1,1], [2,1]])
y = np.array([1,1,2,2])
clf = SVC()
clf.fit(X,y)
print(clf.predict([[-0.8,-1]]))'''
#clf = SVC()
clf = SVC(C = 1000, kernel = 'linear')
monteavgavgQP = list()
monteavgavgPLA = list()
approxavgQP = list()
vectornumberavg = list()
predictavg = list()
for j in range(1):
#clf = SVC(C = 1000, kernel = 'linear')
monteavgQP = list()
monteavgPLA = list()
approxQP = list()
vectoravg = list()
for k in range(1000):
nopoints = 100
line = getRandomLine()
sample = getSample(line[0], line[1], nopoints)
#print(sample)
X = np.c_[sample[:,0], sample[:,1]]
y = sample[:,2]
#print(y)
clf.fit(X,y)
#print(clf.score(X,y))
w, it = doPLA(sample)
#print(len(clf.support_vectors_))
#print(clf.support_vectors_)
#print(clf.support_)
vectoravg.append(len(clf.support_vectors_))
#print(clf.predict(clf.support_vectors_)==1)
#print(clf.predict(clf.support_vectors_))
#print(clf.coef_)
montelistQP = [doMonteCarloQP(line[0], line[1], clf, 500) for i in range(1)]
qpMonte = sum(montelistQP)/len(montelistQP)
monteavgQP.append(sum(montelistQP)/len(montelistQP))
montelist = [ doMonteCarloNP(line[0], line[1], w, 500) for i in range(1)]
plaMonte = sum(montelist)/len(montelist)
monteavgPLA.append(plaMonte)
if(montelistQP < monteavgPLA):
approxQP.append(1)
else:
approxQP.append(0)
#print(sum(monteavgQP)/len(monteavgQP))
#print(sum(monteavgPLA)/len(monteavgPLA))
#print(sum(approxQP)/len(approxQP))
monteavgavgQP.append(sum(monteavgQP)/len(monteavgQP))
monteavgavgPLA.append(sum(monteavgPLA)/len(monteavgPLA))
approxavgQP.append(sum(approxQP)/len(approxQP))
vectornumberavg.append(sum(vectoravg)/len(vectoravg))
print(sum(monteavgavgQP)/len(monteavgavgQP))
print(sum(monteavgavgPLA)/len(monteavgavgPLA))
print("how good is it? ", sum(approxavgQP)/len(approxavgQP))
print("how good is it? ", sum(vectornumberavg)/len(vectornumberavg))
| pramodh-bn/learn-data-edx | Week 7/qp.py | Python | unlicense | 6,393 |
# sets the last write time to now
# usage: ls -Recursion | .\touch
$now = Get-Date
foreach ($i in $input) {
$i.LastWriteTime = $now
echo $i.Name
} | lincore81/ccscripts | touch.ps1 | PowerShell | unlicense | 156 |
---
layout: page
title: Advocacy
date: 2013-01-08 22:41:31.000000000 -06:00
type: page
published: true
status: publish
categories: []
tags: []
header: true
---
The **Open Austin Policy Team** works with local governments and public agencies, in support of open government and civic technologies.
* TOC
{:toc}
---
## Candidate Questionnaires
Since 2011, in every City of Austin election, Open Austin submitted a policy questionnaire to all the candidates. We ask for their response on a variety of open government and important civic tech issues. We do not endorse candidates, but we do encourage voters to be informed on candidate positions.
* [2014 Austin City Council Candidate Questionnaire]({{site.baseurl}}/candidate-questionnaires/2014-austin-city-council.html)
* [2012 Austin City Council Candidate Questionnaire]({{site.baseurl}}/candidate-questionnaires/2012-austin-city-council.html)
* [2011 Austin City Council Candidate Questionnaire]({{site.baseurl}}/candidate-questionnaires/2011-austin-city-council.html)
## Documents and Activity
Here's some of the activity that's occurred during our advocacy for open government.
{:.no_toc}
### 2016 Advocacy Agenda
Open Austin members brainstormed a list of priorities for using data to improve public services, mostly at the city level.
* [Open Austin Advocacy Agenda 2016]({{site.baseurl}}/advocacy/documents/OpenAustinAdvocacyAgenda2016.pdf)
{:.no_toc}
### Open Data Initiative 2.0 - Apr 8, 2015
The city launched its open data initiative with the creation of its new website and open data portal. To increase department participation and open data availability, city management relaunched the effort with the _Open Data Initiative 2.0_.
* [Open Data Initiative 2.0]({{site.baseurl}}/advocacy/documents/20150408_Open_Data_Initiative_2_0.pdf) - Memo from City Manager to department heads announcing the Open Data Initiative 2.0
* [Open Data Particpation Plan]({{site.baseurl}}/advocacy/documents/20150408_Open_Data_Particpation_Plan.pdf) - 90 plan to implement the Open Data Initiative 2.0
{:.no_toc}
### Open Government Briefing Guide - Aug 27, 2014
As part of our outreach effort for the 2014 City of Austin municipal election, we produced a briefing guide and distributed it to all the candidates for mayor and city council. The briefing guide summarized some of the key policies and initiatives related to open government and open data efforts in Austin.
* [Open Government Briefing Guide]({{site.baseurl}}/candidate-questionnaires/documents/2014_OpenAustin_OpenGovBriefing.pdf) (1.8MB PDF document)
{:.no_toc}
### Innovation Office Goals - Oct 9, 2013
We've proposed that the City of Austin create an Office of Civic Innovation, and the City is moving forward on this effort.
In an attempt to clarify the expectations for this office, the Community Technology and Telecommunications Commission adopted a recommendation for items to be included in the mission and goals for the office.
* [Recommendations Relating to the Creation of an Office of Civic Innovation]({{site.baseurl}}/advocacy/documents/document_724B68BF-BE83-EE08-7A4B7DD60EB188ED.pdf)
{:.no_toc}
### Open Government Audit - Aug 28, 2013
The City of Austin Auditor conducted a performance audit of the Open Government Initiative, and presented their findings to the City Council Audit and Finance Committee. A key finding of the report was:
> The lack of a defined strategy is impacting the City’s ability to successfully implement the Open Government initiative, as directed by Council resolution.
We attended the committee meeting and expressed our concerns about the state of the Open Government Initiative, with focus on the lack of community engagement in the Civic Innovation Office effort.
* [Report: AustinGO Website Governance and Management Audit]({{site.baseurl}}/advocacy/documents/au13006.pdf)
* [Presentation by City Auditor: AustinGO Website Governance and Management Audit]({{site.baseurl}}/advocacy/documents/AustinGO-83013.pdf)
* [Presentation by City Staff: AustinGo Webside Governance and Management Audit]({{site.baseurl}}/advocacy/documents/Audit-and-Finance-Presentation-8-28.pdf)
* [Presentation by Open Austin: Open Gov Initiative Community Perspective]({{site.baseurl}}/advocacy/documents/20130828-open-gov-community-perspective-slides.pdf)
* [Video: Audit and Finance Committee, Aug 28, 2013, agenda item 4](http://austintx.swagit.com/play/08282013-642/#4)
{:.no_toc}
### Draft Open Government Directive - Aug 26, 2013
Just days before the report on the performance audit of the Open Government Initiative, the City Manager released a draft Open Government Directive. It's expected that the final directive will be forthcoming once the open Civic Innovation Officer is hired. This directive was developed by city staff, working with the Open Government Working Group setup by the City of Austin Community Technology and Telecommunications Commission, and includes our input.
* <span style="line-height: 14px;">[Memo: Draft Open Government Directive]({{site.baseurl}}/advocacy/documents/Memo-to-Mayor-and-Council-with-attached-Open-Government-Directive.pdf)
</span>
{:.no_toc}
### Innovation Office Proposal - Aug 30, 2012
The Austin City Council conducted a Budget Hearing on August 30, 2012, to receive citizen input on the FY2013 budget. At the hearing, we proposed creating a Civic Innovation Office, to provide leadership for the city's Open Government Initiative. The City Council approved adding $250K funds to the FY2013 budget, to pilot a new innovation office.
* [Civic Innovation Office Proposal]({{site.baseurl}}/advocacy/documents/20120830-civic-innovation-proposal.pdf) by Open Austin
{:.no_toc}
### Open Government Resolution - Dec 8, 2011
On December 8, 2011, the Austin City Council adoped an Open Government Resolution, which called for the City Manager to propose an Open Government Framework, including implementation plans and budgets. We provided input to the resolution, and strongly support its adoption.
* [City of Austin Open Government Resolution]({{site.baseurl}}/advocacy/documents/20111208-austin-opengov-resol.pdf)
## Government Data
* [City of Austin Open Data Portal](https://data.austintexas.gov/) (data.austintexas.gov) - Provides datasets published by the City, as well as reporting and visualization tools that operate on these datasets.
* [City of Austin GIS](http://austintexas.gov/department/gis-and-maps) (Geographic Information Systems) - Downloadable GIS datasets, plus links to various maps and viewers.
* [Capital Metro Geospatial Data](http://www.capmetro.org/datastats.aspx?id=129) - GIS datasets published by the local transit authority.
* [CAPCOG Data, Maps, and Reports](http://www.capcog.org/data-maps-and-reports/) - Published by the Capital Area Council of Governments
* [TNRIS Maps & Data](http://www.tnris.org/get-data?quicktabs_maps_data=1) - Published by the Texas Natural Resources Information System, part of the Texas Water Development Board.
## City of Austin
* [Austin Government Online](http://www.austingo.org/) (AustinGO) - Updates from the City of Austin "AustinGO" team.
* [@atxgo](https://twitter.com/atxgo) - AustinGO2.0 Twitter feed
## Other Resources
* [Code for America / Austin](http://codeforamerica.org/austin/) - In 2012, Austin participated in a _Code for America_ fellowship.
| open-austin/open-austin-org | advocacy/index.md | Markdown | unlicense | 7,416 |
const fs = require('fs');
const electron = require('electron');
const cl = require('node-opencl');
const RUN_GAMELOOP_SYNC = true;
const GAMETICK_CL = true;
const INIT_OPENGL = false;
let canvas; // canvas dom element
let gl; // opengl context
let clCtx; // opencl context
let glProgram; // opengl shader program
let clProgram; // opencl program
let clBuildDevice;
let clQueue;
// let clKernelMove;
let clKernelGol;
let clBufferAlive;
let clBufferImageData;
let
inputIndex = 0,
outputIndex = 1;
let locPosition; // location of position variable in frag shader
let locTexCoord; // location of texture coords variable in frag shader
let locSampler; // location of sampler in frag shader
let vertexCoordBuffer; // buffer for vertext coordinates
let texCoordBuffer; // buffer for texture coordinate
let texture; // texture
let imageData; // uint8array for texture data
let textureWidth = 1600;
let textureHeight = 900;
let gridWidth = 1600;
let gridHeight = 900;
const bytesPerPixel = 4; // bytes per pixel in imageData: R,G,B,A
const pixelTotal = textureWidth * textureHeight;
const bytesTotal = pixelTotal * bytesPerPixel;
const cellsTotal = gridWidth * gridHeight;
let cellNeighbors;
const cellAlive = [];
const frameTimes = [];
let frameTimesIndex = 0;
let lastRenderTime;
let fps = 0;
let fpsDisplay;
const FRAMETIMES_TO_KEEP = 10;
function init() {
(async () => {
initDom();
initDrawData();
if (INIT_OPENGL) {
initOpenGL();
}
initData();
await initOpenCL();
initGame();
initEvents();
startGameLoop();
render();
})();
}
function initDom() {
canvas = document.getElementById('glscreen');
fpsDisplay = document.getElementById('fps');
}
function initDrawData() {
imageData = new Uint8Array(bytesTotal);
}
function initOpenGL() {
gl = canvas.getContext('experimental-webgl');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight);
// init vertex buffer
vertexCoordBuffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, vertexCoordBuffer);
gl.bufferData(
gl.ARRAY_BUFFER,
new Float32Array([
-1.0, -1.0,
1.0, -1.0,
-1.0, 1.0,
-1.0, 1.0,
1.0, -1.0,
1.0, 1.0]),
gl.STATIC_DRAW
);
// ------ SHADER SETUP
const vertexShader = gl.createShader(gl.VERTEX_SHADER);
gl.shaderSource(vertexShader, fs.readFileSync(__dirname + '/shader-vertex.glsl', 'utf-8'));
gl.compileShader(vertexShader);
console.log('vertexShaderLog', gl.getShaderInfoLog(vertexShader));
const fragmentShader = gl.createShader(gl.FRAGMENT_SHADER);
gl.shaderSource(fragmentShader, fs.readFileSync(__dirname + '/shader-fragment.glsl', 'utf-8'));
gl.compileShader(fragmentShader);
console.log('fragmentShaderLog', gl.getShaderInfoLog(fragmentShader));
glProgram = gl.createProgram();
gl.attachShader(glProgram, vertexShader);
gl.attachShader(glProgram, fragmentShader);
gl.linkProgram(glProgram);
console.log('glProgramLog', gl.getProgramInfoLog(glProgram));
gl.useProgram(glProgram);
// ---
locPosition = gl.getAttribLocation(glProgram, 'a_position');
gl.enableVertexAttribArray(locPosition);
// provide texture coordinates for the rectangle.
locTexCoord = gl.getAttribLocation(glProgram, 'a_texCoord');
gl.enableVertexAttribArray(locTexCoord);
// ------ TEXTURE SETUP
texCoordBuffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, texCoordBuffer);
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([
0.0, 0.0,
1.0, 0.0,
0.0, 1.0,
0.0, 1.0,
1.0, 0.0,
1.0, 1.0]), gl.STATIC_DRAW);
// init texture to be all solid
for (let i = 0; i < pixelTotal; i++) {
const offset = i * bytesPerPixel;
imageData[offset + 3] = 255;
}
texture = gl.createTexture();
locSampler = gl.getUniformLocation(glProgram, 'u_sampler');
}
function initData() {
cellNeighbors = new Uint32Array(cellsTotal * 8);
cellAlive[0] = new Uint8Array(cellsTotal);
cellAlive[1] = new Uint8Array(cellsTotal);
// GOL: Cells
let index = 0, indexNeighbors = 0;
const maxX = gridWidth - 1;
const maxY = gridHeight - 1;
for (let y = 0; y < gridHeight; y++) {
const
prevRow = (y - 1) * gridWidth,
thisRow = prevRow + gridWidth,
nextRow = thisRow + gridWidth;
for (let x = 0; x < gridWidth; x++) {
cellNeighbors[indexNeighbors++] = (prevRow + x - 1 + cellsTotal) % cellsTotal;
cellNeighbors[indexNeighbors++] = (prevRow + x + cellsTotal) % cellsTotal;
cellNeighbors[indexNeighbors++] = (prevRow + x + 1 + cellsTotal) % cellsTotal;
cellNeighbors[indexNeighbors++] = (thisRow + x - 1 + cellsTotal) % cellsTotal;
cellNeighbors[indexNeighbors++] = (thisRow + x + 1) % cellsTotal;
cellNeighbors[indexNeighbors++] = (nextRow + x - 1) % cellsTotal;
cellNeighbors[indexNeighbors++] = (nextRow + x) % cellsTotal;
cellNeighbors[indexNeighbors++] = (nextRow + x + 1) % cellsTotal;
cellAlive[0][index++] = (Math.random() > 0.85) + 0;
}
}
}
async function initOpenCL() {
// --- Init opencl
// Best case we'd init a shared opengl/opencl context here, but node-opencl doesn't currently support that
const platforms = cl.getPlatformIDs();
for(let i = 0; i < platforms.length; i++)
console.info(`Platform ${i}: ${cl.getPlatformInfo(platforms[i], cl.PLATFORM_NAME)}`);
const platform = platforms[0];
const devices = cl.getDeviceIDs(platform, cl.DEVICE_TYPE_ALL);
for(let i = 0; i < devices.length; i++)
console.info(` Devices ${i}: ${cl.getDeviceInfo(devices[i], cl.DEVICE_NAME)}`);
console.info('creating context');
clCtx = cl.createContext([cl.CONTEXT_PLATFORM, platform], devices);
// prepare opencl program
// const clProgramSource = fs.readFileSync(__dirname + '/program.opencl', 'utf-8');
// GOL
const clProgramSource = fs.readFileSync(__dirname + '/gol.opencl', 'utf-8');
clProgram = cl.createProgramWithSource(clCtx, clProgramSource);
cl.buildProgram(clProgram);
// create kernels
// build kernel for first device
clBuildDevice = cl.getContextInfo(clCtx, cl.CONTEXT_DEVICES)[0];
console.info('Using device: ' + cl.getDeviceInfo(clBuildDevice, cl.DEVICE_NAME));
try {
// clKernelMove = cl.createKernel(clProgram, 'kmove');
clKernelGol = cl.createKernel(clProgram, 'kgol');
} catch(err) {
console.error(cl.getProgramBuildInfo(clProgram, clBuildDevice, cl.PROGRAM_BUILD_LOG));
process.exit(-1);
}
// create buffers
const clBufferNeighbors = cl.createBuffer(clCtx, cl.MEM_READ_ONLY, cellNeighbors.byteLength);
clBufferAlive = [
cl.createBuffer(clCtx, cl.MEM_READ_WRITE, cellAlive[inputIndex].byteLength),
cl.createBuffer(clCtx, cl.MEM_READ_WRITE, cellAlive[outputIndex].byteLength)
];
clBufferImageData = cl.createBuffer(clCtx, cl.MEM_WRITE_ONLY, imageData.byteLength);
// will be set when needed so we can swap em
// cl.setKernelArg(clKernelGol, 0, 'uchar*', clBufferAlive[0]);
// cl.setKernelArg(clKernelGol, 1, 'uchar*', clBufferAlive[1]);
cl.setKernelArg(clKernelGol, 2, 'uint*', clBufferNeighbors);
cl.setKernelArg(clKernelGol, 3, 'uchar*', clBufferImageData);
// create queue
if (cl.createCommandQueueWithProperties !== undefined) {
clQueue = cl.createCommandQueueWithProperties(clCtx, clBuildDevice, []); // OpenCL 2
} else {
clQueue = cl.createCommandQueue(clCtx, clBuildDevice, null); // OpenCL 1.x
}
process.stdout.write('enqueue writes\n');
cl.enqueueWriteBuffer(clQueue, clBufferAlive[0], true, 0, cellAlive[inputIndex].byteLength, cellAlive[inputIndex], null);
cl.enqueueWriteBuffer(clQueue, clBufferAlive[1], true, 0, cellAlive[outputIndex].byteLength, cellAlive[outputIndex], null);
process.stdout.write('writes done\n');
}
function initGame() {
}
function initEvents() {
window.addEventListener('resize', () => {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
});
}
// ----------- GAME LOOP
let lastLoopTime;
const timePerTick = 50; // ms
let timeSinceLastLoop = 0;
let tickCounter = 0;
function startGameLoop() {
lastLoopTime = Date.now();
if (!RUN_GAMELOOP_SYNC) {
gameLoop();
}
}
function gameLoop() {
const now = Date.now();
timeSinceLastLoop += now - lastLoopTime;
lastLoopTime = now;
while(timeSinceLastLoop > timePerTick) {
if (GAMETICK_CL) {
gameTickCl();
} else {
gameTick();
}
timeSinceLastLoop -= timePerTick;
}
if (!RUN_GAMELOOP_SYNC) {
setTimeout(gameLoop, timePerTick - timeSinceLastLoop);
}
}
function gameTickCl() {
process.stdout.write('gametick cl\n');
cl.setKernelArg(clKernelGol, 0, 'uchar*', clBufferAlive[inputIndex]);
cl.setKernelArg(clKernelGol, 1, 'uchar*', clBufferAlive[outputIndex]);
process.stdout.write('gametick cl 1\n');
cl.enqueueNDRangeKernel(clQueue, clKernelGol, 1, null, [cellsTotal], null);
process.stdout.write('gametick cl 2\n');
cl.enqueueReadBuffer(clQueue, clBufferImageData, true, 0, imageData.byteLength, imageData);
process.stdout.write('gametick cl done\n');
inputIndex = !inputIndex + 0;
outputIndex = !inputIndex + 0;
}
function gameTick() {
tickCounter++;
const input = cellAlive[inputIndex];
const output = cellAlive[outputIndex];
for (let i = 0, n = 0; i < cellsTotal; i++) {
const sum =
input[cellNeighbors[n++]]
+ input[cellNeighbors[n++]]
+ input[cellNeighbors[n++]]
+ input[cellNeighbors[n++]]
+ input[cellNeighbors[n++]]
+ input[cellNeighbors[n++]]
+ input[cellNeighbors[n++]]
+ input[cellNeighbors[n++]];
// sum < 2 -> !(sum & 4294967294)
// sum > 3 -> (sum & 12) 4 bit set OR 8 bit set
const newAlive = (sum === 3 || (sum === 2 && input[i])) + 0
output[i] = newAlive;
imageData[i * 4] = newAlive * 255;
}
// set computed value to red
inputIndex = !inputIndex + 0;
outputIndex = !inputIndex + 0;
}
// ----------- RENDER
function renderOpenGL() {
gl.clearColor(1.0, 0.0, 0.0, 1.0);
gl.clear(gl.COLOR_BUFFER_BIT);
gl.vertexAttribPointer(locPosition, 2, gl.FLOAT, false, 0, 0);
gl.bindBuffer(gl.ARRAY_BUFFER, texCoordBuffer);
gl.vertexAttribPointer(locTexCoord, 2, gl.FLOAT, false, 0, 0);
// texture
gl.bindTexture(gl.TEXTURE_2D, texture);
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, textureWidth, textureHeight, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
gl.bindTexture(gl.TEXTURE_2D, null);
gl.activeTexture(gl.TEXTURE0);
gl.bindTexture(gl.TEXTURE_2D, texture);
gl.uniform1i(locSampler, 0);
// draw
gl.bindBuffer(gl.ARRAY_BUFFER, vertexCoordBuffer);
gl.drawArrays(gl.TRIANGLES, 0, 6);
// console.log(electron.screen.getCursorScreenPoint());
}
function render() {
window.requestAnimationFrame(render);
if (RUN_GAMELOOP_SYNC) {
gameLoop();
}
const now = Date.now();
if (lastRenderTime) {
frameTimes[frameTimesIndex] = now - lastRenderTime;
frameTimesIndex = (frameTimesIndex + 1) % FRAMETIMES_TO_KEEP;
if (frameTimes.length >= FRAMETIMES_TO_KEEP) {
fps = 1000 * frameTimes.length / frameTimes.reduce((pv, cv) => pv + cv);
// do not update every frame
if ((frameTimesIndex % 5) === 0) {
fpsDisplay.innerHTML = fps.toFixed(2);
}
}
}
lastRenderTime = now;
if (INIT_OPENGL) {
renderOpenGL();
}
}
init(); | JohannesBeranek/electron-pixels | renderer.js | JavaScript | unlicense | 11,380 |
package net.yottabyte.game;
import java.awt.*;
/**
* @author Jason Fagan
*/
public class BouncyBall {
private int x;
private int y;
private int vx;
private int vy;
private int radius;
private int drag;
private int mass;
public BouncyBall(int x, int y, int vx, int vy, int radius, int mass, int drag) {
this.x = x;
this.y = y;
this.vx = vx;
this.vy = vy;
this.radius = radius;
this.mass = mass;
this.drag = drag;
}
public void move(Rectangle rect)
{
x += vx;
y += vy;
hitWall(rect);
}
public void paint(Graphics2D g2d) {
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setColor(Color.WHITE);
g2d.fillOval(x, y, radius, radius);
}
public void hitWall(Rectangle rect)
{
if (x <= 0) {
x = 0;
vx = -(vx * drag);
} else if (x + radius >= rect.width) {
x = rect.width - radius;
vx = -(vx * drag);
}
if (y < 0) {
y = 0;
vy = -(vy * drag);
} else if (y + (radius * 2) >= rect.height) {
y = rect.height - (radius * 2);
vy = -(vy * drag);
}
}
// see http://en.wikipedia.org/wiki/Elastic_collision
public boolean hasCollidedWith(BouncyBall ball) {
int dx = Math.abs(getCenterX() - ball.getCenterX());
int dy = Math.abs(getCenterY() - ball.getCenterY());
double distance = Math.sqrt(dx * dx + dy * dy);
return distance <= radius;
}
public void handleCollision(BouncyBall ball) {
int dx = getCenterX() - ball.getCenterX();
int dy = getCenterY() - ball.getCenterY();
// Calculate collision angle
double ca = Math.atan2(dy, dx);
// Calculate force magnitudes
double mgt1 = Math.sqrt(vx * vx + vy * vy);
double mgt2 = Math.sqrt(ball.getVx() * ball.getVx() + ball.getVy() * ball.getVy());
// Calculate direction
double dir1 = Math.atan2(vy, vx);
double dir2 = Math.atan2(ball.getVy(), ball.getVx());
// Calculate new velocities
double vx1 = mgt1 * Math.cos(dir1 - ca);
double vy1 = mgt1 * Math.sin(dir1 - ca);
double vx2 = mgt2 * Math.cos(dir2 - ca);
double vy2 = mgt2 * Math.sin(dir2 - ca);
double vfx1 = ((mass - ball.getMass()) * vx1 + (ball.getMass() + ball.getMass()) * vx2) / (mass + ball.getMass());
double fvx2 = ((mass + mass) * vx1 + (ball.getMass() - mass) * vx2) / (mass + ball.getMass());
double fvy1 = vy1;
double fvy2 = vy2;
vx = (int) (Math.cos(ca) * vfx1 + Math.cos(ca + Math.PI / 2) * fvy1);
vx = (int) (Math.sin(ca) * vfx1 + Math.sin(ca + Math.PI / 2) * fvy1);
ball.setVx((int) (Math.cos(ca) * fvx2 + Math.cos(ca + Math.PI / 2) * fvy2));
ball.setVy((int) (Math.sin(ca) * fvx2 + Math.sin(ca + Math.PI / 2) * fvy2));
}
public int getCenterX() {
return x - radius / 2;
}
public int getCenterY() {
return y - radius / 2;
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
public int getVx() {
return vx;
}
public void setVx(int vx) {
this.vx = vx;
}
public int getVy() {
return vy;
}
public void setVy(int vy) {
this.vy = vy;
}
public int getRadius() {
return radius;
}
public void setRadius(int radius) {
this.radius = radius;
}
public int getDrag() {
return drag;
}
public void setDrag(int drag) {
this.drag = drag;
}
public int getMass() {
return mass;
}
public void setMass(int mass) {
this.mass = mass;
}
}
| jasonfagan/game-experiments | physics/src/main/java/net/yottabyte/game/BouncyBall.java | Java | unlicense | 3,996 |
//
// UITextView+PinchZoom.h
//
// Created by 余洪江 on 16/03/01.
// Copyright © MRJ. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface UITextView (PinchZoom)
@property (nonatomic) CGFloat maxFontSize, minFontSize;
@property (nonatomic, getter = iszoomEnabled) BOOL zoomEnabled;
@end
| mrjlovetian/OC-Category | OC-Category/Classes/UIKit/UITextView/UITextView+PinchZoom.h | C | unlicense | 304 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html><head><meta http-equiv="Content-Type" content="text/html;charset=iso-8859-1">
<title>OpenJPEG: invert.c File Reference</title>
<link href="doxygen.css" rel="stylesheet" type="text/css">
</head><body>
<!-- Generated by Doxygen 1.3.2 -->
<div class="qindex"><a class="qindex" href="index.html">Main Page</a> | <a class="qindex" href="modules.html">Modules</a> | <a class="qindex" href="annotated.html">Data Structures</a> | <a class="qindex" href="files.html">File List</a> | <a class="qindex" href="functions.html">Data Fields</a> | <a class="qindex" href="globals.html">Globals</a> | <a class="qindex" href="pages.html">Related Pages</a></div>
<h1>invert.c File Reference</h1><code>#include "<a class="el" href="opj__includes_8h-source.html">opj_includes.h</a>"</code><br>
<table border=0 cellpadding=0 cellspacing=0>
<tr><td></td></tr>
<tr><td colspan=2><br><h2>Functions</h2></td></tr>
<tr><td class="memItemLeft" nowrap align=right valign=top><a class="el" href="openjpeg_8h.html#a33">OPJ_BOOL</a> </td><td class="memItemRight" valign=bottom><a class="el" href="invert_8c.html#a0">opj_lupDecompose</a> (<a class="el" href="openjpeg_8h.html#a35">OPJ_FLOAT32</a> *matrix, <a class="el" href="openjpeg_8h.html#a43">OPJ_UINT32</a> *permutations, <a class="el" href="openjpeg_8h.html#a35">OPJ_FLOAT32</a> *p_swap_area, <a class="el" href="openjpeg_8h.html#a43">OPJ_UINT32</a> nb_compo)</td></tr>
<tr><td class="mdescLeft"> </td><td class="mdescRight">LUP decomposition. </em> <a href="#a0"></a><em><br><br></td></tr>
<tr><td class="memItemLeft" nowrap align=right valign=top>void </td><td class="memItemRight" valign=bottom><a class="el" href="invert_8c.html#a1">opj_lupSolve</a> (<a class="el" href="openjpeg_8h.html#a35">OPJ_FLOAT32</a> *pResult, <a class="el" href="openjpeg_8h.html#a35">OPJ_FLOAT32</a> *pMatrix, <a class="el" href="openjpeg_8h.html#a35">OPJ_FLOAT32</a> *pVector, <a class="el" href="openjpeg_8h.html#a43">OPJ_UINT32</a> *pPermutations, <a class="el" href="openjpeg_8h.html#a43">OPJ_UINT32</a> nb_compo, <a class="el" href="openjpeg_8h.html#a35">OPJ_FLOAT32</a> *p_intermediate_data)</td></tr>
<tr><td class="mdescLeft"> </td><td class="mdescRight">LUP solving. </em> <a href="#a1"></a><em><br><br></td></tr>
<tr><td class="memItemLeft" nowrap align=right valign=top>void </td><td class="memItemRight" valign=bottom><a class="el" href="invert_8c.html#a2">opj_lupInvert</a> (<a class="el" href="openjpeg_8h.html#a35">OPJ_FLOAT32</a> *pSrcMatrix, <a class="el" href="openjpeg_8h.html#a35">OPJ_FLOAT32</a> *pDestMatrix, <a class="el" href="openjpeg_8h.html#a43">OPJ_UINT32</a> nb_compo, <a class="el" href="openjpeg_8h.html#a43">OPJ_UINT32</a> *pPermutations, <a class="el" href="openjpeg_8h.html#a35">OPJ_FLOAT32</a> *p_src_temp, <a class="el" href="openjpeg_8h.html#a35">OPJ_FLOAT32</a> *p_dest_temp, <a class="el" href="openjpeg_8h.html#a35">OPJ_FLOAT32</a> *p_swap_area)</td></tr>
<tr><td class="mdescLeft"> </td><td class="mdescRight">LUP inversion (call with the result of lupDecompose). </em> <a href="#a2"></a><em><br><br></td></tr>
<tr><td class="memItemLeft" nowrap align=right valign=top><a class="el" href="openjpeg_8h.html#a33">OPJ_BOOL</a> </td><td class="memItemRight" valign=bottom><a class="el" href="group___i_n_v_e_r_t.html#a0">opj_matrix_inversion_f</a> (<a class="el" href="openjpeg_8h.html#a35">OPJ_FLOAT32</a> *pSrcMatrix, <a class="el" href="openjpeg_8h.html#a35">OPJ_FLOAT32</a> *pDestMatrix, <a class="el" href="openjpeg_8h.html#a43">OPJ_UINT32</a> nb_compo)</td></tr>
<tr><td class="mdescLeft"> </td><td class="mdescRight">Calculates a n x n double matrix inversion with a LUP method. </em> <a href="group___i_n_v_e_r_t.html#a0"></a><em><br><br></td></tr>
</table>
<hr><h2>Function Documentation</h2>
<a name="a0" doxytag="invert.c::opj_lupDecompose"></a><p>
<table class="mdTable" width="100%" cellpadding="2" cellspacing="0">
<tr>
<td class="mdRow">
<table cellpadding="0" cellspacing="0" border="0">
<tr>
<td class="md" nowrap valign="top"> <a class="el" href="openjpeg_8h.html#a33">OPJ_BOOL</a> opj_lupDecompose </td>
<td class="md" valign="top">( </td>
<td class="md" nowrap valign="top"><a class="el" href="openjpeg_8h.html#a35">OPJ_FLOAT32</a> * </td>
<td class="mdname" nowrap> <em>matrix</em>, </td>
</tr>
<tr>
<td></td>
<td></td>
<td class="md" nowrap><a class="el" href="openjpeg_8h.html#a43">OPJ_UINT32</a> * </td>
<td class="mdname" nowrap> <em>permutations</em>, </td>
</tr>
<tr>
<td></td>
<td></td>
<td class="md" nowrap><a class="el" href="openjpeg_8h.html#a35">OPJ_FLOAT32</a> * </td>
<td class="mdname" nowrap> <em>p_swap_area</em>, </td>
</tr>
<tr>
<td></td>
<td></td>
<td class="md" nowrap><a class="el" href="openjpeg_8h.html#a43">OPJ_UINT32</a> </td>
<td class="mdname" nowrap> <em>nb_compo</em></td>
</tr>
<tr>
<td></td>
<td class="md">) </td>
<td class="md" colspan="2"><code> [static]</code></td>
</tr>
</table>
</td>
</tr>
</table>
<table cellspacing=5 cellpadding=0 border=0>
<tr>
<td>
</td>
<td>
<p>
LUP decomposition.
<p>
</td>
</tr>
</table>
<a name="a2" doxytag="invert.c::opj_lupInvert"></a><p>
<table class="mdTable" width="100%" cellpadding="2" cellspacing="0">
<tr>
<td class="mdRow">
<table cellpadding="0" cellspacing="0" border="0">
<tr>
<td class="md" nowrap valign="top"> void opj_lupInvert </td>
<td class="md" valign="top">( </td>
<td class="md" nowrap valign="top"><a class="el" href="openjpeg_8h.html#a35">OPJ_FLOAT32</a> * </td>
<td class="mdname" nowrap> <em>pSrcMatrix</em>, </td>
</tr>
<tr>
<td></td>
<td></td>
<td class="md" nowrap><a class="el" href="openjpeg_8h.html#a35">OPJ_FLOAT32</a> * </td>
<td class="mdname" nowrap> <em>pDestMatrix</em>, </td>
</tr>
<tr>
<td></td>
<td></td>
<td class="md" nowrap><a class="el" href="openjpeg_8h.html#a43">OPJ_UINT32</a> </td>
<td class="mdname" nowrap> <em>nb_compo</em>, </td>
</tr>
<tr>
<td></td>
<td></td>
<td class="md" nowrap><a class="el" href="openjpeg_8h.html#a43">OPJ_UINT32</a> * </td>
<td class="mdname" nowrap> <em>pPermutations</em>, </td>
</tr>
<tr>
<td></td>
<td></td>
<td class="md" nowrap><a class="el" href="openjpeg_8h.html#a35">OPJ_FLOAT32</a> * </td>
<td class="mdname" nowrap> <em>p_src_temp</em>, </td>
</tr>
<tr>
<td></td>
<td></td>
<td class="md" nowrap><a class="el" href="openjpeg_8h.html#a35">OPJ_FLOAT32</a> * </td>
<td class="mdname" nowrap> <em>p_dest_temp</em>, </td>
</tr>
<tr>
<td></td>
<td></td>
<td class="md" nowrap><a class="el" href="openjpeg_8h.html#a35">OPJ_FLOAT32</a> * </td>
<td class="mdname" nowrap> <em>p_swap_area</em></td>
</tr>
<tr>
<td></td>
<td class="md">) </td>
<td class="md" colspan="2"><code> [static]</code></td>
</tr>
</table>
</td>
</tr>
</table>
<table cellspacing=5 cellpadding=0 border=0>
<tr>
<td>
</td>
<td>
<p>
LUP inversion (call with the result of lupDecompose).
<p>
</td>
</tr>
</table>
<a name="a1" doxytag="invert.c::opj_lupSolve"></a><p>
<table class="mdTable" width="100%" cellpadding="2" cellspacing="0">
<tr>
<td class="mdRow">
<table cellpadding="0" cellspacing="0" border="0">
<tr>
<td class="md" nowrap valign="top"> void opj_lupSolve </td>
<td class="md" valign="top">( </td>
<td class="md" nowrap valign="top"><a class="el" href="openjpeg_8h.html#a35">OPJ_FLOAT32</a> * </td>
<td class="mdname" nowrap> <em>pResult</em>, </td>
</tr>
<tr>
<td></td>
<td></td>
<td class="md" nowrap><a class="el" href="openjpeg_8h.html#a35">OPJ_FLOAT32</a> * </td>
<td class="mdname" nowrap> <em>pMatrix</em>, </td>
</tr>
<tr>
<td></td>
<td></td>
<td class="md" nowrap><a class="el" href="openjpeg_8h.html#a35">OPJ_FLOAT32</a> * </td>
<td class="mdname" nowrap> <em>pVector</em>, </td>
</tr>
<tr>
<td></td>
<td></td>
<td class="md" nowrap><a class="el" href="openjpeg_8h.html#a43">OPJ_UINT32</a> * </td>
<td class="mdname" nowrap> <em>pPermutations</em>, </td>
</tr>
<tr>
<td></td>
<td></td>
<td class="md" nowrap><a class="el" href="openjpeg_8h.html#a43">OPJ_UINT32</a> </td>
<td class="mdname" nowrap> <em>nb_compo</em>, </td>
</tr>
<tr>
<td></td>
<td></td>
<td class="md" nowrap><a class="el" href="openjpeg_8h.html#a35">OPJ_FLOAT32</a> * </td>
<td class="mdname" nowrap> <em>p_intermediate_data</em></td>
</tr>
<tr>
<td></td>
<td class="md">) </td>
<td class="md" colspan="2"><code> [static]</code></td>
</tr>
</table>
</td>
</tr>
</table>
<table cellspacing=5 cellpadding=0 border=0>
<tr>
<td>
</td>
<td>
<p>
LUP solving.
<p>
</td>
</tr>
</table>
<hr size="1"><address style="align: right;"><small>Generated on Sun Dec 23 13:33:20 2012 for OpenJPEG by
<a href="http://www.doxygen.org/index.html">
<img src="doxygen.png" alt="doxygen" align="middle" border=0 >
</a>1.3.2 </small></address>
</body>
</html>
| patinyanudklin/git_testing | cpe-2015-projects/vendors/jpeg2000/lib/doc/html/invert_8c.html | HTML | unlicense | 10,130 |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel.DataAnnotations.Schema;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
namespace ProjetoModelo.Infra.CrossCutting.Identity
{
public class ApplicationUser : IdentityUser
{
public ApplicationUser()
{
Clients = new Collection<Client>();
}
public string Name { get; set; }
public string Lastname { get; set; }
public string Gender { get; set; }
public DateTime BirthDate { get; set; }
public virtual ICollection<Client> Clients { get; set; }
[NotMapped]
public string CurrentClientId { get; set; }
public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager, ClaimsIdentity ext = null)
{
// Observe que o authenticationType precisa ser o mesmo que foi definido em CookieAuthenticationOptions.AuthenticationType
var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
var claims = new List<Claim>();
if (!string.IsNullOrEmpty(CurrentClientId))
{
claims.Add(new Claim("AspNet.Identity.ClientId", CurrentClientId));
}
// Adicione novos Claims aqui //
// Adicionando Claims externos capturados no login
if (ext != null)
{
await SetExternalProperties(userIdentity, ext);
}
// Gerenciamento de Claims para informaçoes do usuario
//claims.Add(new Claim("AdmRoles", "True"));
userIdentity.AddClaims(claims);
return userIdentity;
}
private async Task SetExternalProperties(ClaimsIdentity identity, ClaimsIdentity ext)
{
if (ext != null)
{
var ignoreClaim = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims";
// Adicionando Claims Externos no Identity
foreach (var c in ext.Claims)
{
if (!c.Type.StartsWith(ignoreClaim))
if (!identity.HasClaim(c.Type, c.Value))
identity.AddClaim(c);
}
}
}
}
} | lsilvestres/Exemplos | Arquitetura Modelo DDD/ProjetoModelo.Infra.CrossCutting.Identity/ApplicationUser.cs | C# | unlicense | 2,453 |
from sqlalchemy import create_engine, Column, Integer, String, ForeignKey, Table
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker, relationship
# demo many to many relationship
# http://docs.sqlalchemy.org/en/rel_0_9/orm/basic_relationships.html#many-to-many
engine = create_engine('sqlite:///manymany.db')
Base = declarative_base()
# Association table linking the two tables
# Also see: http://docs.sqlalchemy.org/en/rel_0_9/orm/basic_relationships.html#association-object
member_club_mapping = Table('member_club_mapping', Base.metadata,
Column('member_id', Integer, ForeignKey('member.id')),
Column('club_id', Integer, ForeignKey('club.id')))
class Member(Base):
__tablename__ = 'member'
id = Column(Integer, primary_key=True)
first_name = Column(String)
last_name = Column(String)
clubs = relationship('Club', back_populates='members',
secondary=member_club_mapping)
def __init__(self, first_name, last_name):
self.first_name = first_name
self.last_name = last_name
class Club(Base):
__tablename__ = 'club'
id = Column(Integer, primary_key=True)
name = Column(String)
members = relationship('Member', back_populates='clubs',
secondary=member_club_mapping)
def __init__(self, name):
self.name = name
# create tables
Base.metadata.create_all(engine)
# create a Session
Session = sessionmaker(bind=engine)
session = Session()
# Populate
member1 = Member('John', 'Doe')
club1 = Club('Club dub')
club1.members.append(member1)
session.add(club1)
club2 = Club('Club dub dub')
club2.members.append(member1)
session.add(club2)
club3 = Club('Club dub step')
session.add(club3)
member2 = Member('Jane', 'Allen')
member2.clubs.extend([club1, club2])
session.add(member2)
session.commit()
# query and print Member
res = session.query(Member).all()
for member in res:
print member.first_name, member.last_name , [club.name for club in member.clubs]
# query and print Club
res = session.query(Club).all()
for club in res:
print club.name, [(member.first_name, member.last_name) for member in club.members]
print 'After removing members with first name: Jane'
# Remove a record
record = session.query(Member).filter(Member.first_name == 'Jane').all()
for r in record:
session.delete(r)
session.commit()
# query and print Member
res = session.query(Member).all()
for member in res:
print member.first_name, member.last_name , [club.name for club in member.clubs]
# query and print
res = session.query(Club).all()
for club in res:
print club.name, [(member.first_name, member.last_name) for member in club.members]
print 'After removing the club, Club dub'
# Remove a record
record = session.query(Club).filter(Club.name == 'Club dub').all()
for r in record:
session.delete(r)
session.commit()
# query and print Member
res = session.query(Member).all()
for member in res:
print member.first_name, member.last_name , [club.name for club in member.clubs]
# query and print
res = session.query(Club).all()
for club in res:
print club.name, [(member.first_name, member.last_name) for member in club.members]
| amitsaha/learning | python/sqla_learning/many_many_relation.py | Python | unlicense | 3,275 |
/**************************************************************************
* Copyright 2016 Observational Health Data Sciences and Informatics (OHDSI)
*
* 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.
*
* Authors: Timur Vakhitov, Christian Reich
* Date: 2021
**************************************************************************/
--1. Update latest_update field to new date
DO $_$
BEGIN
PERFORM VOCABULARY_PACK.SetLatestUpdate(
pVocabularyName => 'NDC',
pVocabularyDate => (SELECT vocabulary_date FROM sources.product LIMIT 1),
pVocabularyVersion => (SELECT vocabulary_version FROM sources.product LIMIT 1),
pVocabularyDevSchema => 'DEV_NDC'
);
PERFORM VOCABULARY_PACK.SetLatestUpdate(
pVocabularyName => 'SPL',
pVocabularyDate => (SELECT vocabulary_date FROM sources.product LIMIT 1),
pVocabularyVersion => (SELECT vocabulary_version FROM sources.product LIMIT 1),
pVocabularyDevSchema => 'DEV_NDC',
pAppendVocabulary => TRUE
);
END $_$;
--2. Truncate all working tables
TRUNCATE TABLE concept_stage;
TRUNCATE TABLE concept_relationship_stage;
TRUNCATE TABLE concept_synonym_stage;
TRUNCATE TABLE pack_content_stage;
TRUNCATE TABLE drug_strength_stage;
--3. Create necessary functions
--get aggregated dose
CREATE OR REPLACE FUNCTION GetAggrDose (active_numerator_strength IN VARCHAR, active_ingred_unit IN VARCHAR) RETURNS VARCHAR
AS
$BODY$
DECLARE
z VARCHAR(4000);
BEGIN
SELECT STRING_AGG(a_n_s||a_i_u, ' / ' ORDER BY LPAD(a_n_s||a_i_u,50,'0')) INTO z FROM
(
SELECT * FROM (
SELECT DISTINCT
UNNEST(regexp_matches(active_numerator_strength, '[^; ]+', 'g')) a_n_s,
UNNEST(regexp_matches(active_ingred_unit, '[^; ]+', 'g')) a_i_u
) AS s0
) AS s1;
RETURN z;
END;
$BODY$
LANGUAGE 'plpgsql' IMMUTABLE PARALLEL SAFE;
--get unique dose
CREATE OR REPLACE FUNCTION GetDistinctDose (active_numerator_strength IN VARCHAR, active_ingred_unit IN VARCHAR, p IN INT) RETURNS VARCHAR
AS
$BODY$
DECLARE
z VARCHAR(4000);
BEGIN
IF p=1 THEN --distinct active_numerator_strength values
SELECT STRING_AGG(a_n_s, '; ' ORDER BY LPAD(a_n_s,50,'0')) INTO z FROM
(
SELECT * FROM (
SELECT DISTINCT
UNNEST(regexp_matches(active_numerator_strength, '[^; ]+', 'g')) a_n_s,--::numeric::varchar a_n_s, --double cast to convert corrupted values e.g. '.7' to 0.7 (numeric) and then back to a text value /*disabled atm*/
UNNEST(regexp_matches(active_ingred_unit, '[^; ]+', 'g')) a_i_u
) AS s0
) AS s1;
ELSE --distinct active_ingred_unit values (but order by active_numerator_strength!)
SELECT STRING_AGG(a_i_u, '; ' ORDER BY LPAD(a_n_s,50,'0')) INTO z FROM
(
SELECT * FROM (
SELECT DISTINCT
UNNEST(regexp_matches(active_numerator_strength, '[^; ]+', 'g')) a_n_s,
UNNEST(regexp_matches(active_ingred_unit, '[^; ]+', 'g')) a_i_u
) AS s0
) AS s1;
END IF;
RETURN z;
END;
$BODY$
LANGUAGE 'plpgsql' IMMUTABLE PARALLEL SAFE;
--4. Load upgraded SPL concepts
INSERT INTO concept_stage (
concept_name,
domain_id,
vocabulary_id,
concept_class_id,
standard_concept,
concept_code,
valid_start_date,
valid_end_date,
invalid_reason
)
SELECT vocabulary_pack.CutConceptName(spl_name) AS concept_name,
CASE
WHEN displayname IN ('COSMETIC')
THEN 'Observation'
WHEN displayname IN (
'MEDICAL DEVICE',
'OTC MEDICAL DEVICE LABEL',
'PRESCRIPTION MEDICAL DEVICE LABEL',
'MEDICAL FOOD',
'DIETARY SUPPLEMENT'
)
THEN 'Device'
ELSE 'Drug'
END AS domain_id,
'SPL' AS vocabulary_id,
CASE
WHEN displayname IN ('BULK INGREDIENT')
THEN 'Ingredient'
WHEN displayname IN (
'CELLULAR THERAPY',
'LICENSED MINIMALLY MANIPULATED CELLS LABEL'
)
THEN 'Cellular Therapy'
WHEN displayname IN ('COSMETIC')
THEN 'Cosmetic'
WHEN displayname IN ('DIETARY SUPPLEMENT')
THEN 'Supplement'
WHEN displayname IN ('HUMAN OTC DRUG LABEL')
THEN 'OTC Drug'
WHEN displayname IN (
'MEDICAL DEVICE',
'OTC MEDICAL DEVICE LABEL',
'PRESCRIPTION MEDICAL DEVICE LABEL'
)
THEN 'Device'
WHEN displayname IN ('MEDICAL FOOD')
THEN 'Food'
WHEN displayname IN ('NON-STANDARDIZED ALLERGENIC LABEL')
THEN 'Non-Stand Allergenic'
WHEN displayname IN ('OTC ANIMAL DRUG LABEL')
THEN 'Animal Drug'
WHEN displayname IN ('PLASMA DERIVATIVE')
THEN 'Plasma Derivative'
WHEN displayname IN ('STANDARDIZED ALLERGENIC')
THEN 'Standard Allergenic'
WHEN displayname IN ('VACCINE LABEL')
THEN 'Vaccine'
ELSE 'Prescription Drug'
END AS concept_class_id,
NULL AS standard_concept,
replaced_spl AS concept_code,
TO_DATE('19700101', 'YYYYMMDD') AS valid_start_date,
spl_date - 1 AS valid_end_date,
'U' AS invalid_reason
FROM (
SELECT DISTINCT FIRST_VALUE(COALESCE(s2.concept_name, c.concept_name)) OVER (
PARTITION BY l.replaced_spl ORDER BY s.valid_start_date,
s.concept_code ROWS BETWEEN unbounded preceding
AND UNBOUNDED FOLLOWING
) spl_name,
FIRST_VALUE(s.displayname) OVER (
PARTITION BY l.replaced_spl ORDER BY s.valid_start_date,
s.concept_code ROWS BETWEEN unbounded preceding
AND UNBOUNDED FOLLOWING
) displayname,
FIRST_VALUE(s.valid_start_date) OVER (
PARTITION BY l.replaced_spl ORDER BY s.valid_start_date ROWS BETWEEN unbounded preceding
AND UNBOUNDED FOLLOWING
) spl_date,
l.replaced_spl
FROM (
SELECT s_int.concept_code,
s_int.replaced_spl,
s_int.displayname,
MIN(s_int.valid_start_date) AS valid_start_date
FROM sources.spl_ext s_int
WHERE s_int.replaced_spl IS NOT NULL -- if there is an SPL codes ( l ) that is mentioned in another record as replaced_spl (path /document/relatedDocument/relatedDocument/setId/@root)
GROUP BY s_int.concept_code,
s_int.replaced_spl,
s_int.displayname
) s
CROSS JOIN LATERAL(SELECT UNNEST(regexp_matches(s.replaced_spl, '[^;]+', 'g')) AS replaced_spl) l
LEFT JOIN concept c ON c.vocabulary_id = 'SPL'
AND c.concept_code = l.replaced_spl
LEFT JOIN sources.spl_ext s2 ON s2.concept_code = l.replaced_spl
) AS s0
WHERE spl_name IS NOT NULL
AND displayname NOT IN (
'IDENTIFICATION OF CBER-REGULATED GENERIC DRUG FACILITY',
'INDEXING - PHARMACOLOGIC CLASS',
'INDEXING - SUBSTANCE',
'WHOLESALE DRUG DISTRIBUTORS AND THIRD-PARTY LOGISTICS FACILITY REPORT'
);
--5. Load main SPL concepts into concept_stage
INSERT INTO concept_stage (
concept_name,
domain_id,
vocabulary_id,
concept_class_id,
standard_concept,
concept_code,
valid_start_date,
valid_end_date,
invalid_reason
)
SELECT vocabulary_pack.CutConceptName(concept_name) concept_name,
CASE
WHEN displayname IN (
'COSMETIC',
'MEDICAL FOOD'
)
THEN 'Observation'
WHEN displayname IN (
'MEDICAL DEVICE',
'OTC MEDICAL DEVICE LABEL',
'PRESCRIPTION MEDICAL DEVICE LABEL'
)
THEN 'Device'
ELSE 'Drug'
END AS domain_id,
'SPL' AS vocabulary_id,
CASE
WHEN displayname IN ('BULK INGREDIENT')
THEN 'Ingredient'
WHEN displayname IN ('CELLULAR THERAPY')
THEN 'Cellular Therapy'
WHEN displayname IN ('COSMETIC')
THEN 'Cosmetic'
WHEN displayname IN ('DIETARY SUPPLEMENT')
THEN 'Supplement'
WHEN displayname IN ('HUMAN OTC DRUG LABEL')
THEN 'OTC Drug'
WHEN displayname IN ('LICENSED MINIMALLY MANIPULATED CELLS LABEL')
THEN 'Cellular Therapy'
WHEN displayname IN (
'MEDICAL DEVICE',
'OTC MEDICAL DEVICE LABEL',
'PRESCRIPTION MEDICAL DEVICE LABEL'
)
THEN 'Device'
WHEN displayname IN ('MEDICAL FOOD')
THEN 'Food'
WHEN displayname IN ('NON-STANDARDIZED ALLERGENIC LABEL')
THEN 'Non-Stand Allergenic'
WHEN displayname IN ('OTC ANIMAL DRUG LABEL')
THEN 'Animal Drug'
WHEN displayname IN ('PLASMA DERIVATIVE')
THEN 'Plasma Derivative'
WHEN displayname IN ('STANDARDIZED ALLERGENIC')
THEN 'Standard Allergenic'
WHEN displayname IN ('VACCINE LABEL')
THEN 'Vaccine'
ELSE 'Prescription Drug'
END AS concept_class_id,
'C' AS standard_concept,
concept_code,
valid_start_date,
TO_DATE('20991231', 'YYYYMMDD') AS valid_end_date,
NULL AS invalid_reason
FROM (
SELECT DISTINCT ON (s_int.concept_code)
s_int.concept_code,
s_int.concept_name,
s_int.displayname,
s_int.valid_start_date
FROM sources.spl_ext s_int
ORDER BY s_int.concept_code,
s_int.valid_start_date DESC
) s
WHERE displayname NOT IN (
'IDENTIFICATION OF CBER-REGULATED GENERIC DRUG FACILITY',
'INDEXING - PHARMACOLOGIC CLASS',
'INDEXING - SUBSTANCE',
'WHOLESALE DRUG DISTRIBUTORS AND THIRD-PARTY LOGISTICS FACILITY REPORT'
)
AND NOT EXISTS (
SELECT 1
FROM concept_stage cs_int
WHERE LOWER(s.concept_code) = LOWER(cs_int.concept_code)
);
--6. Load other SPL into concept_stage (from 'product')
CREATE OR REPLACE VIEW prod --for using INDEX 'idx_f_product'
AS
(
SELECT SUBSTR(productid, devv5.INSTR(productid, '_') + 1) AS concept_code,
dosageformname,
routename,
proprietaryname,
nonproprietaryname,
TRIM(proprietarynamesuffix) AS proprietarynamesuffix,
active_numerator_strength,
active_ingred_unit
FROM sources.product
);
INSERT INTO concept_stage (
concept_name,
domain_id,
vocabulary_id,
concept_class_id,
standard_concept,
concept_code,
valid_start_date,
valid_end_date,
invalid_reason
)
WITH good_spl AS (
SELECT CASE -- add [brandname] if proprietaryname exists and not identical to nonproprietaryname
WHEN brand_name IS NULL
THEN vocabulary_pack.CutConceptName(concept_name)
ELSE vocabulary_pack.CutConceptName(CONCAT (
TRIM(concept_name),
' [',
brand_name,
']'
))
END AS concept_name,
'Drug' AS domain_id,
'SPL' AS vocabulary_id,
concept_class_id,
'C' AS standard_concept,
concept_code,
COALESCE(valid_start_date, latest_update) AS valid_start_date,
TO_DATE('20991231', 'yyyymmdd') AS valid_end_date,
NULL AS invalid_reason
FROM --get unique and aggregated data from source
(
SELECT concept_code,
concept_class_id,
CASE
WHEN multi_nonproprietaryname IS NULL
THEN CONCAT (
SUBSTR(nonproprietaryname, 1, 100),
CASE
WHEN LENGTH(nonproprietaryname) > 100
THEN '...'
END,
' ' || TRIM(SUBSTR(aggr_dose, 1, 100)),
' ' || TRIM(SUBSTR(routename, 1, 100)),
' ',
TRIM(SUBSTR(dosageformname, 1, 100))
)
ELSE CONCAT (
'Multiple formulations: ',
SUBSTR(nonproprietaryname, 1, 100),
CASE
WHEN LENGTH(nonproprietaryname) > 100
THEN '...'
END,
' ' || TRIM(SUBSTR(aggr_dose, 1, 100)),
' ' || TRIM(SUBSTR(routename, 1, 100)),
' ',
TRIM(SUBSTR(dosageformname, 1, 100))
)
END AS concept_name,
vocabulary_pack.CutConceptName(brand_name) AS brand_name,
valid_start_date
FROM (
WITH t AS (
SELECT concept_code,
concept_class_id,
valid_start_date,
GetAggrDose(active_numerator_strength, active_ingred_unit) aggr_dose
FROM (
SELECT concept_code,
concept_class_id,
STRING_AGG(active_numerator_strength, '; ' ORDER BY CONCAT (
active_numerator_strength,
active_ingred_unit
)) AS active_numerator_strength,
STRING_AGG(active_ingred_unit, '; ' ORDER BY CONCAT (
active_numerator_strength,
active_ingred_unit
)) AS active_ingred_unit,
valid_start_date
FROM (
SELECT concept_code,
concept_class_id,
active_numerator_strength,
active_ingred_unit,
MIN(valid_start_date) OVER (PARTITION BY concept_code) AS valid_start_date
FROM (
SELECT GetDistinctDose(active_numerator_strength, active_ingred_unit, 1) AS active_numerator_strength,
GetDistinctDose(active_numerator_strength, active_ingred_unit, 2) AS active_ingred_unit,
SUBSTR(productid, devv5.INSTR(productid, '_') + 1) AS concept_code,
CASE producttypename
WHEN 'VACCINE'
THEN 'Vaccine'
WHEN 'LICENSED VACCINE BULK INTERMEDIATE'
THEN 'Vaccine'
WHEN 'STANDARDIZED ALLERGENIC'
THEN 'Standard Allergenic'
WHEN 'HUMAN PRESCRIPTION DRUG'
THEN 'Prescription Drug'
WHEN 'HUMAN OTC DRUG'
THEN 'OTC Drug'
WHEN 'PLASMA DERIVATIVE'
THEN 'Plasma Derivative'
WHEN 'NON-STANDARDIZED ALLERGENIC'
THEN 'Non-Stand Allergenic'
WHEN 'CELLULAR THERAPY'
THEN 'Cellular Therapy'
END AS concept_class_id,
startmarketingdate AS valid_start_date
FROM sources.product
) AS s0
GROUP BY concept_code,
concept_class_id,
active_numerator_strength,
active_ingred_unit,
valid_start_date
) AS s1
GROUP BY concept_code,
concept_class_id,
valid_start_date
) AS s2
)
SELECT t1.*,
--aggregated unique dosageformname
(
SELECT STRING_AGG(dosageformname, ', ' ORDER BY dosageformname)
FROM (
SELECT DISTINCT p.dosageformname
FROM prod p
WHERE p.concept_code = t1.concept_code
) AS s3
) AS dosageformname,
--aggregated unique routename
(
SELECT STRING_AGG(routename, ', ' ORDER BY routename)
FROM (
SELECT DISTINCT P.routename
FROM prod p
WHERE p.concept_code = t1.concept_code
) AS s4
) AS routename,
--aggregated unique nonproprietaryname
(
SELECT STRING_AGG(nonproprietaryname, ', ' ORDER BY nonproprietaryname)
FROM (
SELECT DISTINCT LOWER(p.nonproprietaryname) nonproprietaryname
FROM prod p
WHERE p.concept_code = t1.concept_code
ORDER BY nonproprietaryname LIMIT 14
) AS s5
) AS nonproprietaryname,
--multiple formulations flag
(
SELECT COUNT(LOWER(p.nonproprietaryname))
FROM prod p
WHERE p.concept_code = t1.concept_code
HAVING COUNT(DISTINCT LOWER(p.nonproprietaryname)) > 1
) AS multi_nonproprietaryname,
(
SELECT STRING_AGG(brand_name, ', ' ORDER BY brand_name)
FROM (
SELECT DISTINCT CASE
WHEN (
LOWER(proprietaryname) <> LOWER(nonproprietaryname)
OR nonproprietaryname IS NULL
)
THEN LOWER(TRIM(CONCAT (
proprietaryname,
' ',
proprietarynamesuffix
)))
ELSE NULL
END AS brand_name
FROM prod p
WHERE p.concept_code = t1.concept_code
ORDER BY brand_name LIMIT 49 --brand_name may be too long for concatenation
) AS s6
) AS brand_name
FROM t t1
) AS s7
) s,
vocabulary v
WHERE v.vocabulary_id = 'SPL'
)
SELECT *
FROM good_spl s
WHERE NOT EXISTS (
SELECT 1
FROM concept_stage cs_int
WHERE LOWER(s.concept_code) = LOWER(cs_int.concept_code)
);
--7. Add full SPL names into concept_synonym_stage
INSERT INTO concept_synonym_stage (
synonym_concept_code,
synonym_vocabulary_id,
synonym_name,
language_concept_id
)
SELECT concept_code AS synonym_concept_code,
'SPL' AS vocabulary_id,
vocabulary_pack.CutConceptSynonymName(CASE
WHEN brand_name IS NULL
THEN TRIM(long_concept_name)
ELSE CONCAT (
TRIM(long_concept_name),
' [',
brand_name,
']'
)
END) AS synonym_name,
4180186 AS language_concept_id -- English
FROM --get unique and aggregated data from source
(
SELECT concept_code,
CASE
WHEN multi_nonproprietaryname IS NULL
THEN CONCAT (
nonproprietaryname,
' ' || aggr_dose,
' ' || routename,
' ',
dosageformname
)
ELSE CONCAT (
'Multiple formulations: ',
nonproprietaryname,
' ' || aggr_dose,
' ' || routename,
' ',
dosageformname
)
END AS long_concept_name,
vocabulary_pack.CutConceptName(brand_name) AS brand_name
FROM (
WITH t AS (
SELECT concept_code,
GetAggrDose(active_numerator_strength, active_ingred_unit) aggr_dose
FROM (
SELECT concept_code,
STRING_AGG(active_numerator_strength, '; ' ORDER BY CONCAT (
active_numerator_strength,
active_ingred_unit
)) AS active_numerator_strength,
STRING_AGG(active_ingred_unit, '; ' ORDER BY CONCAT (
active_numerator_strength,
active_ingred_unit
)) AS active_ingred_unit
FROM (
SELECT DISTINCT GetDistinctDose(active_numerator_strength, active_ingred_unit, 1) AS active_numerator_strength,
GetDistinctDose(active_numerator_strength, active_ingred_unit, 2) AS active_ingred_unit,
SUBSTR(productid, devv5.INSTR(productid, '_') + 1) AS concept_code
FROM sources.product
) AS s0
GROUP BY concept_code
) AS s2
)
SELECT t1.*,
--aggregated unique dosageformname
(
SELECT STRING_AGG(dosageformname, ', ' ORDER BY dosageformname)
FROM (
SELECT DISTINCT p.dosageformname
FROM prod p
WHERE p.concept_code = t1.concept_code
) AS s3
) AS dosageformname,
--aggregated unique routename
(
SELECT STRING_AGG(routename, ', ' ORDER BY routename)
FROM (
SELECT DISTINCT p.routename
FROM prod p
WHERE p.concept_code = t1.concept_code
) AS s4
) AS routename,
--aggregated unique nonproprietaryname
(
SELECT STRING_AGG(nonproprietaryname, ', ' ORDER BY nonproprietaryname)
FROM (
SELECT DISTINCT LOWER(p.nonproprietaryname) nonproprietaryname
FROM prod p
WHERE p.concept_code = t1.concept_code
ORDER BY nonproprietaryname LIMIT 14
) AS s5
) AS nonproprietaryname,
--multiple formulations flag
(
SELECT COUNT(LOWER(P.nonproprietaryname))
FROM prod p
WHERE p.concept_code = t1.concept_code
HAVING COUNT(DISTINCT LOWER(P.nonproprietaryname)) > 1
) AS multi_nonproprietaryname,
(
SELECT STRING_AGG(brand_name, ', ' ORDER BY brand_name)
FROM (
SELECT DISTINCT CASE
WHEN (
LOWER(proprietaryname) <> LOWER(nonproprietaryname)
OR nonproprietaryname IS NULL
)
THEN LOWER(TRIM(CONCAT (
proprietaryname,
' ',
proprietarynamesuffix
)))
ELSE NULL
END AS brand_name
FROM prod p
WHERE p.concept_code = t1.concept_code
ORDER BY brand_name LIMIT 49 --brand_name may be too long for concatenation
) AS s6
) AS brand_name
FROM t t1
) AS s7
) s;
DROP VIEW prod;
--7. Add upgrade SPL relationships
INSERT INTO concept_relationship_stage (
concept_code_1,
concept_code_2,
vocabulary_id_1,
vocabulary_id_2,
relationship_id,
valid_start_date,
valid_end_date,
invalid_reason
)
SELECT replaced_spl AS concept_code_1,
spl_code AS concept_code_2,
'SPL' AS vocabulary_id_1,
'SPL' AS vocabulary_id_2,
'Concept replaced by' AS relationship_id,
spl_date - 1 AS valid_start_date,
TO_DATE('20991231', 'YYYYMMDD') AS valid_end_date,
NULL AS invalid_reason
FROM (
SELECT DISTINCT FIRST_VALUE(s.concept_code) OVER (
PARTITION BY l.replaced_spl ORDER BY s.valid_start_date,
s.concept_code ROWS BETWEEN UNBOUNDED PRECEDING
AND UNBOUNDED FOLLOWING
) spl_code,
FIRST_VALUE(s.valid_start_date) OVER (
PARTITION BY l.replaced_spl ORDER BY s.valid_start_date,
s.concept_code ROWS BETWEEN UNBOUNDED PRECEDING
AND UNBOUNDED FOLLOWING
) spl_date,
l.replaced_spl
FROM (
SELECT s_int.concept_code,
s_int.replaced_spl,
MIN(s_int.valid_start_date) AS valid_start_date
FROM sources.spl_ext s_int
WHERE s_int.replaced_spl IS NOT NULL -- if there is an SPL codes ( l ) that is mentioned in another record as replaced_spl (path /document/relatedDocument/relatedDocument/setId/@root)
GROUP BY s_int.concept_code,
s_int.replaced_spl
) s
CROSS JOIN LATERAL(SELECT UNNEST(regexp_matches(s.replaced_spl, '[^;]+', 'g')) AS replaced_spl) l
) AS s0;
ANALYZE concept_stage;
ANALYZE concept_relationship_stage;
--8. Working with replacement mappings
DO $_$
BEGIN
PERFORM VOCABULARY_PACK.CheckReplacementMappings();
END $_$;
--9. Add mapping from deprecated to fresh concepts
DO $_$
BEGIN
PERFORM VOCABULARY_PACK.AddFreshMAPSTO();
END $_$;
--10. Deprecate 'Maps to' mappings to deprecated and upgraded concepts
DO $_$
BEGIN
PERFORM VOCABULARY_PACK.DeprecateWrongMAPSTO();
END $_$;
--11. Delete ambiguous 'Maps to' mappings
DO $_$
BEGIN
PERFORM VOCABULARY_PACK.DeleteAmbiguousMAPSTO();
END $_$;
--12. Load NDC into temporary table from 'product'
DROP TABLE IF EXISTS main_ndc;
CREATE UNLOGGED TABLE main_ndc (
concept_name TEXT,
long_concept_name TEXT,
domain_id TEXT,
vocabulary_id TEXT,
concept_class_id TEXT,
standard_concept TEXT,
concept_code TEXT,
valid_start_date DATE,
valid_end_date DATE,
invalid_reason TEXT,
is_diluent BOOLEAN DEFAULT FALSE
);
CREATE OR REPLACE VIEW prod --for using INDEX 'idx_f1_product'
AS
(
SELECT CASE
WHEN devv5.INSTR(productndc, '-') = 5
THEN '0' || SUBSTR(productndc, 1, devv5.INSTR(productndc, '-') - 1)
ELSE SUBSTR(productndc, 1, devv5.INSTR(productndc, '-') - 1)
END || CASE
WHEN LENGTH(SUBSTR(productndc, devv5.INSTR(productndc, '-'))) = 4
THEN '0' || SUBSTR(productndc, devv5.INSTR(productndc, '-') + 1)
ELSE SUBSTR(productndc, devv5.INSTR(productndc, '-') + 1)
END AS concept_code,
dosageformname,
routename,
proprietaryname,
nonproprietaryname,
TRIM(proprietarynamesuffix) AS proprietarynamesuffix,
active_numerator_strength,
active_ingred_unit
FROM sources.product
);
INSERT INTO main_ndc
SELECT CASE -- add [brandname] if proprietaryname exists and not identical to nonproprietaryname
WHEN brand_name IS NULL
THEN vocabulary_pack.CutConceptName(concept_name)
ELSE vocabulary_pack.CutConceptName(CONCAT (
TRIM(concept_name),
' [',
brand_name,
']'
))
END AS concept_name,
CASE -- same for long concept name
WHEN brand_name IS NULL
THEN TRIM(long_concept_name)
ELSE CONCAT (
TRIM(long_concept_name),
' [',
brand_name,
']'
)
END AS long_concept_name,
'Drug' AS domain_id,
'NDC' AS vocabulary_id,
'9-digit NDC' AS concept_class_id,
NULL AS standard_concept,
concept_code,
COALESCE(valid_start_date, latest_update) AS valid_start_date,
TO_DATE('20991231', 'yyyymmdd') AS valid_end_date,
NULL AS invalid_reason,
is_diluent
FROM --get unique and aggregated data from source
(
SELECT concept_code,
CASE
WHEN multi_nonproprietaryname IS NULL
THEN CONCAT (
SUBSTR(nonproprietaryname, 1, 100),
CASE
WHEN LENGTH(nonproprietaryname) > 100
THEN '...'
END,
' ' || TRIM(SUBSTR(aggr_dose, 1, 100)),
' ' || TRIM(SUBSTR(routename, 1, 100)),
' ',
TRIM(SUBSTR(dosageformname, 1, 100))
)
ELSE CONCAT (
'Multiple formulations: ',
SUBSTR(nonproprietaryname, 1, 100),
CASE
WHEN LENGTH(nonproprietaryname) > 100
THEN '...'
END,
' ' || TRIM(SUBSTR(aggr_dose, 1, 100)),
' ' || TRIM(SUBSTR(routename, 1, 100)),
' ',
TRIM(SUBSTR(dosageformname, 1, 100))
)
END AS concept_name,
CASE
WHEN multi_nonproprietaryname IS NULL
THEN CONCAT (
nonproprietaryname,
' ' || aggr_dose,
' ' || routename,
' ',
dosageformname
)
ELSE CONCAT (
'Multiple formulations: ',
nonproprietaryname,
' ' || aggr_dose,
' ' || routename,
' ',
dosageformname
)
END AS long_concept_name,
vocabulary_pack.CutConceptName(brand_name) AS brand_name,
valid_start_date,
is_diluent
FROM (
WITH t AS (
SELECT concept_code,
valid_start_date,
GetAggrDose(active_numerator_strength, active_ingred_unit) aggr_dose,
is_diluent
FROM (
SELECT concept_code,
STRING_AGG(active_numerator_strength, '; ' ORDER BY CONCAT (
active_numerator_strength,
active_ingred_unit
)) AS active_numerator_strength,
STRING_AGG(active_ingred_unit, '; ' ORDER BY CONCAT (
active_numerator_strength,
active_ingred_unit
)) AS active_ingred_unit,
valid_start_date,
is_diluent
FROM (
SELECT concept_code,
active_numerator_strength,
active_ingred_unit,
MIN(valid_start_date) OVER (PARTITION BY concept_code) AS valid_start_date,
is_diluent
FROM (
SELECT GetDistinctDose(active_numerator_strength, active_ingred_unit, 1) AS active_numerator_strength,
GetDistinctDose(active_numerator_strength, active_ingred_unit, 2) AS active_ingred_unit,
CASE
WHEN devv5.INSTR(productndc, '-') = 5
THEN '0' || SUBSTR(productndc, 1, devv5.INSTR(productndc, '-') - 1)
ELSE SUBSTR(productndc, 1, devv5.INSTR(productndc, '-') - 1)
END || CASE
WHEN LENGTH(SUBSTR(productndc, devv5.INSTR(productndc, '-'))) = 4
THEN '0' || SUBSTR(productndc, devv5.INSTR(productndc, '-') + 1)
ELSE SUBSTR(productndc, devv5.INSTR(productndc, '-') + 1)
END AS concept_code,
startmarketingdate AS valid_start_date,
CASE
WHEN proprietaryname ILIKE '%diluent%'
THEN TRUE
ELSE FALSE
END AS is_diluent
FROM sources.product
) AS s0
GROUP BY concept_code,
active_numerator_strength,
active_ingred_unit,
valid_start_date,
is_diluent
) AS s1
GROUP BY concept_code,
valid_start_date,
is_diluent
) AS s2
)
SELECT t1.*,
--aggregated unique dosageformname
(
SELECT STRING_AGG(dosageformname, ', ' ORDER BY dosageformname)
FROM (
SELECT DISTINCT p.dosageformname
FROM prod p
WHERE p.concept_code = t1.concept_code
) AS s3
) AS dosageformname,
--aggregated unique routename
(
SELECT STRING_AGG(routename, ', ' ORDER BY routename)
FROM (
SELECT DISTINCT p.routename
FROM prod p
WHERE p.concept_code = t1.concept_code
) AS s4
) AS routename,
--aggregated unique nonproprietaryname
(
SELECT STRING_AGG(nonproprietaryname, ', ' ORDER BY nonproprietaryname)
FROM (
SELECT DISTINCT LOWER(p.nonproprietaryname) nonproprietaryname
FROM prod p
WHERE p.concept_code = t1.concept_code
ORDER BY nonproprietaryname LIMIT 14
) AS s5
) AS nonproprietaryname,
--multiple formulations flag
(
SELECT COUNT(LOWER(p.nonproprietaryname))
FROM prod p
WHERE p.concept_code = t1.concept_code
HAVING COUNT(DISTINCT LOWER(p.nonproprietaryname)) > 1
) AS multi_nonproprietaryname,
(
SELECT STRING_AGG(brand_name, ', ' ORDER BY brand_name)
FROM (
SELECT DISTINCT CASE
WHEN (
LOWER(proprietaryname) <> LOWER(nonproprietaryname)
OR nonproprietaryname IS NULL
)
THEN LOWER(TRIM(proprietaryname || ' ' || proprietarynamesuffix))
ELSE NULL
END AS brand_name
FROM prod p
WHERE p.concept_code = t1.concept_code
ORDER BY brand_name LIMIT 49 --brand_name may be too long for concatenation
) AS s6
) AS brand_name
FROM t t1
) AS s7
) AS s8,
vocabulary v
WHERE v.vocabulary_id = 'NDC';
DROP VIEW prod;
--13. Add NDC to MAIN_NDC from rxnconso
INSERT INTO main_ndc (
concept_name,
long_concept_name,
domain_id,
vocabulary_id,
concept_class_id,
standard_concept,
concept_code,
valid_start_date,
valid_end_date,
invalid_reason
)
SELECT DISTINCT vocabulary_pack.CutConceptName(c.str) AS concept_name,
TRIM(c.str) AS long_concept_name,
'Drug' AS domain_id,
'NDC' AS vocabulary_id,
'11-digit NDC' AS concept_class_id,
NULL AS standard_concept,
s.atv AS concept_code,
latest_update AS valid_start_date,
TO_DATE ('20991231', 'yyyymmdd') AS valid_end_date,
NULL AS invalid_reason
FROM sources.rxnsat s
JOIN sources.rxnconso c ON c.sab = 'RXNORM'
AND c.rxaui = s.rxaui
AND c.rxcui = s.rxcui
JOIN vocabulary v ON v.vocabulary_id = 'NDC'
WHERE s.sab = 'RXNORM'
AND s.atn = 'NDC';
CREATE INDEX idx_main_ndc ON main_ndc (concept_code);
ANALYZE main_ndc;
--14. Add additional NDC with fresh dates and active mapping to RxCUI (source: http://rxnav.nlm.nih.gov/REST/ndcstatus?history=1&ndc=xxx) [part 1 of 3]
INSERT INTO concept_stage (
concept_name,
domain_id,
vocabulary_id,
concept_class_id,
standard_concept,
concept_code,
valid_start_date,
valid_end_date,
invalid_reason
)
SELECT vocabulary_pack.CutConceptName(concept_name) AS concept_name,
'Drug' AS domain_id,
'NDC' AS vocabulary_id,
'11-digit NDC' AS concept_class_id,
NULL AS standard_concept,
concept_code,
startDate AS valid_start_date,
endDate AS valid_end_date,
invalid_reason
FROM (
SELECT DISTINCT ON (n.concept_code)
n.concept_code,
n.startDate,
n.endDate,
n.invalid_reason,
COALESCE(mn.concept_name, c.concept_name, spl.concept_name) concept_name
FROM (
SELECT ndc.concept_code,
startDate,
CASE
WHEN LOWER(status) = 'active'
THEN TO_DATE('20991231', 'yyyymmdd')
ELSE endDate
END endDate,
CASE
WHEN LOWER(status) = 'active'
THEN NULL
ELSE 'D'
END AS invalid_reason
FROM apigrabber.ndc_history ndc
JOIN (
SELECT DISTINCT FIRST_VALUE(ndc_int.activeRxcui) OVER (
PARTITION BY ndc_int.concept_code ORDER BY c_int.invalid_reason NULLS FIRST,
c_int.valid_start_date DESC,
CASE c_int.concept_class_id
WHEN 'Branded Pack'
THEN 1
WHEN 'Quant Branded Drug'
THEN 2
WHEN 'Branded Drug'
THEN 3
WHEN 'Clinical Pack'
THEN 4
WHEN 'Quant Clinical Drug'
THEN 5
WHEN 'Clinical Drug'
THEN 6
ELSE 7
END,
c_int.concept_id
) AS activeRxcui,
ndc_int.concept_code
FROM apigrabber.ndc_history ndc_int
JOIN concept c_int ON c_int.vocabulary_id = 'RxNorm'
AND c_int.concept_code = ndc_int.activeRxcui
) rx ON rx.activeRxcui = ndc.activeRxcui
AND rx.concept_code = ndc.concept_code
) n
LEFT JOIN main_ndc mn ON mn.concept_code = n.concept_code
AND mn.vocabulary_id = 'NDC' --first search name in old sources
LEFT JOIN concept c ON c.concept_code = n.concept_code
AND c.vocabulary_id = 'NDC' --search name in concept
LEFT JOIN sources.spl2ndc_mappings s ON s.ndc_code = n.concept_code--take name from SPL
LEFT JOIN sources.spl_ext spl ON spl.concept_code = s.concept_code
AND COALESCE(spl.ndc_code,s.ndc_code)=s.ndc_code
ORDER BY n.concept_code,
spl.high_value NULLS FIRST,
LENGTH(spl.concept_name) DESC
) AS s0
WHERE concept_name IS NOT NULL;
--15. Add additional NDC with fresh dates from the ndc_history where NDC have't activerxcui (same source). Take dates from COALESCE(NDC API, big XML (SPL), MAIN_NDC, concept, default dates)
CREATE OR REPLACE FUNCTION CheckNDCDate (pDate IN VARCHAR, pDateDefault IN DATE) RETURNS DATE
AS
$BODY$
DECLARE
iDate DATE;
BEGIN
RETURN COALESCE (TO_DATE (pDate, 'YYYYMMDD'), pDateDefault);
EXCEPTION WHEN OTHERS THEN
RETURN pDateDefault;
END;
$BODY$
LANGUAGE 'plpgsql' IMMUTABLE;
WITH ADDITIONALNDCINFO
AS (
SELECT n.concept_code,
COALESCE(n.startdate, CheckNDCDate(l.ndc_valid_start_date, COALESCE(mn.valid_start_date, c.valid_start_date, TO_DATE('19700102', 'YYYYMMDD')))) AS valid_start_date,
COALESCE(
CASE WHEN LOWER(n.status)='active' THEN TO_DATE('20991231', 'YYYYMMDD') ELSE n.enddate END,
CheckNDCDate(l.ndc_valid_end_date, COALESCE(mn.valid_end_date, c.valid_end_date, TO_DATE('20991231', 'YYYYMMDD')))
) AS valid_end_date,
vocabulary_pack.CutConceptName(COALESCE(mn.concept_name, c.concept_name, l.spl_name)) AS concept_name
FROM apigrabber.ndc_history n
LEFT JOIN main_ndc mn ON mn.concept_code = n.concept_code
AND mn.vocabulary_id = 'NDC'
LEFT JOIN concept c ON c.concept_code = n.concept_code
AND c.vocabulary_id = 'NDC'
LEFT JOIN LATERAL(
SELECT DISTINCT
FIRST_VALUE(spl.low_value) OVER (ORDER BY spl.low_value) AS ndc_valid_start_date,
FIRST_VALUE(COALESCE(spl.high_value, '20991231')) OVER (ORDER BY spl.high_value DESC) AS ndc_valid_end_date,
FIRST_VALUE(spl.concept_name) OVER (ORDER BY spl.high_value DESC) AS spl_name
FROM sources.spl2ndc_mappings s
JOIN sources.spl_ext spl ON spl.concept_code = s.concept_code
AND COALESCE(spl.ndc_code, s.ndc_code) = s.ndc_code
WHERE s.ndc_code = n.concept_code
) l ON TRUE
WHERE n.activerxcui IS NULL
)
INSERT INTO concept_stage (
concept_name,
domain_id,
vocabulary_id,
concept_class_id,
standard_concept,
concept_code,
valid_start_date,
valid_end_date,
invalid_reason
)
SELECT concept_name,
'Drug' AS domain_id,
'NDC' AS vocabulary_id,
LENGTH(concept_code) || '-digit NDC' AS concept_class_id,
NULL AS standard_concept,
concept_code,
valid_start_date,
valid_end_date,
CASE
WHEN valid_end_date = TO_DATE('20991231', 'yyyymmdd')
THEN NULL
ELSE 'D'
END AS invalid_reason
FROM additionalndcinfo
WHERE concept_name IS NOT NULL;
--15.1 Fix bug in sources, SPL XML returns 11/06/2103 for NDC:61077-003-33, proof: https://dailymed.nlm.nih.gov/dailymed/fda/fdaDrugXsl.cfm?setid=fcd4b3e8-a40a-4aa1-9745-1c9768dca539&type=display
UPDATE concept_stage
SET valid_start_date = TO_DATE('20131106', 'yyyymmdd')
WHERE concept_code = '61077000333'
AND valid_start_date = TO_DATE('21031106', 'yyyymmdd');
--16. Create temporary table for NDC mappings to RxNorm (source: http://rxnav.nlm.nih.gov/REST/rxcui/xxx/allndcs?history=1)
DROP TABLE IF EXISTS rxnorm2ndc_mappings_ext;
CREATE UNLOGGED TABLE rxnorm2ndc_mappings_ext AS
SELECT concept_code,
ndc_code,
startDate,
endDate,
invalid_reason,
COALESCE(c_name1, c_name2, last_rxnorm_name) concept_name
FROM (
SELECT DISTINCT mp.concept_code,
mn.concept_name c_name1,
c.concept_name c_name2,
LAST_VALUE(rxnorm.concept_name) OVER (
PARTITION BY mp.ndc_code ORDER BY rxnorm.valid_start_date,
rxnorm.concept_id ROWS BETWEEN UNBOUNDED PRECEDING
AND UNBOUNDED FOLLOWING
) last_rxnorm_name,
mp.startDate,
mp.ndc_code,
CASE
WHEN mp.endDate = mp.max_end_date
THEN TO_DATE('20991231', 'yyyymmdd')
ELSE mp.endDate
END endDate,
CASE
WHEN mp.endDate = mp.max_end_date
THEN NULL
ELSE 'D'
END invalid_reason
FROM (
SELECT concept_code,
ndc_code,
startDate,
endDate,
MAX(endDate) OVER () max_end_date
FROM apigrabber.rxnorm2ndc_mappings
) mp
LEFT JOIN main_ndc mn ON mn.concept_code = mp.ndc_code
AND mn.vocabulary_id = 'NDC' --first search name in old sources
LEFT JOIN concept c ON c.concept_code = mp.ndc_code
AND c.vocabulary_id = 'NDC' --search name in concept
LEFT JOIN concept rxnorm ON rxnorm.concept_code = mp.concept_code
AND rxnorm.vocabulary_id = 'RxNorm' --take name from RxNorm
) AS s0;
--17. Add additional NDC with fresh dates from previous temporary table (RXNORM2NDC_MAPPINGS_EXT) [part 3 of 3]
INSERT INTO concept_stage (
concept_name,
domain_id,
vocabulary_id,
concept_class_id,
standard_concept,
concept_code,
valid_start_date,
valid_end_date,
invalid_reason
)
SELECT DISTINCT concept_name,
'Drug' AS domain_id,
'NDC' AS vocabulary_id,
'11-digit NDC' AS concept_class_id,
NULL AS standard_concept,
ndc_code AS concept_code,
FIRST_VALUE(startDate) OVER (
PARTITION BY ndc_code ORDER BY startDate ROWS BETWEEN UNBOUNDED PRECEDING
AND UNBOUNDED FOLLOWING
) AS valid_start_date,
LAST_VALUE(endDate) OVER (
PARTITION BY ndc_code ORDER BY endDate ROWS BETWEEN UNBOUNDED PRECEDING
AND UNBOUNDED FOLLOWING
) AS valid_end_date,
LAST_VALUE(invalid_reason) OVER (
PARTITION BY ndc_code ORDER BY endDate ROWS BETWEEN UNBOUNDED PRECEDING
AND UNBOUNDED FOLLOWING
) AS invalid_reason
FROM rxnorm2ndc_mappings_ext m
WHERE NOT EXISTS (
SELECT 1
FROM concept_stage cs_int
WHERE cs_int.concept_code = m.ndc_code
AND cs_int.vocabulary_id = 'NDC'
);
--18. Add all other NDC from 'product'
INSERT INTO concept_stage (
concept_name,
domain_id,
vocabulary_id,
concept_class_id,
standard_concept,
concept_code,
valid_start_date,
valid_end_date,
invalid_reason
)
SELECT concept_name,
domain_id,
vocabulary_id,
concept_class_id,
standard_concept,
concept_code,
valid_start_date,
valid_end_date,
invalid_reason
FROM main_ndc m
WHERE NOT EXISTS (
SELECT 1
FROM concept_stage cs_int
WHERE cs_int.concept_code = m.concept_code
AND cs_int.vocabulary_id = 'NDC'
);
--19. Add full unique NDC names into concept_synonym_stage
INSERT INTO concept_synonym_stage (
synonym_concept_code,
synonym_vocabulary_id,
synonym_name,
language_concept_id
)
SELECT mn.concept_code,
mn.vocabulary_id,
vocabulary_pack.CutConceptSynonymName(mn.long_concept_name),
4180186 AS language_concept_id -- English
FROM main_ndc mn
WHERE NOT EXISTS (
SELECT 1
FROM concept_stage cs_int
WHERE cs_int.concept_code = mn.concept_code
AND cs_int.vocabulary_id = mn.vocabulary_id
AND REPLACE(LOWER(cs_int.concept_name), ' [diluent]', '') = LOWER(vocabulary_pack.CutConceptSynonymName(mn.long_concept_name))
);
--20. Add mapping from SPL to RxNorm through RxNorm API (source: http://rxnav.nlm.nih.gov/REST/rxcui/xxx/property?propName=SPL_SET_ID)
INSERT INTO concept_relationship_stage (
concept_code_1,
concept_code_2,
vocabulary_id_1,
vocabulary_id_2,
relationship_id,
valid_start_date,
valid_end_date,
invalid_reason
)
SELECT spl_code AS concept_code_1,
concept_code AS concept_code_2,
'SPL' AS vocabulary_id_1,
'RxNorm' AS vocabulary_id_2,
'SPL - RxNorm' AS relationship_id,
TO_DATE('19700101', 'YYYYMMDD') AS valid_start_date,
TO_DATE('20991231', 'YYYYMMDD') AS valid_end_date,
NULL AS invalid_reason
FROM apigrabber.rxnorm2spl_mappings rm
WHERE spl_code IS NOT NULL
AND NOT EXISTS (
SELECT 1
FROM concept c
WHERE c.concept_code = rm.concept_code
AND c.vocabulary_id = 'RxNorm'
AND c.concept_class_id = 'Ingredient'
);
--21. Add mapping from SPL to RxNorm through rxnsat
ANALYZE concept_relationship_stage;
INSERT INTO concept_relationship_stage (
concept_code_1,
concept_code_2,
vocabulary_id_1,
vocabulary_id_2,
relationship_id,
valid_start_date,
valid_end_date,
invalid_reason
)
SELECT DISTINCT a.atv AS concept_code_1,
b.code AS concept_code_2,
'SPL' AS vocabulary_id_1,
'RxNorm' AS vocabulary_id_2,
'SPL - RxNorm' AS relationship_id,
v.latest_update AS valid_start_date,
TO_DATE ('20991231', 'yyyymmdd') AS valid_end_date,
NULL AS invalid_reason
FROM sources.rxnsat a
JOIN sources.rxnsat b ON a.rxcui = b.rxcui
JOIN vocabulary v ON v.vocabulary_id = 'SPL'
WHERE a.sab = 'MTHSPL'
AND a.atn = 'SPL_SET_ID'
AND b.sab = 'RXNORM'
AND b.atn = 'RXN_HUMAN_DRUG'
AND NOT EXISTS (
SELECT 1
FROM concept_relationship_stage crs_int
WHERE crs_int.concept_code_1 = a.atv
AND crs_int.concept_code_2 = b.code
AND crs_int.relationship_id = 'SPL - RxNorm'
AND crs_int.vocabulary_id_1 = 'SPL'
AND crs_int.vocabulary_id_2 = 'RxNorm'
);
--22. Add mapping from NDC to RxNorm from rxnconso
INSERT INTO concept_relationship_stage (
concept_code_1,
concept_code_2,
vocabulary_id_1,
vocabulary_id_2,
relationship_id,
valid_start_date,
valid_end_date,
invalid_reason
)
SELECT DISTINCT s.atv AS concept_code_1,
c.rxcui AS concept_code_2,
'NDC' AS vocabulary_id_1,
'RxNorm' AS vocabulary_id_2,
'Maps to' AS relationship_id,
v.latest_update AS valid_start_date,
TO_DATE ('20991231', 'yyyymmdd') AS valid_end_date,
NULL AS invalid_reason
FROM sources.rxnsat s
JOIN sources.rxnconso c ON c.sab = 'RXNORM'
AND c.rxaui = s.rxaui
AND c.rxcui = s.rxcui
JOIN vocabulary v ON v.vocabulary_id = 'NDC'
WHERE s.sab = 'RXNORM'
AND s.atn = 'NDC';
INSERT INTO concept_relationship_stage (
concept_code_1,
concept_code_2,
vocabulary_id_1,
vocabulary_id_2,
relationship_id,
valid_start_date,
valid_end_date,
invalid_reason
)
SELECT first_half || second_half AS concept_code_1,
concept_code_2,
'NDC' AS vocabulary_id_1,
'RxNorm' AS vocabulary_id_2,
'Maps to' AS relationship_id,
valid_start_date,
TO_DATE ('20991231', 'yyyymmdd') AS valid_end_date,
NULL AS invalid_reason
FROM (
SELECT DISTINCT CASE
WHEN devv5.INSTR(productndc, '-') = 5
THEN '0' || SUBSTR(productndc, 1, devv5.INSTR(productndc, '-') - 1)
ELSE SUBSTR(productndc, 1, devv5.INSTR(productndc, '-') - 1)
END AS first_half,
CASE
WHEN LENGTH(SUBSTR(productndc, devv5.INSTR(productndc, '-'))) = 4
THEN '0' || SUBSTR(productndc, devv5.INSTR(productndc, '-') + 1)
ELSE SUBSTR(productndc, devv5.INSTR(productndc, '-') + 1)
END AS second_half,
v.latest_update AS valid_start_date,
r.rxcui AS concept_code_2 -- RxNorm concept_code
FROM sources.product p
JOIN sources.rxnconso c ON c.code = p.productndc
AND c.sab = 'MTHSPL'
JOIN sources.rxnconso r ON r.rxcui = c.rxcui
AND r.sab = 'RXNORM'
JOIN vocabulary v ON v.vocabulary_id = 'NDC'
) AS s0;
--23. Add additional mapping for NDC codes
--The 9-digit NDC codes that have no mapping can be mapped to the same concept of the 11-digit NDC codes, if all 11-digit NDC codes agree on the same destination Concept
CREATE INDEX IF NOT EXISTS trgm_idx ON concept_stage USING GIN (concept_code devv5.gin_trgm_ops); --for LIKE patterns
CREATE INDEX IF NOT EXISTS trgm_crs_idx ON concept_relationship_stage USING GIN (concept_code_1 devv5.gin_trgm_ops); --for LIKE patterns
ANALYZE concept_stage;
ANALYZE concept_relationship_stage;
INSERT INTO concept_relationship_stage (
concept_code_1,
concept_code_2,
vocabulary_id_1,
vocabulary_id_2,
relationship_id,
valid_start_date,
valid_end_date,
invalid_reason
)
SELECT concept_code_1,
concept_code_2,
vocabulary_id_1,
vocabulary_id_2,
relationship_id,
valid_start_date,
valid_end_date,
invalid_reason
FROM (
SELECT concept_code_1,
concept_code_2,
vocabulary_id_1,
vocabulary_id_2,
relationship_id,
valid_start_date,
valid_end_date,
invalid_reason,
/*PG doesn't support COUNT (DISTINCT concept_code_2) OVER (partition by concept_code_1) -> "Use of DISTINCT is not allowed with the OVER clause"
so replacing with nice trick with dense_rank()
*/
(
DENSE_RANK() OVER (
PARTITION BY concept_code_1 ORDER BY concept_code_2
) + DENSE_RANK() OVER (
PARTITION BY concept_code_1 ORDER BY concept_code_2 DESC
) - 1
) cnt
FROM (
SELECT t.concept_code_9 AS concept_code_1,
r.concept_code_2 AS concept_code_2,
r.vocabulary_id_1 AS vocabulary_id_1,
r.vocabulary_id_2 AS vocabulary_id_2,
r.relationship_id AS relationship_id,
r.valid_start_date AS valid_start_date,
r.valid_end_date AS valid_end_date,
r.invalid_reason AS invalid_reason
FROM concept_relationship_stage r,
(
SELECT c.concept_code AS concept_code_9
FROM concept_stage c,
concept_stage c1
WHERE c.vocabulary_id = 'NDC'
AND c.concept_class_id = '9-digit NDC'
AND c1.concept_code LIKE c.concept_code || '%'
AND c1.vocabulary_id = 'NDC'
AND c1.concept_class_id = '11-digit NDC'
AND NOT EXISTS (
SELECT 1
FROM concept_relationship_stage r_int
WHERE r_int.concept_code_1 = c.concept_code
AND r_int.vocabulary_id_1 = c.vocabulary_id
)
) t
WHERE r.concept_code_1 LIKE t.concept_code_9 || '%'
AND r.vocabulary_id_1 = 'NDC'
AND r.relationship_id = 'Maps to'
AND r.vocabulary_id_2 = 'RxNorm'
GROUP BY t.concept_code_9,
r.concept_code_2,
r.vocabulary_id_1,
r.vocabulary_id_2,
r.relationship_id,
r.valid_start_date,
r.valid_end_date,
r.invalid_reason
) AS s0
) AS s1
WHERE cnt = 1;
DROP INDEX trgm_idx;
DROP INDEX trgm_crs_idx;
--24. MERGE concepts from fresh sources (RXNORM2NDC_MAPPINGS_EXT). Add/merge only fresh mappings (even if rxnorm2ndc_mappings_ext gives us deprecated mappings we put them as fresh: redmine #70209)
WITH to_be_upserted
AS (
SELECT DISTINCT ndc_code,
LAST_VALUE(concept_code) OVER (
PARTITION BY ndc_code ORDER BY invalid_reason nulls LAST,
startDate ROWS BETWEEN UNBOUNDED PRECEDING
AND UNBOUNDED FOLLOWING
) AS concept_code,
LAST_VALUE(startDate) OVER (
PARTITION BY ndc_code ORDER BY invalid_reason nulls LAST,
startDate ROWS BETWEEN UNBOUNDED PRECEDING
AND UNBOUNDED FOLLOWING
) AS startDate,
LAST_VALUE(invalid_reason) OVER (
PARTITION BY ndc_code ORDER BY invalid_reason nulls LAST,
startDate ROWS BETWEEN UNBOUNDED PRECEDING
AND UNBOUNDED FOLLOWING
) AS invalid_reason
FROM rxnorm2ndc_mappings_ext
),
to_be_updated
AS (
UPDATE concept_relationship_stage crs
SET valid_start_date = up.startdate,
valid_end_date = TO_DATE('20991231', 'yyyymmdd'),
invalid_reason = NULL
FROM to_be_upserted up
WHERE crs.concept_code_1 = up.ndc_code
AND crs.concept_code_2 = up.concept_code
AND crs.relationship_id = 'Maps to'
AND crs.vocabulary_id_1 = 'NDC'
AND crs.vocabulary_id_2 = 'RxNorm'
AND up.invalid_reason IS NULL RETURNING crs.*
)
INSERT INTO concept_relationship_stage (
concept_code_1,
concept_code_2,
vocabulary_id_1,
vocabulary_id_2,
relationship_id,
valid_start_date,
valid_end_date,
invalid_reason
)
SELECT tpu.ndc_code,
tpu.concept_code,
'NDC',
'RxNorm',
'Maps to',
tpu.startdate,
TO_DATE('20991231', 'yyyymmdd'),
NULL
FROM to_be_upserted tpu
WHERE (
tpu.ndc_code,
tpu.concept_code,
'NDC',
'RxNorm',
'Maps to'
) NOT IN (
SELECT up.concept_code_1,
up.concept_code_2,
up.vocabulary_id_1,
up.vocabulary_id_2,
up.relationship_id
FROM to_be_updated up
UNION ALL
SELECT crs_int.concept_code_1,
crs_int.concept_code_2,
crs_int.vocabulary_id_1,
crs_int.vocabulary_id_2,
crs_int.relationship_id
FROM concept_relationship_stage crs_int
WHERE crs_int.relationship_id = 'Maps to'
AND crs_int.vocabulary_id_1 = 'NDC'
AND crs_int.vocabulary_id_2 = 'RxNorm'
);
--25. Add PACKAGES
ANALYZE concept_stage;
INSERT INTO concept_stage (
concept_name,
domain_id,
vocabulary_id,
concept_class_id,
standard_concept,
concept_code,
valid_start_date,
valid_end_date,
invalid_reason
)
WITH ndc AS (
SELECT DISTINCT CASE
WHEN devv5.INSTR(productndc, '-') = 5
THEN '0' || SUBSTR(productndc, 1, devv5.INSTR(productndc, '-') - 1)
ELSE SUBSTR(productndc, 1, devv5.INSTR(productndc, '-') - 1)
END || CASE
WHEN LENGTH(SUBSTR(productndc, devv5.INSTR(productndc, '-'))) = 4
THEN '0' || SUBSTR(productndc, devv5.INSTR(productndc, '-') + 1)
ELSE SUBSTR(productndc, devv5.INSTR(productndc, '-') + 1)
END AS concept_code,
productndc
FROM sources.product
)
SELECT DISTINCT cs.concept_name,
cs.domain_id,
cs.vocabulary_id,
'11-digit NDC' AS concept_class_id,
NULL AS standard_concept,
p.pack_code,
MIN(startmarketingdate) OVER (PARTITION BY p.pack_code) AS valid_start_date,
TO_DATE('20991231', 'yyyymmdd') AS valid_end_date,
NULL AS invalid_reason
FROM ndc n
JOIN concept_stage cs ON cs.concept_code = n.concept_code
AND cs.vocabulary_id = 'NDC'
JOIN sources.package p ON p.productndc = n.productndc
LEFT JOIN concept_stage cs1 ON cs1.concept_code = p.pack_code
AND cs1.vocabulary_id = 'NDC'
WHERE cs1.concept_code IS NULL;
--26. Add manual source
--26.1. Add concept_manual
DO $_$
BEGIN
PERFORM VOCABULARY_PACK.ProcessManualConcepts();
END $_$;
--26.2. Add concept_relationship_manual
DO $_$
BEGIN
PERFORM VOCABULARY_PACK.ProcessManualRelationships();
END $_$;
--27. Delete duplicate mappings to packs
--27.1. Add mapping from deprecated to fresh concepts (necessary for the next step)
DO $_$
BEGIN
PERFORM VOCABULARY_PACK.AddFreshMAPSTO();
END $_$;
--27.2. Deprecate 'Maps to' mappings to deprecated and upgraded concepts (necessary for the next step)
DO $_$
BEGIN
PERFORM VOCABULARY_PACK.DeprecateWrongMAPSTO();
END $_$;
--27.3 Do it
DELETE
FROM concept_relationship_stage r
WHERE r.relationship_id = 'Maps to'
AND r.invalid_reason IS NULL
AND r.vocabulary_id_1 = 'NDC'
AND r.vocabulary_id_2 LIKE 'RxNorm%'
AND concept_code_1 IN (
--get all duplicate NDC mappings
SELECT concept_code_1
FROM concept_relationship_stage r_int
WHERE r_int.relationship_id = 'Maps to'
AND r_int.invalid_reason IS NULL
AND r_int.vocabulary_id_1 = 'NDC'
AND r_int.vocabulary_id_2 LIKE 'RxNorm%'
--at least one mapping to pack should exist
AND EXISTS (
SELECT 1
FROM concept c_int
WHERE c_int.concept_code = r_int.concept_code_2
AND c_int.vocabulary_id LIKE 'RxNorm%'
AND c_int.concept_class_id IN (
'Branded Pack',
'Clinical Pack',
'Quant Branded Drug',
'Quant Clinical Drug',
'Branded Drug',
'Clinical Drug'
)
)
GROUP BY concept_code_1
HAVING COUNT(*) > 1
)
AND concept_code_2 NOT IN (
--exclude 'true' mappings to packs [Branded->Clinical->etc]
SELECT c_int.concept_code
FROM concept_relationship_stage r_int,
concept c_int
WHERE r_int.relationship_id = 'Maps to'
AND r_int.invalid_reason IS NULL
AND r_int.vocabulary_id_1 = r.vocabulary_id_1
AND r_int.vocabulary_id_2 LIKE 'RxNorm%'
AND c_int.concept_code = r_int.concept_code_2
AND c_int.vocabulary_id = r_int.vocabulary_id_2
AND r_int.concept_code_1 = r.concept_code_1
ORDER BY c_int.invalid_reason NULLS FIRST,
c_int.standard_concept DESC NULLS LAST, --'S' first, next 'C' and NULL
CASE c_int.concept_class_id
WHEN 'Branded Pack'
THEN 1
WHEN 'Clinical Pack'
THEN 2
WHEN 'Quant Branded Drug'
THEN 3
WHEN 'Quant Clinical Drug'
THEN 4
WHEN 'Branded Drug'
THEN 5
WHEN 'Clinical Drug'
THEN 6
ELSE 7
END,
CASE r_int.vocabulary_id_2
WHEN 'RxNorm'
THEN 1
ELSE 2
END, --mappings to RxNorm first
c_int.valid_start_date DESC,
c_int.concept_id LIMIT 1
);
--28. Add full unique NDC packages names into concept_synonym_stage
INSERT INTO concept_synonym_stage (
synonym_concept_code,
synonym_vocabulary_id,
synonym_name,
language_concept_id
)
WITH ndc AS (
SELECT DISTINCT CASE
WHEN devv5.INSTR(productndc, '-') = 5
THEN '0' || SUBSTR(productndc, 1, devv5.INSTR(productndc, '-') - 1)
ELSE SUBSTR(productndc, 1, devv5.INSTR(productndc, '-') - 1)
END || CASE
WHEN LENGTH(SUBSTR(productndc, devv5.INSTR(productndc, '-'))) = 4
THEN '0' || SUBSTR(productndc, devv5.INSTR(productndc, '-') + 1)
ELSE SUBSTR(productndc, devv5.INSTR(productndc, '-') + 1)
END AS concept_code,
productndc
FROM sources.product
)
SELECT p.pack_code AS synonym_concept_code,
m.vocabulary_id,
vocabulary_pack.CutConceptSynonymName(m.long_concept_name),
4180186 AS language_concept_id -- English
FROM ndc n
JOIN main_ndc m ON m.concept_code = n.concept_code
JOIN sources.package p ON p.productndc = n.productndc
LEFT JOIN concept_synonym_stage css ON css.synonym_concept_code = p.pack_code
WHERE css.synonym_concept_code IS NULL
AND NOT EXISTS (
SELECT 1
FROM concept_stage cs_int
WHERE cs_int.concept_code = p.pack_code
AND cs_int.vocabulary_id = m.vocabulary_id
AND REPLACE(LOWER(cs_int.concept_name), ' [diluent]', '') = LOWER(vocabulary_pack.CutConceptSynonymName(m.long_concept_name))
);
--29. Add relationships (take from 9-digit NDC codes), but only new
ANALYZE concept_relationship_stage;
INSERT INTO concept_relationship_stage (
concept_code_1,
concept_code_2,
vocabulary_id_1,
vocabulary_id_2,
relationship_id,
valid_start_date,
valid_end_date,
invalid_reason
)
WITH ndc AS (
SELECT DISTINCT CASE
WHEN devv5.INSTR(productndc, '-') = 5
THEN '0' || SUBSTR(productndc, 1, devv5.INSTR(productndc, '-') - 1)
ELSE SUBSTR(productndc, 1, devv5.INSTR(productndc, '-') - 1)
END || CASE
WHEN LENGTH(SUBSTR(productndc, devv5.INSTR(productndc, '-'))) = 4
THEN '0' || SUBSTR(productndc, devv5.INSTR(productndc, '-') + 1)
ELSE SUBSTR(productndc, devv5.INSTR(productndc, '-') + 1)
END AS concept_code,
productndc
FROM sources.product
)
SELECT DISTINCT p.pack_code AS concept_code_1,
crs.concept_code_2,
'NDC' AS vocabulary_id_1,
'RxNorm' AS vocabulary_id_2,
'Maps to' AS relationship_id,
crs.valid_start_date,
crs.valid_end_date,
crs.invalid_reason
FROM ndc n
JOIN concept_relationship_stage crs ON crs.concept_code_1 = n.concept_code
AND crs.vocabulary_id_1 = 'NDC'
AND crs.vocabulary_id_2 = 'RxNorm'
JOIN sources.package p ON p.productndc = n.productndc
LEFT JOIN concept_relationship_stage crs1 ON crs1.concept_code_1 = p.pack_code
AND crs1.vocabulary_id_1 = crs.vocabulary_id_1
AND crs1.vocabulary_id_2 = crs.vocabulary_id_2
WHERE crs1.concept_code_1 IS NULL;
--30. Working with replacement mappings
DO $_$
BEGIN
PERFORM VOCABULARY_PACK.CheckReplacementMappings();
END $_$;
--31. Delete ambiguous 'Maps to' mappings
DO $_$
BEGIN
PERFORM VOCABULARY_PACK.DeleteAmbiguousMAPSTO();
END $_$;
--32. Delete records that does not exists in the concept and concept_stage
DELETE
FROM concept_relationship_stage crs
WHERE EXISTS (
SELECT 1
FROM concept_relationship_stage crs_int
LEFT JOIN concept c1 ON c1.concept_code = crs_int.concept_code_1
AND c1.vocabulary_id = crs_int.vocabulary_id_1
LEFT JOIN concept_stage cs1 ON cs1.concept_code = crs_int.concept_code_1
AND cs1.vocabulary_id = crs_int.vocabulary_id_1
LEFT JOIN concept c2 ON c2.concept_code = crs_int.concept_code_2
AND c2.vocabulary_id = crs_int.vocabulary_id_2
LEFT JOIN concept_stage cs2 ON cs2.concept_code = crs_int.concept_code_2
AND cs2.vocabulary_id = crs_int.vocabulary_id_2
WHERE (
(
c1.concept_code IS NULL
AND cs1.concept_code IS NULL
)
OR (
c2.concept_code IS NULL
AND cs2.concept_code IS NULL
)
)
AND crs_int.concept_code_1 = crs.concept_code_1
AND crs_int.vocabulary_id_1 = crs.vocabulary_id_1
AND crs_int.concept_code_2 = crs.concept_code_2
AND crs_int.vocabulary_id_2 = crs.vocabulary_id_2
);
--33. Set proper concept_class_id (Device)
UPDATE concept_stage
SET concept_class_id = 'Device',
domain_id = 'Device',
standard_concept = 'S'
WHERE concept_name ~* ('PUMP( |$)|METER( |$)|LANCET|DEVICE|PEDIALYTE|SUNSCREEN|NEEDLE|MONITOR|FREEDOM|BLOOD GLUCOSE|STERI-STRIP|HUGGIES|GAUZE|STOCKING|DEPEND|CHAMBER|COMPRESSR|COMPRESSOR|NEBULIZER|FREESTYLE|SHARPS|ACCU-CHEK|ELECTROLYTE|'
|| ' TRAY|WAVESENSE|DEPEND|EASY TOUCH|MONIT|ENSURE|XEROFORM|PCCA|REAGENT|UNDERWEAR|CONTOUR|UNDERPAD|UNDERPAD|TRANSMITTER|GX|STERILE PADS|POISE PADS|GLUCERNA|PENTIP|MONOJECT|INSULIN SYR|DIAPHRAGM|PCCA|BD INSULIN|'
|| 'PEDIASURE|BD SYR|SIMILAC|OMNIPOD| DRINK|DRESS|ORALYTE|NUTRAMIGEN|REAGENT STRIPS|INNOSPIRE|TEST STRIPS|CONDOM|DIAPHRAGM|CLEAR SHAMPOO|HEATWRAP|VAPORIZER|UNDERPANTS|HUMIDIFIER|MURI-LUBE')
AND NOT concept_name ~* 'INTRAUTERINE|ZINC OXIDE|OXYMETAZOLINE|BENZ|BUPROPION|ALBUTEROL|MONOJECT|DIMETHICONE|PINE NEEDLE|HYDROQUIONONE|3350 '
AND concept_code NOT IN (
'547760002',
'547760005'
)
AND vocabulary_id = 'NDC';
--After first update we will have these codes as 'Device' in the concept. So we might return classes from the concept in future
UPDATE concept_stage cs
SET concept_class_id = 'Device',
domain_id = 'Device',
standard_concept='S'
FROM concept c
WHERE cs.concept_code = c.concept_code
AND cs.vocabulary_id = 'NDC'
AND cs.concept_class_id <> 'Device'
AND c.vocabulary_id = 'NDC'
AND c.concept_class_id = 'Device';
--Some devices, that cannot be detected using the patterns
UPDATE concept_stage
SET concept_class_id = 'Device',
domain_id = 'Device',
standard_concept = 'S'
WHERE concept_code IN (
'00019960110',
'00019960220',
'17156020105',
'17156052205',
'488151001',
'651740461',
'50914773104',
'48815100101',
'48815100105',
'488151002',
'48815100201',
'48815100205',
'509147720',
'50914772008',
'65174046105',
'699450601',
'69945060110',
'699450602',
'69945060220',
'91237000148',
'91237000144',
'509147731'
)
AND vocabulary_id = 'NDC';
--Devices from the manual table
UPDATE concept_stage cs
SET concept_class_id = 'Device',
domain_id = 'Device',
standard_concept = 'S'
FROM dev_ndc.ndc_manual_mapped m
WHERE m.source_code = cs.concept_code
AND cs.vocabulary_id = 'NDC'
AND m.target_concept_id = 17;
/*Put your updates here..
UPDATE concept_stage SET concept_class_id = 'Device', domain_id = 'Device', standard_concept='S' WHERE concept_code in ('x','y');
*/
/*
UPDATE concept_stage cs
SET concept_class_id = 'Device',
domain_id = 'Device',
standard_concept='S'
FROM ndc_devices i
WHERE cs.concept_code = i.concept_code
AND cs.concept_class_id <> 'Device';
*/
--34. Return proper valid_end_date from base tables
UPDATE concept_relationship_stage crs
SET valid_start_date = i.valid_start_date,
valid_end_date = i.valid_end_date
FROM (
SELECT c1.concept_code AS concept_code_1,
c1.vocabulary_id AS vocabulary_id_1,
c2.concept_code AS concept_code_2,
c2.vocabulary_id AS vocabulary_id_2,
r.relationship_id,
r.valid_start_date,
r.valid_end_date
FROM concept_relationship r
JOIN concept c1 ON c1.concept_id = r.concept_id_1
JOIN concept c2 ON c2.concept_id = r.concept_id_2
WHERE r.invalid_reason IS NOT NULL
) i
WHERE crs.concept_code_1 = i.concept_code_1
AND crs.vocabulary_id_1 = i.vocabulary_id_1
AND crs.concept_code_2 = i.concept_code_2
AND crs.vocabulary_id_2 = i.vocabulary_id_2
AND crs.relationship_id = i.relationship_id
AND crs.valid_end_date <> i.valid_end_date
AND crs.invalid_reason IS NOT NULL;
--35. Mark diluent as [Diluent]
WITH ndc_packages
AS (
SELECT DISTINCT CASE
WHEN devv5.INSTR(productndc, '-') = 5
THEN '0' || SUBSTR(productndc, 1, devv5.INSTR(productndc, '-') - 1)
ELSE SUBSTR(productndc, 1, devv5.INSTR(productndc, '-') - 1)
END || CASE
WHEN LENGTH(SUBSTR(productndc, devv5.INSTR(productndc, '-'))) = 4
THEN '0' || SUBSTR(productndc, devv5.INSTR(productndc, '-') + 1)
ELSE SUBSTR(productndc, devv5.INSTR(productndc, '-') + 1)
END AS concept_code,
productndc
FROM sources.product
),
ndc_codes
AS (
SELECT concept_code
FROM main_ndc
WHERE is_diluent
UNION
SELECT p.pack_code
FROM ndc_packages n
JOIN main_ndc m ON m.concept_code = n.concept_code
AND m.is_diluent
JOIN sources.package p ON p.productndc = n.productndc
UNION
SELECT ndc_code
FROM sources.spl_ext
WHERE is_diluent
AND ndc_code IS NOT NULL
),
ndc_update --update concept_stage
AS (
UPDATE concept_stage cs
SET concept_name = vocabulary_pack.CutConceptSynonymName(COALESCE(css.synonym_name, cs.concept_name) || ' [Diluent]')
FROM ndc_codes nc
LEFT JOIN concept_synonym_stage css ON css.synonym_concept_code = nc.concept_code
AND css.synonym_name NOT ILIKE '%water%' --exclude water
WHERE nc.concept_code = cs.concept_code
AND cs.concept_name NOT LIKE '% [Diluent]' --do not mark already marked codes
AND cs.concept_name NOT ILIKE '%water%'
)
--update concept_synonym_stage
UPDATE concept_synonym_stage css
SET synonym_name = vocabulary_pack.CutConceptSynonymName('Diluent of ' || cs.concept_name)
FROM concept_stage cs
JOIN ndc_codes USING (concept_code)
WHERE cs.concept_code = css.synonym_concept_code
AND cs.concept_name NOT ILIKE '%water%'; --exclude water
--36. Clean up
DROP FUNCTION GetAggrDose (active_numerator_strength IN VARCHAR, active_ingred_unit IN VARCHAR);
DROP FUNCTION GetDistinctDose (active_numerator_strength IN VARCHAR, active_ingred_unit IN VARCHAR, p IN INT);
DROP FUNCTION CheckNDCDate (pDate IN VARCHAR, pDateDefault IN DATE);
DROP TABLE main_ndc;
DROP TABLE rxnorm2ndc_mappings_ext;
-- At the end, the three tables concept_stage, concept_relationship_stage and concept_synonym_stage should be ready to be fed into the generic_update.sql script | OHDSI/Vocabulary-v5.0 | NDC_SPL/load_stage.sql | SQL | unlicense | 59,912 |
/*
@author Zakai Hamilton
@component CoreJson
*/
screens.core.json = function CoreJson(me, { core, storage }) {
me.init = function () {
if (me.platform === "server") {
me.request = require("request");
}
};
me.loadComponent = async function (path, useCache = true) {
var period = path.lastIndexOf(".");
var component_name = path.substring(period + 1);
var package_name = path.substring(0, period);
var url = "/packages/code/" + package_name + "/" + package_name + "_" + component_name + ".json";
var json = await me.loadFile(url, useCache);
return json;
};
me.get = async function (url) {
if (me.platform === "server") {
return new Promise(resolve => {
me.log("requesting: " + url);
me.request.get(url, (error, response, body) => {
if (error) {
resolve({ error });
}
else {
if (body[0] === "<") {
resolve({ error: "response is in an xml format" });
return;
}
let json = JSON.parse(body);
resolve(json);
}
});
});
}
else {
return core.message.send_server("core.json.get", url);
}
};
me.loadFile = async function (path) {
let json = {};
if (path && path.startsWith("/")) {
path = path.substring(1);
}
if (!core.util.isOnline()) {
json = await storage.local.db.get(me.id, path);
if (json) {
return json;
}
}
var info = {
method: "GET",
url: "/" + path
};
let buffer = "{}";
try {
buffer = await core.http.send(info);
}
catch (err) {
var error = "Cannot load json file: " + path + " err: " + err.message || err;
me.log_error(error);
}
if (buffer) {
json = JSON.parse(buffer);
}
await storage.local.db.set(me.id, path, json);
return json;
};
me.compare = function (source, target) {
if (typeof source !== typeof target) {
return false;
}
if (source === target) {
return true;
}
if (!source && !target) {
return true;
}
if (!source || !target) {
return false;
}
else if (Array.isArray(source)) {
var equal = source.length === target.length;
if (equal) {
target.map((item, index) => {
var sourceItem = source[index];
if (!me.compare(sourceItem, item)) {
equal = false;
}
});
}
return equal;
}
else if (typeof source === "object") {
var sourceKeys = Object.getOwnPropertyNames(source);
var targetKeys = Object.getOwnPropertyNames(target);
if (sourceKeys.length !== targetKeys.length) {
return false;
}
for (var i = 0; i < sourceKeys.length; i++) {
var propName = sourceKeys[i];
if (source[propName] !== target[propName]) {
return false;
}
}
return true;
}
else {
return false;
}
};
me.traverse = function (root, path, value) {
var item = root, parent = root, found = false, name = null;
if (root) {
item = path.split(".").reduce((node, token) => {
parent = node;
name = token;
if (!node) {
return;
}
return node[token];
}, root);
if (typeof item !== "undefined") {
value = item;
found = true;
}
}
return { parent, item, value, name, found };
};
me.value = function (root, paths, value) {
var found = false;
Object.entries(paths).forEach(([path, callback]) => {
if (found) {
return;
}
var info = me.traverse(root, path, value);
if (info.found) {
if (callback) {
var result = callback(value, path);
if (result) {
info.value = result;
found = true;
}
}
else {
value = info.value;
found = true;
}
}
});
return value;
};
me.union = function (array, property) {
return array.filter((obj, pos, arr) => {
return arr.map(mapObj => mapObj[property]).indexOf(obj[property]) === pos;
});
};
me.intersection = function (arrays, property) {
var results = [];
results.push(...arrays[0]);
for (var array of arrays) {
var keys = array.map(mapObj => mapObj[property]);
results = results.filter(mapObj => -1 !== keys.indexOf(mapObj[property]));
}
return results;
};
me.processVars = function (object, text, root) {
text = text.replace(/\${[^{}]*}/g, function (match) {
var path = match.substring(2, match.length - 1);
if (path.startsWith("@")) {
path = path.substring(1);
if (path === "date") {
return new Date().toString();
}
else {
var info = core.property.split(object, path);
let item = me.traverse(root, info.value);
if (item.found) {
return core.property.get(object, info.name, item.value);
}
return "";
}
}
let item = me.traverse(root, path);
if (item.found) {
var value = item.value;
if (typeof value === "object") {
value = JSON.stringify(value);
}
return value;
}
return "";
});
return text;
};
me.map = function (root, before, after) {
if (before) {
root = before(root);
}
if (Array.isArray(root)) {
root = Array.from(root);
}
else if (root instanceof ArrayBuffer) {
root = root.slice(0);
}
else if (root !== null && typeof root === "object") {
root = Object.assign({}, root);
}
if (typeof root !== "string") {
for (var key in root) {
root[key] = me.map(root[key], before, after);
}
}
if (after) {
root = after(root);
}
return root;
};
me.isValid = function (str) {
try {
JSON.parse(str);
} catch (e) {
return false;
}
return true;
};
};
| zakaihamilton/screens | packages/code/core/core_json.js | JavaScript | unlicense | 7,342 |
exports = module.exports = addShims;
function addShims() {
Function.prototype.extend = function(parent) {
var child = this;
var args = Array.prototype.slice.call(arguments, 0);
child.prototype = parent;
child.prototype = new (Function.prototype.bind.apply(parent, args))();
child.prototype.constructor = child;
var parentProxy = child.prototype.parent = {};
for (var i in parent) {
switch(typeof parent[i]) {
case 'function':
parentProxy[i] = parent[i].bind(child);
break;
default:
parentProxy[i] = parent[i];
}
}
return this;
};
}
| cabloo/express-elect-seed | api/src/core/core.shims.js | JavaScript | unlicense | 625 |
#!/usr/bin/env bash
CURRENT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
source "$CURRENT_DIR/helpers.sh"
print_battery_percentage() {
# percentage displayed in the 2nd field of the 2nd row
if command_exists "pmset"; then
pmset -g batt | grep -o "[0-9]\{1,3\}%"
elif command_exists "upower"; then
local batteries=( $(upower -e | grep battery) )
local energy
local energy_full
for battery in ${batteries[@]}; do
energy=$(upower -i $battery | awk -v nrg="$energy" '/energy:/ {print nrg+$2}')
energy_full=$(upower -i $battery | awk -v nrgfull="$energy_full" '/energy-full:/ {print nrgfull+$2}')
done
echo $energy $energy_full | awk '{printf("%d%%", ($1/$2)*100)}'
elif command_exists "acpi"; then
acpi -b | grep -Eo "[0-9]+%"
fi
}
main() {
print_battery_percentage
}
main
| Quarkex/dotfiles | tmux/tmux-battery/scripts/battery_percentage.sh | Shell | unlicense | 812 |
package audits
import scala.concurrent.Future
/** Dao for storing and retrieving events */
trait EventDao {
/** Write a new Event to the system */
def write(description: String): Future[Unit]
}
| kdoomsday/doomcart | app/audits/EventDao.scala | Scala | unlicense | 201 |
body {
text-align: center; }
.clearer {
clear: both; }
.modal {
text-align: left; }
h1 {
margin-bottom: 1.3em; }
.alert {
width: 50%;
margin: auto; }
#rules {
margin-top: 1em; }
.rule {
margin: 1px 10px;
padding: 10px 0;
position: relative;
clear: both;
text-align: left;
border: 1px solid transparent;
border-radius: 5px; }
.rule.invalid {
transition: background-color 4s, border-color 4s;
background-color: #f2dede;
border-color: #ebccd1; }
.rule.invalid .glyphicon-arrow-right {
transition: color 4s;
color: #ebccd1; }
.rule .delete_line {
position: absolute;
top: 0;
right: 0;
border: none;
background: none; }
.rule .glyphicon-arrow-right {
font-size: 3em;
position: absolute;
top: 0.8em;
left: 50%;
margin-left: -0.5em;
color: #f3f3f3; }
.rule .match, .rule .replacement {
width: 50%;
padding: 0 50px; }
.rule .match select, .rule .replacement select {
margin: 0 15px 5px 0; }
.rule .match .options, .rule .replacement .options {
display: inline-block; }
.rule .match .options label + label, .rule .match .options .tooltip + label, .rule .replacement .options label + label, .rule .replacement .options .tooltip + label {
margin-left: 15px; }
.rule .match .btn_help, .rule .replacement .btn_help {
font-size: 12px;
line-height: 20px;
float: right;
cursor: pointer;
color: #aaa; }
.rule .match textarea, .rule .replacement textarea {
min-height: 2em;
width: 100%;
max-width: 100%; }
.rule .match {
float: left; }
.rule .replacement {
float: right; }
#controls {
margin-top: 2.5em; }
#controls #add_line {
font-weight: bold; }
| Whisno/Chrome-Text-Customizer | chrome-extension/options.css | CSS | unlicense | 1,764 |
<?php
if(empty($_POST['tipname'])||empty($_POST['tipid'])) exit;
include("../theme/language/en/language.php");
echo $_POST['tipid']."<!-|||->";
switch ($_POST['tipname'])
{
case 'select_mode_free': echo $lang['tip_free'];
break;
case 'select_mode_host': echo $lang['tip_host'];
break;
case 'select_mode_local': echo $lang['tip_local'];
break;
case 'select_mode_3rd': echo $lang['tip_3rd'];
break;
case 'param_room_name': echo $lang['tip_room_name'];
break;
case 'param_host_address': echo $lang['tip_host_address'];
break;
case 'param_local_address': echo $lang['tip_local_address'];
break;
case 'integration_yes': echo $lang['tip_integration_yes'];
break;
case 'integration_no': echo $lang['tip_integration_no'];
break;
case 'integration_select_mode':echo $lang['tip_integration_mode'];
break;
case 'integration_select_db':echo $lang['tip_integration_db'];
break;
case 'param_db_host':echo $lang['tip_param_db_host'];
break;
case 'param_db_port':echo $lang['tip_param_db_port'];
break;
case 'param_db_name':echo $lang['tip_param_db_name'];
break;
case 'param_db_username':echo $lang['tip_param_db_username'];
break;
case 'param_db_password':echo $lang['tip_param_db_password'];
break;
case 'param_db_user_table':echo $lang['tip_param_db_user_table'];
break;
case 'param_uesrname_field':echo $lang['tip_param_uesrname_field'];
break;
case 'param_pw_field':echo $lang['tip_param_pw_field'];
break;
case 'enablemd5':echo $lang['tip_param_enablemd5'];
break;
}
?> | dvelle/The-hustle-game-on-facebook-c.2010 | hustle/hustle/nightworld/phpchat/includes/active_tip_word.php | PHP | unlicense | 1,509 |
// stdafx.cpp : source file that includes just the standard includes
// GetFolderTime.pch will be the pre-compiled header
// stdafx.obj will contain the pre-compiled type information
#include "stdafx.h"
| hyller/CodeLibrary | Visual C++ Example/第10章 文件操作与注册表编程/实例238——获取目录的创建时间/GetFolderTime/StdAfx.cpp | C++ | unlicense | 215 |
//
// UIImage+IL_ContentWithColor.h
// ILDiligence
//
// Created by XueFeng Chen on 2017/5/14.
// Copyright © 2017年 XueFeng Chen. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface UIImage (IL_ContentWithColor)
- (UIImage *)il_imageContentWithColor:(UIColor *)color;
@end
| Inspirelife96/ILDiligence | ILDiligence/ILDiligence/UIImage+IL_ContentWithColor.h | C | unlicense | 291 |
public class RandomColoringDiv2 {
public int getCount(int maxR, int maxG, int maxB, int startR, int startG, int startB, int d1,
int d2) {
int colors = 0;
int minR = Math.max(0, startR - d2);
int minG = Math.max(0, startG - d2);
int minB = Math.max(0, startB - d2);
for (int r = minR; r<maxR; r++) {
int difR = Math.abs(r - startR);
if (difR > d2)
break;
for (int g = minG; g<maxG; g++) {
int difG = Math.abs(g - startG);
if (difG > d2)
break;
for (int b = minB; b<maxB; b++) {
int difB = Math.abs(b - startB);
if (difB > d2)
break;
if (difR >= d1 || difG >= d1 || difB >=d1)
colors++;
}
}
}
return colors;
}
public static void main(String[] args) {
long time;
int answer;
boolean errors = false;
int desiredAnswer;
time = System.currentTimeMillis();
answer = new RandomColoringDiv2().getCount(5, 1, 1, 2, 0, 0, 0, 1);
System.out.println("Time: " + (System.currentTimeMillis() - time) / 1000.0 + " seconds");
desiredAnswer = 3;
System.out.println("Your answer:");
System.out.println("\t" + answer);
System.out.println("Desired answer:");
System.out.println("\t" + desiredAnswer);
if (answer != desiredAnswer) {
errors = true;
System.out.println("DOESN'T MATCH!!!!");
} else
System.out.println("Match :-)");
System.out.println();
time = System.currentTimeMillis();
answer = new RandomColoringDiv2().getCount(4, 2, 2, 0, 0, 0, 3, 3);
System.out.println("Time: " + (System.currentTimeMillis() - time) / 1000.0 + " seconds");
desiredAnswer = 4;
System.out.println("Your answer:");
System.out.println("\t" + answer);
System.out.println("Desired answer:");
System.out.println("\t" + desiredAnswer);
if (answer != desiredAnswer) {
errors = true;
System.out.println("DOESN'T MATCH!!!!");
} else
System.out.println("Match :-)");
System.out.println();
time = System.currentTimeMillis();
answer = new RandomColoringDiv2().getCount(4, 2, 2, 0, 0, 0, 5, 5);
System.out.println("Time: " + (System.currentTimeMillis() - time) / 1000.0 + " seconds");
desiredAnswer = 0;
System.out.println("Your answer:");
System.out.println("\t" + answer);
System.out.println("Desired answer:");
System.out.println("\t" + desiredAnswer);
if (answer != desiredAnswer) {
errors = true;
System.out.println("DOESN'T MATCH!!!!");
} else
System.out.println("Match :-)");
System.out.println();
time = System.currentTimeMillis();
answer = new RandomColoringDiv2().getCount(6, 9, 10, 1, 2, 3, 0, 10);
System.out.println("Time: " + (System.currentTimeMillis() - time) / 1000.0 + " seconds");
desiredAnswer = 540;
System.out.println("Your answer:");
System.out.println("\t" + answer);
System.out.println("Desired answer:");
System.out.println("\t" + desiredAnswer);
if (answer != desiredAnswer) {
errors = true;
System.out.println("DOESN'T MATCH!!!!");
} else
System.out.println("Match :-)");
System.out.println();
time = System.currentTimeMillis();
answer = new RandomColoringDiv2().getCount(6, 9, 10, 1, 2, 3, 4, 10);
System.out.println("Time: " + (System.currentTimeMillis() - time) / 1000.0 + " seconds");
desiredAnswer = 330;
System.out.println("Your answer:");
System.out.println("\t" + answer);
System.out.println("Desired answer:");
System.out.println("\t" + desiredAnswer);
if (answer != desiredAnswer) {
errors = true;
System.out.println("DOESN'T MATCH!!!!");
} else
System.out.println("Match :-)");
System.out.println();
time = System.currentTimeMillis();
answer = new RandomColoringDiv2().getCount(49, 59, 53, 12, 23, 13, 11, 22);
System.out.println("Time: " + (System.currentTimeMillis() - time) / 1000.0 + " seconds");
desiredAnswer = 47439;
System.out.println("Your answer:");
System.out.println("\t" + answer);
System.out.println("Desired answer:");
System.out.println("\t" + desiredAnswer);
if (answer != desiredAnswer) {
errors = true;
System.out.println("DOESN'T MATCH!!!!");
} else
System.out.println("Match :-)");
System.out.println();
if (errors)
System.out.println("Some of the test cases had errors :-(");
else
System.out.println("You're a stud (at least on the test data)! :-D ");
}
}
// Powered by [KawigiEdit] 2.0! | mariusj/contests | srm540/src/RandomColoringDiv2.java | Java | unlicense | 5,179 |
import os
# Application constants
APP_NAME = 'job_offers'
INSTALL_DIR = os.path.dirname(os.path.abspath(__file__))
LOG_FORMAT = '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
LOG_NAME = os.path.join(INSTALL_DIR, 'job_offers.log')
# Testing fixtures
JOB_OFFER_FIXTURES = os.path.join(INSTALL_DIR, "fixtures/job_offers.json")
| jvazquez/organization | organization/job_offers/constants.py | Python | unlicense | 334 |
package hr.element.etb.lift.http
import net.liftweb.http.js._
import net.liftweb.util.Helpers._
package object js {
case class Prompt(text: String, default: String = "") extends JsExp {
def toJsCmd = "prompt(" + text.encJs + "," + default.encJs + ")"
}
case object ReloadPage extends JsCmd {
def toJsCmd = "window.location.reload();"
}
}
| mlegac/etb | lift/src/main/scala/hr/element/etb/lift/http/js.scala | Scala | unlicense | 357 |
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<HTML xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"><HEAD>
<TITLE>Web Gallery - Bonaire 2007-05-10 16-37-06</TITLE>
<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<LINK href="assets/css/global.css" rel="stylesheet" type="text/css">
<META name="description" localizable="true" content="Created by Apple Aperture">
</HEAD><BODY class="detail">
<DIV id="header">
<H1 localizable="true">Bonaire May 2007</H1>
<UL id="nav">
<LI class="index"><A href="index4.html" localizable="true">Index</A></LI><LI class="previous"> <A href="large-27.html"><EM class="previous_text" localizable="true">Previous</EM> </A> </LI><LI class="pageNumber">28 of 52</LI><LI class="next"> <A href="large-29.html"><EM class="next_text" localizable="true">Next</EM> </A> </LI></UL>
<DIV style="clear: both;"></DIV>
</DIV>
<TABLE><TBODY><TR><TD class="sideinfo">
<H2></H2>
<UL id="metadata"><LI>Rating: 3 </LI><LI>Badges: Adjusted Keyword </LI><LI>Aperture: f/6.3 </LI><LI>Shutter Speed: 1/125 </LI><LI>Exposure Bias: 0ev </LI><LI>Focal Length (35mm): 90mm </LI><LI>Focal Length: 60mm </LI><LI>Caption: Sea Horse </LI><LI>Keywords: Bonaire, Diving, Underwater Photography </LI><LI>Name: Bonaire 2007-05-10 16-37-06 </LI><LI>Image Date: 5/10/07 4:37:03 PM GMT+05:00 </LI><LI>ISO Speed Rating: ISO400 </LI><LI>File Size: 15.46 MB </LI><LI>Master Location: Bonaire 2007-05 </LI></UL>
</TD><TD style="width:100%;">
<DIV id="photo"><TABLE startoffset="27"><TR><TD><IMG name="img" src="pictures/picture-28.jpg" width="650" height="435" alt=""></TD></TR></TABLE></DIV>
</TD></TR></TBODY></TABLE>
<DIV id="footer">
<P localizable="true">Copyright 2007, Gregg Kellogg. All rights reserved.</P>
</DIV>
</BODY></HTML> | gkellogg/gkellogg.github.io | galleries/Bonaire 2007-05/large-28.html | HTML | unlicense | 1,873 |
require 'exception_notification/rails'
require 'exception_notification/sidekiq'
ExceptionNotification.configure do |config|
# Ignore additional exception types.
# ActiveRecord::RecordNotFound, AbstractController::ActionNotFound and ActionController::RoutingError are already added.
# config.ignored_exceptions += %w{ActionView::TemplateError CustomError}
# Adds a condition to decide when an exception must be ignored or not.
# The ignore_if method can be invoked multiple times to add extra conditions.
config.ignore_if do |exception, options|
not Rails.env.production?
end
# Notifiers =================================================================
# Email notifier sends notifications by email.
config.add_notifier :email, {
:email_prefix => "[Dysnomia-Exception] ",
:sender_address => %{"exception" <#{Settings.mail_address}>},
:exception_recipients => %w{[email protected]}
}
# Campfire notifier sends notifications to your Campfire room. Requires 'tinder' gem.
# config.add_notifier :campfire, {
# :subdomain => 'my_subdomain',
# :token => 'my_token',
# :room_name => 'my_room'
# }
# HipChat notifier sends notifications to your HipChat room. Requires 'hipchat' gem.
# config.add_notifier :hipchat, {
# :api_token => 'my_token',
# :room_name => 'my_room'
# }
# Webhook notifier sends notifications over HTTP protocol. Requires 'httparty' gem.
# config.add_notifier :webhook, {
# :url => 'http://example.com:5555/hubot/path',
# :http_method => :post
# }
end
| caffeineshock/dysnomia | config/initializers/exception_notification.rb | Ruby | unlicense | 1,580 |
/*globals document, setTimeout, clearTimeout, Audio, navigator */
var MallardMayhem = MallardMayhem || {};
(function () {
"use strict";
MallardMayhem.Duck = function (options) {
var self = this;
this.currentTimeout = null;
this.domElement = document.createElement('span');
this.currentLocation = 0;
this.sounds = {};
this.maxAge = (20 * 1000);
this.lifeSpan = null;
this.id = options.id || null;
this.colour = options.colour || null;
this.name = options.name || 'Quacky';
this.direction = 'right';
this.flyTo = function (coords, callback) {
var baseClass = 'duck-' + self.colour,
randomLocation;
switch (typeof coords) {
case 'string':
coords = coords.split(',');
break;
case 'function':
if (coords.x && coords.y) {
coords = [coords.x, coords.y];
}
break;
}
if (!self.currentLocation) {
self.domElement.style.top = '0px';
self.domElement.style.left = '0px';
self.currentLocation = [(MallardMayhem.stage.offsetWidth / 2), MallardMayhem.stage.offsetHeight - (self.domElement.style.height * 2)];
}
if (self.currentLocation[0] === coords[0] && self.currentLocation[1] === coords[1]) {
if (callback) {
callback();
} else {
randomLocation = MallardMayhem.randomCoord();
self.flyTo(randomLocation);
}
} else {
if (self.currentLocation[1] !== coords[1]) {
if (coords[1] > self.currentLocation[1]) {
if ((coords[1] - self.currentLocation[1]) < MallardMayhem.animationStep) {
self.currentLocation[1] = self.currentLocation[1] + (coords[1] - self.currentLocation[1]);
} else {
self.currentLocation[1] = self.currentLocation[1] + MallardMayhem.animationStep;
}
baseClass = baseClass + '-bottom';
}
if (coords[1] < self.currentLocation[1]) {
if ((self.currentLocation[1] - coords[1]) < MallardMayhem.animationStep) {
self.currentLocation[1] = self.currentLocation[1] - (self.currentLocation[1] - coords[1]);
} else {
self.currentLocation[1] = self.currentLocation[1] - MallardMayhem.animationStep;
}
baseClass = baseClass + '-top';
}
}
if (self.currentLocation[0] !== coords[0]) {
if (coords[0] > self.currentLocation[0]) {
if ((coords[0] - self.currentLocation[0]) < MallardMayhem.animationStep) {
self.currentLocation[0] = self.currentLocation[0] + (coords[0] - self.currentLocation[0]);
} else {
self.currentLocation[0] = self.currentLocation[0] + MallardMayhem.animationStep;
}
baseClass = baseClass + '-right';
}
if (coords[0] < self.currentLocation[0]) {
if ((self.currentLocation[0] - coords[0]) < MallardMayhem.animationStep) {
self.currentLocation[0] = self.currentLocation[0] - (self.currentLocation[0] - coords[0]);
} else {
self.currentLocation[0] = self.currentLocation[0] - MallardMayhem.animationStep;
}
baseClass = baseClass + '-left';
}
}
self.domElement.style.left = self.currentLocation[0] + 'px';
self.domElement.style.top = self.currentLocation[1] + 'px';
if (self.domElement.className !== baseClass) {
self.domElement.className = baseClass;
}
self.currentTimeout = setTimeout(function () {
self.flyTo(coords, callback);
}, MallardMayhem.animationSpeed);
}
};
this.drop = function () {
self.currentLocation[1] = self.currentLocation[1] + (MallardMayhem.animationStep * 2);
self.domElement.style.top = self.currentLocation[1] + 'px';
if (self.currentLocation[1] < MallardMayhem.stage.offsetHeight - 72) {
setTimeout(self.drop, MallardMayhem.animationSpeed);
} else {
self.sounds.fall.currentLocation = self.sounds.fall.pause();
self.sounds.ground.play();
MallardMayhem.removeDuck(self.id);
}
};
this.kill = function () {
clearTimeout(self.currentTimeout);
clearTimeout(self.lifeSpan);
self.domElement.className = 'duck-' + self.colour + '-dead';
self.sounds.fall.play();
setTimeout(self.drop, ((1000 / 4) * 3));
};
this.gotShot = function () {
self.domElement.removeEventListener('mousedown', self.gotShot);
self.domElement.removeEventListener('touchstart', self.gotShot);
MallardMayhem.killDuck(self.id);
};
this.flapWing = function () {
self.sounds.flap.play();
};
this.initialize = function () {
self.domElement.id = self.id;
self.domElement.setAttribute('class', 'duck-' + self.colour + '-right');
self.domElement.addEventListener('mousedown', self.gotShot);
self.domElement.addEventListener('touchstart', self.gotShot);
MallardMayhem.stage.appendChild(self.domElement);
var randomLocation = MallardMayhem.randomCoord(),
format = (navigator.userAgent.indexOf('Firefox') > 1) ? 'ogg' : 'mp3';
self.flyTo(randomLocation);
self.lifeSpan = setTimeout(self.flyAway, self.maxAge);
self.sounds = {
fall : new Audio('./audio/fall.' + format),
ground: new Audio('./audio/ground.' + format)
};
self.sounds.fall.volume = 0.1;
};
this.flyAway = function () {
clearTimeout(self.currentTimeout);
self.domElement.removeEventListener('mousedown', self.gotShot);
self.domElement.removeEventListener('touchstart', self.gotShot);
self.domElement.className = 'duck-' + self.colour + '-top';
self.currentLocation[1] = self.currentLocation[1] - (MallardMayhem.animationStep * 3);
self.domElement.style.top = self.currentLocation[1] + 'px';
if (self.currentLocation[1] > (-60)) {
setTimeout(self.flyAway, MallardMayhem.animationSpeed);
} else {
MallardMayhem.removeDuck(self.id);
}
};
this.initialize();
};
}()); | HTMLToronto/MallardMayhem | mm/mm.client.duck.js | JavaScript | unlicense | 7,282 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
namespace GestionInmobiliaria.RESTServices
{
using GestionInmobiliaria.BusinessEntity;
using GestionInmobiliaria.BusinessLogic;
using System.ServiceModel.Web;
// NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IUnidadInmobiliarias" in both code and config file together.
[ServiceContract]
public interface IUnidadInmobiliarias
{
// La UriTemplate correcta debería de estar en plural, es decir, UnidadesInmobiliarias.
// EL nombre del servicio UnidadInmobiliarias.svc, puede tener el nombre en singular o como se desee: UnidadInmobiliariaService.svc
[OperationContract]
[WebInvoke(Method = "GET", UriTemplate = "UnidadInmobiliarias", ResponseFormat = WebMessageFormat.Json)]
List<UnidadInmobiliaria> Listar();
[OperationContract]
[WebInvoke(Method = "GET", UriTemplate = "UnidadInmobiliarias/{id}", ResponseFormat = WebMessageFormat.Json)]
UnidadInmobiliaria Obtener(string id);
[OperationContract]
[WebInvoke(Method = "POST", UriTemplate = "UnidadInmobiliarias", ResponseFormat = WebMessageFormat.Json)]
int Agregar(UnidadInmobiliaria unidadInmobiliaria);
[OperationContract]
[WebInvoke(Method = "PUT", UriTemplate = "UnidadInmobiliarias", ResponseFormat = WebMessageFormat.Json)]
bool Modificar(UnidadInmobiliaria unidadInmobiliaria);
[OperationContract]
[WebInvoke(Method = "DELETE", UriTemplate = "UnidadInmobiliarias/{id}", ResponseFormat = WebMessageFormat.Json)]
bool Eliminar(string id);
}
} | davidhh20/APPGI-UPC | Source/Services/GestionInmobiliaria.RESTServices/IUnidadInmobiliarias.cs | C# | unlicense | 1,770 |
<?php
namespace SKE\Command;
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\Finder\Finder;
class CacheClearCommand extends ContainerAwareCommand
{
protected $cachePath;
protected $finder;
protected $filesystem;
/**
* @param $cachePath
*/
public function setCachePath($cachePath)
{
$this->cachePath = $cachePath;
}
/**
* @return mixed
*/
public function getCachePath()
{
return $this->cachePath;
}
/**
* @param Filesystem $filesystem
*/
public function setFilesystem(Filesystem $filesystem)
{
$this->filesystem = $filesystem;
}
/**
* @return Filesystem
*/
public function getFilesystem()
{
if(null === $this->filesystem) {
$this->setFilesystem(
new Filesystem()
);
}
return $this->filesystem;
}
/**
* @param Finder $finder
*/
public function setFinder(Finder $finder)
{
$this->finder = $finder;
}
/**
* @return Finder
*/
public function getFinder()
{
if(null === $this->finder) {
$this->setFinder(
Finder::create()
);
}
return $this->finder;
}
/**
* Configures the command
*/
protected function configure()
{
$this->setName('cache:clear')
->setDescription('Clears the cache');
}
/**
* @param InputInterface $input
* @param OutputInterface $output
* @return int|null|void
*/
protected function execute(InputInterface $input, OutputInterface $output)
{
$finder = $this->getFinder();
$finder->in($this->getCachePath());
$finder->ignoreDotFiles(true);
$filesystem = $this->getFilesystem();
$filesystem->remove($finder);
$output->writeln(sprintf("%s <info>success</info>", 'cache:clear'));
}
}
| ooXei1sh/silex-ske-sandbox | src/SKE/Command/CacheClearCommand.php | PHP | unlicense | 2,254 |
// Copyright (c) Microsoft Corporation. All rights reserved.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
using System.Text.RegularExpressions;
using System.Xml;
using Diagnostics.Tracing;
using Diagnostics.Tracing.Parsers;
using FastSerialization;
using Utilities;
using System.IO;
using System.Diagnostics.Tracing;
namespace Diagnostics.Tracing.Parsers
{
/// <summary>
/// A DynamicTraceEventParser is a parser that understands how to read the embedded manifests that occur in the
/// dataStream (System.Diagnostics.Tracing.EventSources do this).
///
/// See also code:TDHDynamicTraceEventParser which knows how to read the manifest that are registered globally with
/// the machine.
/// </summary>
public class DynamicTraceEventParser : TraceEventParser
{
public DynamicTraceEventParser(TraceEventSource source)
: base(source)
{
if (source == null) // Happens during deserialization.
return;
// Try to retieve persisted state
state = (DynamicTraceEventParserState)StateObject;
if (state == null)
{
StateObject = state = new DynamicTraceEventParserState();
dynamicManifests = new Dictionary<Guid, DynamicManifestInfo>();
this.source.RegisterUnhandledEvent(delegate(TraceEvent data)
{
if (data.ID != (TraceEventID)0xFFFE)
return data;
// Look up our information.
DynamicManifestInfo dynamicManifest;
if (!dynamicManifests.TryGetValue(data.ProviderGuid, out dynamicManifest))
{
dynamicManifest = new DynamicManifestInfo();
dynamicManifests.Add(data.ProviderGuid, dynamicManifest);
}
ProviderManifest provider = dynamicManifest.AddChunk(data);
// We have a completed manifest, add it to our list.
if (provider != null)
AddDynamicProvider(provider);
return data;
});
}
else if (allCallbackCalled)
{
foreach (ProviderManifest provider in state.providers.Values)
provider.AddProviderEvents(source, allCallback);
}
}
public override event Action<TraceEvent> All
{
add
{
if (state != null)
{
foreach (ProviderManifest provider in state.providers.Values)
provider.AddProviderEvents(source, value);
}
allCallback += value;
allCallbackCalled = true;
}
remove
{
throw new Exception("Not supported");
}
}
/// <summary>
/// Returns a list of providers (their manifest) that this TraceParser knows about.
/// </summary>
public IEnumerable<ProviderManifest> DynamicProviders
{
get
{
return state.providers.Values;
}
}
/// <summary>
/// Given a manifest describing the provider add its information to the parser.
/// </summary>
/// <param name="providerManifest"></param>
public void AddDynamicProvider(ProviderManifest providerManifest)
{
// Remember this serialized information.
state.providers[providerManifest.Guid] = providerManifest;
// If someone as asked for callbacks on every event, then include these too.
if (allCallbackCalled)
providerManifest.AddProviderEvents(source, allCallback);
}
/// <summary>
/// Utility method that stores all the manifests known to the DynamicTraceEventParser to the directory 'directoryPath'
/// </summary>
public void WriteAllManifests(string directoryPath)
{
Directory.CreateDirectory(directoryPath);
foreach (var providerManifest in DynamicProviders)
{
var filePath = Path.Combine(directoryPath, providerManifest.Name + ".manifest.xml");
providerManifest.WriteToFile(filePath);
}
}
/// <summary>
/// Utility method that read all the manifests the directory 'directoryPath' into the parser.
/// </summary>
public void ReadAllManifests(string directoryPath)
{
foreach (var fileName in Directory.GetFiles(directoryPath, "*.manifest.xml"))
{
AddDynamicProvider(new ProviderManifest(fileName));
}
foreach (var fileName in Directory.GetFiles(directoryPath, "*.man"))
{
AddDynamicProvider(new ProviderManifest(fileName));
}
}
#region private
// This allows protected members to avoid the normal initization.
protected DynamicTraceEventParser(TraceEventSource source, bool noInit) : base(source) { }
private class DynamicManifestInfo
{
internal DynamicManifestInfo() { }
byte[][] Chunks;
int ChunksLeft;
ProviderManifest provider;
byte majorVersion;
byte minorVersion;
ManifestEnvelope.ManifestFormats format;
internal unsafe ProviderManifest AddChunk(TraceEvent data)
{
if (provider != null)
return null;
// TODO
if (data.EventDataLength <= sizeof(ManifestEnvelope) || data.GetByteAt(3) != 0x5B) // magic number
return null;
ushort totalChunks = (ushort)data.GetInt16At(4);
ushort chunkNum = (ushort)data.GetInt16At(6);
if (chunkNum >= totalChunks || totalChunks == 0)
return null;
if (Chunks == null)
{
format = (ManifestEnvelope.ManifestFormats)data.GetByteAt(0);
majorVersion = (byte)data.GetByteAt(1);
minorVersion = (byte)data.GetByteAt(2);
ChunksLeft = totalChunks;
Chunks = new byte[ChunksLeft][];
}
else
{
// Chunks have to agree with the format and version information.
if (format != (ManifestEnvelope.ManifestFormats)data.GetByteAt(0) ||
majorVersion != data.GetByteAt(1) || minorVersion != data.GetByteAt(2))
return null;
}
if (Chunks[chunkNum] != null)
return null;
byte[] chunk = new byte[data.EventDataLength - 8];
Chunks[chunkNum] = data.EventData(chunk, 0, 8, chunk.Length);
--ChunksLeft;
if (ChunksLeft > 0)
return null;
// OK we have a complete set of chunks
byte[] serializedData = Chunks[0];
if (Chunks.Length > 1)
{
int totalLength = 0;
for (int i = 0; i < Chunks.Length; i++)
totalLength += Chunks[i].Length;
// Concatinate all the arrays.
serializedData = new byte[totalLength];
int pos = 0;
for (int i = 0; i < Chunks.Length; i++)
{
Array.Copy(Chunks[i], 0, serializedData, pos, Chunks[i].Length);
pos += Chunks[i].Length;
}
}
Chunks = null;
// string str = Encoding.UTF8.GetString(serializedData);
provider = new ProviderManifest(serializedData, format, majorVersion, minorVersion);
provider.ISDynamic = true;
return provider;
}
}
DynamicTraceEventParserState state;
private Dictionary<Guid, DynamicManifestInfo> dynamicManifests;
Action<TraceEvent> allCallback;
bool allCallbackCalled;
#endregion
}
/// <summary>
/// A ProviderManifest represents the XML manifest associated with teh provider.
/// </summary>
public class ProviderManifest : IFastSerializable
{
// create a manifest from a stream or a file
/// <summary>
/// Read a ProviderManifest from a stream
/// </summary>
public ProviderManifest(Stream manifestStream, int manifestLen = int.MaxValue)
{
format = ManifestEnvelope.ManifestFormats.SimpleXmlFormat;
int len = Math.Min((int)(manifestStream.Length - manifestStream.Position), manifestLen);
serializedManifest = new byte[len];
manifestStream.Read(serializedManifest, 0, len);
}
/// <summary>
/// Read a ProviderManifest from a file.
/// </summary>
public ProviderManifest(string manifestFilePath)
{
format = ManifestEnvelope.ManifestFormats.SimpleXmlFormat;
serializedManifest = File.ReadAllBytes(manifestFilePath);
}
// write a manifest to a stream or a file.
/// <summary>
/// Writes the manifest to 'outputStream' (as UTF8 XML text)
/// </summary>
public void WriteToStream(Stream outputStream)
{
outputStream.Write(serializedManifest, 0, serializedManifest.Length);
}
/// <summary>
/// Writes the manifest to a file 'filePath' (as a UTF8 XML)
/// </summary>
/// <param name="filePath"></param>
public void WriteToFile(string filePath)
{
using (var stream = File.Create(filePath))
WriteToStream(stream);
}
/// <summary>
/// Set if this manifest came from the ETL data stream file.
/// </summary>
public bool ISDynamic { get; internal set; }
// Get at the data in the manifest.
public string Name { get { if (!inited) Init(); return name; } }
public Guid Guid { get { if (!inited) Init(); return guid; } }
/// <summary>
/// Retrieve manifest as one big string.
/// </summary>
public string Manifest { get { if (!inited) Init(); return Encoding.UTF8.GetString(serializedManifest); } }
/// <summary>
/// Retrieve the manifest as XML
/// </summary>
public XmlReader ManifestReader
{
get
{
XmlReaderSettings settings = new XmlReaderSettings();
settings.IgnoreComments = true;
settings.IgnoreWhitespace = true;
// TODO FIX NOW remove
// var manifest = System.Text.Encoding.UTF8.GetString(serializedManifest);
// Trace.WriteLine(manifest);
System.IO.MemoryStream stream = new System.IO.MemoryStream(serializedManifest);
return XmlReader.Create(stream, settings);
}
}
#region private
internal ProviderManifest(byte[] serializedManifest, ManifestEnvelope.ManifestFormats format, byte majorVersion, byte minorVersion)
{
this.serializedManifest = serializedManifest;
this.majorVersion = majorVersion;
this.minorVersion = minorVersion;
this.format = format;
}
internal void AddProviderEvents(ITraceParserServices source, Action<TraceEvent> callback)
{
if (error != null)
return;
if (!inited)
Init();
try
{
Dictionary<string, int> opcodes = new Dictionary<string, int>();
opcodes.Add("win:Info", 0);
opcodes.Add("win:Start", 1);
opcodes.Add("win:Stop", 2);
opcodes.Add("win:DC_Start", 3);
opcodes.Add("win:DC_Stop", 4);
opcodes.Add("win:Extension", 5);
opcodes.Add("win:Reply", 6);
opcodes.Add("win:Resume", 7);
opcodes.Add("win:Suspend", 8);
opcodes.Add("win:Send", 9);
opcodes.Add("win:Receive", 240);
Dictionary<string, TaskInfo> tasks = new Dictionary<string, TaskInfo>();
Dictionary<string, TemplateInfo> templates = new Dictionary<string, TemplateInfo>();
Dictionary<string, IDictionary<long, string>> maps = null;
Dictionary<string, string> strings = new Dictionary<string, string>();
IDictionary<long, string> map = null;
List<EventInfo> events = new List<EventInfo>();
bool alreadyReadMyCulture = false; // I read my culture some time in the past (I can igore things)
string cultureBeingRead = null;
while (reader.Read())
{
// TODO I currently require opcodes,and tasks BEFORE events BEFORE templates.
// Can be fixed by going multi-pass.
switch (reader.Name)
{
case "event":
{
int taskNum = 0;
Guid taskGuid = Guid;
string taskName = reader.GetAttribute("task");
if (taskName != null)
{
TaskInfo taskInfo;
if (tasks.TryGetValue(taskName, out taskInfo))
{
taskNum = taskInfo.id;
taskGuid = taskInfo.guid;
}
}
else
taskName = "";
int eventID = int.Parse(reader.GetAttribute("value"));
int opcode = 0;
string opcodeName = reader.GetAttribute("opcode");
if (opcodeName != null)
{
opcodes.TryGetValue(opcodeName, out opcode);
// Strip off any namespace prefix. TODO is this a good idea?
int colon = opcodeName.IndexOf(':');
if (colon >= 0)
opcodeName = opcodeName.Substring(colon + 1);
}
else
{
opcodeName = "";
// opcodeName = "UnknownEvent" + eventID.ToString();
}
DynamicTraceEventData eventTemplate = new DynamicTraceEventData(
callback, eventID, taskNum, taskName, taskGuid, opcode, opcodeName, Guid, Name);
events.Add(new EventInfo(eventTemplate, reader.GetAttribute("template")));
// This will be looked up in the string table in a second pass.
eventTemplate.MessageFormat = reader.GetAttribute("message");
} break;
case "template":
{
string templateName = reader.GetAttribute("tid");
Debug.Assert(templateName != null);
#if DEBUG
try
{
#endif
templates.Add(templateName, ComputeFieldInfo(reader.ReadSubtree(), maps));
#if DEBUG
}
catch (Exception e)
{
Console.WriteLine("Error: Exception during processing template {0}: {1}", templateName, e.ToString());
throw;
}
#endif
} break;
case "opcode":
// TODO use message for opcode if it is available so it is localized.
opcodes.Add(reader.GetAttribute("name"), int.Parse(reader.GetAttribute("value")));
break;
case "task":
{
TaskInfo info = new TaskInfo();
info.id = int.Parse(reader.GetAttribute("value"));
string guidString = reader.GetAttribute("eventGUID");
if (guidString != null)
info.guid = new Guid(guidString);
tasks.Add(reader.GetAttribute("name"), info);
} break;
case "valueMap":
map = new Dictionary<long, string>(); // value maps use dictionaries
goto DoMap;
case "bitMap":
map = new SortedList<long, string>(); // Bitmaps stored as sorted lists
goto DoMap;
DoMap:
string name = reader.GetAttribute("name");
var mapValues = reader.ReadSubtree();
while (mapValues.Read())
{
if (mapValues.Name == "map")
{
string keyStr = reader.GetAttribute("value");
long key;
if (keyStr.StartsWith("0x", StringComparison.OrdinalIgnoreCase))
key = long.Parse(keyStr.Substring(2), System.Globalization.NumberStyles.AllowHexSpecifier);
else
key = long.Parse(keyStr);
string value = reader.GetAttribute("message");
map[key] = value;
}
}
if (maps == null)
maps = new Dictionary<string, IDictionary<long, string>>();
maps[name] = map;
break;
case "resources":
{
if (!alreadyReadMyCulture)
{
string desiredCulture = System.Globalization.CultureInfo.CurrentCulture.Name;
if (cultureBeingRead != null && string.Compare(cultureBeingRead, desiredCulture, StringComparison.OrdinalIgnoreCase) == 0)
alreadyReadMyCulture = true;
cultureBeingRead = reader.GetAttribute("culture");
}
} break;
case "string":
if (!alreadyReadMyCulture)
strings[reader.GetAttribute("id")] = reader.GetAttribute("value");
break;
}
}
// localize strings for maps.
if (maps != null)
{
foreach (IDictionary<long, string> amap in maps.Values)
{
foreach (var keyValue in new List<KeyValuePair<long, string>>(amap))
{
Match m = Regex.Match(keyValue.Value, @"^\$\(string\.(.*)\)$");
if (m.Success)
{
string newValue;
if (strings.TryGetValue(m.Groups[1].Value, out newValue))
amap[keyValue.Key] = newValue;
}
}
}
}
// Register all the events
foreach (var eventInfo in events)
{
var event_ = eventInfo.eventTemplate;
// Set the template if there is any.
if (eventInfo.templateName != null)
{
var templateInfo = templates[eventInfo.templateName];
event_.payloadNames = templateInfo.payloadNames.ToArray();
event_.payloadFetches = templateInfo.payloadFetches.ToArray();
}
else
{
event_.payloadNames = new string[0];
event_.payloadFetches = new DynamicTraceEventData.PayloadFetch[0];
}
// before registering, localize any message format strings.
string message = event_.MessageFormat;
if (message != null)
{
// Expect $(STRINGNAME) where STRINGNAME needs to be looked up in the string table
// TODO currently we just ignore messages without a valid string name. Is that OK?
event_.MessageFormat = null;
Match m = Regex.Match(message, @"^\$\(string\.(.*)\)$");
if (m.Success)
strings.TryGetValue(m.Groups[1].Value, out event_.MessageFormat);
}
source.RegisterEventTemplate(event_);
}
// Create an event for the manifest event itself so it looks pretty in dumps.
source.RegisterEventTemplate(new DynamicManifestTraceEventData(callback, this));
}
catch (Exception e)
{
// TODO FIX NOW, log this!
Debug.Assert(false, "Exception during manifest parsing");
#if DEBUG
Console.WriteLine("Error: Exception during processing of in-log manifest for provider {0}. Symbolic information may not be complete.", Name);
#endif
error = e;
}
inited = false; // If we call it again, start over from the begining.
}
private class EventInfo
{
public EventInfo(DynamicTraceEventData eventTemplate, string templateName)
{
this.eventTemplate = eventTemplate;
this.templateName = templateName;
}
public DynamicTraceEventData eventTemplate;
public string templateName;
};
private class TaskInfo
{
public int id;
public Guid guid;
};
private class TemplateInfo
{
public List<string> payloadNames;
public List<DynamicTraceEventData.PayloadFetch> payloadFetches;
};
private TemplateInfo ComputeFieldInfo(XmlReader reader, Dictionary<string, IDictionary<long, string>> maps)
{
var ret = new TemplateInfo();
ret.payloadNames = new List<string>();
ret.payloadFetches = new List<DynamicTraceEventData.PayloadFetch>();
ushort offset = 0;
while (reader.Read())
{
if (reader.Name == "data")
{
string inType = reader.GetAttribute("inType");
Type type = GetTypeForManifestTypeName(inType);
ushort size = DynamicTraceEventData.SizeOfType(type);
// Strings are weird in that they are encoded multiple ways.
if (type == typeof(string) && inType == "win:AnsiString")
size = DynamicTraceEventData.NULL_TERMINATED | DynamicTraceEventData.IS_ANSI;
ret.payloadNames.Add(reader.GetAttribute("name"));
IDictionary<long, string> map = null;
string mapName = reader.GetAttribute("map");
if (mapName != null && maps != null)
maps.TryGetValue(mapName, out map);
ret.payloadFetches.Add(new DynamicTraceEventData.PayloadFetch(offset, size, type, map));
if (offset != ushort.MaxValue)
{
Debug.Assert(size != 0);
if (size < DynamicTraceEventData.SPECIAL_SIZES)
offset += size;
else
offset = ushort.MaxValue;
}
}
}
return ret;
}
private static Type GetTypeForManifestTypeName(string manifestTypeName)
{
switch (manifestTypeName)
{
// TODO do we want to support unsigned?
case "win:Pointer":
case "trace:SizeT":
return typeof(IntPtr);
case "win:Boolean":
return typeof(bool);
case "win:UInt8":
case "win:Int8":
return typeof(byte);
case "win:UInt16":
case "win:Int16":
case "trace:Port":
return typeof(short);
case "win:UInt32":
case "win:Int32":
case "trace:IPAddr":
case "trace:IPAddrV4":
return typeof(int);
case "trace:WmiTime":
case "win:UInt64":
case "win:Int64":
return typeof(long);
case "win:Double":
return typeof(double);
case "win:Float":
return typeof(float);
case "win:AnsiString":
case "win:UnicodeString":
return typeof(string);
case "win:GUID":
return typeof(Guid);
case "win:FILETIME":
return typeof(DateTime);
default:
throw new Exception("Unsupported type " + manifestTypeName);
}
}
#region IFastSerializable Members
void IFastSerializable.ToStream(Serializer serializer)
{
serializer.Write(majorVersion);
serializer.Write(minorVersion);
serializer.Write((int)format);
int count = 0;
if (serializedManifest != null)
count = serializedManifest.Length;
serializer.Write(count);
for (int i = 0; i < count; i++)
serializer.Write(serializedManifest[i]);
}
void IFastSerializable.FromStream(Deserializer deserializer)
{
deserializer.Read(out majorVersion);
deserializer.Read(out minorVersion);
format = (ManifestEnvelope.ManifestFormats)deserializer.ReadInt();
int count = deserializer.ReadInt();
serializedManifest = new byte[count];
for (int i = 0; i < count; i++)
serializedManifest[i] = deserializer.ReadByte();
Init();
}
private void Init()
{
try
{
reader = ManifestReader;
while (reader.Read())
{
if (reader.Name == "provider")
{
guid = new Guid(reader.GetAttribute("guid"));
name = reader.GetAttribute("name");
fileName = reader.GetAttribute("resourceFileName");
break;
}
}
if (name == null)
throw new Exception("No provider element found in manifest");
}
catch (Exception e)
{
Debug.Assert(false, "Exception during manifest parsing");
name = "";
error = e;
}
inited = true;
}
#endregion
private XmlReader reader;
private byte[] serializedManifest;
private byte majorVersion;
private byte minorVersion;
ManifestEnvelope.ManifestFormats format;
private Guid guid;
private string name;
private string fileName;
private bool inited;
private Exception error;
#endregion
}
#region internal classes
/// <summary>
/// DynamicTraceEventData is an event that knows how to take runtime information to parse event fields (and payload)
///
/// This meta-data is distilled down to a array of field names and an array of PayloadFetches which contain enough
/// information to find the field data in the payload blob. This meta-data is used in the
/// code:DynamicTraceEventData.PayloadNames and code:DynamicTraceEventData.PayloadValue methods.
/// </summary>
public class DynamicTraceEventData : TraceEvent, IFastSerializable
{
internal DynamicTraceEventData(Action<TraceEvent> action, int eventID, int task, string taskName, Guid taskGuid, int opcode, string opcodeName, Guid providerGuid, string providerName)
: base(eventID, task, taskName, taskGuid, opcode, opcodeName, providerGuid, providerName)
{
Action = action;
}
internal protected event Action<TraceEvent> Action;
protected internal override void Dispatch()
{
if (Action != null)
{
Action(this);
}
}
public override string[] PayloadNames
{
get { Debug.Assert(payloadNames != null); return payloadNames; }
}
public override object PayloadValue(int index)
{
Type type = payloadFetches[index].type;
if (type == null)
return "[CANT PARSE]";
int offset = payloadFetches[index].offset;
if (offset == ushort.MaxValue)
offset = SkipToField(index);
if ((uint)offset >= 0x10000)
return "[CANT PARSE OFFSET]";
switch (Type.GetTypeCode(type))
{
case TypeCode.String:
{
var size = payloadFetches[index].size;
var isAnsi = false;
if (size >= SPECIAL_SIZES)
{
isAnsi = ((size & IS_ANSI) != 0);
var format = (size & ~IS_ANSI);
if (format == NULL_TERMINATED)
{
if ((size & IS_ANSI) != 0)
return GetUTF8StringAt(offset);
else
return GetUnicodeStringAt(offset);
}
else if (format == DynamicTraceEventData.COUNT32_PRECEEDS)
size = (ushort)GetInt32At(offset - 4);
else if (format == DynamicTraceEventData.COUNT16_PRECEEDS)
size = (ushort)GetInt16At(offset - 2);
else
return "[CANT PARSE STRING]";
}
else if (size > 0x8000)
{
size -= 0x8000;
isAnsi = true;
}
if (isAnsi)
return GetFixedAnsiStringAt(size, offset);
else
return GetFixedUnicodeStringAt(size / 2, offset);
}
case TypeCode.Boolean:
return GetByteAt(offset) != 0;
case TypeCode.Byte:
return (byte)GetByteAt(offset);
case TypeCode.SByte:
return (SByte)GetByteAt(offset);
case TypeCode.Int16:
return GetInt16At(offset);
case TypeCode.UInt16:
return (UInt16)GetInt16At(offset);
case TypeCode.Int32:
return GetInt32At(offset);
case TypeCode.UInt32:
return (UInt32)GetInt32At(offset);
case TypeCode.Int64:
return GetInt64At(offset);
case TypeCode.UInt64:
return (UInt64)GetInt64At(offset);
case TypeCode.Single:
return GetSingleAt(offset);
case TypeCode.Double:
return GetDoubleAt(offset);
default:
if (type == typeof(IntPtr))
{
if (PointerSize == 4)
return (UInt32)GetInt32At(offset);
else
return (UInt64)GetInt64At(offset);
}
else if (type == typeof(Guid))
return GetGuidAt(offset);
else if (type == typeof(DateTime))
return DateTime.FromFileTime(GetInt64At(offset));
else if (type == typeof(byte[]))
{
int size = payloadFetches[index].size;
if (size >= DynamicTraceEventData.SPECIAL_SIZES)
{
if (payloadFetches[index].size == DynamicTraceEventData.COUNT32_PRECEEDS)
size = GetInt32At(offset - 4);
else if (payloadFetches[index].size == DynamicTraceEventData.COUNT16_PRECEEDS)
size = (ushort)GetInt16At(offset - 2);
else
return "[CANT PARSE]";
}
var ret = new byte[size];
EventData(ret, 0, offset, ret.Length);
return ret;
}
return "[UNSUPPORTED TYPE]";
}
}
public override string PayloadString(int index)
{
object value = PayloadValue(index);
var map = payloadFetches[index].map;
string ret = null;
long asLong;
if (map != null)
{
asLong = (long)((IConvertible)value).ToInt64(null);
if (map is SortedList<long, string>)
{
StringBuilder sb = new StringBuilder();
// It is a bitmap, compute the bits from the bitmap.
foreach (var keyValue in map)
{
if (asLong == 0)
break;
if ((keyValue.Key & asLong) != 0)
{
if (sb.Length != 0)
sb.Append('|');
sb.Append(keyValue.Value);
asLong &= ~keyValue.Key;
}
}
if (asLong != 0)
{
if (sb.Length != 0)
sb.Append('|');
sb.Append(asLong);
}
else if (sb.Length == 0)
sb.Append('0');
ret = sb.ToString();
}
else
{
// It is a value map, just look up the value
map.TryGetValue(asLong, out ret);
}
}
if (ret != null)
return ret;
// Print large long values as hex by default.
if (value is long)
{
asLong = (long)value;
goto PrintLongAsHex;
}
else if (value is ulong)
{
asLong = (long)(ulong)value;
goto PrintLongAsHex;
}
var asByteArray = value as byte[];
if (asByteArray != null)
{
StringBuilder sb = new StringBuilder();
var limit = Math.Min(asByteArray.Length, 16);
for (int i = 0; i < limit; i++)
{
var b = asByteArray[i];
sb.Append(HexDigit((b / 16)));
sb.Append(HexDigit((b % 16)));
}
if (limit < asByteArray.Length)
sb.Append("...");
return sb.ToString();
}
return value.ToString();
PrintLongAsHex:
if ((int)asLong != asLong)
return "0x" + asLong.ToString("x");
return asLong.ToString();
}
private static char HexDigit(int digit)
{
if (digit < 10)
return (char)('0' + digit);
else
return (char)('A' - 10 + digit);
}
public override string FormattedMessage
{
get
{
if (MessageFormat == null)
return null;
// TODO is this error handling OK?
// Replace all %N with the string value for that parameter.
return Regex.Replace(MessageFormat, @"%(\d+)", delegate(Match m)
{
int index = int.Parse(m.Groups[1].Value) - 1;
if ((uint)index < (uint)PayloadNames.Length)
return PayloadString(index);
else
return "<<Out Of Range>>";
});
}
}
#region private
private int SkipToField(int index)
{
// Find the first field that has a fixed offset.
int offset = 0;
int cur = index;
while (0 < cur)
{
--cur;
offset = payloadFetches[cur].offset;
if (offset != ushort.MaxValue)
break;
}
// TODO it probably does pay to remember the offsets in a particular instance, since otherwise the
// algorithm is N*N
while (cur < index)
{
ushort size = payloadFetches[cur].size;
if (size >= SPECIAL_SIZES)
{
if (size == NULL_TERMINATED)
offset = SkipUnicodeString(offset);
else if (size == (NULL_TERMINATED | IS_ANSI))
offset = SkipUTF8String(offset);
else if (size == POINTER_SIZE)
offset += PointerSize;
else if ((size & ~IS_ANSI) == COUNT32_PRECEEDS)
offset += GetInt32At(offset - 4);
else if ((size & ~IS_ANSI) == COUNT16_PRECEEDS)
offset += (ushort)GetInt16At(offset - 2);
else
return -1;
}
else
offset += size;
cur++;
}
return offset;
}
internal static ushort SizeOfType(Type type)
{
switch (Type.GetTypeCode(type))
{
case TypeCode.String:
return NULL_TERMINATED;
case TypeCode.SByte:
case TypeCode.Byte:
return 1;
case TypeCode.UInt16:
case TypeCode.Int16:
return 2;
case TypeCode.UInt32:
case TypeCode.Int32:
case TypeCode.Boolean: // We follow windows conventions and use 4 bytes for bool.
case TypeCode.Single:
return 4;
case TypeCode.UInt64:
case TypeCode.Int64:
case TypeCode.Double:
case TypeCode.DateTime:
return 8;
default:
if (type == typeof(Guid))
return 16;
if (type == typeof(IntPtr))
return POINTER_SIZE;
throw new Exception("Unsupported type " + type.Name); // TODO
}
}
internal const ushort IS_ANSI = 1; // A bit mask that represents the string is ASCII
// NULL_TERMINATD | IS_ANSI == MaxValue
internal const ushort NULL_TERMINATED = ushort.MaxValue - 1;
// COUNT32_PRECEEDS | IS_ANSI == MaxValue - 2
internal const ushort COUNT32_PRECEEDS = ushort.MaxValue - 3; // Count is a 32 bit int directly before
// COUNT16_PRECEEDS | IS_ANSI == MaxValue -4
internal const ushort COUNT16_PRECEEDS = ushort.MaxValue - 5; // Count is a 16 bit uint directly before
internal const ushort POINTER_SIZE = ushort.MaxValue - 14; // It is the pointer size of the target machine.
internal const ushort UNKNOWN_SIZE = ushort.MaxValue - 15; // Generic unknown.
internal const ushort SPECIAL_SIZES = ushort.MaxValue - 15; // Some room for growth.
internal struct PayloadFetch
{
public PayloadFetch(ushort offset, ushort size, Type type, IDictionary<long, string> map = null)
{
this.offset = offset;
this.size = size;
this.type = type;
this.map = map;
}
public ushort offset; // offset == MaxValue means variable size.
// TODO come up with a real encoding for variable sized things
public ushort size; // See special encodeings above (also size > 0x8000 means fixed lenght ANSI).
public IDictionary<long, string> map;
public Type type;
};
void IFastSerializable.ToStream(Serializer serializer)
{
serializer.Write((int)eventID);
serializer.Write((int)task);
serializer.Write(taskName);
serializer.Write(taskGuid);
serializer.Write((int)opcode);
serializer.Write(opcodeName);
serializer.Write(providerGuid);
serializer.Write(providerName);
serializer.Write(MessageFormat);
serializer.Write(lookupAsWPP);
serializer.Write(payloadNames.Length);
foreach (var payloadName in payloadNames)
serializer.Write(payloadName);
serializer.Write(payloadFetches.Length);
foreach (var payloadFetch in payloadFetches)
{
serializer.Write((short)payloadFetch.offset);
serializer.Write((short)payloadFetch.size);
if (payloadFetch.type == null)
serializer.Write((string)null);
else
serializer.Write(payloadFetch.type.FullName);
serializer.Write((IFastSerializable)null); // This is for the map (eventually)
}
}
void IFastSerializable.FromStream(Deserializer deserializer)
{
eventID = (TraceEventID)deserializer.ReadInt();
task = (TraceEventTask)deserializer.ReadInt();
deserializer.Read(out taskName);
deserializer.Read(out taskGuid);
opcode = (TraceEventOpcode)deserializer.ReadInt();
deserializer.Read(out opcodeName);
deserializer.Read(out providerGuid);
deserializer.Read(out providerName);
deserializer.Read(out MessageFormat);
deserializer.Read(out lookupAsWPP);
int count;
deserializer.Read(out count);
payloadNames = new string[count];
for (int i = 0; i < count; i++)
deserializer.Read(out payloadNames[i]);
deserializer.Read(out count);
payloadFetches = new PayloadFetch[count];
for (int i = 0; i < count; i++)
{
payloadFetches[i].offset = (ushort)deserializer.ReadInt16();
payloadFetches[i].size = (ushort)deserializer.ReadInt16();
var typeName = deserializer.ReadString();
if (typeName != null)
payloadFetches[i].type = Type.GetType(typeName);
IFastSerializable dummy;
deserializer.Read(out dummy); // For map when we use it.
}
}
// Fields
internal PayloadFetch[] payloadFetches;
internal string MessageFormat; // This is in ETW conventions (%N)
#endregion
}
/// <summary>
/// This class is only used to pretty-print the manifest event itself. It is pretty special purpose
/// </summary>
class DynamicManifestTraceEventData : DynamicTraceEventData
{
internal DynamicManifestTraceEventData(Action<TraceEvent> action, ProviderManifest manifest)
: base(action, 0xFFFE, 0, "ManifestData", Guid.Empty, 0, null, manifest.Guid, manifest.Name)
{
this.manifest = manifest;
payloadNames = new string[] { "Format", "MajorVersion", "MinorVersion", "Magic", "TotalChunks", "ChunkNumber" };
payloadFetches = new PayloadFetch[] {
new PayloadFetch(0, 1, typeof(byte)),
new PayloadFetch(1, 1, typeof(byte)),
new PayloadFetch(2, 1, typeof(byte)),
new PayloadFetch(3, 1, typeof(byte)),
new PayloadFetch(4, 2, typeof(ushort)),
new PayloadFetch(6, 2, typeof(ushort)),
};
Action += action;
}
public override StringBuilder ToXml(StringBuilder sb)
{
int totalChunks = GetInt16At(4);
int chunkNumber = GetInt16At(6);
if (chunkNumber + 1 == totalChunks)
{
StringBuilder baseSb = new StringBuilder();
base.ToXml(baseSb);
sb.AppendLine(XmlUtilities.OpenXmlElement(baseSb.ToString()));
sb.Append(manifest.Manifest);
sb.Append("</Event>");
return sb;
}
else
return base.ToXml(sb);
}
#region private
ProviderManifest manifest;
#endregion
}
/// <summary>
/// DynamicTraceEventParserState represents the state of a DynamicTraceEventParser that needs to be
/// serialied to a log file. It does NOT include information about what events are chosen but DOES contain
/// any other necessary information that came from the ETL data file.
/// </summary>
class DynamicTraceEventParserState : IFastSerializable
{
public DynamicTraceEventParserState() { providers = new Dictionary<Guid, ProviderManifest>(); }
internal Dictionary<Guid, ProviderManifest> providers;
#region IFastSerializable Members
void IFastSerializable.ToStream(Serializer serializer)
{
serializer.Write(providers.Count);
foreach (ProviderManifest provider in providers.Values)
serializer.Write(provider);
}
void IFastSerializable.FromStream(Deserializer deserializer)
{
int count;
deserializer.Read(out count);
for (int i = 0; i < count; i++)
{
ProviderManifest provider;
deserializer.Read(out provider);
providers.Add(provider.Guid, provider);
}
}
#endregion
}
}
#endregion
| brian-dot-net/writeasync | projects/TraceSample/source/TraceEvent/DynamicTraceEventParser.cs | C# | unlicense | 49,945 |
<link rel="stylesheet" type="text/css" href="<?php echo base_url(); ?>assets/css/pages/datatables.css">
<link href="<?php echo base_url(); ?>assets/vendors/bootstrapvalidator/css/bootstrapValidator.min.css" rel="stylesheet">
<script type="text/javascript" src="<?php echo base_url(); ?>assets/vendors/bootstrapvalidator/js/bootstrapValidator.min.js"></script>
<style>
@media(max-width: 1024px)
{
.radio-inline + .radio-inline, .checkbox-inline + .checkbox-inline {
margin-top: 0;
margin-left: 8px;
}
}
</style>
<div class="row">
<div class="col-md-12">
<!-- First Basic Table strats here-->
<div class="panel">
<?php if ($status=='2') { ?>
<div class="panel-heading" style="background-color: #2980b9;">
<h3 class="panel-title">
<i class="ti-layout-cta-left"></i> Disetujui
</h3>
</div>
<?php }else if ($status=='1'){ ?>
<div class="panel-heading" style="background-color: #f1c40f;">
<h3 class="panel-title">
<i class="ti-layout-cta-left"></i> Proses
</h3>
</div>
<?php }else if ($status=='3'){ ?>
<div class="panel-heading" style="background-color: #e74c3c;">
<h3 class="panel-title">
<i class="ti-layout-cta-left"></i> Tidak Disetujui
</h3>
</div>
<?php } ?>
<div class="panel-body">
<div class="col-lg-12">
<?php if ($status=='2') { ?>
<p>Anda dapat mencetak rekomendasi kecamatan</p>
<?php }else if ($status=='1') { ?>
<p>Data Anda belum diproses</p>
<?php }else if ($status=='3') { ?>
<p>Data Anda tidak disetujui oleh kecamatan, silahkan periksa kembali data anda. dan lakukan update.</p>
<?php } ?>
</div>
</div>
</div>
</div>
</div>
<form method="post" class="form-horizontal p-10" role="form">
<div class="row">
<div class="col-lg-12">
<!-- First Basic Table strats here-->
<div class="panel">
<div class="panel-heading">
<h3 class="panel-title">
<i class="ti-layout-cta-left"></i> Data Pemohon
</h3>
</div>
<div class="panel-body">
<div class="form-group p-10">
<label class="control-label col-md-3" for="text">NIK Pemohon</label>
<div class="col-md-9">
<input type="text" class="form-control" name="nik_pemohon" id="nik_pemohon" placeholder="NIK Pemohon" value="<?php echo isset($nik_pemohon)?$nik_pemohon:''; ?>" readonly>
</div>
</div>
<div class="form-group p-10">
<label class="control-label col-md-3" for="text">Nama Pemohon</label>
<div class="col-md-9">
<input type="text" class="form-control" name="nama_pemohon" id="nama_pemohon" placeholder="Nama Pemohon" value="<?php echo isset($nama_pemohon)?$nama_pemohon:''; ?>" readonly>
</div>
</div>
<div class="form-group p-10">
<label class="control-label col-md-3" for="text">Tempat Lahir</label>
<div class="col-md-9">
<input type="text" class="form-control" name="tempat_lahir" id="tempat_lahir" placeholder="Tempat Lahir" value="<?php echo isset($tempat_lahir)?$tempat_lahir:''; ?>" readonly>
</div>
</div>
<div class="form-group p-10">
<label class="control-label col-md-3" for="text">Tanggal Lahir</label>
<div class="col-md-9">
<input type="text" class="form-control tanggal" name="tgl_lahir" id="tgl_lahir" placeholder="Tanggal Lahir" data-date-format="dd-mm-yyyy" value="<?php echo isset($tgl_lahir)?$tgl_lahir:''; ?>" readonly>
</div>
</div>
<div class="form-group p-10">
<label class="control-label col-md-3" for="text">Pekerjaan</label>
<div class="col-md-9">
<input type="text" class="form-control" name="pekerjaan" id="pekerjaan" placeholder="Pekerjaan" value="<?php echo isset($pekerjaan)?$pekerjaan:''; ?>" readonly>
</div>
</div>
<div class="form-group p-10">
<label class="control-label col-md-3" for="text">No. Telp</label>
<div class="col-md-9">
<input type="text" class="form-control" name="no_telp" id="no_telp" placeholder="No. Telp" value="<?php echo isset($no_telp)?$no_telp:''; ?>" readonly>
</div>
</div>
<div class="form-group p-10">
<label class="control-label col-md-3" for="text">Negara</label>
<div class="col-md-9">
<input type="text" class="form-control" name="negara_pemohon" id="negara_pemohon" placeholder="Negara" value="<?php echo isset($negara_pemohon)?$negara_pemohon:''; ?>" readonly>
</div>
</div>
<div class="form-group p-10">
<label class="control-label col-md-3" for="text">Alamat</label>
<div class="col-md-9">
<textarea rows="3" class="form-control resize_vertical" name="alamat" id="alamat" placeholder="Alamat" readonly><?php echo isset($alamat)?$alamat:''; ?></textarea>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-lg-12">
<!-- First Basic Table strats here-->
<div class="panel">
<div class="panel-heading">
<h3 class="panel-title">
<i class="ti-layout-cta-left"></i> Data Perusahaan
</h3>
</div>
<div class="panel-body">
<div class="form-group p-10">
<label class="control-label col-md-3" for="text">Nama Usaha</label>
<div class="col-md-9">
<input type="text" class="form-control" name="nama_usaha" id="nama_usaha" placeholder="Nama Usaha" value="<?php echo isset($nama_usaha)?$nama_usaha:''; ?>" readonly >
</div>
</div>
<div class="form-group p-10">
<label class="control-label col-md-3" for="text">Jenis Usaha</label>
<div class="col-md-9">
<input type="text" class="form-control" name="jenis_usaha" id="jenis_usaha" placeholder="Jenis Usaha" value="<?php echo isset($jenis_usaha)?$jenis_usaha:''; ?>" readonly >
</div>
</div>
<div class="form-group p-10">
<label class="control-label col-md-3" for="text">Ukuruan Luas</label>
<div class="col-md-9">
<input type="text" class="form-control" name="ukuran_luas_usaha" id="ukuran_luas_usaha" placeholder="Ukuran Usaha" value="<?php echo isset($ukuran_luas_usaha)?$ukuran_luas_usaha:''; ?>" readonly >
</div>
</div>
<div class="form-group p-10">
<label class="control-label col-md-3" for="text">Lokasi</label>
<div class="col-md-9">
<input type="text" class="form-control" name="lokasi_usaha" id="lokasi_usaha" placeholder="Lokasi Usaha" value="<?php echo isset($lokasi_usaha)?$lokasi_usaha:''; ?>" readonly >
</div>
</div>
<div class="form-group p-10">
<label class="control-label col-md-3" for="text">Status Bangunan</label>
<div class="col-md-9">
<input type="text" class="form-control" name="status_bangunan_tempat_usaha" id="status_bangunan_tempat_usaha" placeholder="Status Bangunan Tempat Usaha" value="<?php echo isset($status_bangunan_tempat_usaha)?$status_bangunan_tempat_usaha:''; ?>" readonly >
</div>
</div>
<div class="form-group p-10">
<label class="control-label col-md-3" for="text">NPWPD</label>
<div class="col-md-9">
<input type="text" class="form-control" name="npwpd" id="npwpd" placeholder="NPWPD" value="<?php echo isset($npwpd)?$npwpd:''; ?>" readonly >
</div>
</div>
<div class="form-group p-10">
<label class="control-label col-md-3" for="text">Klasifikasi Usaha</label>
<div class="col-md-9">
<input type="text" class="form-control" name="klasifikasi_usaha" id="klasifikasi_usaha" placeholder="Klasifikasi Usaha" value="<?php echo isset($klasifikasi_usaha)?$klasifikasi_usaha:''; ?>" readonly >
</div>
</div>
<div class="form-group p-10">
<label class="control-label col-md-3" for="text">Retribusi Pertahun Fiskal</label>
<div class="col-md-9">
<input type="text" class="form-control" name="retribusi_perthn_f" id="retribusi_perthn_f" placeholder="Retribusi Pertahun Fiskal" value="<?php echo isset($retribusi_perthn_f)?$retribusi_perthn_f:''; ?>" >
</div>
</div>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-lg-12">
<!-- First Basic Table strats here-->
<div class="panel">
<div class="panel-heading">
<h3 class="panel-title">
<i class="ti-layout-cta-left"></i> Jenis Pendaftaran
</h3>
</div>
<div class="panel-body">
<div class="form-group p-10">
<label class="control-label col-md-8" for="text"> </label>
<div class="col-md-4">
<div class="col-md-6">
<b>Baru</b>
</div>
<div class="col-md-6">
<b>Ulang</b>
</div>
</div>
</div>
<div class="form-group p-10">
<label class="col-md-8" for="text">1. Jenis Pendaftaran </label>
<div class="col-md-4">
<?php if ($jenis_permohonan=='baru') { ?>
<div class="col-md-6">
<input type="radio" name="jenis_permohonan" class="radio-blue" value="baru" checked="true">
</div>
<div class="col-md-6">
</div>
<?php }else{ ?>
<div class="col-md-6">
</div>
<div class="col-md-6">
<input type="radio" name="jenis_permohonan" class="radio-blue" value="lama" checked="true">
</div>
<?php } ?>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-lg-12">
<!-- First Basic Table strats here-->
<div class="panel">
<div class="panel-heading">
<h3 class="panel-title">
<i class="ti-layout-cta-left"></i> Syarat Umum
</h3>
</div>
<div class="panel-body">
<div class="form-group p-10">
<label class="control-label col-md-8" for="text"> </label>
<div class="col-md-4">
<div class="col-md-6">
<b>Ada</b>
</div>
<div class="col-md-6">
<b>Tidak Ada</b>
</div>
</div>
</div>
<div class="form-group p-10">
<label class="col-md-8" for="text">1. Fotokopi KTP ( 1 (satu) lembar) </label>
<div class="col-md-4">
<?php if ($ktp=='ada') { ?>
<div class="col-md-6">
<input type="radio" name="ktp" class="radio-blue" value="ada" checked="true">
</div>
<div class="col-md-6">
</div>
<?php }else{ ?>
<div class="col-md-6">
</div>
<div class="col-md-6">
<input type="radio" name="ktp" class="radio-blue" value="tidak ada" checked="true">
</div>
<?php } ?>
</div>
</div>
<div class="form-group p-10">
<label class="col-md-8" for="text">2. Fotocopy Tanda Bukti Hak Atas Tanah </label>
<div class="col-md-4">
<?php if ($fc_hak_tanah=='ada') { ?>
<div class="col-md-6">
<input type="radio" name="fc_hak_tanah" class="radio-blue" value="ada" checked="true">
</div>
<div class="col-md-6">
</div>
<?php }else{ ?>
<div class="col-md-6">
</div>
<div class="col-md-6">
<input type="radio" name="fc_hak_tanah" class="radio-blue" value="tidak ada" checked="true">
</div>
<?php } ?>
</div>
</div>
<div class="form-group p-10">
<label class="col-md-8" for="text">3. Surat Pengantar dari kelurahan/desa </label>
<div class="col-md-4">
<?php if ($sp_desa=='ada') { ?>
<div class="col-md-6">
<input type="radio" name="sp_desa" class="radio-blue" value="ada" checked="true">
</div>
<div class="col-md-6">
</div>
<?php }else{ ?>
<div class="col-md-6">
</div>
<div class="col-md-6">
<input type="radio" name="sp_desa" class="radio-blue" value="tidak ada" checked="true">
</div>
<?php } ?>
</div>
</div>
<div class="form-group p-10">
<label class="col-md-8" for="text">4. Surat Permohonan bermaterai 6000 </label>
<div class="col-md-4">
<?php if ($sp_materai=='ada') { ?>
<div class="col-md-6">
<input type="radio" name="sp_materai" class="radio-blue" value="ada" checked="true">
</div>
<div class="col-md-6">
</div>
<?php }else{ ?>
<div class="col-md-6">
</div>
<div class="col-md-6">
<input type="radio" name="sp_materai" class="radio-blue" value="tidak ada" checked="true">
</div>
<?php } ?>
</div>
</div>
<div class="form-group p-10">
<label class="col-md-8" for="text">5. Denah Lokasi </label>
<div class="col-md-4">
<?php if ($denah_lokasi=='ada') { ?>
<div class="col-md-6">
<input type="radio" name="denah_lokasi" class="radio-blue" value="ada" checked="true">
</div>
<div class="col-md-6">
</div>
<?php }else{ ?>
<div class="col-md-6">
</div>
<div class="col-md-6">
<input type="radio" name="denah_lokasi" class="radio-blue" value="tidak ada" checked="true">
</div>
<?php } ?>
</div>
</div>
<div class="form-group p-10">
<label class="col-md-8" for="text">6. Pas Foto Berwarna 3 x 4 ( 3 (tiga) lembar) </label>
<div class="col-md-4">
<?php if ($foto=='ada') { ?>
<div class="col-md-6">
<input type="radio" name="foto" class="radio-blue" value="ada" checked="true">
</div>
<div class="col-md-6">
</div>
<?php }else{ ?>
<div class="col-md-6">
</div>
<div class="col-md-6">
<input type="radio" name="foto" class="radio-blue" value="tidak ada" checked="true">
</div>
<?php } ?>
</div>
</div>
<div class="form-group p-10">
<label class="col-md-8" for="text">7. Fotocopy PBB </label>
<div class="col-md-4">
<?php if ($fc_pbb=='ada') { ?>
<div class="col-md-6">
<input type="radio" name="fc_pbb" class="radio-blue" value="ada" checked="true">
</div>
<div class="col-md-6">
</div>
<?php }else{ ?>
<div class="col-md-6">
</div>
<div class="col-md-6">
<input type="radio" name="fc_pbb" class="radio-blue" value="tidak ada" checked="true">
</div>
<?php } ?>
</div>
</div>
<div class="form-group p-10">
<label class="col-md-8" for="text">8. Rekomendasi dari UPTD Puskesmas setempat </label>
<div class="col-md-4">
<?php if ($rekom_uptd=='ada') { ?>
<div class="col-md-6">
<input type="radio" name="rekom_uptd" class="radio-blue" value="ada" checked="true">
</div>
<div class="col-md-6">
</div>
<?php }else{ ?>
<div class="col-md-6">
</div>
<div class="col-md-6">
<input type="radio" name="rekom_uptd" class="radio-blue" value="tidak ada" checked="true">
</div>
<?php } ?>
</div>
</div>
<div class="form-group p-10">
<label class="col-md-8" for="text">9. Gambar Bangunan</label>
<div class="col-md-4">
<?php if ($gambar_bangunan=='ada') { ?>
<div class="col-md-6">
<input type="radio" name="gambar_bangunan" class="radio-blue" value="ada" checked="true">
</div>
<div class="col-md-6">
</div>
<?php }else{ ?>
<div class="col-md-6">
</div>
<div class="col-md-6">
<input type="radio" name="gambar_bangunan" class="radio-blue" value="tidak ada" checked="true">
</div>
<?php } ?>
</div>
</div>
<div class="form-group p-10">
<label class="col-md-8" for="text">10. Instalasi air, listrik dan telepon</label>
<div class="col-md-4">
<?php if ($instalasi_air=='ada') { ?>
<div class="col-md-6">
<input type="radio" name="instalasi_air" class="radio-blue" value="ada" checked="true">
</div>
<div class="col-md-6">
</div>
<?php }else{ ?>
<div class="col-md-6">
</div>
<div class="col-md-6">
<input type="radio" name="instalasi_air" class="radio-blue" value="tidak ada" checked="true">
</div>
<?php } ?>
</div>
</div>
<div class="form-group p-10">
<label class="col-md-8" for="text">11. Rekomendasi Lurah/Kepala Desa setempat</label>
<div class="col-md-4">
<?php if ($rekom_desa=='ada') { ?>
<div class="col-md-6">
<input type="radio" name="rekom_desa" class="radio-blue" value="ada" checked="true">
</div>
<div class="col-md-6">
</div>
<?php }else{ ?>
<div class="col-md-6">
</div>
<div class="col-md-6">
<input type="radio" name="rekom_desa" class="radio-blue" value="tidak ada" checked="true">
</div>
<?php } ?>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-lg-12">
<!-- First Basic Table strats here-->
<div class="panel">
<div class="panel-heading">
<h3 class="panel-title">
<i class="ti-layout-cta-left"></i> Syarat Tambahan Pendaftaran Ulang
</h3>
</div>
<div class="panel-body">
<div class="form-group p-10">
<label class="control-label col-md-8" for="text"> </label>
<div class="col-md-4">
<div class="col-md-6">
<b>Ada</b>
</div>
<div class="col-md-6">
<b>Tidak Ada</b>
</div>
</div>
</div>
<div class="form-group p-10">
<label class="col-md-8" for="text">1. SIUP Asli </label>
<div class="col-md-4">
<?php if ($siup_asli=='ada') { ?>
<div class="col-md-6">
<input type="radio" name="siup_asli" class="radio-blue" value="ada" checked="true">
</div>
<div class="col-md-6">
</div>
<?php }else{ ?>
<div class="col-md-6">
</div>
<div class="col-md-6">
<input type="radio" name="siup_asli" class="radio-blue" value="tidak ada" checked="true">
</div>
<?php } ?>
</div>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-lg-12">
<!-- First Basic Table strats here-->
<div class="panel">
<div class="panel-heading">
<h3 class="panel-title">
<i class="ti-layout-cta-left"></i> Verifikasi dan Data Kecamatan
</h3>
</div>
<div class="panel-body">
<div class="form-group p-10">
<label class="control-label col-md-3" for="text">Tanggal Register</label>
<div class="col-md-9">
<input type="text" class="form-control tanggal" name="tgl_register" id="tgl_register" placeholder="Tanggal Register" data-date-format="dd-mm-yyyy" value="<?php echo isset($tgl_register)?$tgl_register:''; ?>" readonly>
</div>
</div>
<div class="form-group p-10">
<label class="control-label col-md-3" for="text">No. Registrasi</label>
<div class="col-md-9">
<input type="text" class="form-control" name="no_register" id="no_register" placeholder="No. Registrasi" value="<?php echo isset($no_register)?$no_register:''; ?>" <?php if ($action=='update') { echo 'readonly'; } ?>>
</div>
</div>
<div class="form-group p-10">
<label class="control-label col-md-3" for="text">Nama Petugas Verifikasi</label>
<div class="col-md-9">
<input type="text" class="form-control" name="nama_petugas_verifikasi" id="nama_petugas_verifikasi" placeholder="Nama Petugas Verifikasi" value="<?php echo isset($nama_petugas_verifikasi)?$nama_petugas_verifikasi:''; ?>" readonly>
</div>
</div>
<div class="form-group p-10">
<label class="control-label col-md-3" for="text">Tanggal Verifikasi</label>
<div class="col-md-9">
<input type="text" class="form-control tanggal" name="tgl_verifikasi" id="tgl_verifikasi" placeholder="Tanggal Verifikasi" data-date-format="dd-mm-yyyy" value="<?php echo isset($tgl_verifikasi)?$tgl_verifikasi:''; ?>" readonly>
</div>
</div>
<div class="form-group p-10">
<label class="control-label col-md-3" for="text">Nama Camat</label>
<div class="col-md-9">
<input type="text" class="form-control" name="nama_camat" id="nama_camat" placeholder="Nama Camat" value="<?php echo isset($nama_camat)?$nama_camat:''; ?>" readonly>
</div>
</div>
<div class="form-group p-10">
<label class="control-label col-md-3" for="text">NIP Camat</label>
<div class="col-md-9">
<input type="text" class="form-control" name="nip_camat" id="nip_camat" placeholder="NIP Camat" value="<?php echo isset($nip_camat)?$nip_camat:''; ?>" readonly>
</div>
</div>
</div>
</div>
</div>
</div>
</form>
<div class="col-md-6">
</div>
<?php if ($status=='2') { ?>
<div class="col-md-2">
<a href='#' class="btn btn-lg btn-primary" onclick="printsurat('<?php echo $id ?>')" ><i class='fa fa-print'></i> Izin</a>
</div>
<?php }else{ ?>
<div class="col-md-2">
</div>
<?php } ?>
<div class="col-md-2">
<a href='#' class="btn btn-lg btn-primary" onclick="formulir('<?php echo $id ?>')" ><i class='fa fa-print'></i> Formulir</a>
</div>
<div class="col-md-2">
<a href="<?php echo site_url($this->controller) ?>"> <button style="border-radius: 8;" id="reset" type="button" class="btn btn-lg btn-danger">Kembali</button></a>
</div>
<?php
$this->load->view($this->controller.'_status_view_js');
?> | NizarHafizulllah/simpatenksb | application/modules/kec_siu/views/kec_siu_status_view.php | PHP | unlicense | 29,766 |
package br.com.tosin.ssd.utils;
/**
* Created by roger on 11/03/17.
*/
public class CONSTANTS_DIRECTIONS {
public static final String NORTH = "N";
public static final String SOUTH = "S";
public static final String WEST = "W";
public static final String EAST = "E";
public static final String NORTHWEST = "NW";
public static final String NORTHEAST = "NE";
public static final String SOUTH_WEST = "SW";
public static final String SOUTHEAST = "SE";
}
| TosinRoger/SmartSystemsDesign | src/br/com/tosin/ssd/utils/CONSTANTS_DIRECTIONS.java | Java | unlicense | 526 |
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Reflection;
using System.Windows.Forms;
using IFSExplorer.Properties;
namespace IFSExplorer
{
public partial class MainForm : Form
{
private static readonly Dictionary<int, int> InitialIndexGuesses =
new Dictionary<int, int> {
{257040, 50},
{257400, 31},
{282240, 58},
{293760, 50},
{310800, 38},
{440640, 48},
{674240, 23},
{756576, 20},
{820800, 63},
{836752, 11},
{872640, 42},
{906096, 10}
};
class SaveFilter
{
internal readonly string Extensions;
private readonly string _name;
internal readonly ImageFormat ImageFormat;
internal SaveFilter(string extensions, string name, ImageFormat imageFormat)
{
Extensions = extensions;
_name = name;
ImageFormat = imageFormat;
}
public static string ToString(SaveFilter saveFilter)
{
return string.Format("{0} ({1})|{1}", saveFilter._name, saveFilter.Extensions);
}
}
private static readonly List<SaveFilter> SaveFilters = new List<SaveFilter> {
new SaveFilter("*.bmp;*.dib", "24-bit Bitmap", ImageFormat.Bmp),
new SaveFilter("*.gif", "GIF", ImageFormat.Gif),
new SaveFilter("*.jpg;*.jpeg;*.jfif", "JPEG", ImageFormat.Jpeg),
new SaveFilter("*.png", "PNG", ImageFormat.Png),
new SaveFilter("*.tif;*.tiff", "TIFF", ImageFormat.Tiff),
};
private readonly Dictionary<int, int> _indexGuesses = new Dictionary<int, int>();
private string _indexGuessesFilename;
private Stream _currentStream;
private FileIndex _currentFileIndex;
private DecodedRaw _currentRaw;
public MainForm()
{
InitializeComponent();
saveFileDialog.Filter = string.Join("|", SaveFilters.ConvertAll(SaveFilter.ToString).ToArray());
}
private void MainForm_Load(object sender, EventArgs e)
{
var path = Assembly.GetEntryAssembly().Location;
var directoryName = Path.GetDirectoryName(path);
if (directoryName == null) {
FillInitialGuesses();
return;
}
_indexGuessesFilename = Path.Combine(directoryName, "index_guesses.txt");
if (!File.Exists(_indexGuessesFilename)) {
FillInitialGuesses();
return;
}
var lines = File.ReadAllLines(_indexGuessesFilename);
foreach (var line in lines) {
var split = line.Replace(" ", "").Split(new[] {","}, StringSplitOptions.RemoveEmptyEntries);
if (split.Length != 2) {
continue;
}
int size, index;
if (int.TryParse(split[0], out size) && int.TryParse(split[1], out index)) {
_indexGuesses.Add(size, index);
}
}
}
private void FillInitialGuesses()
{
foreach (var initialIndexGuess in InitialIndexGuesses) {
_indexGuesses.Add(initialIndexGuess.Key, initialIndexGuess.Value);
}
}
private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
{
using (var fileStream = File.OpenWrite(_indexGuessesFilename))
using (var streamWriter = new StreamWriter(fileStream)) {
foreach (var indexGuess in _indexGuesses) {
streamWriter.WriteLine("{0}, {1}", indexGuess.Key, indexGuess.Value);
}
}
}
private void browseToolStripMenuItem_Click(object sender, EventArgs e)
{
var dialogResult = openFileDialog.ShowDialog();
if (dialogResult != DialogResult.OK) {
return;
}
listboxImages.Items.Clear();
if (_currentStream != null) {
_currentStream.Close();
}
_currentStream = openFileDialog.OpenFile();
var mappings = IFSUtils.ParseIFS(_currentStream);
foreach (var mapping in mappings) {
listboxImages.Items.Add(new ImageItem(mapping));
}
}
private void saveSelectedImageToolStripMenuItem_Click(object sender, EventArgs e)
{
if (_currentRaw == null) {
MessageBox.Show(
Resources
.MainForm_saveSelectedImageToolStripMenuItem_Click_Open_an_IFS_file_and_select_a_valid_image_first_,
Resources.MainForm_Bemani_IFS_Explorer,
MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
var dialogResult = saveFileDialog.ShowDialog();
if (dialogResult != DialogResult.OK) {
return;
}
using (var bitmap = DrawToBitmap()) {
var saveFilter = SaveFilters[saveFileDialog.FilterIndex - 1];
var fileName = saveFileDialog.FileName;
if (fileName.IndexOf('.') == -1) {
fileName += string.Format(".{0}", saveFilter.Extensions.Split(';')[0]);
}
bitmap.Save(fileName, saveFilter.ImageFormat);
}
}
private void exitToolStripMenuItem_Click(object sender, EventArgs e)
{
Close();
}
private void aboutBemaniIFSExplorerToolStripMenuItem_Click(object sender, EventArgs e)
{
new AboutBox().ShowDialog();
}
private void listboxImages_SelectedIndexChanged(object sender, EventArgs e)
{
updownIndexSelect.Minimum = 0;
updownIndexSelect.Value = 0;
updownIndexSelect.Maximum = 0;
updownIndexSelect.Enabled = true;
DrawFileIndex();
}
private void updownIndexSelect_ValueChanged(object sender, EventArgs e)
{
DrawFileIndex();
}
private void DrawFileIndex()
{
var imageItem = listboxImages.SelectedItem as ImageItem;
if (imageItem == null) {
return;
}
var fileIndex = imageItem.FileIndex;
if (_currentFileIndex != fileIndex) {
_currentFileIndex = fileIndex;
var rawBytes = IFSUtils.DecompressLSZZ(fileIndex.Read());
try {
_currentRaw = IFSUtils.DecodeRaw(rawBytes);
} catch (Exception e) {
_currentRaw = null;
labelStatus.Text = string.Format("Couldn't decode raw #{0}: {1}", fileIndex.EntryNumber, e);
return;
}
}
if (_currentRaw == null) {
return;
}
if (updownIndexSelect.Value == 0) {
updownIndexSelect.Maximum = _currentRaw.IndexSize - 1;
int indexGuess;
if (!_indexGuesses.TryGetValue(_currentRaw.RawLength, out indexGuess)) {
indexGuess = (int) (((decimal) _currentRaw.IndexSize)/2);
}
updownIndexSelect.Value = indexGuess;
}
var index = (int) updownIndexSelect.Value;
_indexGuesses[_currentRaw.RawLength] = index;
var size = _currentRaw.GetSize(index);
labelStatus.Text = string.Format("#{0}: {1} bytes decompresses to {2} bytes (index {3} = {4}x{5})",
fileIndex.EntryNumber,
fileIndex.Size, _currentRaw.RawLength, index, size.X, size.Y);
var oldImage = pictureboxPreview.Image;
pictureboxPreview.Image = DrawToBitmap();
if (oldImage != null) {
oldImage.Dispose();
}
}
private Bitmap DrawToBitmap()
{
var index = (int) updownIndexSelect.Value;
var size = _currentRaw.GetSize(index);
var bitmap = new Bitmap(size.X, size.Y, PixelFormat.Format32bppArgb);
for (var y = 0; y < size.Y; ++y) {
for (var x = 0; x < size.X; ++x) {
var argb = _currentRaw.GetARGB(index, x, y);
var color = Color.FromArgb(argb);
bitmap.SetPixel(x, y, color);
}
}
return bitmap;
}
private class ImageItem
{
internal readonly FileIndex FileIndex;
internal ImageItem(FileIndex fileIndex)
{
FileIndex = fileIndex;
}
public override string ToString()
{
return string.Format("#{0} ({1})", FileIndex.EntryNumber, FileIndex.Size);
}
}
}
} | kivikakk/ifsexplorer | IFSExplorer/MainForm.cs | C# | unlicense | 9,291 |
#!/usr/bin/env node
var http = require('http');
var moment = require('moment');
var server = undefined;
var threshold = undefined;
var units = undefined;
if (!isValid(process.argv)) {
console.error('invalid arguments, expected hostname threshold and units');
process.exit(-1);
}
var request = http.request('http://' + server + '/api/temperatures', function(response) {
var statusCode = response.statusCode;
var result = [];
var json = undefined;
if (statusCode === 200) {
response.on('data', function(chunk) {
result.push(chunk.toString());
});
response.on('end', function() {
json = JSON.parse(result.join(''));
analyze(json);
});
}
});
request.end();
function analyze(data) {
var length = data.length;
var i, sensorData, sensorId, sensorLog, dates;
var analysis;
for (i = 0; i < length; i++) {
sensorData = data[i];
sensorId = sensorData['_id'];
sensorLog = sensorData['value'];
dates = sensorLog.map(function(log) {
return moment(log.date);
});
dates.sort(function(a, b) {
return (a < b ? -1 : (a > b ? 1 : 0));
});
analysis = dates.reduce(function(analysis, to) {
var from = analysis.previous;
var diff;
if (analysis.previous) {
diff = to.diff(from, units);
if (diff > threshold) {
analysis.result.push({
diff: diff + ' ' + units,
from: from.format('YYMMDDHHmm'),
to: to.format('YYMMDDHHmm')
});
}
}
return {
previous: to,
result: analysis.result
};
}, { result: [] });
console.log(sensorId, analysis.result);
}
}
function isValid(args) {
if (args.length === 5) {
server = args[2];
threshold = parseInt(args[3], 10);
units = args[4];
return true;
}
else {
return false;
}
}
| initcz/thermohome-client-rpi | util/analyzeMissingDates.js | JavaScript | unlicense | 1,860 |
/*******************************************************************************
Add to .git/hooks/pre-commit (and chmod +x) to enable auto-linting/uglifying:
#!/bin/sh
grunt build
if [ $? -ne 0 ]; then
exit 1
fi
git add deflector.min.js
exit 0
*******************************************************************************/
module.exports = function(grunt) {
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
connect: {
all: { options: { base: '.', port: 9999 }}
},
jshint: {
all: ['deflector.js', 'deflector.test.js', 'Gruntfile.js']
},
qunit: {
all: ['index.html']
},
'saucelabs-qunit': {
all: {
options: {
testname: '<%= pkg.name %> tests',
tags: ['master'],
urls: ['http://127.0.0.1:9999/'],
build: process.env.TRAVIS_JOB_ID,
browsers: [
{ browserName: "internet explorer", version: "11" },
{ browserName: "android", version: "4.4" },
{ browserName: "iphone", version: "7.1" }
],
tunnelTimeout: 5,
concurrency: 3
}
}
},
uglify: {
all: { files: { 'deflector.min.js': 'deflector.js' }}
},
watch: {
all: {
files: ['deflector.js', 'deflector.test.js'],
tasks: ['build']
}
}
});
for (var key in grunt.file.readJSON('package.json').devDependencies) {
if (key !== 'grunt' && key.indexOf('grunt') === 0) {
grunt.loadNpmTasks(key);
}
}
grunt.registerTask('build', ['jshint', 'uglify', 'qunit']);
grunt.registerTask('test', ['build', 'connect', 'saucelabs-qunit']);
grunt.registerTask('default', ['build', 'connect', 'watch']);
}; | Twissi/deflector | Gruntfile.js | JavaScript | unlicense | 1,998 |
using System;
using System.Reactive;
using System.Reactive.Concurrency;
using System.Reactive.Subjects;
using System.Threading;
using System.Threading.Tasks;
using BFF.DataVirtualizingCollection.PageStorage;
using MrMeeseeks.Reactive.Extensions;
namespace BFF.DataVirtualizingCollection.DataVirtualizingCollection
{
internal sealed class SyncDataVirtualizingCollection<T> : DataVirtualizingCollectionBase<T>
{
private readonly Func<CancellationToken, int> _countFetcher;
private readonly IScheduler _notificationScheduler;
private readonly IPageStorage<T> _pageStorage;
private readonly Subject<Unit> _resetSubject = new();
private int _count;
internal SyncDataVirtualizingCollection(
Func<int, IPageStorage<T>> pageStoreFactory,
Func<CancellationToken, int> countFetcher,
IObservable<(int Offset, int PageSize, T[] PreviousPage, T[] Page)> observePageFetches,
IDisposable disposeOnDisposal,
IScheduler notificationScheduler)
: base (observePageFetches, disposeOnDisposal, notificationScheduler)
{
_countFetcher = countFetcher;
_notificationScheduler = notificationScheduler;
_count = _countFetcher(CancellationToken.None);
_pageStorage = pageStoreFactory(_count);
_resetSubject.CompositeDisposalWith(CompositeDisposable);
_resetSubject
.Subscribe(_ => ResetInner())
.CompositeDisposalWith(CompositeDisposable);
}
public override int Count => _count;
protected override T GetItemInner(int index)
{
return _pageStorage[index];
}
private void ResetInner()
{
_count = _countFetcher(CancellationToken.None);
_pageStorage.Reset(_count);
_notificationScheduler.Schedule(Unit.Default, (_, __) =>
{
OnPropertyChanged(nameof(Count));
OnCollectionChangedReset();
OnIndexerChanged();
});
}
public override void Reset() => _resetSubject.OnNext(Unit.Default);
public override Task InitializationCompleted { get; } = Task.CompletedTask;
public override async ValueTask DisposeAsync()
{
await base.DisposeAsync().ConfigureAwait(false);
await _pageStorage.DisposeAsync().ConfigureAwait(false);
}
}
} | Yeah69/BFF.DataVirtualizingCollection | BFF.DataVirtualizingCollection/DataVirtualizingCollection/SyncDataVirtualizingCollection.cs | C# | unlicense | 2,505 |
<!DOCTYPE html>
<html lang="en-US">
<head>
<base href="http://localhost/wordpress" />
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Wrigley-1981 The population history of England, 1541-1871: a re | Communicating with Prisoners</title>
<link rel='stylesheet' id='ortext-fonts-css' href='//fonts.googleapis.com/css?family=Lato%3A300%2C400%2C700%2C900%2C300italic%2C400italic%2C700italic' type='text/css' media='all' />
<link rel='stylesheet' id='ortext-style-css' href='http://cwpc.github.io/wp-content/themes/ortext/style.css?ver=4.1' type='text/css' media='all' />
<link rel='stylesheet' id='ortext-layout-style-css' href='http://cwpc.github.io/wp-content/themes/ortext/layouts/content.css?ver=4.1' type='text/css' media='all' />
<link rel='stylesheet' id='ortext_fontawesome-css' href='http://cwpc.github.io/wp-content/themes/ortext/fonts/font-awesome/css/font-awesome.min.css?ver=4.1' type='text/css' media='all' />
<link rel='stylesheet' id='tablepress-default-css' href='http://cwpc.github.io/wp-content/plugins/tablepress/css/default.min.css?ver=1.5.1' type='text/css' media='all' />
<style id='tablepress-default-inline-css' type='text/css'>
.tablepress{width:auto;border:2px solid;margin:0 auto 1em}.tablepress td,.tablepress thead th{text-align:center}.tablepress .column-1{text-align:left}.tablepress-table-name{font-weight:900;text-align:center;font-size:20px;line-height:1.3em}.tablepress tfoot th{font-size:14px}.tablepress-table-description{font-weight:900;text-align:center}
</style>
<script type='text/javascript' src='http://cwpc.github.io/wp-includes/js/jquery/jquery.js?ver=1.11.1'></script>
<script type='text/javascript' src='http://cwpc.github.io/wp-includes/js/jquery/jquery-migrate.min.js?ver=1.2.1'></script>
<link rel='next' title='X-1965 The autobiography of Malcolm X. With the assistance' href='http://cwpc.github.io/refs/x-1965-the-autobiography-of-malcolm-x-with-the-assistance/' />
<link rel='canonical' href='http://cwpc.github.io/refs/wrigley-1981-the-population-history-of-england-1541-1871-a-re/' />
<link rel='shortlink' href='http://cwpc.github.io/?p=31260' />
</head>
<body class="single single-refs postid-31260 custom-background">
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-56314084-1', 'auto');
ga('send', 'pageview');
</script><div id="page" class="hfeed site">
<a class="skip-link screen-reader-text" href="#content">Skip to content</a>
<header id="masthead" class="site-header" role="banner">
<div class="site-branding">
<div class="title-box">
<h1 class="site-title"><a href="http://cwpc.github.io/" rel="home">Communicating with Prisoners</a></h1>
<h2 class="site-description">Public Interest Analysis</h2>
</div>
</div>
<div id="scroller-anchor"></div>
<nav id="site-navigation" class="main-navigation clear" role="navigation">
<span class="menu-toggle"><a href="#">menu</a></span>
<div class="menu-left-nav-container"><ul id="menu-left-nav" class="menu"><li id="menu-item-10830" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-10830"><a title="outline of sections" href="http://cwpc.github.io/outline-post/">Outline</a></li>
<li id="menu-item-11571" class="menu-item menu-item-type-custom menu-item-object-custom menu-item-11571"><a title="context-sensitive notes link" href="http://cwpc.github.io/outline-notes/">Notes</a></li>
<li id="menu-item-11570" class="menu-item menu-item-type-custom menu-item-object-custom menu-item-11570"><a title="context-sensitive data link" href="http://cwpc.github.io/list-datasets/">Data</a></li>
</ul></div>
<div id="rng">
<div id="menu-secondary" class="menu-secondary"><ul id="menu-secondary-items" class="menu-items"><li id="menu-item-10840" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-10840"><a title="about this ortext" href="http://cwpc.github.io/about/">About</a></li>
</ul></div> <div class="search-toggle">
<span class="fa fa-search"></span>
<a href="#search-container" class="screen-reader-text">search</a>
</div>
</div>
</nav><!-- #site-navigation -->
<div id="header-search-container" class="search-box-wrapper clear hide">
<div class="search-box clear">
<form role="search" method="get" class="search-form" action="http://cwpc.github.io/">
<label>
<span class="screen-reader-text">Search for:</span>
<input type="search" class="search-field" placeholder="Search …" value="" name="s" title="Search for:" />
</label>
<input type="submit" class="search-submit" value="Search" />
</form> </div>
</div>
</header><!-- #masthead -->
<div id="content" class="site-content">
<div id="primary" class="content-area">
<main id="main" class="site-main" role="main">
<div class="section-label"></div>
<article id="post-31260" class="post-31260 refs type-refs status-publish hentry">
<header class="entry-header">
<h1 class="entry-title">Wrigley-1981 The population history of England, 1541-1871: a re</h1>
</header><!-- .entry-header -->
<div class="entry-content">
<img class="aligncenter otx-face" alt="face of a prisoner" src="http://cwpc.github.io/wp-content/uploads/faces/prisoner-148.jpg"></br><p>reference-type: Book <br />author: Wrigley, E. A. and Schofield, R. S. <br />year: 1981 <br />title: The population history of England, 1541-1871: a reconstruction <br />place-published: Cambridge, MA <br />publisher: Harvard Univ. Press <br />otx-key: Wrigley-1981 </p>
</div><!-- .entry-content -->
<footer class="entry-footer">
<div class="tags-footer">
</div>
</footer><!-- .entry-footer -->
</article><!-- #post-## -->
<nav class="navigation post-navigation" role="navigation">
<h1 class="screen-reader-text">Post navigation</h1>
<div class="nav-links-nd"><div class="nav-nd-title">In Series of References</div><div class="nav-previous"><a href="http://cwpc.github.io/refs/wb-2003-world-development-indicators/" rel="prev">WB-2003 World Development Indicators</a></div><div class="nav-next"><a href="http://cwpc.github.io/refs/x-1965-the-autobiography-of-malcolm-x-with-the-assistance/" rel="next">X-1965 The autobiography of Malcolm X. With the assistance</a></div> </div><!-- .nav-links -->
</nav><!-- .navigation -->
</main><!-- #main -->
</div><!-- #primary -->
</div><!-- #content -->
<footer id="colophon" class="site-footer" role="contentinfo">
<div class="site-info">
<nav id="site-navigation" class="main-navigation clear" role="navigation">
<span class="menu-toggle"><a href="#">menu</a></span>
<div class="menu-left-nav-container"><ul id="menu-left-nav-1" class="menu"><li class="menu-item menu-item-type-post_type menu-item-object-page menu-item-10830"><a title="outline of sections" href="http://cwpc.github.io/outline-post/">Outline</a></li>
<li class="menu-item menu-item-type-custom menu-item-object-custom menu-item-11571"><a title="context-sensitive notes link" href="http://cwpc.github.io/outline-notes/">Notes</a></li>
<li class="menu-item menu-item-type-custom menu-item-object-custom menu-item-11570"><a title="context-sensitive data link" href="http://cwpc.github.io/list-datasets/">Data</a></li>
</ul></div>
<div id="rng">
<div id="menu-secondary" class="menu-secondary"><ul id="menu-secondary-items" class="menu-items"><li class="menu-item menu-item-type-post_type menu-item-object-page menu-item-10840"><a title="about this ortext" href="http://cwpc.github.io/about/">About</a></li>
</ul></div> <div class="search-toggle-bottom">
<span class="fa fa-search"></span>
<a href="#search-container" class="screen-reader-text">search</a>
</div>
</div>
<div id="header-search-container" class="search-box-wrapper-bottom clear hide">
<div class="search-box clear">
<form role="search" method="get" class="search-form" action="http://cwpc.github.io/">
<label>
<span class="screen-reader-text">Search for:</span>
<input type="search" class="search-field" placeholder="Search …" value="" name="s" title="Search for:" />
</label>
<input type="submit" class="search-submit" value="Search" />
</form> </div>
</div>
<div id="footer-tagline">
<a href="http://cwpc.github.io/">Communicating with Prisoners</a>
</div>
</nav><!-- #site-navigation -->
</div><!-- .site-info -->
</footer><!-- #colophon -->
</div><!-- #page -->
<script type='text/javascript' src='http://cwpc.github.io/wp-content/themes/ortext/js/superfish.min.js?ver=1.7.4'></script>
<script type='text/javascript' src='http://cwpc.github.io/wp-content/themes/ortext/js/superfish-settings.js?ver=1.7.4'></script>
<script type='text/javascript' src='http://cwpc.github.io/wp-content/themes/ortext/js/navigation.js?ver=20120206'></script>
<script type='text/javascript' src='http://cwpc.github.io/wp-content/themes/ortext/js/skip-link-focus-fix.js?ver=20130115'></script>
<script type='text/javascript' src='http://cwpc.github.io/wp-content/themes/ortext/js/hide-search.js?ver=20120206'></script>
<script type='text/javascript' src='http://cwpc.github.io/wp-content/themes/ortext/js/show-hide-comments.js?ver=1.0'></script>
</body>
</html>
<!-- Dynamic page generated in 0.196 seconds. -->
<!-- Cached page generated by WP-Super-Cache on 2015-01-27 23:51:17 -->
<!-- super cache --> | cwpc/cwpc.github.io | refs/wrigley-1981-the-population-history-of-england-1541-1871-a-re/index.html | HTML | unlicense | 9,742 |
#! /bin/bash
## Test of SIMPLI provisionning module
source ../../../../test/test_common.sh "webstorm module provisionning - manual"
## load simpli which will do apt-get update
export SIMPLI_SKIP_APT_UPDATE=1
export SIMPLI_SKIP_APT_UPGRADE=1
source "${SIMPLI_DIR}/bin/index.sh"
OSL_EXIT_abort_execution_if_bad_retcode $?
## provision our stuff
require offirmo/webstorm
OSL_EXIT_abort_execution_if_bad_retcode $?
## display a summary (user-mode only)
print_provisionning_summary
echo
| Offirmo/simpli | modules/offirmo/webstorm/test/run_me_to_install_oss_on_current_machine.sh | Shell | unlicense | 488 |
#!/usr/bin/python
# uart-eg01.py
#
# to run on the other end of the UART
# screen /dev/ttyUSB1 115200
import serial
def readlineCR(uart):
line = b''
while True:
byte = uart.read()
line += byte
if byte == b'\r':
return line
uart = serial.Serial('/dev/ttyUSB0', baudrate=115200, timeout=1)
while True:
uart.write(b'\r\nSay something: ')
line = readlineCR(uart)
if line != b'exit\r':
lineStr = '\r\nYou sent : {}'.format(line.decode('utf-8'))
uart.write(lineStr.encode('utf-8'))
else:
uart.write(b'\r\nexiting\r\n')
uart.close()
exit(0)
| CurtisLeeBolin/Examples_Python | UART01.py | Python | unlicense | 567 |
#include "serverBase.h"
int main(int argc, char** argv)
{
unsigned portNumber = 12943;
if(argc >= 2)
{
portNumber = atoi(argv[1]);
}
try
{
asio::io_service io_service;
asio::ip::tcp::endpoint endpoint(asio::ip::tcp::v4(), portNumber);
TCPServer server(io_service, endpoint);
io_service.run();
}
catch (std::exception& e)
{
std::cerr << e.what() << std::endl;
}
return 0;
}
| AdamHarter/flaming-octo-wookie | server/server.cpp | C++ | unlicense | 444 |
/*
* NOTE: This copyright does *not* cover user programs that use HQ
* program services by normal system calls through the application
* program interfaces provided as part of the Hyperic Plug-in Development
* Kit or the Hyperic Client Development Kit - this is merely considered
* normal use of the program, and does *not* fall under the heading of
* "derived work".
*
* Copyright (C) [2004-2009], Hyperic, Inc.
* This file is part of HQ.
*
* HQ is free software; you can redistribute it and/or modify
* it under the terms version 2 of the GNU General Public License as
* published by the Free Software Foundation. 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.
*/
package org.hyperic.hq.ui.server.session;
import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import javax.security.auth.login.LoginException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hyperic.hq.appdef.shared.AppdefEntityID;
import org.hyperic.hq.auth.shared.SessionManager;
import org.hyperic.hq.auth.shared.SessionNotFoundException;
import org.hyperic.hq.auth.shared.SessionTimeoutException;
import org.hyperic.hq.authz.server.session.AuthzApplicationEvent;
import org.hyperic.hq.authz.server.session.AuthzSubject;
import org.hyperic.hq.authz.server.session.Role;
import org.hyperic.hq.authz.server.session.RoleCreatedEvent;
import org.hyperic.hq.authz.server.session.RoleDeleteRequestedEvent;
import org.hyperic.hq.authz.server.session.RoleRemoveFromSubjectRequestedEvent;
import org.hyperic.hq.authz.server.session.SubjectDeleteRequestedEvent;
import org.hyperic.hq.authz.shared.AuthzConstants;
import org.hyperic.hq.authz.shared.AuthzSubjectManager;
import org.hyperic.hq.authz.shared.PermissionException;
import org.hyperic.hq.authz.shared.PermissionManager;
import org.hyperic.hq.authz.shared.PermissionManagerFactory;
import org.hyperic.hq.bizapp.shared.AuthzBoss;
import org.hyperic.hq.common.server.session.Crispo;
import org.hyperic.hq.common.server.session.CrispoOption;
import org.hyperic.hq.common.shared.CrispoManager;
import org.hyperic.hq.ui.Constants;
import org.hyperic.hq.ui.Dashboard;
import org.hyperic.hq.ui.WebUser;
import org.hyperic.hq.ui.shared.DashboardManager;
import org.hyperic.util.StringUtil;
import org.hyperic.util.config.ConfigResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
/**
*/
@Service
@Transactional
public class DashboardManagerImpl implements DashboardManager, ApplicationListener<AuthzApplicationEvent> {
private Log log = LogFactory.getLog(DashboardManagerImpl.class);
protected SessionManager sessionManager = SessionManager.getInstance();
private DashboardConfigDAO dashDao;
private CrispoManager crispoManager;
private AuthzSubjectManager authzSubjectManager;
@Autowired
public DashboardManagerImpl(DashboardConfigDAO dashDao, CrispoManager crispoManager,
AuthzSubjectManager authzSubjectManager) {
this.dashDao = dashDao;
this.crispoManager = crispoManager;
this.authzSubjectManager = authzSubjectManager;
}
/**
*/
@Transactional(readOnly = true)
public UserDashboardConfig getUserDashboard(AuthzSubject me, AuthzSubject user) throws PermissionException {
PermissionManager permMan = PermissionManagerFactory.getInstance();
if (!me.equals(user) && !permMan.hasAdminPermission(me.getId())) {
throw new PermissionException("You are unauthorized to see this " + "dashboard");
}
return dashDao.findDashboard(user);
}
/**
*/
@Transactional(readOnly = true)
public RoleDashboardConfig getRoleDashboard(AuthzSubject me, Role r) throws PermissionException {
PermissionManager permMan = PermissionManagerFactory.getInstance();
permMan.check(me.getId(), r.getResource().getResourceType(), r.getId(), AuthzConstants.roleOpModifyRole);
return dashDao.findDashboard(r);
}
private ConfigResponse getDefaultConfig() {
return new ConfigResponse();
}
/**
*/
public UserDashboardConfig createUserDashboard(AuthzSubject me, AuthzSubject user, String name)
throws PermissionException {
PermissionManager permMan = PermissionManagerFactory.getInstance();
if (!me.equals(user) && !permMan.hasAdminPermission(me.getId())) {
throw new PermissionException("You are unauthorized to create " + "this dashboard");
}
Crispo cfg = crispoManager.create(getDefaultConfig());
UserDashboardConfig dash = new UserDashboardConfig(user, name, cfg);
dashDao.save(dash);
return dash;
}
/**
*/
public RoleDashboardConfig createRoleDashboard(AuthzSubject me, Role r, String name) throws PermissionException {
PermissionManager permMan = PermissionManagerFactory.getInstance();
permMan.check(me.getId(), r.getResource().getResourceType(), r.getId(), AuthzConstants.roleOpModifyRole);
Crispo cfg = crispoManager.create(getDefaultConfig());
RoleDashboardConfig dash = new RoleDashboardConfig(r, name, cfg);
dashDao.save(dash);
return dash;
}
/**
* Reconfigure a user's dashboard
*/
public void configureDashboard(AuthzSubject me, DashboardConfig cfg, ConfigResponse newCfg)
throws PermissionException {
if (!isEditable(me, cfg)) {
throw new PermissionException("You are unauthorized to modify " + "this dashboard");
}
crispoManager.update(cfg.getCrispo(), newCfg);
}
/**
*/
public void renameDashboard(AuthzSubject me, DashboardConfig cfg, String name) throws PermissionException {
if (!isEditable(me, cfg)) {
throw new PermissionException("You are unauthorized to modify " + "this dashboard");
}
cfg.setName(name);
}
/**
* Determine if a dashboard is editable by the passed user
*/
@Transactional(readOnly = true)
public boolean isEditable(AuthzSubject me, DashboardConfig dash) {
PermissionManager permMan = PermissionManagerFactory.getInstance();
if (permMan.hasAdminPermission(me.getId()))
return true;
return dash.isEditable(me);
}
/**
*/
@Transactional(readOnly = true)
public Collection<DashboardConfig> getDashboards(AuthzSubject me) throws PermissionException {
Collection<DashboardConfig> res = new ArrayList<DashboardConfig>();
PermissionManager permMan = PermissionManagerFactory.getInstance();
if (permMan.hasGuestRole() && permMan.hasAdminPermission(me.getId())) {
res.addAll(dashDao.findAllRoleDashboards());
res.add(getUserDashboard(me, me));
return res;
}
UserDashboardConfig cfg = getUserDashboard(me, me);
if (cfg != null)
res.add(cfg);
if (permMan.hasGuestRole())
res.addAll(dashDao.findRolesFor(me));
return res;
}
/**
* Update dashboard and user configs to account for resource deletion
*
* @param ids An array of ID's of removed resources
*/
public void handleResourceDelete(AppdefEntityID[] ids) {
for (int i = 0; i < ids.length; i++) {
String appdefKey = ids[i].getAppdefKey();
List<CrispoOption> copts = crispoManager.findOptionByValue(appdefKey);
for (CrispoOption o : copts) {
String val = o.getValue();
String newVal = removeResource(val, appdefKey);
if (!val.equals(newVal)) {
crispoManager.updateOption(o, newVal);
log.debug("Update option key=" + o.getKey() + " old =" + val + " new =" + newVal);
}
}
}
}
/**
*/
@Transactional(readOnly = true)
public ConfigResponse getRssUserPreferences(String user, String token) throws LoginException {
ConfigResponse preferences;
try {
AuthzSubject me = authzSubjectManager.findSubjectByName(user);
preferences = getUserDashboard(me, me).getConfig();
} catch (Exception e) {
throw new LoginException("Username has no preferences");
}
// Let's make sure that the rss auth token matches
String prefToken = preferences.getValue(Constants.RSS_TOKEN);
if (token == null || !token.equals(prefToken))
throw new LoginException("Username and Auth token do not match");
return preferences;
}
private String removeResource(String val, String resource) {
val = StringUtil.remove(val, resource);
val = StringUtil.replace(val, Constants.EMPTY_DELIMITER, Constants.DASHBOARD_DELIMITER);
return val;
}
public void onApplicationEvent(AuthzApplicationEvent event) {
if(event instanceof SubjectDeleteRequestedEvent) {
dashDao.handleSubjectRemoval(((SubjectDeleteRequestedEvent)event).getSubject());
}else if(event instanceof RoleDeleteRequestedEvent) {
roleRemoved(((RoleDeleteRequestedEvent)event).getRole());
}else if(event instanceof RoleCreatedEvent) {
roleCreated(((RoleCreatedEvent)event).getRole());
}else if(event instanceof RoleRemoveFromSubjectRequestedEvent) {
roleRemovedFromSubject(((RoleRemoveFromSubjectRequestedEvent)event).getRole(), ((RoleRemoveFromSubjectRequestedEvent)event).getSubject());
}
}
private void roleRemoved(Role role) {
RoleDashboardConfig cfg = dashDao.findDashboard(role);
if (cfg == null) {
return;
}
List<CrispoOption> opts = crispoManager.findOptionByKey(Constants.DEFAULT_DASHBOARD_ID);
for (CrispoOption opt : opts) {
if (Integer.valueOf(opt.getValue()).equals(cfg.getId())) {
crispoManager.updateOption(opt, null);
}
}
dashDao.handleRoleRemoval(role);
}
private void roleCreated(Role role) {
Crispo cfg = crispoManager.create(getDefaultConfig());
RoleDashboardConfig dash = new RoleDashboardConfig(role, role.getName() + " Role Dashboard", cfg);
dashDao.save(dash);
}
private void roleRemovedFromSubject(Role r, AuthzSubject from) {
RoleDashboardConfig cfg = dashDao.findDashboard(r);
Crispo c = from.getPrefs();
if (c != null) {
for (CrispoOption opt : c.getOptions()) {
if (opt.getKey().equals(Constants.DEFAULT_DASHBOARD_ID) &&
Integer.valueOf(opt.getValue()).equals(cfg.getId())) {
crispoManager.updateOption(opt, null);
break;
}
}
}
}
@Transactional(readOnly = true)
public List<DashboardConfig> findEditableDashboardConfigs(WebUser user, AuthzBoss boss)
throws SessionNotFoundException, SessionTimeoutException, PermissionException, RemoteException {
AuthzSubject me = boss.findSubjectById(user.getSessionId(), user.getSubject().getId());
Collection<DashboardConfig> dashboardCollection = getDashboards(me);
List<DashboardConfig> editableDashboardConfigs = new ArrayList<DashboardConfig>();
for (DashboardConfig config : dashboardCollection) {
if (isEditable(me, config)) {
editableDashboardConfigs.add(config);
}
}
return editableDashboardConfigs;
}
@Transactional(readOnly = true)
public List<Dashboard> findEditableDashboards(WebUser user, AuthzBoss boss) throws SessionNotFoundException,
SessionTimeoutException, PermissionException, RemoteException {
List<DashboardConfig> dashboardConfigs = findEditableDashboardConfigs(user, boss);
List<Dashboard> editableDashboards = new ArrayList<Dashboard>();
for (DashboardConfig config : dashboardConfigs) {
Dashboard dashboard = new Dashboard();
dashboard.set_name(config.getName());
dashboard.setId(config.getId());
editableDashboards.add(dashboard);
}
return editableDashboards;
}
/**
* Find a given dashboard by its id
* @param id the id of the dashboard
* @param user current user
* @param boss the authzboss
* @return the DashboardConfig of the corresponding DashboardId or null if
* none
*/
@Transactional(readOnly = true)
public DashboardConfig findDashboard(Integer id, WebUser user, AuthzBoss boss) {
Collection<DashboardConfig> dashboardCollection;
try {
AuthzSubject me = boss.findSubjectById(user.getSessionId(), user.getSubject().getId());
dashboardCollection = getDashboards(me);
} catch (Exception e) {
return null;
}
for (DashboardConfig config : dashboardCollection) {
if (config.getId().equals(id)) {
return config;
}
}
return null;
}
}
| cc14514/hq6 | hq-web/src/main/java/org/hyperic/hq/ui/server/session/DashboardManagerImpl.java | Java | unlicense | 13,750 |
from rec import CourseRecord
from score import RoomScore
from evaluation import ScheduleEvaluation
FULL_HOURS = 8 # 8:00AM - 4:00PM utilization
PARTIAL_HOURS = FULL_HOURS * 0.75 #75%
HALF_HOURS = FULL_HOURS * 0.50 #50%
SPARSE_HOURS = FULL_HOURS * 0.25 #25%
class LocationScore:
def __init__(self, evals=None):
self.evals = evals
self.courses = None
self.location = None
self.daily_weights = {"M": {}, "T": {}, "W": {}, "R": {}, "F": {} ,"S": {}}
self.daily_totals = {"M": {}, "T": {}, "W": {}, "R": {}, "F": {} ,"S": {}}
self.final_weighted = 0
self.weight_rank = 0 # 0 = worst, 1 = best
if evals != None:
self.courses = self.evals.get_records()
self.location = self.find_location()
self.final_weighted = self.calculate_final_weighted_score()
def reset_daily_weights(self):
for day in ["M", "T", "W", "R", "F", "S"]:
self.daily_weights[day] = 0
self.daily_totals[day] = 0
def get_daily_weight(self,day_of_week):
return self.daily_weights[day_of_week]
def normalize_final_weighted_score(self,minimum,maximum):
value = self.final_weighted
value -= minimum
if maximum - minimum > 0:
value /= ( maximum - minimum )
else:
value = 0
self.weight_rank = "{0:.2f}".format(value * 10)
def calculate_final_weighted_score(self):
score_sum = 0.00
score_total = 0.00
#reset daily stuff
self.reset_daily_weights()
for course, score in self.courses:
days = course.rec["DAYS_OF_WEEK"]
#score_sum += score.get_weighted_score(course)
score_total += 1.00
for day in ["M", "T", "W", "R", "F", "S"]:
if day in days:
self.daily_weights[day] += score.get_weighted_score(course)
self.daily_totals[day] += 1
for day in ["M", "T", "W", "R", "F", "S"]:
if self.daily_totals[day] > 0:
self.daily_weights[day] /= self.daily_totals[day]
self.daily_weights[day] = self.adjust_utilization(self.daily_weights[day],self.daily_totals[day])
score_sum += self.daily_weights[day]
else:
self.daily_weights[day] = 0
return score_sum / score_total
def adjust_utilization(self,weights,totals):
max_score = 1.00
if totals >= FULL_HOURS: # 8 Hours or more, give slight boost to score
weights *= 1.15 # 15% Boost
elif totals >= PARTIAL_HOURS: # Small Penalty
weights *= (PARTIAL_HOURS/FULL_HOURS)
elif totals >= HALF_HOURS: # Medium Penalty
weights *= (HALF_HOURS/FULL_HOURS)
elif totals > SPARSE_HOURS: # Large Penalty
weights *= (SPARSE_HOURS/FULL_HOURS)
else: # Very Large Penalty
weights *= (1.00/FULL_HOURS)
return weights
def get_location(self):
return self.location
def find_location(self):
for course, score in self.courses:
location = str( course.rec["BUILDING"] )+ " " + str( course.rec["ROOM"] )
# just need to find the first one, so break after this happens
break
return location
def get_final_weighted_score(self):
return self.final_weighted
def get_score_rank(self):
return self.weight_rank
def get_evals(self):
return self.evals
| jbrackins/scheduling-research | src/location.py | Python | unlicense | 3,581 |
package es.com.blogspot.elblogdepicodev.activiti;
import java.text.MessageFormat;
import java.util.HashMap;
import java.util.Map;
import org.activiti.engine.ProcessEngine;
import org.activiti.engine.ProcessEngineConfiguration;
import org.activiti.engine.ProcessEngines;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.runtime.ProcessInstance;
import org.h2.tools.Server;
import es.com.blogspot.elblogdepicodev.activiti.misc.Producto;
public class Errores {
public static void main(String[] args) throws Exception {
Server server = null;
try {
server = Server.createTcpServer().start();
ProcessEngines.init();
ProcessEngine processEngine = ProcessEngineConfiguration.createProcessEngineConfigurationFromResource("activiti-mysql.cfg.xml").buildProcessEngine();
RuntimeService runtimeService = processEngine.getRuntimeService();
RepositoryService repositoryService = processEngine.getRepositoryService();
repositoryService.createDeployment().addClasspathResource("bpmn/Errores.bpmn20.xml").deploy();
Producto producto = new Producto("Arch Linux T-Shirt", 10l);
Map variables = new HashMap();
variables.put("producto", producto);
ProcessInstance pi = runtimeService.startProcessInstanceByKey("errores", variables);
System.out.println(MessageFormat.format("Las nuevas existencias de {0} son {1}", producto.getNombre(), producto.getExistencias()));
} finally {
ProcessEngines.destroy();
if (server != null)
server.stop();
}
}
} | picodotdev/elblogdepicodev | HelloWorldActiviti/src/main/java/es/com/blogspot/elblogdepicodev/activiti/Errores.java | Java | unlicense | 1,554 |
package ua.clinic.tests.integration;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import ua.ibt.clinic.api.DetailsAPI;
import ua.ibt.clinic.api.DoctorAPI;
import java.text.SimpleDateFormat;
import static org.junit.Assert.assertEquals;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
/**
* Created by Iryna Tkachova on 11.03.2017.
*/
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@AutoConfigureMockMvc
public class UserdetailsControllerTest {
private static final Logger logger = LoggerFactory.getLogger(UserdetailsControllerTest.class);
@Autowired
private MockMvc mockMvc;
@Test
public void test_addDetails() throws Exception {
logger.debug(">>>>>>>>>> test_addDetails >>>>>>>>>>");
DetailsAPI detailsAPI = new DetailsAPI();
detailsAPI.iduser = Long.valueOf(984844);
detailsAPI.numcard = "aa-111";
detailsAPI.name = "Ivan";
detailsAPI.surname = "Ivanenko";
detailsAPI.middlename = "Ivanovich";
detailsAPI.birthday = new SimpleDateFormat("yyyy-MM-dd").parse("2001-10-10");
detailsAPI.sex = "M";
detailsAPI.notes = "test";
ObjectMapper om = new ObjectMapper();
String content = om.writeValueAsString(detailsAPI);
MvcResult result = mockMvc.perform(post("/details/set")
.accept(MediaType.APPLICATION_JSON_UTF8)
.contentType(MediaType.APPLICATION_JSON_UTF8)
.content(content)
)
.andExpect(status().isOk())
.andReturn();
String reply = result.getResponse().getContentAsString();
DetailsAPI resultData = om.readValue(reply, DetailsAPI.class);
assertEquals("Reurn code in not 0",resultData.retcode.longValue(), 0L);
}
@Test
public void test_setDoctor() throws Exception {
logger.debug(">>>>>>>>>> test_setDoctor >>>>>>>>>>");
DoctorAPI doctorAPI = new DoctorAPI();
doctorAPI.iduser = Long.valueOf(984844);
doctorAPI.tabnumber = Long.valueOf(22222);
ObjectMapper om = new ObjectMapper();
String content = om.writeValueAsString(doctorAPI);
MvcResult result = mockMvc.perform(post("/doctor/set")
.accept(MediaType.APPLICATION_JSON_UTF8)
.contentType(MediaType.APPLICATION_JSON_UTF8)
.content(content)
)
.andExpect(status().isOk())
.andReturn();
String reply = result.getResponse().getContentAsString();
DetailsAPI resultData = om.readValue(reply, DetailsAPI.class);
assertEquals("Reurn code in not 0",resultData.retcode.longValue(), 0L);
}
}
| beamka/Polyclinic | Clinic/src/test/java/ua/clinic/tests/integration/UserdetailsControllerTest.java | Java | unlicense | 3,482 |
@"%~dp0edit.bat" %*
| kodybrown/dos | open.bat | Batchfile | unlicense | 21 |
require 'google_tts/connector'
require 'google_tts/query_builder'
require 'google_tts/parser'
require 'google_tts/mp3writer'
module GoogleTts
VERSION = "0.1.0"
class Client
include GoogleTts
def initialize(connector = Connector.new,
query_builder = QueryBuilder.new,
mp3writer = Mp3Writer.new,
parser = Parser.new)
@connector = connector
@parser = parser
@query_builder = query_builder
@mp3writer = mp3writer
end
def save(name, text)
sentences = @parser.sentences(text)
queries = @query_builder.generate_from(*sentences)
contents = @connector.get_contents(*queries)
@mp3writer.save(name, *contents)
end
end
def self.instantiate(params = {})
proxy = params[:proxy] || @proxy
connection = proxy ? Net::HTTP::Proxy(proxy[:host], proxy[:port]) : Net::HTTP
lang = params[:lang] || :en
output = params[:output] || "out"
Client.new(Connector.new(connection), QueryBuilder.new(lang), Mp3Writer.new(output))
end
def self.with_random_proxy(_params = {})
@proxy = ProxyFetcher.random_proxy
self
end
end
| filipesperandio/google_tts2 | lib/google_tts.rb | Ruby | unlicense | 1,167 |
Imports System.Collections.Generic
Public Enum DutyType
Undefined
Lekarska
Pielęgniarska
Other
End Enum
Public Class Duty
' Formating:
' f_ - form value
' d_ data base value
' other
'Public id_ As UInteger
Public d_id_ As Integer
Public f_id_ As Integer
Public f_date_ As Date
Public f_personel_id_ As Integer ' forgein key of <-> HospitalStaff.f_id_
Public f_has_duty_ As Boolean ' Optional value
Private table_name_ As String = "DUTY"
Private timeFormat_ As String = "yyyy-MM-dd"
Function IsInitialized() As Boolean
Return d_id_ > -1
End Function
Function Get_d_Id() As String
Return d_id_.ToString
End Function
Function Get_f_Id() As String
Return f_id_.ToString
End Function
Function Get_f_Date() As String
Return f_date_.ToString(timeFormat_)
End Function
Function Get_f_Personel_Id() As String
Return f_personel_id_.ToString
End Function
Function Get_Has_Duty() As String
Return f_has_duty_.ToString
End Function
Function Get_TableName() As String
Return table_name_
End Function
Private cQuote As String = Chr(34)
Function ValidateAndUpdate(
ByVal f_id As String,
ByVal f_date As String,
ByVal f_personel_id As String,
Optional ByVal f_has_duty As String = ""
) As Boolean
Dim f_id_local As Integer = -1
Dim f_date_local As Date
Dim f_personel_id_local As Integer = -1
Dim f_has_duty_local As Boolean = False
Dim validation_passed = True
Try
If f_id = String.Empty Then
f_id_local = -1
d_id_ = -1 ' IF Ward id was not set then the data shall be treated not initialized
Else
f_id_local = CInt(f_id)
End If
If f_date = String.Empty Then
f_date_local = Date.MinValue
Else
If Not Date.TryParse(f_date, f_date_local) Then
f_date_local = Date.MinValue
End If
End If
If f_personel_id = String.Empty Then
f_personel_id_local = -1
Else
f_personel_id_local = CInt(f_personel_id)
End If
If (f_has_duty = "1" Or f_has_duty = "True" Or f_has_duty = "true") Then
f_has_duty_local = True
End If
Catch ex As Exception
validation_passed = False
MsgBox("Hospital staff validation failed - wrong data " & ex.Message, MsgBoxStyle.Information)
'Toolbox.Log("Ward validation failed - wrong data " & ex.Message, MsgBoxStyle.Information)
End Try
If validation_passed Then
Update(f_id_local, f_date_local, f_personel_id_local, f_has_duty_local)
End If
Return validation_passed
End Function
Sub Update(
ByVal f_id As Integer,
ByVal f_date As Date,
ByVal f_personel_id As Integer,
ByVal f_has_duty As Boolean
)
f_id_ = f_id
f_date_ = f_date
f_personel_id_ = f_personel_id
f_has_duty_ = f_has_duty
End Sub
Sub Clear() ' Reset class fields
f_id_ = -1
f_date_ = Date.MinValue
f_personel_id_ = -1
f_has_duty_ = False
End Sub
' This Parse method and FormQuerry_Select must keep the same columns order
Function Parse(ByVal s As String) As Boolean
Dim d_id_local As String
Dim f_id_local As String
Dim f_date_local As String
Dim f_personel_id_local As String
Dim f_has_duty_local As String = "0"
Dim parts As String() = Toolbox.SplitString(s)
d_id_local = parts(0)
f_id_local = parts(1)
f_date_local = parts(2)
f_personel_id_local = parts(3)
f_has_duty_local = parts(4)
If Not f_has_duty_local = "1" Then ' Only "1" in database is accepted as "true" value.
f_has_duty_local = "0"
End If
ValidateAndUpdate(f_id_local, f_date_local, f_personel_id_local, f_has_duty_local)
d_id_ = CInt(d_id_local)
End Function
' This FormQuerry_Select method and Parse must keep the same columns order
Function FormQuerry_Select() As String
' THE DUTY QUERRY ORDER: | 0 | 1 | 2 | 3 | 4 |
' THE DUTY QUERRY ORDER: | ID | ID_DUTY | DATE | STAFF_ID | HAS_DUTY |
' THE DUTY QUERRY ORDER: | INTEGER PRIMARY KEY AUTOINCREMENT | INTEGER NOT NULL | DATE NOT NULL | INTEGER NOT NULL | BOOLEAN |
Dim querry As String = String.Empty
Dim date_condition As String = String.Empty
Dim personel_condition As String = String.Empty
querry = "SELECT ID, ID_DUTY, DATE, STAFF_ID, HAS_DUTY FROM DUTY"
If f_date_ > Date.MinValue Then
date_condition = " DATE = " + cQuote + f_date_.ToString(timeFormat_) + cQuote
End If
If f_personel_id_ > -1 Then
personel_condition = " STAFF_ID = " + f_personel_id_.ToString()
End If
' Search filtering over Duty Date and/or Personel ID. Use these fields for filtering only when defined.
If f_date_ > Date.MinValue Or f_personel_id_ > -1 Then
querry += " WHERE "
If f_date_ > Date.MinValue And f_personel_id_ > -1 Then
querry += date_condition + " AND " + personel_condition
End If
If f_date_ > Date.MinValue And f_personel_id_ = -1 Then
querry += date_condition
End If
If f_date_ = Date.MinValue And f_personel_id_ > -1 Then
querry += personel_condition
End If
End If
querry += ";"
Return querry
End Function
' This FormQuerry_Select method and Parse must keep the same columns order
' Defined in email 2017-07-06:
' data_przyjecia, data_wypisu, id_pacjenta, id_oddzialu
Function FormQuerry_SelectSpecialForExport() As String
' THE DUTY QUERRY ORDER: | 0 | 2 | 2 |
' THE DUTY QUERRY ORDER: | ID | STAFF_ID | DATE |
' THE DUTY QUERRY ORDER: | INTEGER PRIMARY KEY AUTOINCREMENT | INTEGER NOT NULL | DATE NOT NULL |
Dim querry As String = String.Empty
querry = "SELECT ID, STAFF_ID, STRFTIME('%Y-%m-%d',DATE) FROM DUTY"
querry += ";"
Return querry
End Function
' This FormQuerry_Select method and Parse must keep the same columns order
' Defined in email 2017-09-19:
' (id_personelu, data) + and data base id.
Function FormQuerry_SelectSpecialForExport_Header() As String
Dim header As String = String.Empty
header = "id_wpisu;id_personelu;data_dyżuru;"
Return header
End Function
Public Function FormQuerry_Insert() As String
Dim querry As String = String.Empty
Dim has_duty_sql_string = "0"
If f_has_duty_ = True Then
has_duty_sql_string = "1"
End If
querry = "INSERT INTO DUTY (ID_DUTY, DATE, STAFF_ID, HAS_DUTY) VALUES (" +
f_id_.ToString & "," &
cQuote & f_date_.ToString(timeFormat_) & cQuote & "," &
f_personel_id_.ToString & "," &
has_duty_sql_string &
");"
Return querry
End Function
Function FormQuerry_Update() As String ' Same as Update
Dim querry As String = String.Empty
' Utworzenie querry
' TODO: Complete that
' "Type=" & quote & DutyType.ToString() & quote & ", " &
Dim has_duty_sql_string = "0"
If f_has_duty_ = True Then
has_duty_sql_string = "1"
End If
querry = "UPDATE DUTY SET " &
" ID_DUTY = " & f_id_.ToString() & ", " &
" DATE = " & cQuote & f_date_.ToString(timeFormat_) & cQuote & ", " &
" STAFF_ID = " & f_personel_id_.ToString() & ", " &
" HAS_DUTY = " & has_duty_sql_string & " " &
" WHERE ID = " & +d_id_.ToString &
";"
Return querry
End Function
Function FormQuerry_Delete() As String
Dim querry As String = String.Empty
querry = "DELETE FROM DUTY " &
" WHERE ID = " & +d_id_.ToString & ";"
Return querry
End Function
Private Shared Function FormQuerry_DropTableIfExists() As String
Dim querry As String = String.Empty
querry = "DROP TABLE IF EXISTS DUTY; "
Return querry
End Function
Private Shared Function FormQuerry_CreateTableIfNotExists() As String
Dim querry As String = String.Empty
querry = "CREATE TABLE IF NOT EXISTS DUTY (
ID INTEGER PRIMARY KEY AUTOINCREMENT,
ID_DUTY INTEGER NOT NULL,
DATE DATE NOT NULL,
STAFF_ID INTEGER NOT NULL,
HAS_DUTY BOOLEAN
);"
Return querry
End Function
Public Shared Function FormQuerry_DropAndCreateTable() As String
Dim querry As String = String.Empty
querry = FormQuerry_DropTableIfExists()
querry += FormQuerry_CreateTableIfNotExists()
Return querry
End Function
End Class
| sirsz/Elpis | Elpis/Source/Model/Duty.vb | Visual Basic | unlicense | 9,492 |
"""redblue_project URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.9/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Add an import: from blog import urls as blog_urls
2. Import the include() function: from django.conf.urls import url, include
3. Add a URL to urlpatterns: url(r'^blog/', include(blog_urls))
"""
from django.conf.urls import url, include
from django.contrib import admin
urlpatterns = [
url(r'^red/', include('apps.red_app.urls', namespace='red_namespace')),
url(r'^blue/', include('apps.blue_app.urls', namespace='blue_namespace')),
url(r'^admin/', admin.site.urls),
]
| thinkAmi-sandbox/Django_iis_global_static_sample | redblue_project/urls.py | Python | unlicense | 991 |
using UnityEngine;
using UnityEngine.SceneManagement;
public class ShowModeA : MonoBehaviour {
public Texture AModeTexture;
public Texture BModeTexture;
private PlayerControllerBMode playerControllerBMode;
private GameController gameController;
void Start () {
InitPlayerController();
InitGameController();
UpdateModeAndTexture();
}
void InitPlayerController()
{
GameObject playerGameObject = GameObject.FindGameObjectWithTag("Player");
if (playerGameObject != null)
playerControllerBMode = playerGameObject.GetComponent<PlayerControllerBMode>();
else
Debug.Log("Error: Player no encontrado.");
}
private void InitGameController()
{
GameObject gameControllerObject = GameObject.FindGameObjectWithTag("GameController");
if (gameControllerObject != null)
gameController = gameControllerObject.GetComponent<GameController>();
else
Debug.Log("Error: Game Controller no encontrado.");
}
public void UpdateModeAndTexture(){
if (PlayerPrefs.GetInt("active_mode", 1) == 2)
{
GetComponent<Renderer>().material.SetTexture("_MainTex", AModeTexture);
playerControllerBMode.enabled = true;
gameController.InitHighscore();
gameController.ChangeBackground(2);
}
else
{
GetComponent<Renderer>().material.SetTexture("_MainTex", BModeTexture);
playerControllerBMode.enabled = false;
gameController.InitHighscore();
gameController.ChangeBackground(1);
}
}
}
| Maximetinu/No-Mans-Flappy-Unity | Assets/Scripts/MenuButtons/ShowModeA.cs | C# | unlicense | 1,678 |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>MergeType - FAKE - F# Make</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="">
<meta name="author" content="Steffen Forkmann, Mauricio Scheffer, Colin Bull">
<script src="https://code.jquery.com/jquery-1.8.0.js"></script>
<script src="https://code.jquery.com/ui/1.8.23/jquery-ui.js"></script>
<script src="https://netdna.bootstrapcdn.com/twitter-bootstrap/2.2.1/js/bootstrap.min.js"></script>
<script type="text/javascript" src="http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>
<link href="https://netdna.bootstrapcdn.com/twitter-bootstrap/2.2.1/css/bootstrap-combined.min.css" rel="stylesheet">
<link type="text/css" rel="stylesheet" href="http://fsharp.github.io/FAKE/content/style.css" />
<script type="text/javascript" src="http://fsharp.github.io/FAKE/content/tips.js"></script>
<!-- HTML5 shim, for IE6-8 support of HTML5 elements -->
<!--[if lt IE 9]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
</head>
<body>
<div class="container">
<div class="masthead">
<ul class="nav nav-pills pull-right">
<li><a href="http://fsharp.org">fsharp.org</a></li>
<li><a href="http://github.com/fsharp/fake">github page</a></li>
</ul>
<h3 class="muted"><a href="http://fsharp.github.io/FAKE/index.html">FAKE - F# Make</a></h3>
</div>
<hr />
<div class="row">
<div class="span9" id="main">
<h1>MergeType</h1>
<div class="xmldoc">
<p>Git merge option.</p>
</div>
<h3>Union Cases</h3>
<table class="table table-bordered member-list">
<thead>
<tr><td>Union Case</td><td>Description</td></tr>
</thead>
<tbody>
<tr>
<td class="member-name">
<code onmouseout="hideTip(event, '1885', 1885)" onmouseover="showTip(event, '1885', 1885)">
FirstNeedsFastForward
</code>
<div class="tip" id="1885">
<strong>Signature:</strong> <br />
</div>
</td>
<td class="xmldoc">
<a href="https://github.com/fsharp/FAKE/blob/master/src/app/FakeLib/Git/Merge.fs#L22-22" class="github-link">
<img src="../content/img/github.png" class="normal" />
<img src="../content/img/github-blue.png" class="hover" />
</a>
</td>
</tr>
<tr>
<td class="member-name">
<code onmouseout="hideTip(event, '1886', 1886)" onmouseover="showTip(event, '1886', 1886)">
NeedsRealMerge
</code>
<div class="tip" id="1886">
<strong>Signature:</strong> <br />
</div>
</td>
<td class="xmldoc">
<a href="https://github.com/fsharp/FAKE/blob/master/src/app/FakeLib/Git/Merge.fs#L24-24" class="github-link">
<img src="../content/img/github.png" class="normal" />
<img src="../content/img/github-blue.png" class="hover" />
</a>
</td>
</tr>
<tr>
<td class="member-name">
<code onmouseout="hideTip(event, '1887', 1887)" onmouseover="showTip(event, '1887', 1887)">
SameCommit
</code>
<div class="tip" id="1887">
<strong>Signature:</strong> <br />
</div>
</td>
<td class="xmldoc">
<a href="https://github.com/fsharp/FAKE/blob/master/src/app/FakeLib/Git/Merge.fs#L21-21" class="github-link">
<img src="../content/img/github.png" class="normal" />
<img src="../content/img/github-blue.png" class="hover" />
</a>
</td>
</tr>
<tr>
<td class="member-name">
<code onmouseout="hideTip(event, '1888', 1888)" onmouseover="showTip(event, '1888', 1888)">
SecondNeedsFastForward
</code>
<div class="tip" id="1888">
<strong>Signature:</strong> <br />
</div>
</td>
<td class="xmldoc">
<a href="https://github.com/fsharp/FAKE/blob/master/src/app/FakeLib/Git/Merge.fs#L23-23" class="github-link">
<img src="../content/img/github.png" class="normal" />
<img src="../content/img/github-blue.png" class="hover" />
</a>
</td>
</tr>
</tbody>
</table>
</div>
<div class="span3">
<a href="http://fsharp.github.io/FAKE/index.html">
<img src="http://fsharp.github.io/FAKE/pics/logo.png" style="width:140px;height:140px;margin:10px 0px 0px 35px;border-style:none;" />
</a>
<ul class="nav nav-list" id="menu">
<li class="nav-header">FAKE - F# Make</li>
<li class="divider"></li>
<li><a href="http://fsharp.github.io/FAKE/index.html">Home page</a></li>
<li class="divider"></li>
<li><a href="https://www.nuget.org/packages/FAKE">Get FAKE - F# Make via NuGet</a></li>
<li><a href="http://github.com/fsharp/fake">Source Code on GitHub</a></li>
<li><a href="http://github.com/fsharp/fake/blob/master/License.txt">License (Apache 2)</a></li>
<li><a href="http://fsharp.github.io/FAKE/RELEASE_NOTES.html">Release Notes</a></li>
<li><a href="http://fsharp.github.io/FAKE//contributing.html">Contributing to FAKE - F# Make</a></li>
<li><a href="http://fsharp.github.io/FAKE/users.html">Who is using FAKE?</a></li>
<li><a href="http://stackoverflow.com/questions/tagged/f%23-fake">Ask a question</a></li>
<li class="nav-header">Tutorials</li>
<li><a href="http://fsharp.github.io/FAKE/gettingstarted.html">Getting started</a></li>
<li class="divider"></li>
<li><a href="http://fsharp.github.io/FAKE/nuget.html">NuGet package restore</a></li>
<li><a href="http://fsharp.github.io/FAKE/fxcop.html">Using FxCop in a build</a></li>
<li><a href="http://fsharp.github.io/FAKE/assemblyinfo.html">Generating AssemblyInfo</a></li>
<li><a href="http://fsharp.github.io/FAKE/create-nuget-package.html">Create NuGet packages</a></li>
<li><a href="http://fsharp.github.io/FAKE/specifictargets.html">Running specific targets</a></li>
<li><a href="http://fsharp.github.io/FAKE/commandline.html">Running FAKE from command line</a></li>
<li><a href="http://fsharp.github.io/FAKE/parallel-build.html">Running targets in parallel</a></li>
<li><a href="http://fsharp.github.io/FAKE/fsc.html">Using the F# compiler from FAKE</a></li>
<li><a href="http://fsharp.github.io/FAKE/customtasks.html">Creating custom tasks</a></li>
<li><a href="http://fsharp.github.io/FAKE/teamcity.html">TeamCity integration</a></li>
<li><a href="http://fsharp.github.io/FAKE/canopy.html">Running canopy tests</a></li>
<li><a href="http://fsharp.github.io/FAKE/octopusdeploy.html">Octopus Deploy</a></li>
<li><a href="http://fsharp.github.io/FAKE/typescript.html">TypeScript support</a></li>
<li><a href="http://fsharp.github.io/FAKE/azurewebjobs.html">Azure WebJobs support</a></li>
<li><a href="http://fsharp.github.io/FAKE/azurecloudservices.html">Azure Cloud Services support</a></li>
<li><a href="http://fsharp.github.io/FAKE/androidpublisher.html">Android publisher</a></li>
<li><a href="http://fsharp.github.io/FAKE/watch.html">File Watcher</a></li>
<li class="divider"></li>
<li><a href="http://fsharp.github.io/FAKE/deploy.html">Fake.Deploy</a></li>
<li class="nav-header">Reference</li>
<li><a href="http://fsharp.github.io/FAKE/apidocs/index.html">API Reference</a></li>
</ul>
</div>
</div>
</div>
<a href="http://github.com/fsharp/fake"><img style="position: absolute; top: 0; right: 0; border: 0;" src="https://s3.amazonaws.com/github/ribbons/forkme_right_gray_6d6d6d.png" alt="Fork me on GitHub"></a>
</body>
</html>
| Slesa/Poseidon | src/packages/FAKE/docs/apidocs/fake-git-merge-mergetype.html | HTML | unlicense | 8,346 |
//
// Author: Wolfgang Spraul
//
// This is free and unencumbered software released into the public domain.
// For details see the UNLICENSE file at the root of the source tree.
//
#include "model.h"
#include "control.h"
// for slx9 and slx9
#define NUM_ROWS 4
#define FRAMES_DATA_START 0
//#define FRAMES_DATA_LEN (NUM_ROWS*FRAMES_PER_ROW*XC6_FRAME_SIZE)
#define BRAM_DATA_START FRAMES_DATA_LEN
//#define BRAM_DATA_LEN (4*144*XC6_FRAME_SIZE)
#define IOB_DATA_START (BRAM_DATA_START + BRAM_DATA_LEN)
#define IOB_WORDS (cfg->reg[cfg->FLR_reg].int_v) // 16-bit words, for slx4 and slx9
//#define IOB_DATA_LEN (IOB_WORDS*2)
#define BITS_LEN (IOB_DATA_START+IOB_DATA_LEN)
const struct xc_die *xc_die_info(int idcode)
{
static const struct xc_die xc6slx9_info = {
.idcode = XC6SLX9,
.num_logical_rows = 73,
.num_logical_cols = 45,
.num_rows = 4, // num_logical-5/17 5=2t+1c+2b 17=8+c+8
.num_cols = 18, // num_logical-(10-1)/2 10=5l+1c+5r
.num_bram_in_KB = 576,
.left_wiring =
/* row 3 */ "UWUWUWUW" "WWWWUUUU" \
/* row 2 */ "UUUUUUUU" "WWWWWWUU" \
/* row 1 */ "WWWUUWUU" "WUUWUUWU" \
/* row 0 */ "UWUUWUUW" "UUWWWWUU",
.right_wiring =
/* row 3 */ "UUWWUWUW" "WWWWUUUU" \
/* row 2 */ "UUUUUUUU" "WWWWWWUU" \
/* row 1 */ "WWWUUWUU" "WUUWUUWU" \
/* row 0 */ "UWUUWUUW" "UUWWWWUU",
.major_str = "M L Bg M L D M R M Ln M L Bg M L",
.num_majors = 18,
.majors = {
// maj_zero: 505 bytes = extra 8-bit for each minor?
[0] = { XC_MAJ_ZERO, 4 },
[1] = { XC_MAJ_LEFT, 30 },
[2] = { XC_MAJ_XM | XC_MAJ_TOP_BOT_IO, 31 },
[3] = { XC_MAJ_XL | XC_MAJ_TOP_BOT_IO, 30 },
[4] = { XC_MAJ_BRAM | XC_MAJ_GCLK_SEP, 25 },
[5] = { XC_MAJ_XM | XC_MAJ_TOP_BOT_IO, 31 },
[6] = { XC_MAJ_XL | XC_MAJ_TOP_BOT_IO, 30 },
[7] = { XC_MAJ_MACC, 24 },
[8] = { XC_MAJ_XM | XC_MAJ_TOP_BOT_IO, 31 },
[9] = { XC_MAJ_CENTER | XC_MAJ_TOP_BOT_IO, 31 },
[10] = { XC_MAJ_XM | XC_MAJ_TOP_BOT_IO, 31 },
[11] = { XC_MAJ_XL, 30 },
[12] = { XC_MAJ_XM | XC_MAJ_TOP_BOT_IO, 31 },
[13] = { XC_MAJ_XL | XC_MAJ_TOP_BOT_IO, 30 },
[14] = { XC_MAJ_BRAM | XC_MAJ_GCLK_SEP, 25 },
[15] = { XC_MAJ_XM | XC_MAJ_TOP_BOT_IO, 31 },
[16] = { XC_MAJ_XL | XC_MAJ_TOP_BOT_IO, 30 },
[17] = { XC_MAJ_RIGHT, 30 }},
.num_t2_ios = 224,
.t2_io = {
[0] = { .pair = 1, .pos_side = 1, .bank = 2, .y = XC6_SLX9_TOTAL_TILE_ROWS - BOT_OUTER_ROW, .x = 38, .type_idx = 3 },
[1] = { .pair = 1, .pos_side = 0, .bank = 2, .y = XC6_SLX9_TOTAL_TILE_ROWS - BOT_OUTER_ROW, .x = 38, .type_idx = 2 },
[2] = { .pair = 2, .pos_side = 1, .bank = 2, .y = XC6_SLX9_TOTAL_TILE_ROWS - BOT_OUTER_ROW, .x = 38, .type_idx = 0 },
[3] = { .pair = 2, .pos_side = 0, .bank = 2, .y = XC6_SLX9_TOTAL_TILE_ROWS - BOT_OUTER_ROW, .x = 38, .type_idx = 1 },
[4] = { .pair = 3, .pos_side = 1, .bank = 2, .y = XC6_SLX9_TOTAL_TILE_ROWS - BOT_OUTER_ROW, .x = 36, .type_idx = 3 },
[5] = { .pair = 3, .pos_side = 0, .bank = 2, .y = XC6_SLX9_TOTAL_TILE_ROWS - BOT_OUTER_ROW, .x = 36, .type_idx = 2 },
[6] = { .pair = 12, .pos_side = 1, .bank = 2, .y = XC6_SLX9_TOTAL_TILE_ROWS - BOT_OUTER_ROW, .x = 36, .type_idx = 0 },
[7] = { .pair = 12, .pos_side = 0, .bank = 2, .y = XC6_SLX9_TOTAL_TILE_ROWS - BOT_OUTER_ROW, .x = 36, .type_idx = 1 },
[8] = { .pair = 13, .pos_side = 1, .bank = 2, .y = XC6_SLX9_TOTAL_TILE_ROWS - BOT_OUTER_ROW, .x = 31, .type_idx = 3 },
[9] = { .pair = 13, .pos_side = 0, .bank = 2, .y = XC6_SLX9_TOTAL_TILE_ROWS - BOT_OUTER_ROW, .x = 31, .type_idx = 2 },
[10] = { .pair = 14, .pos_side = 1, .bank = 2, .y = XC6_SLX9_TOTAL_TILE_ROWS - BOT_OUTER_ROW, .x = 31, .type_idx = 0 },
[11] = { .pair = 14, .pos_side = 0, .bank = 2, .y = XC6_SLX9_TOTAL_TILE_ROWS - BOT_OUTER_ROW, .x = 31, .type_idx = 1 },
[12] = { .pair = 23, .pos_side = 1, .bank = 2, .y = XC6_SLX9_TOTAL_TILE_ROWS - BOT_OUTER_ROW, .x = 29, .type_idx = 3 },
[13] = { .pair = 23, .pos_side = 0, .bank = 2, .y = XC6_SLX9_TOTAL_TILE_ROWS - BOT_OUTER_ROW, .x = 29, .type_idx = 2 },
[14] = { .pair = 16, .pos_side = 1, .bank = 2, .y = XC6_SLX9_TOTAL_TILE_ROWS - BOT_OUTER_ROW, .x = 29, .type_idx = 0 },
[15] = { .pair = 16, .pos_side = 0, .bank = 2, .y = XC6_SLX9_TOTAL_TILE_ROWS - BOT_OUTER_ROW, .x = 29, .type_idx = 1 },
[16] = { .pair = 29, .pos_side = 1, .bank = 2, .y = XC6_SLX9_TOTAL_TILE_ROWS - BOT_OUTER_ROW, .x = 25, .type_idx = 3 },
[17] = { .pair = 29, .pos_side = 0, .bank = 2, .y = XC6_SLX9_TOTAL_TILE_ROWS - BOT_OUTER_ROW, .x = 25, .type_idx = 2 },
[18] = { .pair = 30, .pos_side = 1, .bank = 2, .y = XC6_SLX9_TOTAL_TILE_ROWS - BOT_OUTER_ROW, .x = 25, .type_idx = 0 },
[19] = { .pair = 30, .pos_side = 0, .bank = 2, .y = XC6_SLX9_TOTAL_TILE_ROWS - BOT_OUTER_ROW, .x = 25, .type_idx = 1 },
// 20-25 are for gclk switches and remain 0
[26] = { .pair = 31, .pos_side = 1, .bank = 2, .y = XC6_SLX9_TOTAL_TILE_ROWS - BOT_OUTER_ROW, .x = 21, .type_idx = 3 },
[27] = { .pair = 31, .pos_side = 0, .bank = 2, .y = XC6_SLX9_TOTAL_TILE_ROWS - BOT_OUTER_ROW, .x = 21, .type_idx = 2 },
[28] = { .pair = 32, .pos_side = 1, .bank = 2, .y = XC6_SLX9_TOTAL_TILE_ROWS - BOT_OUTER_ROW, .x = 21, .type_idx = 0 },
[29] = { .pair = 32, .pos_side = 0, .bank = 2, .y = XC6_SLX9_TOTAL_TILE_ROWS - BOT_OUTER_ROW, .x = 21, .type_idx = 1 },
[30] = { .pair = 45, .pos_side = 1, .bank = 2, .y = XC6_SLX9_TOTAL_TILE_ROWS - BOT_OUTER_ROW, .x = 19, .type_idx = 3 },
[31] = { .pair = 45, .pos_side = 0, .bank = 2, .y = XC6_SLX9_TOTAL_TILE_ROWS - BOT_OUTER_ROW, .x = 19, .type_idx = 2 },
[32] = { .pair = 41, .pos_side = 1, .bank = 2, .y = XC6_SLX9_TOTAL_TILE_ROWS - BOT_OUTER_ROW, .x = 19, .type_idx = 0 },
[33] = { .pair = 41, .pos_side = 0, .bank = 2, .y = XC6_SLX9_TOTAL_TILE_ROWS - BOT_OUTER_ROW, .x = 19, .type_idx = 1 },
[34] = { .pair = 43, .pos_side = 1, .bank = 2, .y = XC6_SLX9_TOTAL_TILE_ROWS - BOT_OUTER_ROW, .x = 14, .type_idx = 3 },
[35] = { .pair = 43, .pos_side = 0, .bank = 2, .y = XC6_SLX9_TOTAL_TILE_ROWS - BOT_OUTER_ROW, .x = 14, .type_idx = 2 },
[36] = { .pair = 46, .pos_side = 1, .bank = 2, .y = XC6_SLX9_TOTAL_TILE_ROWS - BOT_OUTER_ROW, .x = 14, .type_idx = 0 },
[37] = { .pair = 46, .pos_side = 0, .bank = 2, .y = XC6_SLX9_TOTAL_TILE_ROWS - BOT_OUTER_ROW, .x = 14, .type_idx = 1 },
[38] = { .pair = 48, .pos_side = 1, .bank = 2, .y = XC6_SLX9_TOTAL_TILE_ROWS - BOT_OUTER_ROW, .x = 12, .type_idx = 3 },
[39] = { .pair = 48, .pos_side = 0, .bank = 2, .y = XC6_SLX9_TOTAL_TILE_ROWS - BOT_OUTER_ROW, .x = 12, .type_idx = 2 },
[40] = { .pair = 49, .pos_side = 1, .bank = 2, .y = XC6_SLX9_TOTAL_TILE_ROWS - BOT_OUTER_ROW, .x = 12, .type_idx = 0 },
[41] = { .pair = 49, .pos_side = 0, .bank = 2, .y = XC6_SLX9_TOTAL_TILE_ROWS - BOT_OUTER_ROW, .x = 12, .type_idx = 1 },
[42] = { .pair = 62, .pos_side = 1, .bank = 2, .y = XC6_SLX9_TOTAL_TILE_ROWS - BOT_OUTER_ROW, .x = 7, .type_idx = 3 },
[43] = { .pair = 62, .pos_side = 0, .bank = 2, .y = XC6_SLX9_TOTAL_TILE_ROWS - BOT_OUTER_ROW, .x = 7, .type_idx = 2 },
[44] = { .pair = 63, .pos_side = 1, .bank = 2, .y = XC6_SLX9_TOTAL_TILE_ROWS - BOT_OUTER_ROW, .x = 7, .type_idx = 0 },
[45] = { .pair = 63, .pos_side = 0, .bank = 2, .y = XC6_SLX9_TOTAL_TILE_ROWS - BOT_OUTER_ROW, .x = 7, .type_idx = 1 },
[46] = { .pair = 64, .pos_side = 1, .bank = 2, .y = XC6_SLX9_TOTAL_TILE_ROWS - BOT_OUTER_ROW, .x = 5, .type_idx = 3 },
[47] = { .pair = 64, .pos_side = 0, .bank = 2, .y = XC6_SLX9_TOTAL_TILE_ROWS - BOT_OUTER_ROW, .x = 5, .type_idx = 2 },
[48] = { .pair = 65, .pos_side = 1, .bank = 2, .y = XC6_SLX9_TOTAL_TILE_ROWS - BOT_OUTER_ROW, .x = 5, .type_idx = 0 },
[49] = { .pair = 65, .pos_side = 0, .bank = 2, .y = XC6_SLX9_TOTAL_TILE_ROWS - BOT_OUTER_ROW, .x = 5, .type_idx = 1 },
[50] = { .pair = 1, .pos_side = 1, .bank = 3, .y = 68, .x = LEFT_OUTER_COL, .type_idx = 1 },
[51] = { .pair = 1, .pos_side = 0, .bank = 3, .y = 68, .x = LEFT_OUTER_COL, .type_idx = 0 },
[52] = { .pair = 2, .pos_side = 1, .bank = 3, .y = 67, .x = LEFT_OUTER_COL, .type_idx = 1 },
[53] = { .pair = 2, .pos_side = 0, .bank = 3, .y = 67, .x = LEFT_OUTER_COL, .type_idx = 0 },
[54] = { .pair = 31, .pos_side = 1, .bank = 3, .y = 66, .x = LEFT_OUTER_COL, .type_idx = 1 },
[55] = { .pair = 31, .pos_side = 0, .bank = 3, .y = 66, .x = LEFT_OUTER_COL, .type_idx = 0 },
[56] = { .pair = 32, .pos_side = 1, .bank = 3, .y = 65, .x = LEFT_OUTER_COL, .type_idx = 1 },
[57] = { .pair = 32, .pos_side = 0, .bank = 3, .y = 65, .x = LEFT_OUTER_COL, .type_idx = 0 },
[58] = { .pair = 33, .pos_side = 1, .bank = 3, .y = 61, .x = LEFT_OUTER_COL, .type_idx = 1 },
[59] = { .pair = 33, .pos_side = 0, .bank = 3, .y = 61, .x = LEFT_OUTER_COL, .type_idx = 0 },
[60] = { .pair = 34, .pos_side = 1, .bank = 3, .y = 58, .x = LEFT_OUTER_COL, .type_idx = 1 },
[61] = { .pair = 34, .pos_side = 0, .bank = 3, .y = 58, .x = LEFT_OUTER_COL, .type_idx = 0 },
[62] = { .pair = 35, .pos_side = 1, .bank = 3, .y = 55, .x = LEFT_OUTER_COL, .type_idx = 1 },
[63] = { .pair = 35, .pos_side = 0, .bank = 3, .y = 55, .x = LEFT_OUTER_COL, .type_idx = 0 },
[64] = { .pair = 36, .pos_side = 1, .bank = 3, .y = 52, .x = LEFT_OUTER_COL, .type_idx = 1 },
[65] = { .pair = 36, .pos_side = 0, .bank = 3, .y = 52, .x = LEFT_OUTER_COL, .type_idx = 0 },
[66] = { .pair = 37, .pos_side = 1, .bank = 3, .y = 49, .x = LEFT_OUTER_COL, .type_idx = 1 },
[67] = { .pair = 37, .pos_side = 0, .bank = 3, .y = 49, .x = LEFT_OUTER_COL, .type_idx = 0 },
[68] = { .pair = 38, .pos_side = 1, .bank = 3, .y = 46, .x = LEFT_OUTER_COL, .type_idx = 1 },
[69] = { .pair = 38, .pos_side = 0, .bank = 3, .y = 46, .x = LEFT_OUTER_COL, .type_idx = 0 },
[70] = { .pair = 39, .pos_side = 1, .bank = 3, .y = 42, .x = LEFT_OUTER_COL, .type_idx = 1 },
[71] = { .pair = 39, .pos_side = 0, .bank = 3, .y = 42, .x = LEFT_OUTER_COL, .type_idx = 0 },
[72] = { .pair = 40, .pos_side = 1, .bank = 3, .y = 39, .x = LEFT_OUTER_COL, .type_idx = 1 },
[73] = { .pair = 40, .pos_side = 0, .bank = 3, .y = 39, .x = LEFT_OUTER_COL, .type_idx = 0 },
[74] = { .pair = 41, .pos_side = 1, .bank = 3, .y = 38, .x = LEFT_OUTER_COL, .type_idx = 1 },
[75] = { .pair = 41, .pos_side = 0, .bank = 3, .y = 38, .x = LEFT_OUTER_COL, .type_idx = 0 },
[76] = { .pair = 42, .pos_side = 1, .bank = 3, .y = 37, .x = LEFT_OUTER_COL, .type_idx = 1 },
[77] = { .pair = 42, .pos_side = 0, .bank = 3, .y = 37, .x = LEFT_OUTER_COL, .type_idx = 0 },
// 78-83 are for gclk switches and remain 0
[84] = { .pair = 43, .pos_side = 1, .bank = 3, .y = 33, .x = LEFT_OUTER_COL, .type_idx = 1 },
[85] = { .pair = 43, .pos_side = 0, .bank = 3, .y = 33, .x = LEFT_OUTER_COL, .type_idx = 0 },
[86] = { .pair = 44, .pos_side = 1, .bank = 3, .y = 32, .x = LEFT_OUTER_COL, .type_idx = 1 },
[87] = { .pair = 44, .pos_side = 0, .bank = 3, .y = 32, .x = LEFT_OUTER_COL, .type_idx = 0 },
[88] = { .pair = 45, .pos_side = 1, .bank = 3, .y = 31, .x = LEFT_OUTER_COL, .type_idx = 1 },
[89] = { .pair = 45, .pos_side = 0, .bank = 3, .y = 31, .x = LEFT_OUTER_COL, .type_idx = 0 },
[90] = { .pair = 46, .pos_side = 1, .bank = 3, .y = 30, .x = LEFT_OUTER_COL, .type_idx = 1 },
[91] = { .pair = 46, .pos_side = 0, .bank = 3, .y = 30, .x = LEFT_OUTER_COL, .type_idx = 0 },
[92] = { .pair = 47, .pos_side = 1, .bank = 3, .y = 29, .x = LEFT_OUTER_COL, .type_idx = 1 },
[93] = { .pair = 47, .pos_side = 0, .bank = 3, .y = 29, .x = LEFT_OUTER_COL, .type_idx = 0 },
[94] = { .pair = 48, .pos_side = 1, .bank = 3, .y = 28, .x = LEFT_OUTER_COL, .type_idx = 1 },
[95] = { .pair = 48, .pos_side = 0, .bank = 3, .y = 28, .x = LEFT_OUTER_COL, .type_idx = 0 },
[96] = { .pair = 49, .pos_side = 1, .bank = 3, .y = 14, .x = LEFT_OUTER_COL, .type_idx = 1 },
[97] = { .pair = 49, .pos_side = 0, .bank = 3, .y = 14, .x = LEFT_OUTER_COL, .type_idx = 0 },
[98] = { .pair = 50, .pos_side = 1, .bank = 3, .y = 13, .x = LEFT_OUTER_COL, .type_idx = 1 },
[99] = { .pair = 50, .pos_side = 0, .bank = 3, .y = 13, .x = LEFT_OUTER_COL, .type_idx = 0 },
[100] = { .pair = 51, .pos_side = 1, .bank = 3, .y = 12, .x = LEFT_OUTER_COL, .type_idx = 1 },
[101] = { .pair = 51, .pos_side = 0, .bank = 3, .y = 12, .x = LEFT_OUTER_COL, .type_idx = 0 },
[102] = { .pair = 52, .pos_side = 1, .bank = 3, .y = 11, .x = LEFT_OUTER_COL, .type_idx = 1 },
[103] = { .pair = 52, .pos_side = 0, .bank = 3, .y = 11, .x = LEFT_OUTER_COL, .type_idx = 0 },
[104] = { .pair = 53, .pos_side = 1, .bank = 3, .y = 9, .x = LEFT_OUTER_COL, .type_idx = 1 },
[105] = { .pair = 53, .pos_side = 0, .bank = 3, .y = 9, .x = LEFT_OUTER_COL, .type_idx = 0 },
[106] = { .pair = 54, .pos_side = 1, .bank = 3, .y = 7, .x = LEFT_OUTER_COL, .type_idx = 1 },
[107] = { .pair = 54, .pos_side = 0, .bank = 3, .y = 7, .x = LEFT_OUTER_COL, .type_idx = 0 },
[108] = { .pair = 55, .pos_side = 1, .bank = 3, .y = 5, .x = LEFT_OUTER_COL, .type_idx = 1 },
[109] = { .pair = 55, .pos_side = 0, .bank = 3, .y = 5, .x = LEFT_OUTER_COL, .type_idx = 0 },
[110] = { .pair = 83, .pos_side = 1, .bank = 3, .y = 3, .x = LEFT_OUTER_COL, .type_idx = 1 },
[111] = { .pair = 83, .pos_side = 0, .bank = 3, .y = 3, .x = LEFT_OUTER_COL, .type_idx = 0 },
[112] = { .pair = 1, .pos_side = 1, .bank = 0, .y = TOP_OUTER_ROW, .x = 5, .type_idx = 0 },
[113] = { .pair = 1, .pos_side = 0, .bank = 0, .y = TOP_OUTER_ROW, .x = 5, .type_idx = 1 },
[114] = { .pair = 2, .pos_side = 1, .bank = 0, .y = TOP_OUTER_ROW, .x = 5, .type_idx = 2 },
[115] = { .pair = 2, .pos_side = 0, .bank = 0, .y = TOP_OUTER_ROW, .x = 5, .type_idx = 3 },
[116] = { .pair = 3, .pos_side = 1, .bank = 0, .y = TOP_OUTER_ROW, .x = 7, .type_idx = 0 },
[117] = { .pair = 3, .pos_side = 0, .bank = 0, .y = TOP_OUTER_ROW, .x = 7, .type_idx = 1 },
[118] = { .pair = 4, .pos_side = 1, .bank = 0, .y = TOP_OUTER_ROW, .x = 7, .type_idx = 2 },
[119] = { .pair = 4, .pos_side = 0, .bank = 0, .y = TOP_OUTER_ROW, .x = 7, .type_idx = 3 },
[120] = { .pair = 5, .pos_side = 1, .bank = 0, .y = TOP_OUTER_ROW, .x = 12, .type_idx = 0 },
[121] = { .pair = 5, .pos_side = 0, .bank = 0, .y = TOP_OUTER_ROW, .x = 12, .type_idx = 1 },
[122] = { .pair = 6, .pos_side = 1, .bank = 0, .y = TOP_OUTER_ROW, .x = 12, .type_idx = 2 },
[123] = { .pair = 6, .pos_side = 0, .bank = 0, .y = TOP_OUTER_ROW, .x = 12, .type_idx = 3 },
[124] = { .pair = 10, .pos_side = 1, .bank = 0, .y = TOP_OUTER_ROW, .x = 14, .type_idx = 0 },
[125] = { .pair = 10, .pos_side = 0, .bank = 0, .y = TOP_OUTER_ROW, .x = 14, .type_idx = 1 },
[126] = { .pair = 8, .pos_side = 1, .bank = 0, .y = TOP_OUTER_ROW, .x = 14, .type_idx = 2 },
[127] = { .pair = 8, .pos_side = 0, .bank = 0, .y = TOP_OUTER_ROW, .x = 14, .type_idx = 3 },
[128] = { .pair = 11, .pos_side = 1, .bank = 0, .y = TOP_OUTER_ROW, .x = 19, .type_idx = 0 },
[129] = { .pair = 11, .pos_side = 0, .bank = 0, .y = TOP_OUTER_ROW, .x = 19, .type_idx = 1 },
[130] = { .pair = 33, .pos_side = 1, .bank = 0, .y = TOP_OUTER_ROW, .x = 19, .type_idx = 2 },
[131] = { .pair = 33, .pos_side = 0, .bank = 0, .y = TOP_OUTER_ROW, .x = 19, .type_idx = 3 },
[132] = { .pair = 34, .pos_side = 1, .bank = 0, .y = TOP_OUTER_ROW, .x = 21, .type_idx = 0 },
[133] = { .pair = 34, .pos_side = 0, .bank = 0, .y = TOP_OUTER_ROW, .x = 21, .type_idx = 1 },
[134] = { .pair = 35, .pos_side = 1, .bank = 0, .y = TOP_OUTER_ROW, .x = 21, .type_idx = 2 },
[135] = { .pair = 35, .pos_side = 0, .bank = 0, .y = TOP_OUTER_ROW, .x = 21, .type_idx = 3 },
// 136-141 are for gclk switches and remain 0
[142] = { .pair = 36, .pos_side = 1, .bank = 0, .y = TOP_OUTER_ROW, .x = 25, .type_idx = 0 },
[143] = { .pair = 36, .pos_side = 0, .bank = 0, .y = TOP_OUTER_ROW, .x = 25, .type_idx = 1 },
[144] = { .pair = 37, .pos_side = 1, .bank = 0, .y = TOP_OUTER_ROW, .x = 25, .type_idx = 2 },
[145] = { .pair = 37, .pos_side = 0, .bank = 0, .y = TOP_OUTER_ROW, .x = 25, .type_idx = 3 },
[146] = { .pair = 38, .pos_side = 1, .bank = 0, .y = TOP_OUTER_ROW, .x = 29, .type_idx = 0 },
[147] = { .pair = 38, .pos_side = 0, .bank = 0, .y = TOP_OUTER_ROW, .x = 29, .type_idx = 1 },
[148] = { .pair = 39, .pos_side = 1, .bank = 0, .y = TOP_OUTER_ROW, .x = 29, .type_idx = 2 },
[149] = { .pair = 39, .pos_side = 0, .bank = 0, .y = TOP_OUTER_ROW, .x = 29, .type_idx = 3 },
[150] = { .pair = 41, .pos_side = 1, .bank = 0, .y = TOP_OUTER_ROW, .x = 31, .type_idx = 0 },
[151] = { .pair = 41, .pos_side = 0, .bank = 0, .y = TOP_OUTER_ROW, .x = 31, .type_idx = 1 },
[152] = { .pair = 62, .pos_side = 1, .bank = 0, .y = TOP_OUTER_ROW, .x = 31, .type_idx = 2 },
[153] = { .pair = 62, .pos_side = 0, .bank = 0, .y = TOP_OUTER_ROW, .x = 31, .type_idx = 3 },
[154] = { .pair = 63, .pos_side = 1, .bank = 0, .y = TOP_OUTER_ROW, .x = 36, .type_idx = 0 },
[155] = { .pair = 63, .pos_side = 0, .bank = 0, .y = TOP_OUTER_ROW, .x = 36, .type_idx = 1 },
[156] = { .pair = 64, .pos_side = 1, .bank = 0, .y = TOP_OUTER_ROW, .x = 36, .type_idx = 2 },
[157] = { .pair = 64, .pos_side = 0, .bank = 0, .y = TOP_OUTER_ROW, .x = 36, .type_idx = 3 },
[158] = { .pair = 65, .pos_side = 1, .bank = 0, .y = TOP_OUTER_ROW, .x = 38, .type_idx = 0 },
[159] = { .pair = 65, .pos_side = 0, .bank = 0, .y = TOP_OUTER_ROW, .x = 38, .type_idx = 1 },
[160] = { .pair = 66, .pos_side = 1, .bank = 0, .y = TOP_OUTER_ROW, .x = 38, .type_idx = 2 },
[161] = { .pair = 66, .pos_side = 0, .bank = 0, .y = TOP_OUTER_ROW, .x = 38, .type_idx = 3 },
[162] = { .pair = 1, .pos_side = 1, .bank = 1, .y = 4, .x = XC6_SLX9_TOTAL_TILE_COLS - RIGHT_OUTER_O, .type_idx = 0 },
[163] = { .pair = 1, .pos_side = 0, .bank = 1, .y = 4, .x = XC6_SLX9_TOTAL_TILE_COLS - RIGHT_OUTER_O, .type_idx = 1 },
[164] = { .pair = 29, .pos_side = 1, .bank = 1, .y = 5, .x = XC6_SLX9_TOTAL_TILE_COLS - RIGHT_OUTER_O, .type_idx = 0 },
[165] = { .pair = 29, .pos_side = 0, .bank = 1, .y = 5, .x = XC6_SLX9_TOTAL_TILE_COLS - RIGHT_OUTER_O, .type_idx = 1 },
[166] = { .pair = 30, .pos_side = 1, .bank = 1, .y = 7, .x = XC6_SLX9_TOTAL_TILE_COLS - RIGHT_OUTER_O, .type_idx = 0 },
[167] = { .pair = 30, .pos_side = 0, .bank = 1, .y = 7, .x = XC6_SLX9_TOTAL_TILE_COLS - RIGHT_OUTER_O, .type_idx = 1 },
[168] = { .pair = 31, .pos_side = 1, .bank = 1, .y = 9, .x = XC6_SLX9_TOTAL_TILE_COLS - RIGHT_OUTER_O, .type_idx = 0 },
[169] = { .pair = 31, .pos_side = 0, .bank = 1, .y = 9, .x = XC6_SLX9_TOTAL_TILE_COLS - RIGHT_OUTER_O, .type_idx = 1 },
[170] = { .pair = 32, .pos_side = 1, .bank = 1, .y = 11, .x = XC6_SLX9_TOTAL_TILE_COLS - RIGHT_OUTER_O, .type_idx = 0 },
[171] = { .pair = 32, .pos_side = 0, .bank = 1, .y = 11, .x = XC6_SLX9_TOTAL_TILE_COLS - RIGHT_OUTER_O, .type_idx = 1 },
[172] = { .pair = 33, .pos_side = 1, .bank = 1, .y = 12, .x = XC6_SLX9_TOTAL_TILE_COLS - RIGHT_OUTER_O, .type_idx = 0 },
[173] = { .pair = 33, .pos_side = 0, .bank = 1, .y = 12, .x = XC6_SLX9_TOTAL_TILE_COLS - RIGHT_OUTER_O, .type_idx = 1 },
[174] = { .pair = 34, .pos_side = 1, .bank = 1, .y = 13, .x = XC6_SLX9_TOTAL_TILE_COLS - RIGHT_OUTER_O, .type_idx = 0 },
[175] = { .pair = 34, .pos_side = 0, .bank = 1, .y = 13, .x = XC6_SLX9_TOTAL_TILE_COLS - RIGHT_OUTER_O, .type_idx = 1 },
[176] = { .pair = 35, .pos_side = 1, .bank = 1, .y = 14, .x = XC6_SLX9_TOTAL_TILE_COLS - RIGHT_OUTER_O, .type_idx = 0 },
[177] = { .pair = 35, .pos_side = 0, .bank = 1, .y = 14, .x = XC6_SLX9_TOTAL_TILE_COLS - RIGHT_OUTER_O, .type_idx = 1 },
[178] = { .pair = 36, .pos_side = 1, .bank = 1, .y = 28, .x = XC6_SLX9_TOTAL_TILE_COLS - RIGHT_OUTER_O, .type_idx = 0 },
[179] = { .pair = 36, .pos_side = 0, .bank = 1, .y = 28, .x = XC6_SLX9_TOTAL_TILE_COLS - RIGHT_OUTER_O, .type_idx = 1 },
[180] = { .pair = 37, .pos_side = 1, .bank = 1, .y = 29, .x = XC6_SLX9_TOTAL_TILE_COLS - RIGHT_OUTER_O, .type_idx = 0 },
[181] = { .pair = 37, .pos_side = 0, .bank = 1, .y = 29, .x = XC6_SLX9_TOTAL_TILE_COLS - RIGHT_OUTER_O, .type_idx = 1 },
[182] = { .pair = 38, .pos_side = 1, .bank = 1, .y = 30, .x = XC6_SLX9_TOTAL_TILE_COLS - RIGHT_OUTER_O, .type_idx = 0 },
[183] = { .pair = 38, .pos_side = 0, .bank = 1, .y = 30, .x = XC6_SLX9_TOTAL_TILE_COLS - RIGHT_OUTER_O, .type_idx = 1 },
[184] = { .pair = 39, .pos_side = 1, .bank = 1, .y = 31, .x = XC6_SLX9_TOTAL_TILE_COLS - RIGHT_OUTER_O, .type_idx = 0 },
[185] = { .pair = 39, .pos_side = 0, .bank = 1, .y = 31, .x = XC6_SLX9_TOTAL_TILE_COLS - RIGHT_OUTER_O, .type_idx = 1 },
[186] = { .pair = 40, .pos_side = 1, .bank = 1, .y = 32, .x = XC6_SLX9_TOTAL_TILE_COLS - RIGHT_OUTER_O, .type_idx = 0 },
[187] = { .pair = 40, .pos_side = 0, .bank = 1, .y = 32, .x = XC6_SLX9_TOTAL_TILE_COLS - RIGHT_OUTER_O, .type_idx = 1 },
[188] = { .pair = 41, .pos_side = 1, .bank = 1, .y = 33, .x = XC6_SLX9_TOTAL_TILE_COLS - RIGHT_OUTER_O, .type_idx = 0 },
[189] = { .pair = 41, .pos_side = 0, .bank = 1, .y = 33, .x = XC6_SLX9_TOTAL_TILE_COLS - RIGHT_OUTER_O, .type_idx = 1 },
// 190-195 are for gclk switches and remain 0
[196] = { .pair = 42, .pos_side = 1, .bank = 1, .y = 37, .x = XC6_SLX9_TOTAL_TILE_COLS - RIGHT_OUTER_O, .type_idx = 0 },
[197] = { .pair = 42, .pos_side = 0, .bank = 1, .y = 37, .x = XC6_SLX9_TOTAL_TILE_COLS - RIGHT_OUTER_O, .type_idx = 1 },
[198] = { .pair = 43, .pos_side = 1, .bank = 1, .y = 38, .x = XC6_SLX9_TOTAL_TILE_COLS - RIGHT_OUTER_O, .type_idx = 0 },
[199] = { .pair = 43, .pos_side = 0, .bank = 1, .y = 38, .x = XC6_SLX9_TOTAL_TILE_COLS - RIGHT_OUTER_O, .type_idx = 1 },
[200] = { .pair = 44, .pos_side = 1, .bank = 1, .y = 39, .x = XC6_SLX9_TOTAL_TILE_COLS - RIGHT_OUTER_O, .type_idx = 0 },
[201] = { .pair = 44, .pos_side = 0, .bank = 1, .y = 39, .x = XC6_SLX9_TOTAL_TILE_COLS - RIGHT_OUTER_O, .type_idx = 1 },
[202] = { .pair = 45, .pos_side = 1, .bank = 1, .y = 42, .x = XC6_SLX9_TOTAL_TILE_COLS - RIGHT_OUTER_O, .type_idx = 0 },
[203] = { .pair = 45, .pos_side = 0, .bank = 1, .y = 42, .x = XC6_SLX9_TOTAL_TILE_COLS - RIGHT_OUTER_O, .type_idx = 1 },
[204] = { .pair = 46, .pos_side = 1, .bank = 1, .y = 46, .x = XC6_SLX9_TOTAL_TILE_COLS - RIGHT_OUTER_O, .type_idx = 0 },
[205] = { .pair = 46, .pos_side = 0, .bank = 1, .y = 46, .x = XC6_SLX9_TOTAL_TILE_COLS - RIGHT_OUTER_O, .type_idx = 1 },
[206] = { .pair = 47, .pos_side = 1, .bank = 1, .y = 49, .x = XC6_SLX9_TOTAL_TILE_COLS - RIGHT_OUTER_O, .type_idx = 0 },
[207] = { .pair = 47, .pos_side = 0, .bank = 1, .y = 49, .x = XC6_SLX9_TOTAL_TILE_COLS - RIGHT_OUTER_O, .type_idx = 1 },
[208] = { .pair = 48, .pos_side = 1, .bank = 1, .y = 52, .x = XC6_SLX9_TOTAL_TILE_COLS - RIGHT_OUTER_O, .type_idx = 0 },
[209] = { .pair = 48, .pos_side = 0, .bank = 1, .y = 52, .x = XC6_SLX9_TOTAL_TILE_COLS - RIGHT_OUTER_O, .type_idx = 1 },
[210] = { .pair = 49, .pos_side = 1, .bank = 1, .y = 55, .x = XC6_SLX9_TOTAL_TILE_COLS - RIGHT_OUTER_O, .type_idx = 0 },
[211] = { .pair = 49, .pos_side = 0, .bank = 1, .y = 55, .x = XC6_SLX9_TOTAL_TILE_COLS - RIGHT_OUTER_O, .type_idx = 1 },
[212] = { .pair = 50, .pos_side = 1, .bank = 1, .y = 58, .x = XC6_SLX9_TOTAL_TILE_COLS - RIGHT_OUTER_O, .type_idx = 0 },
[213] = { .pair = 50, .pos_side = 0, .bank = 1, .y = 58, .x = XC6_SLX9_TOTAL_TILE_COLS - RIGHT_OUTER_O, .type_idx = 1 },
[214] = { .pair = 51, .pos_side = 1, .bank = 1, .y = 61, .x = XC6_SLX9_TOTAL_TILE_COLS - RIGHT_OUTER_O, .type_idx = 0 },
[215] = { .pair = 51, .pos_side = 0, .bank = 1, .y = 61, .x = XC6_SLX9_TOTAL_TILE_COLS - RIGHT_OUTER_O, .type_idx = 1 },
[216] = { .pair = 52, .pos_side = 1, .bank = 1, .y = 65, .x = XC6_SLX9_TOTAL_TILE_COLS - RIGHT_OUTER_O, .type_idx = 0 },
[217] = { .pair = 52, .pos_side = 0, .bank = 1, .y = 65, .x = XC6_SLX9_TOTAL_TILE_COLS - RIGHT_OUTER_O, .type_idx = 1 },
[218] = { .pair = 53, .pos_side = 1, .bank = 1, .y = 66, .x = XC6_SLX9_TOTAL_TILE_COLS - RIGHT_OUTER_O, .type_idx = 0 },
[219] = { .pair = 53, .pos_side = 0, .bank = 1, .y = 66, .x = XC6_SLX9_TOTAL_TILE_COLS - RIGHT_OUTER_O, .type_idx = 1 },
[220] = { .pair = 61, .pos_side = 1, .bank = 1, .y = 67, .x = XC6_SLX9_TOTAL_TILE_COLS - RIGHT_OUTER_O, .type_idx = 0 },
[221] = { .pair = 61, .pos_side = 0, .bank = 1, .y = 67, .x = XC6_SLX9_TOTAL_TILE_COLS - RIGHT_OUTER_O, .type_idx = 1 },
[222] = { .pair = 74, .pos_side = 1, .bank = 1, .y = 68, .x = XC6_SLX9_TOTAL_TILE_COLS - RIGHT_OUTER_O, .type_idx = 0 },
[223] = { .pair = 74, .pos_side = 0, .bank = 1, .y = 68, .x = XC6_SLX9_TOTAL_TILE_COLS - RIGHT_OUTER_O, .type_idx = 1 }},
// gclk: ug382 table 1-6 page 25
.num_gclk_pins = XC6_NUM_GCLK_PINS,
.gclk_t2_io_idx = { // indices into t2_io
/* 0 */ 19, 18, 17, 16,
/* 4 */ 199, 198, 197, 196,
/* 8 */ 189, 188, 187, 186,
/* 12 */ 145, 144, 143, 142,
/* 16 */ 135, 134, 133, 132,
/* 20 */ 87, 86, 85, 84,
/* 24 */ 77, 76, 75, 74,
/* 28 */ 29, 28, 27, 26 },
// todo: gclk 2,3,28,29 positions not yet verified
.gclk_t2_switches = { // 16-bit words into type2 data
/* 0 */ 20*4+ 6, 20*4+ 9, 20*4+ 0, 20*4+ 3,
/* 4 */ 190*4+18, 190*4+21, 190*4+12, 190*4+15,
/* 8 */ 190*4+ 6, 190*4+ 9, 190*4+ 0, 190*4+ 3,
/* 12 */ 136*4+18, 136*4+21, 136*4+12, 136*4+15,
/* 16 */ 136*4+ 6, 136*4+ 9, 136*4+ 0, 136*4+ 3,
/* 20 */ 78*4+21, 78*4+18, 78*4+15, 78*4+12,
/* 24 */ 78*4+ 9, 78*4+ 6, 78*4+ 3, 78*4+ 0,
/* 28 */ 20*4+18, 20*4+21, 20*4+12, 20*4+15 },
.mcb_ypos = 20,
.num_mui = 8,
.mui_pos = { 40, 43, 47, 50, 53, 56, 59, 63 },
.sel_logicin = {
24, 15, 7, 42, 5, 12, 62, 16,
47, 20, 38, 23, 48, 57, 44, 4 }};
switch (idcode & IDCODE_MASK) {
case XC6SLX9: return &xc6slx9_info;
}
HERE();
fprintf(stderr, "#E unknown id_code %i\n", idcode);
return 0;
}
int xc_die_center_major(const struct xc_die *die)
{
int i;
for (i = 0; i < die->num_majors; i++) {
if (die->majors[i].flags & XC_MAJ_CENTER)
return i;
}
HERE();
return -1;
}
const struct xc6_pkg_info *xc6_pkg_info(enum xc6_pkg pkg)
{
// see ug385
static const struct xc6_pkg_info pkg_tqg144 = {
.pkg = TQG144,
.num_pins = /*physical pinouts*/ 144 + /*on die but unbonded*/ 98,
.pin = {
// name bank bufio2 description pair pos_side
{ "P144", 0, "TL", "IO_L1P_HSWAPEN_0", 1, 1 },
{ "P143", 0, "TL", "IO_L1N_VREF_0", 1, 0 },
{ "P142", 0, "TL", "IO_L2P_0", 2, 1 },
{ "P141", 0, "TL", "IO_L2N_0", 2, 0 },
{ "P140", 0, "TL", "IO_L3P_0", 3, 1 },
{ "P139", 0, "TL", "IO_L3N_0", 3, 0 },
{ "P138", 0, "TL", "IO_L4P_0", 4, 1 },
{ "P137", 0, "TL", "IO_L4N_0", 4, 0 },
{ "P134", 0, "TL", "IO_L34P_GCLK19_0", 34, 1 },
{ "P133", 0, "TL", "IO_L34N_GCLK18_0", 34, 0 },
{ "P132", 0, "TL", "IO_L35P_GCLK17_0", 35, 1 },
{ "P131", 0, "TL", "IO_L35N_GCLK16_0", 35, 0 },
{ "P127", 0, "TR", "IO_L36P_GCLK15_0", 36, 1 },
{ "P126", 0, "TR", "IO_L36N_GCLK14_0", 36, 0 },
{ "P124", 0, "TR", "IO_L37P_GCLK13_0", 37, 1 },
{ "P123", 0, "TR", "IO_L37N_GCLK12_0", 37, 0 },
{ "P121", 0, "TR", "IO_L62P_0", 62, 1 },
{ "P120", 0, "TR", "IO_L62N_VREF_0", 62, 0 },
{ "P119", 0, "TR", "IO_L63P_SCP7_0", 63, 1 },
{ "P118", 0, "TR", "IO_L63N_SCP6_0", 63, 0 },
{ "P117", 0, "TR", "IO_L64P_SCP5_0", 64, 1 },
{ "P116", 0, "TR", "IO_L64N_SCP4_0", 64, 0 },
{ "P115", 0, "TR", "IO_L65P_SCP3_0", 65, 1 },
{ "P114", 0, "TR", "IO_L65N_SCP2_0", 65, 0 },
{ "P112", 0, "TR", "IO_L66P_SCP1_0", 66, 1 },
{ "P111", 0, "TR", "IO_L66N_SCP0_0", 66, 0 },
{ "P109", -1, "NA", "TCK", 0, 0 },
{ "P110", -1, "NA", "TDI", 0, 0 },
{ "P107", -1, "NA", "TMS", 0, 0 },
{ "P106", -1, "NA", "TDO", 0, 0 },
{ "P105", 1, "RT", "IO_L1P_1", 1, 1 },
{ "P104", 1, "RT", "IO_L1N_VREF_1", 1, 0 },
{ "P102", 1, "RT", "IO_L32P_1", 32, 1 },
{ "P101", 1, "RT", "IO_L32N_1", 32, 0 },
{ "P100", 1, "RT", "IO_L33P_1", 33, 1 },
{ "P99", 1, "RT", "IO_L33N_1", 33, 0 },
{ "P98", 1, "RT", "IO_L34P_1", 34, 1 },
{ "P97", 1, "RT", "IO_L34N_1", 34, 0 },
{ "P95", 1, "RT", "IO_L40P_GCLK11_1", 40, 1 },
{ "P94", 1, "RT", "IO_L40N_GCLK10_1", 40, 0 },
{ "P93", 1, "RT", "IO_L41P_GCLK9_IRDY1_1", 41, 1 },
{ "P92", 1, "RT", "IO_L41N_GCLK8_1", 41, 0 },
{ "P88", 1, "RB", "IO_L42P_GCLK7_1", 42, 1 },
{ "P87", 1, "RB", "IO_L42N_GCLK6_TRDY1_1", 42, 0 },
{ "P85", 1, "RB", "IO_L43P_GCLK5_1", 43, 1 },
{ "P84", 1, "RB", "IO_L43N_GCLK4_1", 43, 0 },
{ "P83", 1, "RB", "IO_L45P_1", 45, 1 },
{ "P82", 1, "RB", "IO_L45N_1", 45, 0 },
{ "P81", 1, "RB", "IO_L46P_1", 46, 1 },
{ "P80", 1, "RB", "IO_L46N_1", 46, 0 },
{ "P79", 1, "RB", "IO_L47P_1", 47, 1 },
{ "P78", 1, "RB", "IO_L47N_1", 47, 0 },
{ "P75", 1, "RB", "IO_L74P_AWAKE_1", 74, 1 },
{ "P74", 1, "RB", "IO_L74N_DOUT_BUSY_1", 74, 0 },
{ "P73", -1, "NA", "SUSPEND", 0, 0 },
{ "P72", 2, "NA", "CMPCS_B_2", 0, 0 },
{ "P71", 2, "NA", "DONE_2", 0, 0 },
{ "P70", 2, "BR", "IO_L1P_CCLK_2", 1, 1 },
{ "P69", 2, "BR", "IO_L1N_M0_CMPMISO_2", 1, 0 },
{ "P67", 2, "BR", "IO_L2P_CMPCLK_2", 2, 1 },
{ "P66", 2, "BR", "IO_L2N_CMPMOSI_2", 2, 0 },
{ "P65", 2, "BR", "IO_L3P_D0_DIN_MISO_MISO1_2", 3, 1 },
{ "P64", 2, "BR", "IO_L3N_MOSI_CSI_B_MISO0_2", 3, 0 },
{ "P62", 2, "BR", "IO_L12P_D1_MISO2_2", 12, 1 },
{ "P61", 2, "BR", "IO_L12N_D2_MISO3_2", 12, 0 },
{ "P60", 2, "BR", "IO_L13P_M1_2", 13, 1 },
{ "P59", 2, "BR", "IO_L13N_D10_2", 13, 0 },
{ "P58", 2, "BR", "IO_L14P_D11_2", 14, 1 },
{ "P57", 2, "BR", "IO_L14N_D12_2", 14, 0 },
{ "P56", 2, "BR", "IO_L30P_GCLK1_D13_2", 30, 1 },
{ "P55", 2, "BR", "IO_L30N_GCLK0_USERCCLK_2", 30, 0 },
{ "P51", 2, "BL", "IO_L31P_GCLK31_D14_2", 31, 1 },
{ "P50", 2, "BL", "IO_L31N_GCLK30_D15_2", 31, 0 },
{ "P48", 2, "BL", "IO_L48P_D7_2", 48, 1 },
{ "P47", 2, "BL", "IO_L48N_RDWR_B_VREF_2", 48, 0 },
{ "P46", 2, "BL", "IO_L49P_D3_2", 49, 1 },
{ "P45", 2, "BL", "IO_L49N_D4_2", 49, 0 },
{ "P44", 2, "BL", "IO_L62P_D5_2", 62, 1 },
{ "P43", 2, "BL", "IO_L62N_D6_2", 62, 0 },
{ "P41", 2, "BL", "IO_L64P_D8_2", 64, 1 },
{ "P40", 2, "BL", "IO_L64N_D9_2", 64, 0 },
{ "P39", 2, "BL", "IO_L65P_INIT_B_2", 65, 1 },
{ "P38", 2, "BL", "IO_L65N_CSO_B_2", 65, 0 },
{ "P37", 2, "NA", "PROGRAM_B_2", 0, 0 },
{ "P35", 3, "LB", "IO_L1P_3", 1, 1 },
{ "P34", 3, "LB", "IO_L1N_VREF_3", 1, 0 },
{ "P33", 3, "LB", "IO_L2P_3", 2, 1 },
{ "P32", 3, "LB", "IO_L2N_3", 2, 0 },
{ "P30", 3, "LB", "IO_L36P_3", 36, 1 },
{ "P29", 3, "LB", "IO_L36N_3", 36, 0 },
{ "P27", 3, "LB", "IO_L37P_3", 37, 1 },
{ "P26", 3, "LB", "IO_L37N_3", 37, 0 },
{ "P24", 3, "LB", "IO_L41P_GCLK27_3", 41, 1 },
{ "P23", 3, "LB", "IO_L41N_GCLK26_3", 41, 0 },
{ "P22", 3, "LB", "IO_L42P_GCLK25_TRDY2_3", 42, 1 },
{ "P21", 3, "LB", "IO_L42N_GCLK24_3", 42, 0 },
{ "P17", 3, "LT", "IO_L43P_GCLK23_3", 43, 1 },
{ "P16", 3, "LT", "IO_L43N_GCLK22_IRDY2_3", 43, 0 },
{ "P15", 3, "LT", "IO_L44P_GCLK21_3", 44, 1 },
{ "P14", 3, "LT", "IO_L44N_GCLK20_3", 44, 0 },
{ "P12", 3, "LT", "IO_L49P_3", 49, 1 },
{ "P11", 3, "LT", "IO_L49N_3", 49, 0 },
{ "P10", 3, "LT", "IO_L50P_3", 50, 1 },
{ "P9", 3, "LT", "IO_L50N_3", 50, 0 },
{ "P8", 3, "LT", "IO_L51P_3", 51, 1 },
{ "P7", 3, "LT", "IO_L51N_3", 51, 0 },
{ "P6", 3, "LT", "IO_L52P_3", 52, 1 },
{ "P5", 3, "LT", "IO_L52N_3", 52, 0 },
{ "P2", 3, "LT", "IO_L83P_3", 83, 1 },
{ "P1", 3, "LT", "IO_L83N_VREF_3", 83, 0 },
{ "P108", -1, "NA", "GND", 0, 0 },
{ "P113", -1, "NA", "GND", 0, 0 },
{ "P13", -1, "NA", "GND", 0, 0 },
{ "P130", -1, "NA", "GND", 0, 0 },
{ "P136", -1, "NA", "GND", 0, 0 },
{ "P25", -1, "NA", "GND", 0, 0 },
{ "P3", -1, "NA", "GND", 0, 0 },
{ "P49", -1, "NA", "GND", 0, 0 },
{ "P54", -1, "NA", "GND", 0, 0 },
{ "P68", -1, "NA", "GND", 0, 0 },
{ "P77", -1, "NA", "GND", 0, 0 },
{ "P91", -1, "NA", "GND", 0, 0 },
{ "P96", -1, "NA", "GND", 0, 0 },
{ "P129", -1, "NA", "VCCAUX", 0, 0 },
{ "P20", -1, "NA", "VCCAUX", 0, 0 },
{ "P36", -1, "NA", "VCCAUX", 0, 0 },
{ "P53", -1, "NA", "VCCAUX", 0, 0 },
{ "P90", -1, "NA", "VCCAUX", 0, 0 },
{ "P128", -1, "NA", "VCCINT", 0, 0 },
{ "P19", -1, "NA", "VCCINT", 0, 0 },
{ "P28", -1, "NA", "VCCINT", 0, 0 },
{ "P52", -1, "NA", "VCCINT", 0, 0 },
{ "P89", -1, "NA", "VCCINT", 0, 0 },
{ "P122", 0, "NA", "VCCO_0", 0, 0 },
{ "P125", 0, "NA", "VCCO_0", 0, 0 },
{ "P135", 0, "NA", "VCCO_0", 0, 0 },
{ "P103", 1, "NA", "VCCO_1", 0, 0 },
{ "P76", 1, "NA", "VCCO_1", 0, 0 },
{ "P86", 1, "NA", "VCCO_1", 0, 0 },
{ "P42", 2, "NA", "VCCO_2", 0, 0 },
{ "P63", 2, "NA", "VCCO_2", 0, 0 },
{ "P18", 3, "NA", "VCCO_3", 0, 0 },
{ "P31", 3, "NA", "VCCO_3", 0, 0 },
{ "P4", 3, "NA", "VCCO_3", 0, 0 },
// rest is unbonded (.description = 0)
{ "UNB113", 2, "BR", 0, 23, 1 },
{ "UNB114", 2, "BR", 0, 23, 0 },
{ "UNB115", 2, "BR", 0, 16, 1 },
{ "UNB116", 2, "BR", 0, 16, 0 },
{ "UNB117", 2, "BR", 0, 29, 1 },
{ "UNB118", 2, "BR", 0, 29, 0 },
{ "UNB123", 2, "BL", 0, 32, 1 },
{ "UNB124", 2, "BL", 0, 32, 0 },
{ "UNB125", 2, "BL", 0, 45, 1 },
{ "UNB126", 2, "BL", 0, 45, 0 },
{ "UNB127", 2, "BL", 0, 41, 1 },
{ "UNB128", 2, "BL", 0, 41, 0 },
{ "UNB129", 2, "BL", 0, 43, 1 },
{ "UNB130", 2, "BL", 0, 43, 0 },
{ "UNB131", 2, "BL", 0, 46, 1 },
{ "UNB132", 2, "BL", 0, 46, 0 },
{ "UNB139", 2, "BL", 0, 63, 1 },
{ "UNB140", 2, "BL", 0, 63, 0 },
{ "UNB149", 3, "LB", 0, 31, 1 },
{ "UNB150", 3, "LB", 0, 31, 0 },
{ "UNB151", 3, "LB", 0, 32, 1 },
{ "UNB152", 3, "LB", 0, 32, 0 },
{ "UNB153", 3, "LB", 0, 33, 1 },
{ "UNB154", 3, "LB", 0, 33, 0 },
{ "UNB155", 3, "LB", 0, 34, 1 },
{ "UNB156", 3, "LB", 0, 34, 0 },
{ "UNB157", 3, "LB", 0, 35, 1 },
{ "UNB158", 3, "LB", 0, 35, 0 },
{ "UNB163", 3, "LB", 0, 38, 1 },
{ "UNB164", 3, "LB", 0, 38, 0 },
{ "UNB165", 3, "LB", 0, 39, 1 },
{ "UNB166", 3, "LB", 0, 39, 0 },
{ "UNB167", 3, "LB", 0, 40, 1 },
{ "UNB168", 3, "LB", 0, 40, 0 },
{ "UNB177", 3, "LT", 0, 45, 1 },
{ "UNB178", 3, "LT", 0, 45, 0 },
{ "UNB179", 3, "LT", 0, 46, 1 },
{ "UNB180", 3, "LT", 0, 46, 0 },
{ "UNB181", 3, "LT", 0, 47, 1 },
{ "UNB182", 3, "LT", 0, 47, 0 },
{ "UNB183", 3, "LT", 0, 48, 1 },
{ "UNB184", 3, "LT", 0, 48, 0 },
{ "UNB193", 3, "LT", 0, 53, 1 },
{ "UNB194", 3, "LT", 0, 53, 0 },
{ "UNB195", 3, "LT", 0, 54, 1 },
{ "UNB196", 3, "LT", 0, 54, 0 },
{ "UNB197", 3, "LT", 0, 55, 1 },
{ "UNB198", 3, "LT", 0, 55, 0 },
{ "UNB9", 0, "TL", 0, 5, 1 },
{ "UNB10", 0, "TL", 0, 5, 0 },
{ "UNB11", 0, "TL", 0, 6, 1 },
{ "UNB12", 0, "TL", 0, 6, 0 },
{ "UNB13", 0, "TL", 0, 10, 1 },
{ "UNB14", 0, "TL", 0, 10, 0 },
{ "UNB15", 0, "TL", 0, 8, 1 },
{ "UNB16", 0, "TL", 0, 8, 0 },
{ "UNB17", 0, "TL", 0, 11, 1 },
{ "UNB18", 0, "TL", 0, 11, 0 },
{ "UNB19", 0, "TL", 0, 33, 1 },
{ "UNB20", 0, "TL", 0, 33, 0 },
{ "UNB29", 0, "TR", 0, 38, 1 },
{ "UNB30", 0, "TR", 0, 38, 0 },
{ "UNB31", 0, "TR", 0, 39, 1 },
{ "UNB32", 0, "TR", 0, 39, 0 },
{ "UNB33", 0, "TR", 0, 41, 1 },
{ "UNB34", 0, "TR", 0, 41, 0 },
{ "UNB47", 1, "RT", 0, 29, 1 },
{ "UNB48", 1, "RT", 0, 29, 0 },
{ "UNB49", 1, "RT", 0, 30, 1 },
{ "UNB50", 1, "RT", 0, 30, 0 },
{ "UNB51", 1, "RT", 0, 31, 1 },
{ "UNB52", 1, "RT", 0, 31, 0 },
{ "UNB59", 1, "RT", 0, 35, 1 },
{ "UNB60", 1, "RT", 0, 35, 0 },
{ "UNB61", 1, "RT", 0, 36, 1 },
{ "UNB62", 1, "RT", 0, 36, 0 },
{ "UNB63", 1, "RT", 0, 37, 1 },
{ "UNB64", 1, "RT", 0, 37, 0 },
{ "UNB65", 1, "RT", 0, 38, 1 },
{ "UNB66", 1, "RT", 0, 38, 0 },
{ "UNB67", 1, "RT", 0, 39, 1 },
{ "UNB68", 1, "RT", 0, 39, 0 },
{ "UNB77", 1, "RB", 0, 44, 1 },
{ "UNB78", 1, "RB", 0, 44, 0 },
{ "UNB85", 1, "RB", 0, 48, 1 },
{ "UNB86", 1, "RB", 0, 48, 0 },
{ "UNB87", 1, "RB", 0, 49, 1 },
{ "UNB88", 1, "RB", 0, 49, 0 },
{ "UNB89", 1, "RB", 0, 50, 1 },
{ "UNB90", 1, "RB", 0, 50, 0 },
{ "UNB91", 1, "RB", 0, 51, 1 },
{ "UNB92", 1, "RB", 0, 51, 0 },
{ "UNB93", 1, "RB", 0, 52, 1 },
{ "UNB94", 1, "RB", 0, 52, 0 },
{ "UNB95", 1, "RB", 0, 53, 1 },
{ "UNB96", 1, "RB", 0, 53, 0 },
{ "UNB97", 1, "RB", 0, 61, 1 },
{ "UNB98", 1, "RB", 0, 61, 0 }}};
static const struct xc6_pkg_info pkg_ftg256 = {
.pkg = FTG256,
// todo: any unbonded pins?
.num_pins = /*physical pinouts*/ 256 + /*on die but unbonded*/ 0,
// name bank bufio2 description pair pos_side
.pin = {
{ "C4", 0, "TL", "IO_L1P_HSWAPEN_0", 1, 1 },
{ "A4", 0, "TL", "IO_L1N_VREF_0", 1, 0 },
{ "B5", 0, "TL", "IO_L2P_0", 2, 1 },
{ "A5", 0, "TL", "IO_L2N_0", 2, 0 },
{ "D5", 0, "TL", "IO_L3P_0", 3, 1 },
{ "C5", 0, "TL", "IO_L3N_0", 3, 0 },
{ "B6", 0, "TL", "IO_L4P_0", 4, 1 },
{ "A6", 0, "TL", "IO_L4N_0", 4, 0 },
{ "F7", 0, "TL", "IO_L5P_0", 5, 1 },
{ "E6", 0, "TL", "IO_L5N_0", 5, 0 },
{ "C7", 0, "TL", "IO_L6P_0", 6, 1 },
{ "A7", 0, "TL", "IO_L6N_0", 6, 0 },
{ "D6", 0, "TL", "IO_L7P_0", 7, 1 },
{ "C6", 0, "TL", "IO_L7N_0", 7, 0 },
{ "B8", 0, "TL", "IO_L33P_0", 33, 1 },
{ "A8", 0, "TL", "IO_L33N_0", 33, 0 },
{ "C9", 0, "TL", "IO_L34P_GCLK19_0", 34, 1 },
{ "A9", 0, "TL", "IO_L34N_GCLK18_0", 34, 0 },
{ "B10", 0, "TL", "IO_L35P_GCLK17_0", 35, 1 },
{ "A10", 0, "TL", "IO_L35N_GCLK16_0", 35, 0 },
{ "E7", 0, "TR", "IO_L36P_GCLK15_0", 36, 1 },
{ "E8", 0, "TR", "IO_L36N_GCLK14_0", 36, 0 },
{ "E10", 0, "TR", "IO_L37P_GCLK13_0", 37, 1 },
{ "C10", 0, "TR", "IO_L37N_GCLK12_0", 37, 0 },
{ "D8", 0, "TR", "IO_L38P_0", 38, 1 },
{ "C8", 0, "TR", "IO_L38N_VREF_0", 38, 0 },
{ "C11", 0, "TR", "IO_L39P_0", 39, 1 },
{ "A11", 0, "TR", "IO_L39N_0", 39, 0 },
{ "F9", 0, "TR", "IO_L40P_0", 40, 1 },
{ "D9", 0, "TR", "IO_L40N_0", 40, 0 },
{ "B12", 0, "TR", "IO_L62P_0", 62, 1 },
{ "A12", 0, "TR", "IO_L62N_VREF_0", 62, 0 },
{ "C13", 0, "TR", "IO_L63P_SCP7_0", 63, 1 },
{ "A13", 0, "TR", "IO_L63N_SCP6_0", 63, 0 },
{ "F10", 0, "TR", "IO_L64P_SCP5_0", 64, 1 },
{ "E11", 0, "TR", "IO_L64N_SCP4_0", 64, 0 },
{ "B14", 0, "TR", "IO_L65P_SCP3_0", 65, 1 },
{ "A14", 0, "TR", "IO_L65N_SCP2_0", 65, 0 },
{ "D11", 0, "TR", "IO_L66P_SCP1_0", 66, 1 },
{ "D12", 0, "TR", "IO_L66N_SCP0_0", 66, 0 },
{ "C14", -1, "NA", "TCK" },
{ "C12", -1, "NA", "TDI" },
{ "A15", -1, "NA", "TMS" },
{ "E14", -1, "NA", "TDO" },
{ "E13", 1, "RT", "IO_L1P_A25_1", 1, 1 },
{ "E12", 1, "RT", "IO_L1N_A24_VREF_1", 1, 0 },
{ "B15", 1, "RT", "IO_L29P_A23_M1A13_1", 29, 1 },
{ "B16", 1, "RT", "IO_L29N_A22_M1A14_1", 29, 0 },
{ "F12", 1, "RT", "IO_L30P_A21_M1RESET_1", 30, 1 },
{ "G11", 1, "RT", "IO_L30N_A20_M1A11_1", 30, 0 },
{ "D14", 1, "RT", "IO_L31P_A19_M1CKE_1", 31, 1 },
{ "D16", 1, "RT", "IO_L31N_A18_M1A12_1", 31, 0 },
{ "F13", 1, "RT", "IO_L32P_A17_M1A8_1", 32, 1 },
{ "F14", 1, "RT", "IO_L32N_A16_M1A9_1", 32, 0 },
{ "C15", 1, "RT", "IO_L33P_A15_M1A10_1", 33, 1 },
{ "C16", 1, "RT", "IO_L33N_A14_M1A4_1", 33, 0 },
{ "E15", 1, "RT", "IO_L34P_A13_M1WE_1", 34, 1 },
{ "E16", 1, "RT", "IO_L34N_A12_M1BA2_1", 34, 0 },
{ "F15", 1, "RT", "IO_L35P_A11_M1A7_1", 35, 1 },
{ "F16", 1, "RT", "IO_L35N_A10_M1A2_1", 35, 0 },
{ "G14", 1, "RT", "IO_L36P_A9_M1BA0_1", 36, 1 },
{ "G16", 1, "RT", "IO_L36N_A8_M1BA1_1", 36, 0 },
{ "H15", 1, "RT", "IO_L37P_A7_M1A0_1", 37, 1 },
{ "H16", 1, "RT", "IO_L37N_A6_M1A1_1", 37, 0 },
{ "G12", 1, "RT", "IO_L38P_A5_M1CLK_1", 38, 1 },
{ "H11", 1, "RT", "IO_L38N_A4_M1CLKN_1", 38, 0 },
{ "H13", 1, "RT", "IO_L39P_M1A3_1", 39, 1 },
{ "H14", 1, "RT", "IO_L39N_M1ODT_1", 39, 0 },
{ "J11", 1, "RT", "IO_L40P_GCLK11_M1A5_1", 40, 1 },
{ "J12", 1, "RT", "IO_L40N_GCLK10_M1A6_1", 40, 0 },
{ "J13", 1, "RT", "IO_L41P_GCLK9_IRDY1_M1RASN_1", 41, 1 },
{ "K14", 1, "RT", "IO_L41N_GCLK8_M1CASN_1", 41, 0 },
{ "K12", 1, "RB", "IO_L42P_GCLK7_M1UDM_1", 42, 1 },
{ "K11", 1, "RB", "IO_L42N_GCLK6_TRDY1_M1LDM_1", 42, 0 },
{ "J14", 1, "RB", "IO_L43P_GCLK5_M1DQ4_1", 43, 1 },
{ "J16", 1, "RB", "IO_L43N_GCLK4_M1DQ5_1", 43, 0 },
{ "K15", 1, "RB", "IO_L44P_A3_M1DQ6_1", 44, 1 },
{ "K16", 1, "RB", "IO_L44N_A2_M1DQ7_1", 44, 0 },
{ "N14", 1, "RB", "IO_L45P_A1_M1LDQS_1", 45, 1 },
{ "N16", 1, "RB", "IO_L45N_A0_M1LDQSN_1", 45, 0 },
{ "M15", 1, "RB", "IO_L46P_FCS_B_M1DQ2_1", 46, 1 },
{ "M16", 1, "RB", "IO_L46N_FOE_B_M1DQ3_1", 46, 0 },
{ "L14", 1, "RB", "IO_L47P_FWE_B_M1DQ0_1", 47, 1 },
{ "L16", 1, "RB", "IO_L47N_LDC_M1DQ1_1", 47, 0 },
{ "P15", 1, "RB", "IO_L48P_HDC_M1DQ8_1", 48, 1 },
{ "P16", 1, "RB", "IO_L48N_M1DQ9_1", 48, 0 },
{ "R15", 1, "RB", "IO_L49P_M1DQ10_1", 49, 1 },
{ "R16", 1, "RB", "IO_L49N_M1DQ11_1", 49, 0 },
{ "R14", 1, "RB", "IO_L50P_M1UDQS_1", 50, 1 },
{ "T15", 1, "RB", "IO_L50N_M1UDQSN_1", 50, 0 },
{ "T14", 1, "RB", "IO_L51P_M1DQ12_1", 51, 1 },
{ "T13", 1, "RB", "IO_L51N_M1DQ13_1", 51, 0 },
{ "R12", 1, "RB", "IO_L52P_M1DQ14_1", 52, 1 },
{ "T12", 1, "RB", "IO_L52N_M1DQ15_1", 52, 0 },
{ "L12", 1, "RB", "IO_L53P_1", 53, 1 },
{ "L13", 1, "RB", "IO_L53N_VREF_1", 53, 0 },
{ "M13", 1, "RB", "IO_L74P_AWAKE_1", 74, 1 },
{ "M14", 1, "RB", "IO_L74N_DOUT_BUSY_1", 74, 0 },
{ "P14", -1, "NA", "SUSPEND" },
{ "L11", 2, "NA", "CMPCS_B_2" },
{ "P13", 2, "NA", "DONE_2" },
{ "R11", 2, "BR", "IO_L1P_CCLK_2", 1, 1 },
{ "T11", 2, "BR", "IO_L1N_M0_CMPMISO_2", 1, 0 },
{ "M12", 2, "BR", "IO_L2P_CMPCLK_2", 2, 1 },
{ "M11", 2, "BR", "IO_L2N_CMPMOSI_2", 2, 0 },
{ "P10", 2, "BR", "IO_L3P_D0_DIN_MISO_MISO1_2", 3, 1 },
{ "T10", 2, "BR", "IO_L3N_MOSI_CSI_B_MISO0_2", 3, 0 },
{ "N12", 2, "BR", "IO_L12P_D1_MISO2_2", 12, 1 },
{ "P12", 2, "BR", "IO_L12N_D2_MISO3_2", 12, 0 },
{ "N11", 2, "BR", "IO_L13P_M1_2", 13, 1 },
{ "P11", 2, "BR", "IO_L13N_D10_2", 13, 0 },
{ "N9", 2, "BR", "IO_L14P_D11_2", 14, 1 },
{ "P9", 2, "BR", "IO_L14N_D12_2", 14, 0 },
{ "R9", 2, "BR", "IO_L23P_2", 23, 1 },
{ "T9", 2, "BR", "IO_L23N_2", 23, 0 },
{ "L10", 2, "BR", "IO_L16P_2", 16, 1 },
{ "M10", 2, "BR", "IO_L16N_VREF_2", 16, 0 },
{ "M9", 2, "BR", "IO_L29P_GCLK3_2", 29, 1 },
{ "N8", 2, "BR", "IO_L29N_GCLK2_2", 29, 0 },
{ "P8", 2, "BR", "IO_L30P_GCLK1_D13_2", 30, 1 },
{ "T8", 2, "BR", "IO_L30N_GCLK0_USERCCLK_2", 30, 0 },
{ "P7", 2, "BL", "IO_L31P_GCLK31_D14_2", 31, 1 },
{ "M7", 2, "BL", "IO_L31N_GCLK30_D15_2", 31, 0 },
{ "R7", 2, "BL", "IO_L32P_GCLK29_2", 32, 1 },
{ "T7", 2, "BL", "IO_L32N_GCLK28_2", 32, 0 },
{ "P6", 2, "BL", "IO_L47P_2", 47, 1 },
{ "T6", 2, "BL", "IO_L47N_2", 47, 0 },
{ "R5", 2, "BL", "IO_L48P_D7_2", 48, 1 },
{ "T5", 2, "BL", "IO_L48N_RDWR_B_VREF_2", 48, 0 },
{ "N5", 2, "BL", "IO_L49P_D3_2", 49, 1 },
{ "P5", 2, "BL", "IO_L49N_D4_2", 49, 0 },
{ "L8", 2, "BL", "IO_L62P_D5_2", 62, 1 },
{ "L7", 2, "BL", "IO_L62N_D6_2", 62, 0 },
{ "P4", 2, "BL", "IO_L63P_2", 63, 1 },
{ "T4", 2, "BL", "IO_L63N_2", 63, 0 },
{ "M6", 2, "BL", "IO_L64P_D8_2", 64, 1 },
{ "N6", 2, "BL", "IO_L64N_D9_2", 64, 0 },
{ "R3", 2, "BL", "IO_L65P_INIT_B_2", 65, 1 },
{ "T3", 2, "BL", "IO_L65N_CSO_B_2", 65, 0 },
{ "T2", 2, "NA", "PROGRAM_B_2" },
{ "M4", 3, "LB", "IO_L1P_3", 1, 1 },
{ "M3", 3, "LB", "IO_L1N_VREF_3", 1, 0 },
{ "M5", 3, "LB", "IO_L2P_3", 2, 1 },
{ "N4", 3, "LB", "IO_L2N_3", 2, 0 },
{ "R2", 3, "LB", "IO_L32P_M3DQ14_3", 32, 1 },
{ "R1", 3, "LB", "IO_L32N_M3DQ15_3", 32, 0 },
{ "P2", 3, "LB", "IO_L33P_M3DQ12_3", 33, 1 },
{ "P1", 3, "LB", "IO_L33N_M3DQ13_3", 33, 0 },
{ "N3", 3, "LB", "IO_L34P_M3UDQS_3", 34, 1 },
{ "N1", 3, "LB", "IO_L34N_M3UDQSN_3", 34, 0 },
{ "M2", 3, "LB", "IO_L35P_M3DQ10_3", 35, 1 },
{ "M1", 3, "LB", "IO_L35N_M3DQ11_3", 35, 0 },
{ "L3", 3, "LB", "IO_L36P_M3DQ8_3", 36, 1 },
{ "L1", 3, "LB", "IO_L36N_M3DQ9_3", 36, 0 },
{ "K2", 3, "LB", "IO_L37P_M3DQ0_3", 37, 1 },
{ "K1", 3, "LB", "IO_L37N_M3DQ1_3", 37, 0 },
{ "J3", 3, "LB", "IO_L38P_M3DQ2_3", 38, 1 },
{ "J1", 3, "LB", "IO_L38N_M3DQ3_3", 38, 0 },
{ "H2", 3, "LB", "IO_L39P_M3LDQS_3", 39, 1 },
{ "H1", 3, "LB", "IO_L39N_M3LDQSN_3", 39, 0 },
{ "G3", 3, "LB", "IO_L40P_M3DQ6_3", 40, 1 },
{ "G1", 3, "LB", "IO_L40N_M3DQ7_3", 40, 0 },
{ "F2", 3, "LB", "IO_L41P_GCLK27_M3DQ4_3", 41, 1 },
{ "F1", 3, "LB", "IO_L41N_GCLK26_M3DQ5_3", 41, 0 },
{ "K3", 3, "LB", "IO_L42P_GCLK25_TRDY2_M3UDM_3", 42, 1 },
{ "J4", 3, "LB", "IO_L42N_GCLK24_M3LDM_3", 42, 0 },
{ "J6", 3, "LT", "IO_L43P_GCLK23_M3RASN_3", 43, 1 },
{ "H5", 3, "LT", "IO_L43N_GCLK22_IRDY2_M3CASN_3", 43, 0 },
{ "H4", 3, "LT", "IO_L44P_GCLK21_M3A5_3", 44, 1 },
{ "H3", 3, "LT", "IO_L44N_GCLK20_M3A6_3", 44, 0 },
{ "L4", 3, "LT", "IO_L45P_M3A3_3", 45, 1 },
{ "L5", 3, "LT", "IO_L45N_M3ODT_3", 45, 0 },
{ "E2", 3, "LT", "IO_L46P_M3CLK_3", 46, 1 },
{ "E1", 3, "LT", "IO_L46N_M3CLKN_3", 46, 0 },
{ "K5", 3, "LT", "IO_L47P_M3A0_3", 47, 1 },
{ "K6", 3, "LT", "IO_L47N_M3A1_3", 47, 0 },
{ "C3", 3, "LT", "IO_L48P_M3BA0_3", 48, 1 },
{ "C2", 3, "LT", "IO_L48N_M3BA1_3", 48, 0 },
{ "D3", 3, "LT", "IO_L49P_M3A7_3", 49, 1 },
{ "D1", 3, "LT", "IO_L49N_M3A2_3", 49, 0 },
{ "C1", 3, "LT", "IO_L50P_M3WE_3", 50, 1 },
{ "B1", 3, "LT", "IO_L50N_M3BA2_3", 50, 0 },
{ "G6", 3, "LT", "IO_L51P_M3A10_3", 51, 1 },
{ "G5", 3, "LT", "IO_L51N_M3A4_3", 51, 0 },
{ "B2", 3, "LT", "IO_L52P_M3A8_3", 52, 1 },
{ "A2", 3, "LT", "IO_L52N_M3A9_3", 52, 0 },
{ "F4", 3, "LT", "IO_L53P_M3CKE_3", 53, 1 },
{ "F3", 3, "LT", "IO_L53N_M3A12_3", 53, 0 },
{ "E4", 3, "LT", "IO_L54P_M3RESET_3", 54, 1 },
{ "E3", 3, "LT", "IO_L54N_M3A11_3", 54, 0 },
{ "F6", 3, "LT", "IO_L55P_M3A13_3", 55, 1 },
{ "F5", 3, "LT", "IO_L55N_M3A14_3", 55, 0 },
{ "B3", 3, "LT", "IO_L83P_3", 83, 1 },
{ "A3", 3, "LT", "IO_L83N_VREF_3", 83, 0 },
{ "A1", -1, "NA", "GND" },
{ "A16", -1, "NA", "GND" },
{ "B11", -1, "NA", "GND" },
{ "B7", -1, "NA", "GND" },
{ "D13", -1, "NA", "GND" },
{ "D4", -1, "NA", "GND" },
{ "E9", -1, "NA", "GND" },
{ "G15", -1, "NA", "GND" },
{ "G2", -1, "NA", "GND" },
{ "G8", -1, "NA", "GND" },
{ "H12", -1, "NA", "GND" },
{ "H7", -1, "NA", "GND" },
{ "H9", -1, "NA", "GND" },
{ "J5", -1, "NA", "GND" },
{ "J8", -1, "NA", "GND" },
{ "K7", -1, "NA", "GND" },
{ "K9", -1, "NA", "GND" },
{ "L15", -1, "NA", "GND" },
{ "L2", -1, "NA", "GND" },
{ "M8", -1, "NA", "GND" },
{ "N13", -1, "NA", "GND" },
{ "P3", -1, "NA", "GND" },
{ "R10", -1, "NA", "GND" },
{ "R6", -1, "NA", "GND" },
{ "T1", -1, "NA", "GND" },
{ "T16", -1, "NA", "GND" },
{ "E5", -1, "NA", "VCCAUX" },
{ "F11", -1, "NA", "VCCAUX" },
{ "F8", -1, "NA", "VCCAUX" },
{ "G10", -1, "NA", "VCCAUX" },
{ "H6", -1, "NA", "VCCAUX" },
{ "J10", -1, "NA", "VCCAUX" },
{ "L6", -1, "NA", "VCCAUX" },
{ "L9", -1, "NA", "VCCAUX" },
{ "G7", -1, "NA", "VCCINT" },
{ "G9", -1, "NA", "VCCINT" },
{ "H10", -1, "NA", "VCCINT" },
{ "H8", -1, "NA", "VCCINT" },
{ "J7", -1, "NA", "VCCINT" },
{ "J9", -1, "NA", "VCCINT" },
{ "K10", -1, "NA", "VCCINT" },
{ "K8", -1, "NA", "VCCINT" },
{ "B13", 0, "NA", "VCCO_0" },
{ "B4", 0, "NA", "VCCO_0" },
{ "B9", 0, "NA", "VCCO_0" },
{ "D10", 0, "NA", "VCCO_0" },
{ "D7", 0, "NA", "VCCO_0" },
{ "D15", 1, "NA", "VCCO_1" },
{ "G13", 1, "NA", "VCCO_1" },
{ "J15", 1, "NA", "VCCO_1" },
{ "K13", 1, "NA", "VCCO_1" },
{ "N15", 1, "NA", "VCCO_1" },
{ "R13", 1, "NA", "VCCO_1" },
{ "N10", 2, "NA", "VCCO_2" },
{ "N7", 2, "NA", "VCCO_2" },
{ "R4", 2, "NA", "VCCO_2" },
{ "R8", 2, "NA", "VCCO_2" },
{ "D2", 3, "NA", "VCCO_3" },
{ "G4", 3, "NA", "VCCO_3" },
{ "J2", 3, "NA", "VCCO_3" },
{ "K4", 3, "NA", "VCCO_3" },
{ "N2", 3, "NA", "VCCO_3" }}};
static const struct xc6_pkg_info pkg_csg324 = {
.pkg = CSG324,
.num_pins = 324,
.pin = {
{ "D4", 0, "TL", "IO_L1P_HSWAPEN_0", 1, 1 },
{ "C4", 0, "TL", "IO_L1N_VREF_0", 1, 0 },
{ "B2", 0, "TL", "IO_L2P_0", 2, 1 },
{ "A2", 0, "TL", "IO_L2N_0", 2, 0 },
{ "D6", 0, "TL", "IO_L3P_0", 3, 1 },
{ "C6", 0, "TL", "IO_L3N_0", 3, 0 },
{ "B3", 0, "TL", "IO_L4P_0", 4, 1 },
{ "A3", 0, "TL", "IO_L4N_0", 4, 0 },
{ "B4", 0, "TL", "IO_L5P_0", 5, 1 },
{ "A4", 0, "TL", "IO_L5N_0", 5, 0 },
{ "C5", 0, "TL", "IO_L6P_0", 6, 1 },
{ "A5", 0, "TL", "IO_L6N_0", 6, 0 },
{ "F7", 0, "TL", "IO_L7P_0", 7, 1 },
{ "E6", 0, "TL", "IO_L7N_0", 7, 0 },
{ "B6", 0, "TL", "IO_L8P_0", 8, 1 },
{ "A6", 0, "TL", "IO_L8N_VREF_0", 8, 0 },
{ "E7", 0, "TL", "IO_L9P_0", 9, 1 },
{ "E8", 0, "TL", "IO_L9N_0", 9, 0 },
{ "C7", 0, "TL", "IO_L10P_0", 10, 1 },
{ "A7", 0, "TL", "IO_L10N_0", 10, 0 },
{ "D8", 0, "TL", "IO_L11P_0", 11, 1 },
{ "C8", 0, "TL", "IO_L11N_0", 11, 0 },
{ "G8", 0, "TL", "IO_L32P_0", 32, 1 },
{ "F8", 0, "TL", "IO_L32N_0", 32, 0 },
{ "B8", 0, "TL", "IO_L33P_0", 33, 1 },
{ "A8", 0, "TL", "IO_L33N_0", 33, 0 },
{ "D9", 0, "TL", "IO_L34P_GCLK19_0", 34, 1 },
{ "C9", 0, "TL", "IO_L34N_GCLK18_0", 34, 0 },
{ "B9", 0, "TL", "IO_L35P_GCLK17_0", 35, 1 },
{ "A9", 0, "TL", "IO_L35N_GCLK16_0", 35, 0 },
{ "D11", 0, "TR", "IO_L36P_GCLK15_0", 36, 1 },
{ "C11", 0, "TR", "IO_L36N_GCLK14_0", 36, 0 },
{ "C10", 0, "TR", "IO_L37P_GCLK13_0", 37, 1 },
{ "A10", 0, "TR", "IO_L37N_GCLK12_0", 37, 0 },
{ "G9", 0, "TR", "IO_L38P_0", 38, 1 },
{ "F9", 0, "TR", "IO_L38N_VREF_0", 38, 0 },
{ "B11", 0, "TR", "IO_L39P_0", 39, 1 },
{ "A11", 0, "TR", "IO_L39N_0", 39, 0 },
{ "G11", 0, "TR", "IO_L40P_0", 40, 1 },
{ "F10", 0, "TR", "IO_L40N_0", 40, 0 },
{ "B12", 0, "TR", "IO_L41P_0", 41, 1 },
{ "A12", 0, "TR", "IO_L41N_0", 41, 0 },
{ "F11", 0, "TR", "IO_L42P_0", 42, 1 },
{ "E11", 0, "TR", "IO_L42N_0", 42, 0 },
{ "D12", 0, "TR", "IO_L47P_0", 47, 1 },
{ "C12", 0, "TR", "IO_L47N_0", 47, 0 },
{ "C13", 0, "TR", "IO_L50P_0", 50, 1 },
{ "A13", 0, "TR", "IO_L50N_0", 50, 0 },
{ "F12", 0, "TR", "IO_L51P_0", 51, 1 },
{ "E12", 0, "TR", "IO_L51N_0", 51, 0 },
{ "B14", 0, "TR", "IO_L62P_0", 62, 1 },
{ "A14", 0, "TR", "IO_L62N_VREF_0", 62, 0 },
{ "F13", 0, "TR", "IO_L63P_SCP7_0", 63, 1 },
{ "E13", 0, "TR", "IO_L63N_SCP6_0", 63, 0 },
{ "C15", 0, "TR", "IO_L64P_SCP5_0", 64, 1 },
{ "A15", 0, "TR", "IO_L64N_SCP4_0", 64, 0 },
{ "D14", 0, "TR", "IO_L65P_SCP3_0", 65, 1 },
{ "C14", 0, "TR", "IO_L65N_SCP2_0", 65, 0 },
{ "B16", 0, "TR", "IO_L66P_SCP1_0", 66, 1 },
{ "A16", 0, "TR", "IO_L66N_SCP0_0", 66, 0 },
{ "A17", 0, "NA", "TCK", 0, 0 },
{ "D15", 0, "NA", "TDI", 0, 0 },
{ "B18", 0, "NA", "TMS", 0, 0 },
{ "D16", 0, "NA", "TDO", 0, 0 },
{ "F15", 1, "RT", "IO_L1P_A25_1", 1, 1 },
{ "F16", 1, "RT", "IO_L1N_A24_VREF_1", 1, 0 },
{ "C17", 1, "RT", "IO_L29P_A23_M1A13_1", 29, 1 },
{ "C18", 1, "RT", "IO_L29N_A22_M1A14_1", 29, 0 },
{ "F14", 1, "RT", "IO_L30P_A21_M1RESET_1", 30, 1 },
{ "G14", 1, "RT", "IO_L30N_A20_M1A11_1", 30, 0 },
{ "D17", 1, "RT", "IO_L31P_A19_M1CKE_1", 31, 1 },
{ "D18", 1, "RT", "IO_L31N_A18_M1A12_1", 31, 0 },
{ "H12", 1, "RT", "IO_L32P_A17_M1A8_1", 32, 1 },
{ "G13", 1, "RT", "IO_L32N_A16_M1A9_1", 32, 0 },
{ "E16", 1, "RT", "IO_L33P_A15_M1A10_1", 33, 1 },
{ "E18", 1, "RT", "IO_L33N_A14_M1A4_1", 33, 0 },
{ "K12", 1, "RT", "IO_L34P_A13_M1WE_1", 34, 1 },
{ "K13", 1, "RT", "IO_L34N_A12_M1BA2_1", 34, 0 },
{ "F17", 1, "RT", "IO_L35P_A11_M1A7_1", 35, 1 },
{ "F18", 1, "RT", "IO_L35N_A10_M1A2_1", 35, 0 },
{ "H13", 1, "RT", "IO_L36P_A9_M1BA0_1", 36, 1 },
{ "H14", 1, "RT", "IO_L36N_A8_M1BA1_1", 36, 0 },
{ "H15", 1, "RT", "IO_L37P_A7_M1A0_1", 37, 1 },
{ "H16", 1, "RT", "IO_L37N_A6_M1A1_1", 37, 0 },
{ "G16", 1, "RT", "IO_L38P_A5_M1CLK_1", 38, 1 },
{ "G18", 1, "RT", "IO_L38N_A4_M1CLKN_1", 38, 0 },
{ "J13", 1, "RT", "IO_L39P_M1A3_1", 39, 1 },
{ "K14", 1, "RT", "IO_L39N_M1ODT_1", 39, 0 },
{ "L12", 1, "RT", "IO_L40P_GCLK11_M1A5_1", 40, 1 },
{ "L13", 1, "RT", "IO_L40N_GCLK10_M1A6_1", 40, 0 },
{ "K15", 1, "RT", "IO_L41P_GCLK9_IRDY1_M1RASN_1", 41, 1 },
{ "K16", 1, "RT", "IO_L41N_GCLK8_M1CASN_1", 41, 0 },
{ "L15", 1, "RB", "IO_L42P_GCLK7_M1UDM_1", 42, 1 },
{ "L16", 1, "RB", "IO_L42N_GCLK6_TRDY1_M1LDM_1", 42, 0 },
{ "H17", 1, "RB", "IO_L43P_GCLK5_M1DQ4_1", 43, 1 },
{ "H18", 1, "RB", "IO_L43N_GCLK4_M1DQ5_1", 43, 0 },
{ "J16", 1, "RB", "IO_L44P_A3_M1DQ6_1", 44, 1 },
{ "J18", 1, "RB", "IO_L44N_A2_M1DQ7_1", 44, 0 },
{ "K17", 1, "RB", "IO_L45P_A1_M1LDQS_1", 45, 1 },
{ "K18", 1, "RB", "IO_L45N_A0_M1LDQSN_1", 45, 0 },
{ "L17", 1, "RB", "IO_L46P_FCS_B_M1DQ2_1", 46, 1 },
{ "L18", 1, "RB", "IO_L46N_FOE_B_M1DQ3_1", 46, 0 },
{ "M16", 1, "RB", "IO_L47P_FWE_B_M1DQ0_1", 47, 1 },
{ "M18", 1, "RB", "IO_L47N_LDC_M1DQ1_1", 47, 0 },
{ "N17", 1, "RB", "IO_L48P_HDC_M1DQ8_1", 48, 1 },
{ "N18", 1, "RB", "IO_L48N_M1DQ9_1", 48, 0 },
{ "P17", 1, "RB", "IO_L49P_M1DQ10_1", 49, 1 },
{ "P18", 1, "RB", "IO_L49N_M1DQ11_1", 49, 0 },
{ "N15", 1, "RB", "IO_L50P_M1UDQS_1", 50, 1 },
{ "N16", 1, "RB", "IO_L50N_M1UDQSN_1", 50, 0 },
{ "T17", 1, "RB", "IO_L51P_M1DQ12_1", 51, 1 },
{ "T18", 1, "RB", "IO_L51N_M1DQ13_1", 51, 0 },
{ "U17", 1, "RB", "IO_L52P_M1DQ14_1", 52, 1 },
{ "U18", 1, "RB", "IO_L52N_M1DQ15_1", 52, 0 },
{ "M14", 1, "RB", "IO_L53P_1", 53, 1 },
{ "N14", 1, "RB", "IO_L53N_VREF_1", 53, 0 },
{ "L14", 1, "RB", "IO_L61P_1", 61, 1 },
{ "M13", 1, "RB", "IO_L61N_1", 61, 0 },
{ "P15", 1, "RB", "IO_L74P_AWAKE_1", 74, 1 },
{ "P16", 1, "RB", "IO_L74N_DOUT_BUSY_1", 74, 0 },
{ "R16", 0, "NA", "SUSPEND", 0, 0 },
{ "P13", 2, "NA", "CMPCS_B_2", 0, 0 },
{ "V17", 2, "NA", "DONE_2", 0, 0 },
{ "R15", 2, "BR", "IO_L1P_CCLK_2", 1, 1 },
{ "T15", 2, "BR", "IO_L1N_M0_CMPMISO_2", 1, 0 },
{ "U16", 2, "BR", "IO_L2P_CMPCLK_2", 2, 1 },
{ "V16", 2, "BR", "IO_L2N_CMPMOSI_2", 2, 0 },
{ "R13", 2, "BR", "IO_L3P_D0_DIN_MISO_MISO1_2", 3, 1 },
{ "T13", 2, "BR", "IO_L3N_MOSI_CSI_B_MISO0_2", 3, 0 },
{ "U15", 2, "BR", "IO_L5P_2", 5, 1 },
{ "V15", 2, "BR", "IO_L5N_2", 5, 0 },
{ "T14", 2, "BR", "IO_L12P_D1_MISO2_2", 12, 1 },
{ "V14", 2, "BR", "IO_L12N_D2_MISO3_2", 12, 0 },
{ "N12", 2, "BR", "IO_L13P_M1_2", 13, 1 },
{ "P12", 2, "BR", "IO_L13N_D10_2", 13, 0 },
{ "U13", 2, "BR", "IO_L14P_D11_2", 14, 1 },
{ "V13", 2, "BR", "IO_L14N_D12_2", 14, 0 },
{ "M11", 2, "BR", "IO_L15P_2", 15, 1 },
{ "N11", 2, "BR", "IO_L15N_2", 15, 0 },
{ "R11", 2, "BR", "IO_L16P_2", 16, 1 },
{ "T11", 2, "BR", "IO_L16N_VREF_2", 16, 0 },
{ "T12", 2, "BR", "IO_L19P_2", 19, 1 },
{ "V12", 2, "BR", "IO_L19N_2", 19, 0 },
{ "N10", 2, "BR", "IO_L20P_2", 20, 1 },
{ "P11", 2, "BR", "IO_L20N_2", 20, 0 },
{ "M10", 2, "BR", "IO_L22P_2", 22, 1 },
{ "N9", 2, "BR", "IO_L22N_2", 22, 0 },
{ "U11", 2, "BR", "IO_L23P_2", 23, 1 },
{ "V11", 2, "BR", "IO_L23N_2", 23, 0 },
{ "R10", 2, "BR", "IO_L29P_GCLK3_2", 29, 1 },
{ "T10", 2, "BR", "IO_L29N_GCLK2_2", 29, 0 },
{ "U10", 2, "BR", "IO_L30P_GCLK1_D13_2", 30, 1 },
{ "V10", 2, "BR", "IO_L30N_GCLK0_USERCCLK_2", 30, 0 },
{ "R8", 2, "BL", "IO_L31P_GCLK31_D14_2", 31, 1 },
{ "T8", 2, "BL", "IO_L31N_GCLK30_D15_2", 31, 0 },
{ "T9", 2, "BL", "IO_L32P_GCLK29_2", 32, 1 },
{ "V9", 2, "BL", "IO_L32N_GCLK28_2", 32, 0 },
{ "M8", 2, "BL", "IO_L40P_2", 40, 1 },
{ "N8", 2, "BL", "IO_L40N_2", 40, 0 },
{ "U8", 2, "BL", "IO_L41P_2", 41, 1 },
{ "V8", 2, "BL", "IO_L41N_VREF_2", 41, 0 },
{ "U7", 2, "BL", "IO_L43P_2", 43, 1 },
{ "V7", 2, "BL", "IO_L43N_2", 43, 0 },
{ "N7", 2, "BL", "IO_L44P_2", 44, 1 },
{ "P8", 2, "BL", "IO_L44N_2", 44, 0 },
{ "T6", 2, "BL", "IO_L45P_2", 45, 1 },
{ "V6", 2, "BL", "IO_L45N_2", 45, 0 },
{ "R7", 2, "BL", "IO_L46P_2", 46, 1 },
{ "T7", 2, "BL", "IO_L46N_2", 46, 0 },
{ "N6", 2, "BL", "IO_L47P_2", 47, 1 },
{ "P7", 2, "BL", "IO_L47N_2", 47, 0 },
{ "R5", 2, "BL", "IO_L48P_D7_2", 48, 1 },
{ "T5", 2, "BL", "IO_L48N_RDWR_B_VREF_2", 48, 0 },
{ "U5", 2, "BL", "IO_L49P_D3_2", 49, 1 },
{ "V5", 2, "BL", "IO_L49N_D4_2", 49, 0 },
{ "R3", 2, "BL", "IO_L62P_D5_2", 62, 1 },
{ "T3", 2, "BL", "IO_L62N_D6_2", 62, 0 },
{ "T4", 2, "BL", "IO_L63P_2", 63, 1 },
{ "V4", 2, "BL", "IO_L63N_2", 63, 0 },
{ "N5", 2, "BL", "IO_L64P_D8_2", 64, 1 },
{ "P6", 2, "BL", "IO_L64N_D9_2", 64, 0 },
{ "U3", 2, "BL", "IO_L65P_INIT_B_2", 65, 1 },
{ "V3", 2, "BL", "IO_L65N_CSO_B_2", 65, 0 },
{ "V2", 2, "NA", "PROGRAM_B_2", 0, 0 },
{ "N4", 3, "LB", "IO_L1P_3", 1, 1 },
{ "N3", 3, "LB", "IO_L1N_VREF_3", 1, 0 },
{ "P4", 3, "LB", "IO_L2P_3", 2, 1 },
{ "P3", 3, "LB", "IO_L2N_3", 2, 0 },
{ "L6", 3, "LB", "IO_L31P_3", 31, 1 },
{ "M5", 3, "LB", "IO_L31N_VREF_3", 31, 0 },
{ "U2", 3, "LB", "IO_L32P_M3DQ14_3", 32, 1 },
{ "U1", 3, "LB", "IO_L32N_M3DQ15_3", 32, 0 },
{ "T2", 3, "LB", "IO_L33P_M3DQ12_3", 33, 1 },
{ "T1", 3, "LB", "IO_L33N_M3DQ13_3", 33, 0 },
{ "P2", 3, "LB", "IO_L34P_M3UDQS_3", 34, 1 },
{ "P1", 3, "LB", "IO_L34N_M3UDQSN_3", 34, 0 },
{ "N2", 3, "LB", "IO_L35P_M3DQ10_3", 35, 1 },
{ "N1", 3, "LB", "IO_L35N_M3DQ11_3", 35, 0 },
{ "M3", 3, "LB", "IO_L36P_M3DQ8_3", 36, 1 },
{ "M1", 3, "LB", "IO_L36N_M3DQ9_3", 36, 0 },
{ "L2", 3, "LB", "IO_L37P_M3DQ0_3", 37, 1 },
{ "L1", 3, "LB", "IO_L37N_M3DQ1_3", 37, 0 },
{ "K2", 3, "LB", "IO_L38P_M3DQ2_3", 38, 1 },
{ "K1", 3, "LB", "IO_L38N_M3DQ3_3", 38, 0 },
{ "L4", 3, "LB", "IO_L39P_M3LDQS_3", 39, 1 },
{ "L3", 3, "LB", "IO_L39N_M3LDQSN_3", 39, 0 },
{ "J3", 3, "LB", "IO_L40P_M3DQ6_3", 40, 1 },
{ "J1", 3, "LB", "IO_L40N_M3DQ7_3", 40, 0 },
{ "H2", 3, "LB", "IO_L41P_GCLK27_M3DQ4_3", 41, 1 },
{ "H1", 3, "LB", "IO_L41N_GCLK26_M3DQ5_3", 41, 0 },
{ "K4", 3, "LB", "IO_L42P_GCLK25_TRDY2_M3UDM_3", 42, 1 },
{ "K3", 3, "LB", "IO_L42N_GCLK24_M3LDM_3", 42, 0 },
{ "L5", 3, "LT", "IO_L43P_GCLK23_M3RASN_3", 43, 1 },
{ "K5", 3, "LT", "IO_L43N_GCLK22_IRDY2_M3CASN_3", 43, 0 },
{ "H4", 3, "LT", "IO_L44P_GCLK21_M3A5_3", 44, 1 },
{ "H3", 3, "LT", "IO_L44N_GCLK20_M3A6_3", 44, 0 },
{ "L7", 3, "LT", "IO_L45P_M3A3_3", 45, 1 },
{ "K6", 3, "LT", "IO_L45N_M3ODT_3", 45, 0 },
{ "G3", 3, "LT", "IO_L46P_M3CLK_3", 46, 1 },
{ "G1", 3, "LT", "IO_L46N_M3CLKN_3", 46, 0 },
{ "J7", 3, "LT", "IO_L47P_M3A0_3", 47, 1 },
{ "J6", 3, "LT", "IO_L47N_M3A1_3", 47, 0 },
{ "F2", 3, "LT", "IO_L48P_M3BA0_3", 48, 1 },
{ "F1", 3, "LT", "IO_L48N_M3BA1_3", 48, 0 },
{ "H6", 3, "LT", "IO_L49P_M3A7_3", 49, 1 },
{ "H5", 3, "LT", "IO_L49N_M3A2_3", 49, 0 },
{ "E3", 3, "LT", "IO_L50P_M3WE_3", 50, 1 },
{ "E1", 3, "LT", "IO_L50N_M3BA2_3", 50, 0 },
{ "F4", 3, "LT", "IO_L51P_M3A10_3", 51, 1 },
{ "F3", 3, "LT", "IO_L51N_M3A4_3", 51, 0 },
{ "D2", 3, "LT", "IO_L52P_M3A8_3", 52, 1 },
{ "D1", 3, "LT", "IO_L52N_M3A9_3", 52, 0 },
{ "H7", 3, "LT", "IO_L53P_M3CKE_3", 53, 1 },
{ "G6", 3, "LT", "IO_L53N_M3A12_3", 53, 0 },
{ "E4", 3, "LT", "IO_L54P_M3RESET_3", 54, 1 },
{ "D3", 3, "LT", "IO_L54N_M3A11_3", 54, 0 },
{ "F6", 3, "LT", "IO_L55P_M3A13_3", 55, 1 },
{ "F5", 3, "LT", "IO_L55N_M3A14_3", 55, 0 },
{ "C2", 3, "LT", "IO_L83P_3", 83, 1 },
{ "C1", 3, "LT", "IO_L83N_VREF_3", 83, 0 },
{ "A1", 0, "NA", "GND", 0, 0 },
{ "A18", 0, "NA", "GND", 0, 0 },
{ "B13", 0, "NA", "GND", 0, 0 },
{ "B7", 0, "NA", "GND", 0, 0 },
{ "C16", 0, "NA", "GND", 0, 0 },
{ "C3", 0, "NA", "GND", 0, 0 },
{ "D10", 0, "NA", "GND", 0, 0 },
{ "D5", 0, "NA", "GND", 0, 0 },
{ "E15", 0, "NA", "GND", 0, 0 },
{ "G12", 0, "NA", "GND", 0, 0 },
{ "G17", 0, "NA", "GND", 0, 0 },
{ "G2", 0, "NA", "GND", 0, 0 },
{ "G5", 0, "NA", "GND", 0, 0 },
{ "H10", 0, "NA", "GND", 0, 0 },
{ "H8", 0, "NA", "GND", 0, 0 },
{ "J11", 0, "NA", "GND", 0, 0 },
{ "J15", 0, "NA", "GND", 0, 0 },
{ "J4", 0, "NA", "GND", 0, 0 },
{ "J9", 0, "NA", "GND", 0, 0 },
{ "K10", 0, "NA", "GND", 0, 0 },
{ "K8", 0, "NA", "GND", 0, 0 },
{ "L11", 0, "NA", "GND", 0, 0 },
{ "L9", 0, "NA", "GND", 0, 0 },
{ "M17", 0, "NA", "GND", 0, 0 },
{ "M2", 0, "NA", "GND", 0, 0 },
{ "M6", 0, "NA", "GND", 0, 0 },
{ "N13", 0, "NA", "GND", 0, 0 },
{ "R1", 0, "NA", "GND", 0, 0 },
{ "R14", 0, "NA", "GND", 0, 0 },
{ "R18", 0, "NA", "GND", 0, 0 },
{ "R4", 0, "NA", "GND", 0, 0 },
{ "R9", 0, "NA", "GND", 0, 0 },
{ "T16", 0, "NA", "GND", 0, 0 },
{ "U12", 0, "NA", "GND", 0, 0 },
{ "U6", 0, "NA", "GND", 0, 0 },
{ "V1", 0, "NA", "GND", 0, 0 },
{ "V18", 0, "NA", "GND", 0, 0 },
{ "B1", 0, "NA", "VCCAUX", 0, 0 },
{ "B17", 0, "NA", "VCCAUX", 0, 0 },
{ "E14", 0, "NA", "VCCAUX", 0, 0 },
{ "E5", 0, "NA", "VCCAUX", 0, 0 },
{ "E9", 0, "NA", "VCCAUX", 0, 0 },
{ "G10", 0, "NA", "VCCAUX", 0, 0 },
{ "J12", 0, "NA", "VCCAUX", 0, 0 },
{ "K7", 0, "NA", "VCCAUX", 0, 0 },
{ "M9", 0, "NA", "VCCAUX", 0, 0 },
{ "P10", 0, "NA", "VCCAUX", 0, 0 },
{ "P14", 0, "NA", "VCCAUX", 0, 0 },
{ "P5", 0, "NA", "VCCAUX", 0, 0 },
{ "G7", 0, "NA", "VCCINT", 0, 0 },
{ "H11", 0, "NA", "VCCINT", 0, 0 },
{ "H9", 0, "NA", "VCCINT", 0, 0 },
{ "J10", 0, "NA", "VCCINT", 0, 0 },
{ "J8", 0, "NA", "VCCINT", 0, 0 },
{ "K11", 0, "NA", "VCCINT", 0, 0 },
{ "K9", 0, "NA", "VCCINT", 0, 0 },
{ "L10", 0, "NA", "VCCINT", 0, 0 },
{ "L8", 0, "NA", "VCCINT", 0, 0 },
{ "M12", 0, "NA", "VCCINT", 0, 0 },
{ "M7", 0, "NA", "VCCINT", 0, 0 },
{ "B10", 0, "NA", "VCCO_0", 0, 0 },
{ "B15", 0, "NA", "VCCO_0", 0, 0 },
{ "B5", 0, "NA", "VCCO_0", 0, 0 },
{ "D13", 0, "NA", "VCCO_0", 0, 0 },
{ "D7", 0, "NA", "VCCO_0", 0, 0 },
{ "E10", 0, "NA", "VCCO_0", 0, 0 },
{ "E17", 1, "NA", "VCCO_1", 0, 0 },
{ "G15", 1, "NA", "VCCO_1", 0, 0 },
{ "J14", 1, "NA", "VCCO_1", 0, 0 },
{ "J17", 1, "NA", "VCCO_1", 0, 0 },
{ "M15", 1, "NA", "VCCO_1", 0, 0 },
{ "R17", 1, "NA", "VCCO_1", 0, 0 },
{ "P9", 2, "NA", "VCCO_2", 0, 0 },
{ "R12", 2, "NA", "VCCO_2", 0, 0 },
{ "R6", 2, "NA", "VCCO_2", 0, 0 },
{ "U14", 2, "NA", "VCCO_2", 0, 0 },
{ "U4", 2, "NA", "VCCO_2", 0, 0 },
{ "U9", 2, "NA", "VCCO_2", 0, 0 },
{ "E2", 3, "NA", "VCCO_3", 0, 0 },
{ "G4", 3, "NA", "VCCO_3", 0, 0 },
{ "J2", 3, "NA", "VCCO_3", 0, 0 },
{ "J5", 3, "NA", "VCCO_3", 0, 0 },
{ "M4", 3, "NA", "VCCO_3", 0, 0 },
{ "R2", 3, "NA", "VCCO_3", 0, 0 }}};
switch (pkg) {
case TQG144: return &pkg_tqg144;
case FTG256: return &pkg_ftg256;
case CSG324: return &pkg_csg324;
default: ;
}
HERE();
return 0;
}
const char *xc6_find_pkg_pin(const struct xc6_pkg_info *pkg_info, const char *description)
{
int i;
for (i = 0; i < pkg_info->num_pins; i++) {
if (!strcmp(pkg_info->pin[i].description, description))
return pkg_info->pin[i].name;
}
HERE();
return 0;
}
int get_major_minors(int idcode, int major)
{
static const int minors_per_major[] = // for slx9
{
/* 0 */ 4, // 505 bytes = middle 8-bit for each minor?
/* 1 */ 30, // left
/* 2 */ 31, // logic M
/* 3 */ 30, // logic L
/* 4 */ 25, // bram
/* 5 */ 31, // logic M
/* 6 */ 30, // logic L
/* 7 */ 24, // macc
/* 8 */ 31, // logic M
/* 9 */ 31, // center
/* 10 */ 31, // logic M
/* 11 */ 30, // logic L
/* 12 */ 31, // logic M
/* 13 */ 30, // logic L
/* 14 */ 25, // bram
/* 15 */ 31, // logic M
/* 16 */ 30, // logic L
/* 17 */ 30, // right
};
if ((idcode & IDCODE_MASK) != XC6SLX9)
EXIT(1);
if (major < 0 || major
> sizeof(minors_per_major)/sizeof(minors_per_major[0]))
EXIT(1);
return minors_per_major[major];
}
enum major_type get_major_type(int idcode, int major)
{
static const int major_types[] = // for slx9
{
/* 0 */ MAJ_ZERO,
/* 1 */ MAJ_LEFT,
/* 2 */ MAJ_LOGIC_XM,
/* 3 */ MAJ_LOGIC_XL,
/* 4 */ MAJ_BRAM,
/* 5 */ MAJ_LOGIC_XM,
/* 6 */ MAJ_LOGIC_XL,
/* 7 */ MAJ_MACC,
/* 8 */ MAJ_LOGIC_XM,
/* 9 */ MAJ_CENTER,
/* 10 */ MAJ_LOGIC_XM,
/* 11 */ MAJ_LOGIC_XL,
/* 12 */ MAJ_LOGIC_XM,
/* 13 */ MAJ_LOGIC_XL,
/* 14 */ MAJ_BRAM,
/* 15 */ MAJ_LOGIC_XM,
/* 16 */ MAJ_LOGIC_XL,
/* 17 */ MAJ_RIGHT
};
if ((idcode & IDCODE_MASK) != XC6SLX9)
EXIT(1);
if (major < 0 || major
> sizeof(major_types)/sizeof(major_types[0]))
EXIT(1);
return major_types[major];
}
int get_rightside_major(int idcode)
{
if ((idcode & IDCODE_MASK) != XC6SLX9) {
HERE();
return -1;
}
return XC6_SLX9_RIGHTMOST_MAJOR;
}
int get_major_framestart(int idcode, int major)
{
int i, frame_count;
frame_count = 0;
for (i = 0; i < major; i++)
frame_count += get_major_minors(idcode, i);
return frame_count;
}
int get_frames_per_row(int idcode)
{
return get_major_framestart(idcode, get_rightside_major(idcode)+1);
}
//
// routing switches
//
struct sw_mip_src
{
int minor;
int m0_sw_to;
int m0_two_bits_o;
int m0_two_bits_val;
int m0_one_bit_start;
int m1_sw_to;
int m1_two_bits_o;
int m1_two_bits_val;
int m1_one_bit_start;
int from_w[6];
};
static int bidir_check(int sw_to, int sw_from)
{
// the first member of bidir switch pairs is where the bits reside
static const int bidir[] = {
LW + (LI_BX|LD1), FAN_B,
LW + (LI_AX|LD1), GFAN0,
LW + LI_AX, GFAN0,
LW + (LI_CE|LD1), GFAN1,
LW + (LI_CI|LD1), GFAN1,
LW + LI_BX, LW + (LI_CI|LD1),
LW + LI_BX, LW + (LI_DI|LD1),
LW + (LI_AX|LD1), LW + (LI_CI|LD1),
LW + (LI_BX|LD1), LW + (LI_CE|LD1),
LW + LI_AX, LW + (LI_CE|LD1) };
int i;
// bidirectional switches are ignored on one side, and
// marked as bidir on the other side
for (i = 0; i < sizeof(bidir)/sizeof(*bidir)/2; i++) {
if ((sw_from == bidir[i*2] && sw_to == bidir[i*2+1])
|| (sw_from == bidir[i*2+1] && sw_to == bidir[i*2]))
return 1;
}
return 0;
}
static int wire_decrement(int wire)
{
int _wire, flags;
if (wire >= DW && wire <= DW_LAST) {
_wire = wire - DW;
flags = _wire & DIR_FLAGS;
_wire &= ~DIR_FLAGS;
if (_wire%4 == 0)
return DW + ((_wire + 3) | flags);
return DW + ((_wire - 1) | flags);
}
if (wire >= LW && wire <= LW_LAST) {
_wire = wire - LW;
flags = _wire & LD1;
_wire &= ~LD1;
if (_wire == LO_A)
return LW + (LO_D|flags);
if (_wire == LO_AMUX)
return LW + (LO_DMUX|flags);
if (_wire == LO_AQ)
return LW + (LO_DQ|flags);
if ((_wire >= LO_B && _wire <= LO_D)
|| (_wire >= LO_BMUX && _wire <= LO_DMUX)
|| (_wire >= LO_BQ && _wire <= LO_DQ))
return LW + ((_wire-1)|flags);
}
if (wire == NO_WIRE) return wire;
HERE();
return wire;
}
static enum extra_wires clean_S0N3(enum extra_wires wire)
{
int flags;
if (wire < DW || wire > DW_LAST) return wire;
wire -= DW;
flags = wire & DIR_FLAGS;
wire &= ~DIR_FLAGS;
if (flags & DIR_S0 && wire%4 != 0)
flags &= ~DIR_S0;
if (flags & DIR_N3 && wire%4 != 3)
flags &= ~DIR_N3;
return DW + (wire | flags);
}
static int src_to_bitpos(struct xc6_routing_bitpos* bitpos, int* cur_el, int max_el,
const struct sw_mip_src* src, int src_len)
{
int i, j, rc;
for (i = 0; i < src_len; i++) {
for (j = 0; j < sizeof(src->from_w)/sizeof(src->from_w[0]); j++) {
if (src[i].from_w[j] == NO_WIRE) continue;
if (*cur_el >= max_el) FAIL(EINVAL);
bitpos[*cur_el].from = clean_S0N3(src[i].from_w[j]);
bitpos[*cur_el].to = clean_S0N3(src[i].m0_sw_to);
bitpos[*cur_el].bidir = bidir_check(src[i].m0_sw_to, src[i].from_w[j]);
bitpos[*cur_el].minor = src[i].minor;
bitpos[*cur_el].two_bits_o = src[i].m0_two_bits_o;
bitpos[*cur_el].two_bits_val = src[i].m0_two_bits_val;
bitpos[*cur_el].one_bit_o = src[i].m0_one_bit_start + j*2;
(*cur_el)++;
if (*cur_el >= max_el) FAIL(EINVAL);
bitpos[*cur_el].from = clean_S0N3(src[i].from_w[j]);
bitpos[*cur_el].to = clean_S0N3(src[i].m1_sw_to);
bitpos[*cur_el].bidir = bidir_check(src[i].m1_sw_to, src[i].from_w[j]);
bitpos[*cur_el].minor = src[i].minor;
bitpos[*cur_el].two_bits_o = src[i].m1_two_bits_o;
bitpos[*cur_el].two_bits_val = src[i].m1_two_bits_val;
bitpos[*cur_el].one_bit_o = src[i].m1_one_bit_start + j*2;
(*cur_el)++;
}
}
return 0;
fail:
return rc;
}
#define LOGIN_ROW 2
#define LOGIN_MIP_ROWS 8
static const int logicin_matrix[] =
{
/*mip 12*/
/* 000 */ LW + (LI_C6|LD1), LW + LI_D6,
/* 016 */ LW + (LI_B1|LD1), LW + (LI_DI|LD1),
/* 032 */ LW + (LI_C5|LD1), LW + LI_D5,
/* 048 */ LW + (LI_CI|LD1), LW + LI_A2,
/* 064 */ LW + (LI_C4|LD1), LW + LI_D4,
/* 080 */ LW + LI_A1, LW + LI_CE,
/* 096 */ LW + (LI_C3|LD1), LW + LI_D3,
/* 112 */ LW + (LI_B2|LD1), LW + (LI_WE|LD1),
/*mip 14*/
/* 000 */ LW + LI_C1, LW + LI_DX,
/* 016 */ LW + (LI_A3|LD1), LW + LI_B3,
/* 032 */ LW + (LI_CX|LD1), LW + (LI_D2|LD1),
/* 048 */ LW + (LI_A4|LD1), LW + LI_B4,
/* 064 */ LW + (LI_D1|LD1), LW + LI_BX,
/* 080 */ LW + (LI_A5|LD1), LW + LI_B5,
/* 096 */ LW + (LI_AX|LD1), LW + LI_C2,
/* 112 */ LW + (LI_A6|LD1), LW + LI_B6,
/*mip 16*/
/* 000 */ LW + (LI_B3|LD1), LW + LI_A3,
/* 016 */ LW + (LI_C2|LD1), LW + (LI_DX|LD1),
/* 032 */ LW + (LI_B4|LD1), LW + LI_A4,
/* 048 */ LW + LI_CX, LW + LI_D1,
/* 064 */ LW + (LI_B5|LD1), LW + LI_A5,
/* 080 */ LW + (LI_BX|LD1), LW + LI_D2,
/* 096 */ LW + (LI_B6|LD1), LW + LI_A6,
/* 112 */ LW + (LI_C1|LD1), LW + LI_AX,
/*mip 18*/
/* 000 */ LW + LI_B2, FAN_B,
/* 016 */ LW + (LI_D6|LD1), LW + LI_C6,
/* 032 */ LW + (LI_A1|LD1), LW + (LI_CE|LD1),
/* 048 */ LW + (LI_D5|LD1), LW + LI_C5,
/* 064 */ LW + (LI_A2|LD1), LW + (LI_BI|LD1),
/* 080 */ LW + (LI_D4|LD1), LW + LI_C4,
/* 096 */ LW + (LI_AI|LD1), LW + LI_B1,
/* 112 */ LW + (LI_D3|LD1), LW + LI_C3
};
static int mip_to_bitpos(struct xc6_routing_bitpos* bitpos, int* cur_el,
int max_el, int minor, int m0_two_bits_val, int m0_one_bit_start,
int m1_two_bits_val, int m1_one_bit_start, int (*from_ws)[8][6])
{
struct sw_mip_src src;
int i, j, rc;
src.minor = minor;
src.m0_two_bits_o = 0;
src.m0_two_bits_val = m0_two_bits_val;
src.m0_one_bit_start = m0_one_bit_start;
src.m1_two_bits_o = 14;
src.m1_two_bits_val = m1_two_bits_val;
src.m1_one_bit_start = m1_one_bit_start;
for (i = 0; i < 8; i++) {
int logicin_o = ((src.minor-12)/2)*LOGIN_MIP_ROWS*LOGIN_ROW;
logicin_o += i*LOGIN_ROW;
src.m0_sw_to = logicin_matrix[logicin_o+0];
src.m1_sw_to = logicin_matrix[logicin_o+1];
if (i) {
src.m0_two_bits_o += 16;
src.m0_one_bit_start += 16;
src.m1_two_bits_o += 16;
src.m1_one_bit_start += 16;
}
for (j = 0; j < sizeof(src.from_w)/sizeof(src.from_w[0]); j++)
src.from_w[j] = (*from_ws)[i][j];
rc = src_to_bitpos(bitpos, cur_el, max_el, &src, /*src_len*/ 1);
if (rc) FAIL(rc);
}
return 0;
fail:
return rc;
}
int get_xc6_routing_bitpos(struct xc6_routing_bitpos** bitpos, int* num_bitpos)
{
int i, j, k, rc;
*num_bitpos = 0;
*bitpos = malloc(MAX_SWITCHBOX_SIZE * sizeof(**bitpos));
if (!(*bitpos)) FAIL(ENOMEM);
// mip 0-10 (6*288=1728 switches)
{ struct sw_mip_src src[] = {
{0, DW + ((W_WW4*4+3) | DIR_BEG), 0, 2, 3,
DW + ((W_NW4*4+3) | DIR_BEG), 14, 1, 2,
{LW + (LO_BMUX|LD1), LW + (LO_DQ|LD1), LW + (LO_D|LD1),
LW + LO_BMUX, LW + LO_DQ, LW + LO_D}},
{0, DW + ((W_WW4*4+3) | DIR_BEG), 0, 1, 3,
DW + ((W_NW4*4+3) | DIR_BEG), 14, 2, 2,
{DW + ((W_SW2*4+2)|DIR_N3), DW + ((W_SS2*4+2)|DIR_N3), DW + ((W_WW2*4+2)|DIR_N3),
DW + W_NE2*4+3, DW + W_NN2*4+3, DW + W_NW2*4+3}},
{0, DW + ((W_WW4*4+3) | DIR_BEG), 0, 0, 3,
DW + ((W_NW4*4+3) | DIR_BEG), 14, 0, 2,
{DW + ((W_SW4*4+2)|DIR_N3), DW + ((W_SS4*4+2)|DIR_N3), DW + W_NE4*4+3,
DW + W_NN4*4+3, DW + W_NW4*4+3, DW + W_WW4*4+3}},
{0, DW + ((W_SS4*4+3) | DIR_BEG), 16, 2, 18,
DW + ((W_SW4*4+3) | DIR_BEG), 30, 1, 19,
{DW + W_SW2*4+3, DW + W_WW2*4+3, DW + ((W_NW2*4+0)|DIR_S0),
DW + W_SS2*4+3, DW + W_SE2*4+3, DW + W_EE2*4+3}},
{0, DW + ((W_SS4*4+3) | DIR_BEG), 16, 1, 18,
DW + ((W_SW4*4+3) | DIR_BEG), 30, 2, 19,
{LW + LO_D, LW + LO_DQ, LW + LO_BMUX,
LW + (LO_D|LD1), LW + (LO_DQ|LD1), LW + (LO_BMUX|LD1)}},
{0, DW + ((W_SS4*4+3) | DIR_BEG), 16, 0, 18,
DW + ((W_SW4*4+3) | DIR_BEG), 30, 0, 19,
{DW + W_SW4*4+3, DW + W_SS4*4+3, DW + ((W_WW4*4+0)|DIR_S0),
DW + ((W_NW4*4+0)|DIR_S0), DW + W_SE4*4+3, DW + W_EE4*4+3}},
{2, DW + ((W_NN4*4+3) | DIR_BEG), 0, 2, 3,
DW + ((W_NE4*4+3) | DIR_BEG), 14, 1, 2,
{LW + (LO_BMUX|LD1), LW + (LO_DQ|LD1), LW + (LO_D|LD1),
LW + LO_BMUX, LW + LO_DQ, LW + LO_D}},
{2, DW + ((W_NN4*4+3) | DIR_BEG), 0, 1, 3,
DW + ((W_NE4*4+3) | DIR_BEG), 14, 2, 2,
{DW + W_EE2*4+3, DW + W_SE2*4+3, DW + ((W_WW2*4+2)|DIR_N3),
DW + W_NE2*4+3, DW + W_NN2*4+3, DW + W_NW2*4+3}},
{2, DW + ((W_NN4*4+3) | DIR_BEG), 0, 0, 3,
DW + ((W_NE4*4+3) | DIR_BEG), 14, 0, 2,
{DW + W_EE4*4+3, DW + W_SE4*4+3, DW + W_NE4*4+3,
DW + W_NN4*4+3, DW + W_NW4*4+3, DW + W_WW4*4+3}},
{2, DW + ((W_EE4*4+3) | DIR_BEG), 16, 2, 18,
DW + ((W_SE4*4+3) | DIR_BEG), 30, 1, 19,
{DW + W_SW2*4+3, DW + W_NN2*4+3, DW + W_NE2*4+3,
DW + W_SS2*4+3, DW + W_SE2*4+3, DW + W_EE2*4+3}},
{2, DW + ((W_EE4*4+3) | DIR_BEG), 16, 1, 18,
DW + ((W_SE4*4+3) | DIR_BEG), 30, 2, 19,
{LW + LO_D, LW + LO_DQ, LW + LO_BMUX,
LW + (LO_D|LD1), LW + (LO_DQ|LD1), LW + (LO_BMUX|LD1)}},
{2, DW + ((W_EE4*4+3) | DIR_BEG), 16, 0, 18,
DW + ((W_SE4*4+3) | DIR_BEG), 30, 0, 19,
{DW + W_SW4*4+3, DW + W_SS4*4+3, DW + W_NN4*4+3,
DW + W_NE4*4+3, DW + W_SE4*4+3, DW + W_EE4*4+3}},
{4, DW + ((W_NW2*4+3) | DIR_BEG), 0, 2, 3,
DW + ((W_NN2*4+3) | DIR_BEG), 14, 1, 2,
{LW + (LO_BMUX|LD1), LW + (LO_DQ|LD1), LW + (LO_D|LD1),
LW + LO_BMUX, LW + LO_DQ, LW + LO_D}},
{4, DW + ((W_NW2*4+3) | DIR_BEG), 0, 1, 3,
DW + ((W_NN2*4+3) | DIR_BEG), 14, 2, 2,
{DW + W_NE2*4+3, DW + W_NN2*4+3, DW + ((W_WL1*4+2)|DIR_N3),
DW + W_WR1*4+3, DW + W_NR1*4+3, DW + W_NL1*4+3}},
{4, DW + ((W_NW2*4+3) | DIR_BEG), 0, 0, 3,
DW + ((W_NN2*4+3) | DIR_BEG), 14, 0, 2,
{DW + W_NW4*4+3, DW + W_WW4*4+3, DW + W_NE4*4+3,
DW + W_NN4*4+3, DW + ((W_WW2*4+2)|DIR_N3), DW + W_NW2*4+3}},
{4, DW + ((W_WW2*4+3) | DIR_BEG), 16, 2, 18,
DW + ((W_SW2*4+3) | DIR_BEG), 30, 1, 19,
{DW + W_SR1*4+3, DW + W_SL1*4+3, DW + ((W_WR1*4+0)|DIR_S0),
DW + W_WL1*4+3, DW + W_SW2*4+3, DW + W_SS2*4+3}},
{4, DW + ((W_WW2*4+3) | DIR_BEG), 16, 1, 18,
DW + ((W_SW2*4+3) | DIR_BEG), 30, 2, 19,
{LW + LO_D, LW + LO_DQ, LW + LO_BMUX,
LW + (LO_D|LD1), LW + (LO_DQ|LD1), LW + (LO_BMUX|LD1)}},
{4, DW + ((W_WW2*4+3) | DIR_BEG), 16, 0, 18,
DW + ((W_SW2*4+3) | DIR_BEG), 30, 0, 19,
{DW + W_WW2*4+3, DW + ((W_NW2*4+0)|DIR_S0), DW + W_SW4*4+3,
DW + W_SS4*4+3, DW + ((W_WW4*4+0)|DIR_S0), DW + ((W_NW4*4+0)|DIR_S0)}},
{6, DW + ((W_NE2*4+3) | DIR_BEG), 0, 2, 3,
DW + ((W_EE2*4+3) | DIR_BEG), 14, 1, 2,
{LW + (LO_BMUX|LD1), LW + (LO_DQ|LD1), LW + (LO_D|LD1),
LW + LO_BMUX, LW + LO_DQ, LW + LO_D}},
{6, DW + ((W_NE2*4+3) | DIR_BEG), 0, 1, 3,
DW + ((W_EE2*4+3) | DIR_BEG), 14, 2, 2,
{DW + W_NE2*4+3, DW + W_NN2*4+3, DW + W_EL1*4+3,
DW + W_ER1*4+3, DW + W_NR1*4+3, DW + W_NL1*4+3}},
{6, DW + ((W_NE2*4+3) | DIR_BEG), 0, 0, 3,
DW + ((W_EE2*4+3) | DIR_BEG), 14, 0, 2,
{DW + W_EE4*4+3, DW + W_SE4*4+3, DW + W_NE4*4+3,
DW + W_NN4*4+3, DW + W_EE2*4+3, DW + W_SE2*4+3}},
{6, DW + ((W_SS2*4+3) | DIR_BEG), 16, 2, 18,
DW + ((W_SE2*4+3) | DIR_BEG), 30, 1, 19,
{DW + W_SR1*4+3, DW + W_SL1*4+3, DW + W_ER1*4+3,
DW + W_EL1*4+3, DW + W_SW2*4+3, DW + W_SS2*4+3}},
{6, DW + ((W_SS2*4+3) | DIR_BEG), 16, 1, 18,
DW + ((W_SE2*4+3) | DIR_BEG), 30, 2, 19,
{LW + LO_D, LW + LO_DQ, LW + LO_BMUX,
LW + (LO_D|LD1), LW + (LO_DQ|LD1), LW + (LO_BMUX|LD1)}},
{6, DW + ((W_SS2*4+3) | DIR_BEG), 16, 0, 18,
DW + ((W_SE2*4+3) | DIR_BEG), 30, 0, 19,
{DW + W_SE2*4+3, DW + W_EE2*4+3, DW + W_SW4*4+3,
DW + W_SS4*4+3, DW + W_SE4*4+3, DW + W_EE4*4+3}},
{8, DW + ((W_WR1*4+0) | DIR_BEG), 0, 2, 3,
DW + ((W_NL1*4+2) | DIR_BEG), 14, 1, 2,
{LW + (LO_BMUX|LD1), LW + (LO_DQ|LD1), LW + (LO_D|LD1),
LW + LO_BMUX, LW + LO_DQ, LW + LO_D}},
{8, DW + ((W_WR1*4+0) | DIR_BEG), 0, 1, 3,
DW + ((W_NL1*4+2) | DIR_BEG), 14, 2, 2,
{DW + W_NE2*4+3, DW + W_NN2*4+3, DW + ((W_WL1*4+2)|DIR_N3),
DW + W_WR1*4+3, DW + W_NR1*4+3, DW + W_NL1*4+3}},
{8, DW + ((W_WR1*4+0) | DIR_BEG), 0, 0, 3,
DW + ((W_NL1*4+2) | DIR_BEG), 14, 0, 2,
{DW + W_NW4*4+3, DW + W_WW4*4+3, DW + W_NE4*4+3,
DW + W_NN4*4+3, DW + ((W_WW2*4+2)|DIR_N3), DW + W_NW2*4+3}},
{8, DW + ((W_SR1*4+0) | DIR_BEG), 16, 2, 18,
DW + ((W_WL1*4+2) | DIR_BEG), 30, 1, 19,
{DW + W_SR1*4+3, DW + W_SL1*4+3, DW + ((W_WR1*4+0)|DIR_S0),
DW + W_WL1*4+3, DW + W_SW2*4+3, DW + W_SS2*4+3}},
{8, DW + ((W_SR1*4+0) | DIR_BEG), 16, 1, 18,
DW + ((W_WL1*4+2) | DIR_BEG), 30, 2, 19,
{LW + LO_D, LW + LO_DQ, LW + LO_BMUX,
LW + (LO_D|LD1), LW + (LO_DQ|LD1), LW + (LO_BMUX|LD1)}},
{8, DW + ((W_SR1*4+0) | DIR_BEG), 16, 0, 18,
DW + ((W_WL1*4+2) | DIR_BEG), 30, 0, 19,
{DW + W_WW2*4+3, DW + ((W_NW2*4+0)|DIR_S0), DW + W_SW4*4+3,
DW + W_SS4*4+3, DW + ((W_WW4*4+0)|DIR_S0), DW + ((W_NW4*4+0)|DIR_S0)}},
{10, DW + ((W_EL1*4+2) | DIR_BEG), 0, 2, 3,
DW + ((W_NR1*4+3) | DIR_BEG), 14, 1, 2,
{LW + (LO_BMUX|LD1), LW + (LO_DQ|LD1), LW + (LO_D|LD1),
LW + LO_BMUX, LW + LO_DQ, LW + LO_D}},
{10, DW + ((W_EL1*4+2) | DIR_BEG), 0, 1, 3,
DW + ((W_NR1*4+3) | DIR_BEG), 14, 2, 2,
{DW + W_NE2*4+3, DW + W_NN2*4+3, DW + W_EL1*4+3,
DW + W_ER1*4+3, DW + W_NR1*4+3, DW + W_NL1*4+3}},
{10, DW + ((W_EL1*4+2) | DIR_BEG), 0, 0, 3,
DW + ((W_NR1*4+3) | DIR_BEG), 14, 0, 2,
{DW + W_EE4*4+3, DW + W_SE4*4+3, DW + W_NE4*4+3,
DW + W_NN4*4+3, DW + W_EE2*4+3, DW + W_SE2*4+3}},
{10, DW + ((W_SL1*4+3) | DIR_BEG), 16, 2, 18,
DW + ((W_ER1*4+0) | DIR_BEG), 30, 1, 19,
{DW + W_SR1*4+3, DW + W_SL1*4+3, DW + W_ER1*4+3,
DW + W_EL1*4+3, DW + W_SW2*4+3, DW + W_SS2*4+3}},
{10, DW + ((W_SL1*4+3) | DIR_BEG), 16, 1, 18,
DW + ((W_ER1*4+0) | DIR_BEG), 30, 2, 19,
{LW + LO_D, LW + LO_DQ, LW + LO_BMUX,
LW + (LO_D|LD1), LW + (LO_DQ|LD1), LW + (LO_BMUX|LD1)}},
{10, DW + ((W_SL1*4+3) | DIR_BEG), 16, 0, 18,
DW + ((W_ER1*4+0) | DIR_BEG), 30, 0, 19,
{DW + W_SE2*4+3, DW + W_EE2*4+3, DW + W_SW4*4+3,
DW + W_SS4*4+3, DW + W_SE4*4+3, DW + W_EE4*4+3}}};
for (i = 0;; i++) {
rc = src_to_bitpos(*bitpos, num_bitpos, MAX_SWITCHBOX_SIZE,
src, sizeof(src)/sizeof(*src));
if (rc) FAIL(rc);
if (i >= 3) break;
for (j = 0; j < sizeof(src)/sizeof(*src); j++) {
src[j].m0_sw_to = wire_decrement(src[j].m0_sw_to);
src[j].m0_two_bits_o += 32;
src[j].m0_one_bit_start += 32;
src[j].m1_sw_to = wire_decrement(src[j].m1_sw_to);
src[j].m1_two_bits_o += 32;
src[j].m1_one_bit_start += 32;
for (k = 0; k < sizeof(src[0].from_w)/sizeof(src[0].from_w[0]); k++)
src[j].from_w[k] = wire_decrement(src[j].from_w[k]);
}
}
}
// mip 12-18, decrementing directional wires (1024 switches)
{ struct sw_mip_src src[] = {
{12, NO_WIRE, 0, 2, 2,
NO_WIRE, 14, 2, 3,
{DW + W_EL1*4+3, DW + W_ER1*4+3, DW + W_WL1*4+3,
DW + W_WR1*4+3, DW + W_EE2*4+3, DW + W_SE2*4+3}},
{12, NO_WIRE, 0, 0, 2,
NO_WIRE, 14, 0, 3,
{DW + W_SS2*4+3, DW + W_SW2*4+3, DW + ((W_NW2*4+0)|DIR_S0),
DW + W_WW2*4+3, DW + W_NE2*4+3, DW + W_NN2*4+3}},
{12, NO_WIRE, 0, 1, 2,
NO_WIRE, 14, 1, 3,
{NO_WIRE, NO_WIRE, DW + ((W_NL1*4+0)|DIR_S0),
DW + W_NR1*4+3, DW + W_SL1*4+3, DW + W_SR1*4+3}},
{14, NO_WIRE, 0, 1, 3,
NO_WIRE, 14, 1, 2,
{DW + ((W_EL1*4+0)|DIR_S0), DW + W_ER1*4+3, DW + W_WL1*4+3,
DW + ((W_WR1*4+0)|DIR_S0), DW + W_EE2*4+3, DW + W_SE2*4+3}},
{14, NO_WIRE, 0, 0, 3,
NO_WIRE, 14, 0, 2,
{DW + W_SS2*4+3, DW + W_SW2*4+3, DW + ((W_NW2*4+0)|DIR_S0),
DW + W_WW2*4+3, DW + ((W_NE2*4+0)|DIR_S0), DW + ((W_NN2*4+0)|DIR_S0)}},
{14, NO_WIRE, 0, 2, 3,
NO_WIRE, 14, 2, 2,
{NO_WIRE, NO_WIRE, DW + ((W_NL1*4+0)|DIR_S0),
DW + W_NR1*4+3, DW + W_SL1*4+3, DW + W_SR1*4+3}},
{16, NO_WIRE, 0, 2, 2,
NO_WIRE, 14, 2, 3,
{DW + W_EL1*4+3, DW + W_ER1*4+3, DW + W_WL1*4+3,
DW + W_WR1*4+3, DW + W_EE2*4+3, DW + W_SE2*4+3}},
{16, NO_WIRE, 0, 0, 2,
NO_WIRE, 14, 0, 3,
{DW + W_SS2*4+3, DW + W_SW2*4+3, DW + W_NW2*4+3,
DW + ((W_WW2*4+2)|DIR_N3), DW + W_NE2*4+3, DW + W_NN2*4+3}},
{16, NO_WIRE, 0, 1, 2,
NO_WIRE, 14, 1, 3,
{NO_WIRE, NO_WIRE, DW + W_NL1*4+3,
DW + W_NR1*4+3, DW + W_SL1*4+3, DW + ((W_SR1*4+2)|DIR_N3)}},
{18, NO_WIRE, 0, 1, 3,
NO_WIRE, 14, 1, 2,
{DW + W_EL1*4+3, DW + ((W_ER1*4+2)|DIR_N3), DW + ((W_WL1*4+2)|DIR_N3),
DW + W_WR1*4+3, DW + W_EE2*4+3, DW + W_SE2*4+3}},
{18, NO_WIRE, 0, 0, 3,
NO_WIRE, 14, 0, 2,
{DW + ((W_SS2*4+2)|DIR_N3), DW + ((W_SW2*4+2)|DIR_N3), DW + W_NW2*4+3,
DW + ((W_WW2*4+2)|DIR_N3), DW + W_NE2*4+3, DW + W_NN2*4+3}},
{18, NO_WIRE, 0, 2, 3,
NO_WIRE, 14, 2, 2,
{NO_WIRE, NO_WIRE, DW + W_NL1*4+3,
DW + W_NR1*4+3, DW + W_SL1*4+3, DW + ((W_SR1*4+2)|DIR_N3)}}};
for (i = 0; i < 8; i++) {
for (j = 0; j < sizeof(src)/sizeof(*src); j++) {
int logicin_o = ((src[j].minor-12)/2)*LOGIN_MIP_ROWS*LOGIN_ROW;
logicin_o += i*LOGIN_ROW;
src[j].m0_sw_to = logicin_matrix[logicin_o+0];
src[j].m1_sw_to = logicin_matrix[logicin_o+1];
if (i) {
src[j].m0_two_bits_o += 16;
src[j].m0_one_bit_start += 16;
src[j].m1_two_bits_o += 16;
src[j].m1_one_bit_start += 16;
if (!(i%2)) // at 2, 4 and 6 we decrement the wires
for (k = 0; k < sizeof(src[0].from_w)/sizeof(src[0].from_w[0]); k++)
src[j].from_w[k] = wire_decrement(src[j].from_w[k]);
}
}
rc = src_to_bitpos(*bitpos, num_bitpos, MAX_SWITCHBOX_SIZE,
src, sizeof(src)/sizeof(*src));
if (rc) FAIL(rc);
}
}
// VCC/GND/GFAN, logicin and logicout sources
// mip12-14
{ int logicin_src[8][6] = {
{VCC_WIRE, LW + (LO_D|LD1), LW + LO_DQ, LW + (LO_BMUX|LD1), LOGICIN_S62, LOGICIN_S20},
{GFAN1, LW + (LO_D|LD1), LW + LO_DQ, LW + (LO_BMUX|LD1), LOGICIN_S62, LOGICIN_S20},
{VCC_WIRE, LW + LO_C, LW + (LO_CQ|LD1), LW + LO_AMUX, LOGICIN_S62, LW + (LI_AX|LD1)},
{GFAN1, LW + LO_C, LW + (LO_CQ|LD1), LW + LO_AMUX, LOGICIN_S62, LW + (LI_AX|LD1)},
{VCC_WIRE, LW + (LO_B|LD1), LW + LO_BQ, LW + (LO_DMUX|LD1), LW + (LI_AX|LD1), LW + (LI_CI|LD1)},
{GFAN0, LW + (LO_B|LD1), LW + LO_BQ, LW + (LO_DMUX|LD1), LW + (LI_AX|LD1), LW + (LI_CI|LD1)},
{VCC_WIRE, LW + LO_A, LW + (LO_AQ|LD1), LW + LO_CMUX, LOGICIN20, LW + (LI_CI|LD1)},
{GFAN0, LW + LO_A, LW + (LO_AQ|LD1), LW + LO_CMUX, LOGICIN20, LW + (LI_CI|LD1)},
};
rc = mip_to_bitpos(*bitpos, num_bitpos, MAX_SWITCHBOX_SIZE,
12, 3, 2, 3, 3, &logicin_src);
if (rc) FAIL(rc);
logicin_src[1][0] = logicin_src[3][0] = logicin_src[5][0] = logicin_src[7][0] = VCC_WIRE;
logicin_src[0][0] = logicin_src[2][0] = GFAN1;
logicin_src[4][0] = logicin_src[6][0] = GFAN0;
rc = mip_to_bitpos(*bitpos, num_bitpos, MAX_SWITCHBOX_SIZE,
14, 3, 3, 3, 2, &logicin_src);
if (rc) FAIL(rc);
}
{ int logicin_src[8][6] = {
{ LW + LI_BX, LOGICIN52 },
{ LW + LI_BX, LOGICIN52 },
{ LW + LI_BX, LW + (LI_DI|LD1) },
{ LW + LI_BX, LW + (LI_DI|LD1) },
{ LW + (LI_DI|LD1), LOGICIN_N28 },
{ LW + (LI_DI|LD1), LOGICIN_N28 },
{ LOGICIN_N52, LOGICIN_N28 },
{ LOGICIN_N52, LOGICIN_N28 }};
rc = mip_to_bitpos(*bitpos, num_bitpos, MAX_SWITCHBOX_SIZE,
12, 1, 2, 1, 3, &logicin_src);
if (rc) FAIL(rc);
rc = mip_to_bitpos(*bitpos, num_bitpos, MAX_SWITCHBOX_SIZE,
14, 2, 3, 2, 2, &logicin_src);
if (rc) FAIL(rc);
}
// mip16-18
{ int logicin_src[8][6] = {
{VCC_WIRE, LW + LO_D, LW + (LO_DQ|LD1), LW + LO_BMUX, LOGICIN_S36, LOGICIN_S44},
{GFAN1, LW + LO_D, LW + (LO_DQ|LD1), LW + LO_BMUX, LOGICIN_S36, LOGICIN_S44},
{VCC_WIRE, LW + (LO_C|LD1), LW + LO_CQ, LW + (LO_AMUX|LD1), LOGICIN_S36, LW + LI_AX},
{GFAN1, LW + (LO_C|LD1), LW + LO_CQ, LW + (LO_AMUX|LD1), LOGICIN_S36, LW + LI_AX},
{VCC_WIRE, LW + LO_B, LW + (LO_BQ|LD1), LW + LO_DMUX, LW + LI_AX, LW + (LI_CE|LD1)},
{GFAN0, LW + LO_B, LW + (LO_BQ|LD1), LW + LO_DMUX, LW + LI_AX, LW + (LI_CE|LD1)},
{VCC_WIRE, LW + (LO_A|LD1), LW + LO_AQ, LW + (LO_CMUX|LD1), LOGICIN44, LW + (LI_CE|LD1)},
{GFAN0, LW + (LO_A|LD1), LW + LO_AQ, LW + (LO_CMUX|LD1), LOGICIN44, LW + (LI_CE|LD1)},
};
rc = mip_to_bitpos(*bitpos, num_bitpos, MAX_SWITCHBOX_SIZE,
16, 3, 2, 3, 3, &logicin_src);
if (rc) FAIL(rc);
logicin_src[1][0] = logicin_src[3][0] = logicin_src[5][0] = logicin_src[7][0] = VCC_WIRE;
logicin_src[0][0] = logicin_src[2][0] = GFAN1;
logicin_src[4][0] = logicin_src[6][0] = GFAN0;
rc = mip_to_bitpos(*bitpos, num_bitpos, MAX_SWITCHBOX_SIZE,
18, 3, 3, 3, 2, &logicin_src);
if (rc) FAIL(rc);
}
{ int logicin_src[8][6] = {
{ LW + (LI_BX|LD1), LOGICIN21 },
{ LW + (LI_BX|LD1), LOGICIN21 },
{ LW + (LI_BX|LD1), FAN_B },
{ LW + (LI_BX|LD1), FAN_B },
{ FAN_B, LOGICIN_N60 },
{ FAN_B, LOGICIN_N60 },
{ LOGICIN_N21, LOGICIN_N60 },
{ LOGICIN_N21, LOGICIN_N60 }};
rc = mip_to_bitpos(*bitpos, num_bitpos, MAX_SWITCHBOX_SIZE,
16, 1, 2, 1, 3, &logicin_src);
if (rc) FAIL(rc);
rc = mip_to_bitpos(*bitpos, num_bitpos, MAX_SWITCHBOX_SIZE,
18, 2, 3, 2, 2, &logicin_src);
if (rc) FAIL(rc);
}
// minor 20 switches (SR, CLK, GFAN = 113 switches (4 bidir added on other side))
{ const struct sw_mip_src src[] = {
{20, SR1, 6, 3, 0, .from_w =
{GCLK11, GCLK10, GCLK13, GCLK12, GCLK9, GCLK8}},
{20, SR1, 6, 2, 0, .from_w =
{DW+W_WR1*4+2, DW+W_NR1*4+2, VCC_WIRE, GND_WIRE, DW+W_ER1*4+2, DW+W_SR1*4+2}},
{20, SR1, 6, 1, 0, .from_w =
{FAN_B, LW+(LI_DI|LD1), LW+(LI_BX|LD1), LW+LI_BX, GCLK15, GCLK14}},
{20, SR0, 8, 3, 10, .from_w =
{GCLK8, GCLK9, GCLK10, GCLK13, GCLK12, GCLK11}},
{20, SR0, 8, 2, 10, .from_w =
{GCLK14, GCLK15, LW+(LI_DI|LD1), LW+(LI_BX|LD1), LW+LI_BX, FAN_B}},
{20, SR0, 8, 1, 10, .from_w = {DW+W_SR1*4+2, DW+W_ER1*4+2, DW+W_NR1*4+2,
VCC_WIRE, NO_WIRE /*is this GND?*/, DW+W_WR1*4+2}},
{20, CLK0, 16, 3, 18, .from_w =
{GCLK0, GCLK1, GCLK2, GCLK5, GCLK4, GCLK3}},
{20, CLK0, 16, 2, 18, .from_w =
{GCLK6, GCLK7, GCLK8, GCLK11, GCLK10, GCLK9}},
{20, CLK0, 16, 1, 18, .from_w =
{GCLK12, GCLK13, GCLK14, LW+(LI_BX|LD1), LW+(LI_CI|LD1), GCLK15}},
{20, CLK0, 16, 0, 18, .from_w =
{DW+W_NR1*4+2, DW+W_WR1*4+2, DW+W_SR1*4+1, VCC_WIRE, NO_WIRE, DW+W_ER1*4+1}},
{20, CLK1, 46, 3, 40, .from_w =
{GCLK3, GCLK2, GCLK5, GCLK4, GCLK1, GCLK0}},
{20, CLK1, 46, 2, 40, .from_w =
{GCLK15, GCLK14, LW+(LI_BX|LD1), LW+(LI_CI|LD1), GCLK13, GCLK12}},
{20, CLK1, 46, 1, 40, .from_w =
{GCLK9, GCLK8, GCLK11, GCLK10, GCLK7, GCLK6}},
{20, CLK1, 46, 0, 40, .from_w =
{DW+W_ER1*4+1, DW+W_SR1*4+1, VCC_WIRE, NO_WIRE, DW+W_WR1*4+2, DW+W_NR1*4+2}},
{20, GFAN0, 54, 3, 48, .from_w =
{GCLK3, GCLK4, GCLK5, GCLK2, GCLK1, GCLK0}},
{20, GFAN0, 54, 2, 48, .from_w =
{DW+W_WR1*4+1, GND_WIRE, VCC_WIRE, DW+W_NR1*4+1, DW+W_ER1*4+1, DW+W_SR1*4+1}},
{20, GFAN0, 54, 1, 48, .from_w =
{LW+(LI_CE|LD1), LW+(LI_AX|LD1), LW+LI_AX, LW+(LI_CI|LD1), GCLK7, GCLK6}},
{20, GFAN1, 56, 3, 58, .from_w =
{GCLK0, GCLK1, GCLK4, GCLK5, GCLK2, GCLK3}},
{20, GFAN1, 56, 2, 58, .from_w =
{GCLK6, GCLK7, LW+(LI_AX|LD1), LW+LI_AX, LW+(LI_CI|LD1), LW+(LI_CE|LD1)}},
{20, GFAN1, 56, 1, 58, .from_w =
{DW+W_SR1*4+1, DW+W_ER1*4+1, GND_WIRE, VCC_WIRE, DW+W_NR1*4+1, DW+W_WR1*4+1}}};
for (i = 0; i < sizeof(src)/sizeof(*src); i++) {
for (j = 0; j < sizeof(src[0].from_w)/sizeof(src[0].from_w[0]); j++) {
if (src[i].from_w[j] == NO_WIRE) continue;
if (*num_bitpos >= MAX_SWITCHBOX_SIZE) FAIL(EINVAL);
(*bitpos)[*num_bitpos].from = src[i].from_w[j];
(*bitpos)[*num_bitpos].to = src[i].m0_sw_to;
(*bitpos)[*num_bitpos].bidir = bidir_check(src[i].from_w[j], src[i].m0_sw_to);
(*bitpos)[*num_bitpos].minor = 20;
(*bitpos)[*num_bitpos].two_bits_o = src[i].m0_two_bits_o;
(*bitpos)[*num_bitpos].two_bits_val = src[i].m0_two_bits_val;
(*bitpos)[*num_bitpos].one_bit_o = src[i].m0_one_bit_start + j;
(*num_bitpos)++;
}
}}
return 0;
fail:
return rc;
}
void free_xc6_routing_bitpos(struct xc6_routing_bitpos* bitpos)
{
free(bitpos);
}
uint64_t xc6_lut_value(int lut_pos, int lutw_tl, int lutw_tr, int lutw_bl, int lutw_br)
{
// XC6_LMAP_ macros are offsets into this array:
static const int xc6_lut_wiring[4][8] = {
// xm-m a; xm-m c;
{ 15, 14, 12, 13, 8, 9, 11, 10 },
// xm-m b; xm-m d;
{ 0, 1, 3, 2, 7, 6, 4, 5 },
// xm-x a; xm-x b; xl-l b; xl-l d; xl-x a; xl-x b;
{ 8, 9, 10, 11, 14, 15, 12, 13 },
// xm-x c; xm-x d; xl-l a; xl-l c; xl-x c; xl-x d;
{ 7, 6, 5, 4, 1, 0, 3, 2 }};
uint64_t v;
int full_word_positions[16], i;
// expand 8 bits to 16 bits
for (i = 0; i < 8; i++) {
full_word_positions[i] = xc6_lut_wiring[lut_pos][i];
full_word_positions[i+8] = (xc6_lut_wiring[lut_pos][i]+8)%16;
}
// swap top and bottom words if needed
if (lut_pos == XC6_LMAP_XM_M_B
|| lut_pos == XC6_LMAP_XM_M_D
|| lut_pos == XC6_LMAP_XM_X_C
|| lut_pos == XC6_LMAP_XM_X_D
|| lut_pos == XC6_LMAP_XL_L_A
|| lut_pos == XC6_LMAP_XL_L_C
|| lut_pos == XC6_LMAP_XL_X_C
|| lut_pos == XC6_LMAP_XL_X_D) {
int temp_w;
temp_w = lutw_tl; lutw_tl = lutw_bl; lutw_bl = temp_w;
temp_w = lutw_tr; lutw_tr = lutw_br; lutw_br = temp_w;
}
// assemble bits
v = 0;
for (i = 0; i < 16; i+=2) {
// top side
if (lutw_tr & (1<<full_word_positions[i]))
v |= 1ULL << (i*2);
if (lutw_tr & (1<<full_word_positions[i+1]))
v |= 1ULL << (i*2+1);
if (lutw_tl & (1<<full_word_positions[i]))
v |= 1ULL << (i*2+2);
if (lutw_tl & (1<<full_word_positions[i+1]))
v |= 1ULL << (i*2+3);
// bottom side
if (lutw_br & (1<<full_word_positions[i]))
v |= 1ULL << (32+i*2);
if (lutw_br & (1<<full_word_positions[i+1]))
v |= 1ULL << (32+i*2+1);
if (lutw_bl & (1<<full_word_positions[i]))
v |= 1ULL << (32+i*2+2);
if (lutw_bl & (1<<full_word_positions[i+1]))
v |= 1ULL << (32+i*2+3);
}
return v;
}
| DeanoC/fpgatools | libs/parts.c | C | unlicense | 90,903 |
// Implements http://rosettacode.org/wiki/Loops/For
// not_tested
use std::iter;
fn main() {
for i in iter::range_inclusive(1u, 5) {
for _ in iter::range_inclusive(1u, i) {
print!("*")
}
println!("")
}
}
| prakhar1989/rust-rosetta | src/loops-for.rs | Rust | unlicense | 251 |
# Xcode Snippets
## CLI Build
```bash
xcodebuild -list -project Project.xcodeproj
xcodebuild -scheme iOS build
```
## CLI Test
```bash
xcodebuild test -project Project.xcodeproj -scheme Tests -destination 'platform=iOS Simulator,name=iPad Air 2,OS=10.0'
```
## CLI xcrun
```bash
xcrun -sdk iphoneos swiftc -target armv7-apple-ios10.0 main.swift
```
## Trouble Shooting
```bash
# clean == ⌘ + ⌥ + k
# full clean == ⌘ + ⌥ + ⇧ + k
```
## Switch Xcode Install
```bash
sudo xcode-select -switch /Applications/Xcode.app/Contents/Developer
```
## Add new-iOS Support to legacy Xcode
```bash
# hella unsupported
sudo ln -s /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/DeviceSupport/11.0\ \(15A372\) /Applications/Xcode8.app/Contents/Developer/Platforms/iPhoneOS.platform/DeviceSupport/11.0
```
## Playgrounds
```bash
# Inserting the following into a playground simulates a playholder and will cause the playground to exit to the simulator it's containing:
override public func viewDidAppear(_ animated: Bool) {
<#code#>
}
```
```swift
import PlaygroundSupport
...
PlaygroundPage.current.liveView = viewController.view
...
PlaygroundPage.current.needsIndefiniteExecution
```
## Simulator
```bash
xcrun simctl list | grep Air
xcrun simctl boot "iPad Air 2"
xcrun simctl install booted Project.swiftmodule
```
## Devices
```bash
instruments -s devices
```
| mlavergn/cheatsheets | xcode.md | Markdown | unlicense | 1,406 |
/*
* Copyright 2002-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.util;
import java.util.Arrays;
import java.util.Collection;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
/**
* Miscellaneous collection utility methods.
* Mainly for internal use within the framework.
*
* @author Juergen Hoeller
* @author Rob Harrop
* @since 1.1.3
*/
public abstract class CollectionUtils {
/**
* Return <code>true</code> if the supplied Collection is <code>null</code>
* or empty. Otherwise, return <code>false</code>.
* @param collection the Collection to check
* @return whether the given Collection is empty
*/
public static boolean isEmpty(Collection collection) {
return (collection == null || collection.isEmpty());
}
/**
* Return <code>true</code> if the supplied Map is <code>null</code>
* or empty. Otherwise, return <code>false</code>.
* @param map the Map to check
* @return whether the given Map is empty
*/
public static boolean isEmpty(Map map) {
return (map == null || map.isEmpty());
}
/**
* Convert the supplied array into a List. A primitive array gets
* converted into a List of the appropriate wrapper type.
* <p>A <code>null</code> source value will be converted to an
* empty List.
* @param source the (potentially primitive) array
* @return the converted List result
* @see ObjectUtils#toObjectArray(Object)
*/
public static List arrayToList(Object source) {
return Arrays.asList(ObjectUtils.toObjectArray(source));
}
/**
* Merge the given array into the given Collection.
* @param array the array to merge (may be <code>null</code>)
* @param collection the target Collection to merge the array into
*/
public static void mergeArrayIntoCollection(Object array, Collection collection) {
if (collection == null) {
throw new IllegalArgumentException("Collection must not be null");
}
Object[] arr = ObjectUtils.toObjectArray(array);
for (int i = 0; i < arr.length; i++) {
collection.add(arr[i]);
}
}
/**
* Merge the given Properties instance into the given Map,
* copying all properties (key-value pairs) over.
* <p>Uses <code>Properties.propertyNames()</code> to even catch
* default properties linked into the original Properties instance.
* @param props the Properties instance to merge (may be <code>null</code>)
* @param map the target Map to merge the properties into
*/
public static void mergePropertiesIntoMap(Properties props, Map map) {
if (map == null) {
throw new IllegalArgumentException("Map must not be null");
}
if (props != null) {
for (Enumeration en = props.propertyNames(); en.hasMoreElements();) {
String key = (String) en.nextElement();
map.put(key, props.getProperty(key));
}
}
}
/**
* Check whether the given Iterator contains the given element.
* @param iterator the Iterator to check
* @param element the element to look for
* @return <code>true</code> if found, <code>false</code> else
*/
public static boolean contains(Iterator iterator, Object element) {
if (iterator != null) {
while (iterator.hasNext()) {
Object candidate = iterator.next();
if (ObjectUtils.nullSafeEquals(candidate, element)) {
return true;
}
}
}
return false;
}
/**
* Check whether the given Enumeration contains the given element.
* @param enumeration the Enumeration to check
* @param element the element to look for
* @return <code>true</code> if found, <code>false</code> else
*/
public static boolean contains(Enumeration enumeration, Object element) {
if (enumeration != null) {
while (enumeration.hasMoreElements()) {
Object candidate = enumeration.nextElement();
if (ObjectUtils.nullSafeEquals(candidate, element)) {
return true;
}
}
}
return false;
}
/**
* Check whether the given Collection contains the given element instance.
* <p>Enforces the given instance to be present, rather than returning
* <code>true</code> for an equal element as well.
* @param collection the Collection to check
* @param element the element to look for
* @return <code>true</code> if found, <code>false</code> else
*/
public static boolean containsInstance(Collection collection, Object element) {
if (collection != null) {
for (Iterator it = collection.iterator(); it.hasNext();) {
Object candidate = it.next();
if (candidate == element) {
return true;
}
}
}
return false;
}
/**
* Return <code>true</code> if any element in '<code>candidates</code>' is
* contained in '<code>source</code>'; otherwise returns <code>false</code>.
* @param source the source Collection
* @param candidates the candidates to search for
* @return whether any of the candidates has been found
*/
public static boolean containsAny(Collection source, Collection candidates) {
if (isEmpty(source) || isEmpty(candidates)) {
return false;
}
for (Iterator it = candidates.iterator(); it.hasNext();) {
if (source.contains(it.next())) {
return true;
}
}
return false;
}
/**
* Return the first element in '<code>candidates</code>' that is contained in
* '<code>source</code>'. If no element in '<code>candidates</code>' is present in
* '<code>source</code>' returns <code>null</code>. Iteration order is
* {@link Collection} implementation specific.
* @param source the source Collection
* @param candidates the candidates to search for
* @return the first present object, or <code>null</code> if not found
*/
public static Object findFirstMatch(Collection source, Collection candidates) {
if (isEmpty(source) || isEmpty(candidates)) {
return null;
}
for (Iterator it = candidates.iterator(); it.hasNext();) {
Object candidate = it.next();
if (source.contains(candidate)) {
return candidate;
}
}
return null;
}
/**
* Find a single value of the given type in the given Collection.
* @param collection the Collection to search
* @param type the type to look for
* @return a value of the given type found if there is a clear match,
* or <code>null</code> if none or more than one such value found
*/
public static Object findValueOfType(Collection collection, Class type) {
if (isEmpty(collection)) {
return null;
}
Object value = null;
for (Iterator it = collection.iterator(); it.hasNext();) {
Object obj = it.next();
if (type == null || type.isInstance(obj)) {
if (value != null) {
// More than one value found... no clear single value.
return null;
}
value = obj;
}
}
return value;
}
/**
* Find a single value of one of the given types in the given Collection:
* searching the Collection for a value of the first type, then
* searching for a value of the second type, etc.
* @param collection the collection to search
* @param types the types to look for, in prioritized order
* @return a value of one of the given types found if there is a clear match,
* or <code>null</code> if none or more than one such value found
*/
public static Object findValueOfType(Collection collection, Class[] types) {
if (isEmpty(collection) || ObjectUtils.isEmpty(types)) {
return null;
}
for (int i = 0; i < types.length; i++) {
Object value = findValueOfType(collection, types[i]);
if (value != null) {
return value;
}
}
return null;
}
/**
* Determine whether the given Collection only contains a single unique object.
* @param collection the Collection to check
* @return <code>true</code> if the collection contains a single reference or
* multiple references to the same instance, <code>false</code> else
*/
public static boolean hasUniqueObject(Collection collection) {
if (isEmpty(collection)) {
return false;
}
boolean hasCandidate = false;
Object candidate = null;
for (Iterator it = collection.iterator(); it.hasNext();) {
Object elem = it.next();
if (!hasCandidate) {
hasCandidate = true;
candidate = elem;
}
else if (candidate != elem) {
return false;
}
}
return true;
}
}
| codeApeFromChina/resource | frame_packages/java_libs/spring-2.5.6-src/src/org/springframework/util/CollectionUtils.java | Java | unlicense | 8,998 |
# belfast-cares-app
### Prerequisites
- NPM installed : https://nodejs.org/en/download/
- Git installed : https://git-scm.com/download/win
- Java 8 JDK : http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html
- Android SDK : https://developer.android.com/studio/index.html
### Setting up your environment
```
npm install -g cordova
npm install -g ionic
ionic lib update
cd belfast-cares-app
ionic platform add browser
```
### Running the App
```
ionic build browser
ionic serve
```
To run on Android:
```
ionic platform add android
ionic platform build android
ionic run android
```
| belfastcares/belfast-cares-app | README.md | Markdown | unlicense | 621 |
#define LOG_MODULE PacketLogModuleIgmpLayer
#include "IgmpLayer.h"
#include "PacketUtils.h"
#include "Logger.h"
#include <string.h>
#include "EndianPortable.h"
namespace pcpp
{
/*************
* IgmpLayer
*************/
IgmpLayer::IgmpLayer(IgmpType type, const IPv4Address& groupAddr, uint8_t maxResponseTime, ProtocolType igmpVer)
{
m_DataLen = getHeaderSizeByVerAndType(igmpVer, type);
m_Data = new uint8_t[m_DataLen];
memset(m_Data, 0, m_DataLen);
m_Protocol = igmpVer;
setType(type);
if (groupAddr.isValid())
setGroupAddress(groupAddr);
getIgmpHeader()->maxResponseTime = maxResponseTime;
}
void IgmpLayer::setGroupAddress(const IPv4Address& groupAddr)
{
igmp_header* hdr = getIgmpHeader();
hdr->groupAddress = groupAddr.toInt();
}
IgmpType IgmpLayer::getType() const
{
uint8_t type = getIgmpHeader()->type;
if (type < (uint8_t)IgmpType_MembershipQuery ||
(type > (uint8_t)IgmpType_LeaveGroup && type < (uint8_t)IgmpType_MulticastTracerouteResponse) ||
(type > (uint8_t)IgmpType_MulticastTraceroute && type < (uint8_t)IgmpType_MembershipReportV3) ||
(type > (uint8_t)IgmpType_MembershipReportV3 && type < (uint8_t)IgmpType_MulticastRouterAdvertisement) ||
type > IgmpType_MulticastRouterTermination)
return IgmpType_Unknown;
return (IgmpType)type;
}
void IgmpLayer::setType(IgmpType type)
{
if (type == IgmpType_Unknown)
return;
igmp_header* hdr = getIgmpHeader();
hdr->type = type;
}
ProtocolType IgmpLayer::getIGMPVerFromData(uint8_t* data, size_t dataLen, bool& isQuery)
{
isQuery = false;
if (dataLen < 8 || data == NULL)
return UnknownProtocol;
switch ((int)data[0])
{
case IgmpType_MembershipReportV2:
case IgmpType_LeaveGroup:
return IGMPv2;
case IgmpType_MembershipReportV1:
return IGMPv1;
case IgmpType_MembershipReportV3:
return IGMPv3;
case IgmpType_MembershipQuery:
{
isQuery = true;
if (dataLen >= sizeof(igmpv3_query_header))
return IGMPv3;
if (data[1] == 0)
return IGMPv1;
else
return IGMPv2;
}
default:
return UnknownProtocol;
}
}
uint16_t IgmpLayer::calculateChecksum()
{
ScalarBuffer<uint16_t> buffer;
buffer.buffer = (uint16_t*)getIgmpHeader();
buffer.len = getHeaderLen();
return computeChecksum(&buffer, 1);
}
size_t IgmpLayer::getHeaderSizeByVerAndType(ProtocolType igmpVer, IgmpType igmpType) const
{
if (igmpVer == IGMPv1 || igmpVer == IGMPv2)
return sizeof(igmp_header);
if (igmpVer == IGMPv3)
{
if (igmpType == IgmpType_MembershipQuery)
return sizeof(igmpv3_query_header);
else if (igmpType == IgmpType_MembershipReportV3)
return sizeof(igmpv3_report_header);
}
return 0;
}
std::string IgmpLayer::toString() const
{
std::string igmpVer = "";
switch (getProtocol())
{
case IGMPv1:
igmpVer = "1";
break;
case IGMPv2:
igmpVer = "2";
break;
default:
igmpVer = "3";
}
std::string msgType;
switch (getType())
{
case IgmpType_MembershipQuery:
msgType = "Membership Query";
break;
case IgmpType_MembershipReportV1:
msgType = "Membership Report";
break;
case IgmpType_DVMRP:
msgType = "DVMRP";
break;
case IgmpType_P1Mv1:
msgType = "PIMv1";
break;
case IgmpType_CiscoTrace:
msgType = "Cisco Trace";
break;
case IgmpType_MembershipReportV2:
msgType = "Membership Report";
break;
case IgmpType_LeaveGroup:
msgType = "Leave Group";
break;
case IgmpType_MulticastTracerouteResponse:
msgType = "Multicast Traceroute Response";
break;
case IgmpType_MulticastTraceroute:
msgType = "Multicast Traceroute";
break;
case IgmpType_MembershipReportV3:
msgType = "Membership Report";
break;
case IgmpType_MulticastRouterAdvertisement:
msgType = "Multicast Router Advertisement";
break;
case IgmpType_MulticastRouterSolicitation:
msgType = "Multicast Router Solicitation";
break;
case IgmpType_MulticastRouterTermination:
msgType = "Multicast Router Termination";
break;
default:
msgType = "Unknown";
break;
}
std::string result = "IGMPv" + igmpVer + " Layer, " + msgType + " message";
return result;
}
/*************
* IgmpV1Layer
*************/
void IgmpV1Layer::computeCalculateFields()
{
igmp_header* hdr = getIgmpHeader();
hdr->checksum = 0;
hdr->checksum = htobe16(calculateChecksum());
hdr->maxResponseTime = 0;
}
/*************
* IgmpV2Layer
*************/
void IgmpV2Layer::computeCalculateFields()
{
igmp_header* hdr = getIgmpHeader();
hdr->checksum = 0;
hdr->checksum = htobe16(calculateChecksum());
}
/******************
* IgmpV3QueryLayer
******************/
IgmpV3QueryLayer::IgmpV3QueryLayer(uint8_t* data, size_t dataLen, Layer* prevLayer, Packet* packet) :
IgmpLayer(data, dataLen, prevLayer, packet, IGMPv3)
{
}
IgmpV3QueryLayer::IgmpV3QueryLayer(const IPv4Address& multicastAddr, uint8_t maxResponseTime, uint8_t s_qrv) :
IgmpLayer(IgmpType_MembershipQuery, multicastAddr, maxResponseTime, IGMPv3)
{
getIgmpV3QueryHeader()->s_qrv = s_qrv;
}
uint16_t IgmpV3QueryLayer::getSourceAddressCount() const
{
return be16toh(getIgmpV3QueryHeader()->numOfSources);
}
IPv4Address IgmpV3QueryLayer::getSourceAddressAtIndex(int index) const
{
uint16_t numOfSources = getSourceAddressCount();
if (index < 0 || index >= numOfSources)
return IPv4Address();
// verify numOfRecords is a reasonable number that points to data within the packet
int ptrOffset = index * sizeof(uint32_t) + sizeof(igmpv3_query_header);
if (ptrOffset + sizeof(uint32_t) > getDataLen())
return IPv4Address();
uint8_t* ptr = m_Data + ptrOffset;
return IPv4Address(*(uint32_t*)ptr);
}
size_t IgmpV3QueryLayer::getHeaderLen() const
{
uint16_t numOfSources = getSourceAddressCount();
int headerLen = numOfSources * sizeof(uint32_t) + sizeof(igmpv3_query_header);
// verify numOfRecords is a reasonable number that points to data within the packet
if ((size_t)headerLen > getDataLen())
return getDataLen();
return (size_t)headerLen;
}
void IgmpV3QueryLayer::computeCalculateFields()
{
igmpv3_query_header* hdr = getIgmpV3QueryHeader();
hdr->checksum = 0;
hdr->checksum = htobe16(calculateChecksum());
}
bool IgmpV3QueryLayer::addSourceAddress(const IPv4Address& addr)
{
return addSourceAddressAtIndex(addr, getSourceAddressCount());
}
bool IgmpV3QueryLayer::addSourceAddressAtIndex(const IPv4Address& addr, int index)
{
uint16_t sourceAddrCount = getSourceAddressCount();
if (index < 0 || index > (int)sourceAddrCount)
{
PCPP_LOG_ERROR("Cannot add source address at index " << index << ", index is out of bounds");
return false;
}
size_t offset = sizeof(igmpv3_query_header) + index * sizeof(uint32_t);
if (offset > getHeaderLen())
{
PCPP_LOG_ERROR("Cannot add source address at index " << index << ", index is out of packet bounds");
return false;
}
if (!extendLayer(offset, sizeof(uint32_t)))
{
PCPP_LOG_ERROR("Cannot add source address at index " << index << ", didn't manage to extend layer");
return false;
}
memcpy(m_Data + offset, addr.toBytes(), sizeof(uint32_t));
getIgmpV3QueryHeader()->numOfSources = htobe16(sourceAddrCount+1);
return true;
}
bool IgmpV3QueryLayer::removeSourceAddressAtIndex(int index)
{
uint16_t sourceAddrCount = getSourceAddressCount();
if (index < 0 || index > (int)sourceAddrCount-1)
{
PCPP_LOG_ERROR("Cannot remove source address at index " << index << ", index is out of bounds");
return false;
}
size_t offset = sizeof(igmpv3_query_header) + index * sizeof(uint32_t);
if (offset >= getHeaderLen())
{
PCPP_LOG_ERROR("Cannot remove source address at index " << index << ", index is out of packet bounds");
return false;
}
if (!shortenLayer(offset, sizeof(uint32_t)))
{
PCPP_LOG_ERROR("Cannot remove source address at index " << index << ", didn't manage to shorten layer");
return false;
}
getIgmpV3QueryHeader()->numOfSources = htobe16(sourceAddrCount-1);
return true;
}
bool IgmpV3QueryLayer::removeAllSourceAddresses()
{
size_t offset = sizeof(igmpv3_query_header);
size_t numOfBytesToShorted = getHeaderLen() - offset;
if (!shortenLayer(offset, numOfBytesToShorted))
{
PCPP_LOG_ERROR("Cannot remove all source addresses, didn't manage to shorten layer");
return false;
}
getIgmpV3QueryHeader()->numOfSources = 0;
return true;
}
/*******************
* IgmpV3ReportLayer
*******************/
uint16_t IgmpV3ReportLayer::getGroupRecordCount() const
{
return be16toh(getReportHeader()->numOfGroupRecords);
}
igmpv3_group_record* IgmpV3ReportLayer::getFirstGroupRecord() const
{
// check if there are group records at all
if (getHeaderLen() <= sizeof(igmpv3_report_header))
return NULL;
uint8_t* curGroupPtr = m_Data + sizeof(igmpv3_report_header);
return (igmpv3_group_record*)curGroupPtr;
}
igmpv3_group_record* IgmpV3ReportLayer::getNextGroupRecord(igmpv3_group_record* groupRecord) const
{
if (groupRecord == NULL)
return NULL;
// prev group was the last group
if ((uint8_t*)groupRecord + groupRecord->getRecordLen() - m_Data >= (int)getHeaderLen())
return NULL;
igmpv3_group_record* nextGroup = (igmpv3_group_record*)((uint8_t*)groupRecord + groupRecord->getRecordLen());
return nextGroup;
}
void IgmpV3ReportLayer::computeCalculateFields()
{
igmpv3_report_header* hdr = getReportHeader();
hdr->checksum = 0;
hdr->checksum = htobe16(calculateChecksum());
}
igmpv3_group_record* IgmpV3ReportLayer::addGroupRecordAt(uint8_t recordType, const IPv4Address& multicastAddress, const std::vector<IPv4Address>& sourceAddresses, int offset)
{
if (offset > (int)getHeaderLen())
{
PCPP_LOG_ERROR("Cannot add group record, offset is out of layer bounds");
return NULL;
}
size_t groupRecordSize = sizeof(igmpv3_group_record) + sizeof(uint32_t)*sourceAddresses.size();
if (!extendLayer(offset, groupRecordSize))
{
PCPP_LOG_ERROR("Cannot add group record, cannot extend layer");
return NULL;
}
uint8_t* groupRecordBuffer = new uint8_t[groupRecordSize];
memset(groupRecordBuffer, 0, groupRecordSize);
igmpv3_group_record* newGroupRecord = (igmpv3_group_record*)groupRecordBuffer;
newGroupRecord->multicastAddress = multicastAddress.toInt();
newGroupRecord->recordType = recordType;
newGroupRecord->auxDataLen = 0;
newGroupRecord->numOfSources = htobe16(sourceAddresses.size());
int srcAddrOffset = 0;
for (std::vector<IPv4Address>::const_iterator iter = sourceAddresses.begin(); iter != sourceAddresses.end(); iter++)
{
memcpy(newGroupRecord->sourceAddresses + srcAddrOffset, iter->toBytes(), sizeof(uint32_t));
srcAddrOffset += sizeof(uint32_t);
}
memcpy(m_Data + offset, groupRecordBuffer, groupRecordSize);
delete[] groupRecordBuffer;
getReportHeader()->numOfGroupRecords = htobe16(getGroupRecordCount() + 1);
return (igmpv3_group_record*)(m_Data + offset);
}
igmpv3_group_record* IgmpV3ReportLayer::addGroupRecord(uint8_t recordType, const IPv4Address& multicastAddress, const std::vector<IPv4Address>& sourceAddresses)
{
return addGroupRecordAt(recordType, multicastAddress, sourceAddresses, (int)getHeaderLen());
}
igmpv3_group_record* IgmpV3ReportLayer::addGroupRecordAtIndex(uint8_t recordType, const IPv4Address& multicastAddress, const std::vector<IPv4Address>& sourceAddresses, int index)
{
int groupCnt = (int)getGroupRecordCount();
if (index < 0 || index > groupCnt)
{
PCPP_LOG_ERROR("Cannot add group record, index " << index << " out of bounds");
return NULL;
}
size_t offset = sizeof(igmpv3_report_header);
igmpv3_group_record* curRecord = getFirstGroupRecord();
for (int i = 0; i < index; i++)
{
if (curRecord == NULL)
{
PCPP_LOG_ERROR("Cannot add group record, cannot find group record at index " << i);
return NULL;
}
offset += curRecord->getRecordLen();
curRecord = getNextGroupRecord(curRecord);
}
return addGroupRecordAt(recordType, multicastAddress, sourceAddresses, (int)offset);
}
bool IgmpV3ReportLayer::removeGroupRecordAtIndex(int index)
{
int groupCnt = (int)getGroupRecordCount();
if (index < 0 || index >= groupCnt)
{
PCPP_LOG_ERROR("Cannot remove group record, index " << index << " is out of bounds");
return false;
}
size_t offset = sizeof(igmpv3_report_header);
igmpv3_group_record* curRecord = getFirstGroupRecord();
for (int i = 0; i < index; i++)
{
if (curRecord == NULL)
{
PCPP_LOG_ERROR("Cannot remove group record at index " << index << ", cannot find group record at index " << i);
return false;
}
offset += curRecord->getRecordLen();
curRecord = getNextGroupRecord(curRecord);
}
if (!shortenLayer((int)offset, curRecord->getRecordLen()))
{
PCPP_LOG_ERROR("Cannot remove group record at index " << index << ", cannot shorted layer");
return false;
}
getReportHeader()->numOfGroupRecords = htobe16(groupCnt-1);
return true;
}
bool IgmpV3ReportLayer::removeAllGroupRecords()
{
int offset = (int)sizeof(igmpv3_report_header);
if (!shortenLayer(offset, getHeaderLen()-offset))
{
PCPP_LOG_ERROR("Cannot remove all group records, cannot shorted layer");
return false;
}
getReportHeader()->numOfGroupRecords = 0;
return true;
}
/*********************
* igmpv3_group_record
*********************/
uint16_t igmpv3_group_record::getSourceAddressCount() const
{
return be16toh(numOfSources);
}
IPv4Address igmpv3_group_record::getSourceAddressAtIndex(int index) const
{
uint16_t numOfRecords = getSourceAddressCount();
if (index < 0 || index >= numOfRecords)
return IPv4Address();
int offset = index * sizeof(uint32_t);
const uint8_t* ptr = sourceAddresses + offset;
return IPv4Address(*(uint32_t*)ptr);
}
size_t igmpv3_group_record::getRecordLen() const
{
uint16_t numOfRecords = getSourceAddressCount();
int headerLen = numOfRecords * sizeof(uint32_t) + sizeof(igmpv3_group_record);
return (size_t)headerLen;
}
}
| seladb/PcapPlusPlus | Packet++/src/IgmpLayer.cpp | C++ | unlicense | 14,266 |
#include "line_modification.hh"
#include "buffer.hh"
#include "unit_tests.hh"
namespace Kakoune
{
static LineModification make_line_modif(const Buffer::Change& change)
{
LineCount num_added = 0, num_removed = 0;
if (change.type == Buffer::Change::Insert)
{
num_added = change.end.line - change.begin.line;
// inserted a new line at buffer end but end coord is on same line
if (change.at_end and change.end.column != 0)
++num_added;
}
else
{
num_removed = change.end.line - change.begin.line;
// removed last line, but end coord is on same line
if (change.at_end and change.end.column != 0)
++num_removed;
}
// modified a line
if (not change.at_end and
(change.begin.column != 0 or change.end.column != 0))
{
++num_removed;
++num_added;
}
return { change.begin.line, change.begin.line, num_removed, num_added };
}
Vector<LineModification> compute_line_modifications(const Buffer& buffer, size_t timestamp)
{
Vector<LineModification> res;
for (auto& buf_change : buffer.changes_since(timestamp))
{
auto change = make_line_modif(buf_change);
auto pos = std::upper_bound(res.begin(), res.end(), change.new_line,
[](const LineCount& l, const LineModification& c)
{ return l < c.new_line; });
if (pos != res.begin())
{
auto& prev = *(pos-1);
if (change.new_line <= prev.new_line + prev.num_added)
{
--pos;
const LineCount removed_from_previously_added_by_pos =
clamp(pos->new_line + pos->num_added - change.new_line,
0_line, std::min(pos->num_added, change.num_removed));
pos->num_removed += change.num_removed - removed_from_previously_added_by_pos;
pos->num_added += change.num_added - removed_from_previously_added_by_pos;
}
else
{
change.old_line -= prev.diff();
pos = res.insert(pos, change);
}
}
else
pos = res.insert(pos, change);
auto next = pos + 1;
auto diff = buf_change.end.line - buf_change.begin.line;
if (buf_change.type == Buffer::Change::Erase)
{
auto delend = std::upper_bound(next, res.end(), change.new_line + change.num_removed,
[](const LineCount& l, const LineModification& c)
{ return l < c.new_line; });
for (auto it = next; it != delend; ++it)
{
const LineCount removed_from_previously_added_by_it =
std::min(it->num_added, change.new_line + change.num_removed - it->new_line);
pos->num_removed += it->num_removed - removed_from_previously_added_by_it;
pos->num_added += it->num_added - removed_from_previously_added_by_it;
}
next = res.erase(next, delend);
for (auto it = next; it != res.end(); ++it)
it->new_line -= diff;
}
else
{
for (auto it = next; it != res.end(); ++it)
it->new_line += diff;
}
}
return res;
}
bool operator==(const LineModification& lhs, const LineModification& rhs)
{
return std::tie(lhs.old_line, lhs.new_line, lhs.num_removed, lhs.num_added) ==
std::tie(rhs.old_line, rhs.new_line, rhs.num_removed, rhs.num_added);
}
UnitTest test_line_modifications{[]()
{
{
Buffer buffer("test", Buffer::Flags::None, "line 1\nline 2\n");
auto ts = buffer.timestamp();
buffer.erase(buffer.iterator_at({1, 0}), buffer.iterator_at({2, 0}));
auto modifs = compute_line_modifications(buffer, ts);
kak_assert(modifs.size() == 1 && modifs[0] == LineModification{ 1 COMMA 1 COMMA 1 COMMA 0 });
}
{
Buffer buffer("test", Buffer::Flags::None, "line 1\nline 2\n");
auto ts = buffer.timestamp();
buffer.insert(buffer.iterator_at({1, 7}), "line 3");
auto modifs = compute_line_modifications(buffer, ts);
kak_assert(modifs.size() == 1 && modifs[0] == LineModification{ 2 COMMA 2 COMMA 0 COMMA 1 });
}
{
Buffer buffer("test", Buffer::Flags::None, "line 1\nline 2\nline 3\n");
auto ts = buffer.timestamp();
buffer.insert(buffer.iterator_at({1, 4}), "hoho\nhehe");
buffer.erase(buffer.iterator_at({0, 0}), buffer.iterator_at({1, 0}));
auto modifs = compute_line_modifications(buffer, ts);
kak_assert(modifs.size() == 1 && modifs[0] == LineModification{ 0 COMMA 0 COMMA 2 COMMA 2 });
}
{
Buffer buffer("test", Buffer::Flags::None, "line 1\nline 2\nline 3\nline 4\n");
auto ts = buffer.timestamp();
buffer.erase(buffer.iterator_at({0,0}), buffer.iterator_at({3,0}));
buffer.insert(buffer.iterator_at({1,0}), "newline 1\nnewline 2\nnewline 3\n");
buffer.erase(buffer.iterator_at({0,0}), buffer.iterator_at({1,0}));
{
auto modifs = compute_line_modifications(buffer, ts);
kak_assert(modifs.size() == 1 && modifs[0] == LineModification{ 0 COMMA 0 COMMA 4 COMMA 3 });
}
buffer.insert(buffer.iterator_at({3,0}), "newline 4\n");
{
auto modifs = compute_line_modifications(buffer, ts);
kak_assert(modifs.size() == 1 && modifs[0] == LineModification{ 0 COMMA 0 COMMA 4 COMMA 4 });
}
}
{
Buffer buffer("test", Buffer::Flags::None, "line 1\n");
auto ts = buffer.timestamp();
buffer.insert(buffer.iterator_at({0,0}), "n");
buffer.insert(buffer.iterator_at({0,1}), "e");
buffer.insert(buffer.iterator_at({0,2}), "w");
auto modifs = compute_line_modifications(buffer, ts);
kak_assert(modifs.size() == 1 && modifs[0] == LineModification{ 0 COMMA 0 COMMA 1 COMMA 1 });
}
}};
}
| alpha123/kakoune | src/line_modification.cc | C++ | unlicense | 6,123 |
// -*- Mode: objc -*-
@import Cocoa;
#import "CoreConfigurationModel.h"
@interface KarabinerKitConfigurationManager : NSObject
@property(readonly) KarabinerKitCoreConfigurationModel* coreConfigurationModel;
+ (KarabinerKitConfigurationManager*)sharedManager;
- (void)save;
@end
| epegzz/Karabiner-Elements | src/apps/lib/KarabinerKit/KarabinerKit/ConfigurationManager.h | C | unlicense | 284 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.