code stringlengths 3 1.05M | repo_name stringlengths 4 116 | path stringlengths 4 991 | language stringclasses 9 values | license stringclasses 15 values | size int32 3 1.05M |
|---|---|---|---|---|---|
<?php
$registration_notice = '';
$success = false;
if ( isset($_POST['submit_registration']) ) { // process registration
$username = isset($_POST['username']) ? trim($_POST['username']) : '';
$email = isset($_POST['email']) ? trim($_POST['email']) : '';
$password = isset($_POST['password']) ? trim($_POST['password']) : '';
$password2 = isset($_POST['password2']) ? trim($_POST['password2']) : '';
if ( !empty($username) &&
!empty($email) &&
!empty($password) &&
$password == $password2 ) {
$registration = $db->prepare("INSERT INTO users (`login`, `email`, `password`, `created_at`) VALUES (?, ?, PASSWORD(?), ?)");
$success = $registration->execute(
array(
$username,
$email,
$password,
date(MYSQL_DATETIME)
)
);
if ($success) {
$registration_notice = "Registrazione eseguita correttamente. Ti è stata inviata un'email di conferma.";
$success = true;
} else { // fail
$registration_notice = "Registrazione fallita. Per favore riprova.";
}
} else { // invalid data
$registration_notice = "Campi non validi. Per favore aggiorna la pagina e riprova.";
}
echo $registration_notice;
if (!$success) { include_once INC . 'forms/register.php'; }
} else { // show registration form
include_once INC . 'forms/register.php';
}
| simonewebdesign/Fushi | application/accounts/register.php | PHP | mit | 1,329 |
'use strict';
var angular = require('angular');
module.exports = angular.module('services.notifications', [])
.factory('notifications', ['$rootScope', function ($rootScope) {
var notifications = {
'STICKY' : [],
'ROUTE_CURRENT' : [],
'ROUTE_NEXT' : []
};
var notificationsService = {};
var addNotification = function (notificationsArray, notificationObj) {
if (!angular.isObject(notificationObj)) {
throw new Error("Only object can be added to the notification service");
}
notificationsArray.push(notificationObj);
return notificationObj;
};
$rootScope.$on('$routeChangeSuccess', function () {
notifications.ROUTE_CURRENT.length = 0;
notifications.ROUTE_CURRENT = angular.copy(notifications.ROUTE_NEXT);
notifications.ROUTE_NEXT.length = 0;
});
notificationsService.getCurrent = function(){
return [].concat(notifications.STICKY, notifications.ROUTE_CURRENT);
};
notificationsService.pushSticky = function(notification) {
return addNotification(notifications.STICKY, notification);
};
notificationsService.pushForCurrentRoute = function(notification) {
return addNotification(notifications.ROUTE_CURRENT, notification);
};
notificationsService.pushForNextRoute = function(notification) {
return addNotification(notifications.ROUTE_NEXT, notification);
};
notificationsService.remove = function(notification){
angular.forEach(notifications, function (notificationsByType) {
var idx = notificationsByType.indexOf(notification);
if (idx>-1){
notificationsByType.splice(idx,1);
}
});
};
notificationsService.removeAll = function(){
angular.forEach(notifications, function (notificationsByType) {
notificationsByType.length = 0;
});
};
return notificationsService;
}]);
| evangalen/webpack-angular-app | client/src/common/services/notifications.js | JavaScript | mit | 1,830 |
import KolibriModule from 'kolibri_module';
import { getCurrentSession } from 'kolibri.coreVue.vuex.actions';
import router from 'kolibri.coreVue.router';
import Vue from 'kolibri.lib.vue';
import store from 'kolibri.coreVue.vuex.store';
import heartbeat from 'kolibri.heartbeat';
/*
* A class for single page apps that control routing and vuex state.
* Override the routes, mutations, initialState, and RootVue getters.
*/
export default class KolibriApp extends KolibriModule {
/*
* @return {Array[Object]} Array of objects that define vue-router route configurations.
* These will get passed to our internal router, so the handlers should
* be functions that invoke vuex actions.
*/
get routes() {
return [];
}
/*
* @return {Object} An object of vuex mutations, with keys as the mutation name, and
* values that are methods that perform the store mutation.
*/
get mutations() {
return {};
}
/*
* @return {Object} The initial state of the vuex store for this app, this will be merged with
* the core app initial state to instantiate the store.
*/
get initialState() {
return {};
}
/*
* @return {Object} A component definition for the root component of this single page app.
*/
get RootVue() {
return {};
}
/*
* @return {Store} A convenience getter to return the vuex store.
*/
get store() {
return store;
}
/*
* @return {Array[Function]} Array of vuex actions that will do initial state setting before the
* routes are handled. Use this to do initial state setup that needs to
* be dynamically determined, and done before every route in the app.
* Each function should return a promise that resolves when the state
* has been set. These will be invoked after the current session has
* been set in the vuex store, in order to allow these actions to
* reference getters that return data set by the getCurrentSession
* action. As this has always been bootstrapped into the base template
* this should not cause any real slow down in page loading.
*/
get stateSetters() {
return [];
}
ready() {
this.store.registerModule({
state: this.initialState,
mutations: this.mutations,
});
getCurrentSession(store).then(() => {
Promise.all([
// Invoke each of the state setters before initializing the app.
...this.stateSetters.map(setter => setter(this.store)),
]).then(() => {
heartbeat.start();
this.rootvue = new Vue(
Object.assign(
{
el: 'rootvue',
store: store,
router: router.init(this.routes),
},
this.RootVue
)
);
});
});
}
}
| christianmemije/kolibri | kolibri/core/assets/src/kolibri_app.js | JavaScript | mit | 3,037 |
#!/bin/python
"""Fixes some common spelling errors. Might I add that this is one of the
reasons why having a website is useful?
"""
import os
import sys
def levenshtein_ratio(s1, s2, cutoff=None):
max_len = max(len(s1), len(s2))
if cutoff is not None:
cutoff = int(math.ceil((1.0 - cutoff) * max_len) + .1)
return 1.0 - (
float(levenshtein(s1, s2, cutoff=cutoff))
/ max_len
)
def levenshtein(s1, s2, cutoff=None):
"""Compute the Levenshtein edit distance between two strings. If the
minimum distance will be greater than cutoff, then quit early and return
at least cutoff.
"""
if len(s1) < len(s2):
return levenshtein(s2, s1, cutoff)
# len(s1) >= len(s2)
if len(s2) == 0:
return len(s1)
previous_row = range(len(s2) + 1)
for i, c1 in enumerate(s1):
current_row = [i + 1]
current_row_min = sys.maxint
for j, c2 in enumerate(s2):
insertions = previous_row[j + 1] + 1 # j+1 instead of j since previous_row and current_row are one character longer
deletions = current_row[j] + 1 # than s2
substitutions = previous_row[j] + (c1 != c2)
min_all_three = min(
insertions,
deletions,
substitutions
)
current_row.append(min_all_three)
current_row_min = min(current_row_min, min_all_three)
if cutoff is not None and current_row_min > cutoff:
return current_row_min
previous_row = current_row
return previous_row[-1]
def fix_misspellings(test=None):
if test is None:
test = False
words = (
'Anniversary',
'Bonus',
'Cemetery',
'Heritage',
'Historic',
'Historical',
'Monument',
'Memorial',
'National',
'Park',
'Preserve',
'Recreation',
'Recreational',
'Scenic',
)
ok_words = (
'Hermitage',
'History',
'Presence',
'Reception',
'Reservation',
'Renovation',
'Parks',
'Part',
)
for word in words:
command = r"grep -i -P -o '\b[{first_letter}][a-z]{{{length_minus_one},{length_plus_one}}}\b' master_list.csv | sort -u".format(
first_letter=word[0],
length_minus_one=(len(word[1:]) - 1),
length_plus_one=(len(word[1:]) + 1),
)
if test:
print('Running {command}'.format(command=command))
maybe_misspellings = os.popen(command).readlines()
# Trim newlines
maybe_misspellings = [m[:-1] for m in maybe_misspellings]
# Ignore the correct spelling
for j in (word, word.lower(), word.upper()):
if j in maybe_misspellings:
maybe_misspellings.remove(j)
# Ignore ok words
for i in ok_words:
for j in (i, i.lower(), i.upper()):
if j in maybe_misspellings:
maybe_misspellings.remove(j)
# 'Recreationa' => 'Recreational', not 'Recreation'
removals = []
for mm in maybe_misspellings:
if word == 'Historic' or word == 'Recreation':
if 'a' in mm[-3:].lower() or 'l' in mm[-3:].lower():
removals.append(mm)
for r in removals:
maybe_misspellings.remove(r)
# Misspellings must have most of the letters from the word
misspellings = [mm for mm in maybe_misspellings if levenshtein_ratio(mm[1:].lower(), word[1:].lower()) >= .65]
for misspelling in misspellings:
if misspelling == misspelling.upper():
replacement = word.upper()
elif misspelling == misspelling.lower():
replacement = word.lower()
else:
replacement = word
if test:
print(
'{word} found {times} times'.format(
word=misspelling,
times=os.popen(
r"grep -c -P '\b{word}\b' list.csv".format(
word=misspelling,
)
).readlines()[0][:-1],
)
)
print(
'Replacing {word} with {replacement}'.format(
word=misspelling,
replacement=replacement,
)
)
else:
os.system(
r"sed -i -r 's/\b{misspelling}\b/{replacement}/g' list.csv".format(
misspelling=misspelling,
replacement=replacement,
)
)
if __name__ == '__main__':
if len(sys.argv) != 2:
print('Usage: {program} [--test|--run]'.format(program=sys.argv[0]))
sys.exit(1)
elif sys.argv[1] == '--test':
fix_misspellings(test=True)
elif sys.argv[1] == '--run':
fix_misspellings(test=False)
# Fix whte space too
os.system(r"sed -i -r 's/\s+$//' list.csv")
else:
print('Usage: {program} [--test|--run]'.format(program=sys.argv[0]))
sys.exit(1)
| bskari/park-stamper | parks/scripts/initialize_db/fix_spelling.py | Python | mit | 5,292 |
module.exports = require('./lib/tapioca'); | salomaosnff/tapioca-load | index.js | JavaScript | mit | 42 |
package com.thedreamsanctuary.main.java.dreamplus.commands;
import com.thedreamsanctuary.main.java.dreamplus.DreamPlus;
import com.thedreamsanctuary.main.java.dreamplus.executors.DPFood;
import java.util.Random;
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
/**
* @author Ajcool1050
*/
public class GetOtherDrunkCommand implements CommandExecutor
{
final DreamPlus dp;
public GetOtherDrunkCommand(DreamPlus dp)
{
this.dp = dp;
}
@Override
public boolean onCommand(CommandSender sender, Command command, String string, String[] args)
{
if (sender instanceof Player)
{
Player player = (Player) sender;
if (player.hasPermission("dreamplus.command.getotherdrunk"))
{
if (args.length == 2)
{
Player receiver = player.getServer().getPlayer(args[0]);
if (receiver != null)
{
if (isInt(args[1]))
{
int seconds = Integer.parseInt(args[1]);
DPFood.drinkLager(receiver, seconds);
Random random = new Random();
int number = random.nextInt(50) + 1;
if (number == 1)
{
receiver.sendMessage(ChatColor.DARK_GRAY + "["
+ ChatColor.DARK_AQUA + "Kesaro"
+ ChatColor.DARK_GRAY + " -> "
+ ChatColor.GRAY + "You"
+ ChatColor.DARK_GRAY + "]"
+ ChatColor.AQUA + " u fukin wot m8 ill bash ur fkin hed in i swer on me mum");
}
player.sendMessage(ChatColor.GOLD + receiver.getName() + " sure did enjoy their VoxelLager");
}
else player.sendMessage(ChatColor.GOLD + "Usage: /getotherdrunk [player] [seconds]");
}
else player.sendMessage(ChatColor.GOLD + "That player could not be found.");
}
else player.sendMessage(ChatColor.GOLD + "Usage: /getotherdrunk [player] [seconds]");
}
else player.sendMessage("You are not able to execute that command.");
}
else sender.sendMessage("Must be and ingame player to execute command.");
return false;
}
private static boolean isInt(String s)
{
try
{
Integer.parseInt(s);
}
catch (NumberFormatException nfe)
{
return false;
}
return true;
}
}
| TheDreamSanctuary/DreamPlus | main/java/com/thedreamsanctuary/main/java/dreamplus/commands/GetOtherDrunkCommand.java | Java | mit | 3,041 |
module.exports = function(server){
return {
login: require('./login')(server),
logout: require('./logout')(server)
}
}
| julien-sarazin/learning-nodejs | actions/auth/index.js | JavaScript | mit | 135 |
namespace SubsetSums
{
using System.Collections.Generic;
using System.Linq;
public static class SubsetsSumEvaluator
{
/// <summary>
/// Evaluates all possible subset sums. Negative numbers not allowed.
/// </summary>
/// <param name="numbers"></param>
/// <returns></returns>
public static IList<int> FindPossibleSums(int[] numbers)
{
int maxPossibleSum = numbers.Sum();
bool[] possibleSums = new bool[maxPossibleSum + 1];
possibleSums[0] = true;
bool hasZero = false;
int minSum = 0;
int maxSum = 0;
int tempMaxSum = 0;
foreach (var number in numbers)
{
if (!hasZero && number == 0)
{
hasZero = true;
}
for (int i = maxSum; i >= minSum; i--)
{
if (possibleSums[i])
{
var currentNumber = i + number;
if (tempMaxSum < currentNumber)
{
tempMaxSum = currentNumber;
}
possibleSums[currentNumber] = true;
}
}
maxSum = tempMaxSum;
}
var sums = new List<int>();
if (hasZero)
{
sums.Add(0);
}
for (int i = 1; i < possibleSums.Length; i++)
{
if (possibleSums[i])
{
sums.Add(i);
}
}
return sums;
}
/// <summary>
/// Evaluates all possible subset sums. Negative numbers allowed.
/// </summary>
/// <param name="numbers"></param>
/// <returns></returns>
public static IList<int> FindPossibleSumsWithNegative(int[] numbers)
{
// var possitiveNumbers = new List<int>();
// var negativeNumbers = new List<int>();
int minPossibleSum = 0;
int maxPossibleSum = 0;
foreach (var number in numbers)
{
if (number >= 0)
{
// possitiveNumbers.Add(number);
maxPossibleSum += number;
}
else
{
// negativeNumbers.Add(number);
minPossibleSum += number;
}
}
int offset = -1 * minPossibleSum;
bool[] possibleSums = new bool[maxPossibleSum + offset + 1];
possibleSums[offset] = true;
bool hasZero = false;
int minSum = offset;
int maxSum = offset;
int tempMinSum = offset;
int tempMaxSum = offset;
foreach (var number in numbers.Where(n => n >= 0))
{
if (!hasZero && number == 0)
{
hasZero = true;
}
tempMaxSum = maxSum;
for (int i = maxSum; i >= minSum; i--)
{
if (possibleSums[i])
{
var currentNumber = i + number;
if (tempMaxSum < currentNumber)
{
tempMaxSum = currentNumber;
}
possibleSums[currentNumber] = true;
}
}
maxSum = tempMaxSum;
}
foreach (var number in numbers.Where(n => n < 0))
{
tempMinSum = minSum;
for (int i = minSum; i <= maxSum; i++)
{
if (possibleSums[i])
{
var currentNumber = i + number;
if (!hasZero && currentNumber == offset)
{
hasZero = true;
}
if (tempMinSum > currentNumber)
{
tempMinSum = currentNumber;
}
possibleSums[currentNumber] = true;
}
}
minSum = tempMinSum;
}
var sums = new List<int>();
for (int i = 0; i < offset; i++)
{
if (possibleSums[i])
{
sums.Add(i - offset);
}
}
if (hasZero)
{
sums.Add(0);
}
for (int i = offset + 1; i < possibleSums.Length; i++)
{
if (possibleSums[i])
{
sums.Add(i - offset);
}
}
return sums;
}
}
}
| bstaykov/Telerik-DSA | 2015/DynamicProgramming/SubsetSums/SubsetsSumEvaluator.cs | C# | mit | 5,009 |
import { Model } from 'type-r';
import { RestfulFetchOptions, RestfulEndpoint, RestfulIOOptions, HttpMethod } from './restful';
export declare type ConstructUrl = (params: {
[key: string]: any;
}, model?: Model) => string;
export declare function fetchModelIO(method: HttpMethod, url: ConstructUrl, options?: RestfulFetchOptions): ModelFetchEndpoint;
declare class ModelFetchEndpoint extends RestfulEndpoint {
method: HttpMethod;
constructUrl: ConstructUrl;
constructor(method: HttpMethod, constructUrl: ConstructUrl, { mockData, ...options }?: RestfulFetchOptions);
list(): Promise<void>;
destroy(): Promise<void>;
create(): Promise<void>;
update(): Promise<void>;
read(id: any, options: RestfulIOOptions, model: Model): Promise<any>;
}
export {};
| Volicon/Type-R | endpoints/restful/lib/fetchModel.d.ts | TypeScript | mit | 785 |
class CreatePosts < ActiveRecord::Migration
def change
create_table :posts do |t|
t.integer :user_id
t.string :title
t.text :content
t.timestamps null: false
end
end
end
| Bulldogse45/website_on_rails | db/migrate/20151116004951_create_posts.rb | Ruby | mit | 207 |
<?php
// /var/www/symfony2.0/alf/vendor/symfony/src/Symfony/Bundle/FrameworkBundle/Resources/views/Exception/error.atom.twig
return array (
);
| radzikowski/alf | app/cache/dev/assetic/config/e/e3d82803dd71bab66d782bbf081c9e4b.php | PHP | mit | 144 |
using Qwack.Core.Basic;
using Qwack.Core.Instruments;
namespace Qwack.Core.Models
{
public interface IAssetPathPayoff
{
IAssetInstrument AssetInstrument { get; }
double AverageResult { get; }
bool IsComplete { get; }
double ResultStdError { get; }
CashFlowSchedule ExpectedFlows(IAssetFxModel model);
CashFlowSchedule[] ExpectedFlowsByPath(IAssetFxModel model);
void Finish(IFeatureCollection collection);
void Process(IPathBlock block);
void SetupFeatures(IFeatureCollection pathProcessFeaturesCollection);
string RegressionKey { get; }
}
}
| cetusfinance/qwack | src/Qwack.Core/Models/IAssetPathPayoff.cs | C# | mit | 658 |
package org.scenarioo.pizza.pageObjects;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import static org.junit.jupiter.api.Assertions.*;
public class SummaryPage extends BasePage {
public static void assertPizzaVerduraAndRedWineAreListed() {
WebDriver webDriver = getWebDriver();
String pizza = webDriver.findElement(By.id("summary_pizza")).getText();
String drinks = webDriver.findElement(By.id("summary_drinks")).getText();
assertEquals("Pizza Verdura", pizza);
assertEquals("Vino Rosso", drinks);
}
public static void clickOrderButton() {
getStepElement().findElement(By.className("next")).click();
}
private static WebElement getStepElement() {
return getWebDriver().findElement(By.id("step-summary"));
}
}
| scenarioo/pizza-delivery | src/test/java/org/scenarioo/pizza/pageObjects/SummaryPage.java | Java | mit | 861 |
namespace ConsoleTestApp.Features.C
{
using System;
using Miruken.Mvc.Console;
using Buffer = Miruken.Mvc.Console.Buffer;
public class CView : View<CController>
{
private readonly Menu menu;
public CView()
{
var output = new Buffer();
Content = output;
output.Header("C View");
output.WriteLine("C Feature");
output.Block("Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?");
menu = new Menu(new MenuItem("Back", ConsoleKey.B, () => Controller.Back()));
output.WriteLine(menu.ToString());
}
public override void KeyPressed(ConsoleKeyInfo keyInfo)
{
menu.Listen(keyInfo);
}
}
} | Miruken-DotNet/Miruken.Mvc | Test/ConsoleTestApp/Features/C/CView.cs | C# | mit | 1,574 |
/*
* Copyright (c) 2015 Phoenix Scholars Co. (http://dpq.co.ir)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
'use strict';
angular.module('pluf')
/**
* @memberof pluf
* @ngdoc service
* @name $monitor
* @description مدیریت تمام مانیتورها را ایجاد میکند
*
* مانیتورها در واحد زمان باید به روز شوند. این سرویس نه تنها مانیتورها را ایجاد
* بلکه آنها را در واحد زمان به روز میکند.
*
* در صورتی که استفاده از یک مانیتور تمام شود،این سرویس مانیتورهای ایجاد شده را
* حذف میکند تا میزان انتقال اطلاعات را کم کند.
*
* @see PMonitor
*
*/
.service('$collection', function($pluf, PCollection, PObjectFactory) {
var _cache = new PObjectFactory(function(data) {
return new PCollection(data);
});
/**
* Creates new collection
*
* @memberof $collection
* @return Promise<PCollection>
* createdreceipt
*
*/
this.newCollection = $pluf.createNew({
method : 'POST',
url : '/api/collection/new'
}, _cache);
/**
* Gets collection detail. Input could be id or name of collection.
*
* @memberof $collection
* @return Promise<PCollection>
* createdreceipt
*
*/
this.collection = $pluf.createGet({
method : 'GET',
url : '/api/collection/{id}',
}, _cache);
/**
* Lists all collections
*
* @memberof $collection
* @return Promise<PaginatorPage<PCollection>>
* createdreceipt
*
*/
this.collections = $pluf.createFind({
method : 'GET',
url : '/api/collection/find',
}, _cache);
});
| phoenix-scholars/angular-pluf | src/collection/services/collection.js | JavaScript | mit | 2,721 |
package com.nestedworld.nestedworld.data.database.entities;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import com.nestedworld.nestedworld.data.database.entities.base.BaseEntity;
import org.greenrobot.greendao.annotation.Entity;
import org.greenrobot.greendao.annotation.Generated;
import org.greenrobot.greendao.annotation.Id;
import org.greenrobot.greendao.annotation.Unique;
@Entity()
public class ShopItem extends BaseEntity {
@Expose
@SerializedName("id")
@Unique
public long shopItemId;
@Expose
public String name;
@Expose
public String kind;
@Expose
public String power;
@Expose
public Boolean premium;
@Expose
public String description;
@Expose
public long price;
@Expose
public String image;
@Id(autoincrement = true)
@Unique
private Long id;
@Generated(hash = 33734647)
public ShopItem(long shopItemId, String name, String kind, String power,
Boolean premium, String description, long price, String image,
Long id) {
this.shopItemId = shopItemId;
this.name = name;
this.kind = kind;
this.power = power;
this.premium = premium;
this.description = description;
this.price = price;
this.image = image;
this.id = id;
}
@Generated(hash = 872247774)
public ShopItem() {
}
public long getShopItemId() {
return this.shopItemId;
}
public void setShopItemId(long shopItemId) {
this.shopItemId = shopItemId;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public String getKind() {
return this.kind;
}
public void setKind(String kind) {
this.kind = kind;
}
public String getPower() {
return this.power;
}
public void setPower(String power) {
this.power = power;
}
public Boolean getPremium() {
return this.premium;
}
public void setPremium(Boolean premium) {
this.premium = premium;
}
public String getDescription() {
return this.description;
}
public void setDescription(String description) {
this.description = description;
}
public long getPrice() {
return this.price;
}
public void setPrice(long price) {
this.price = price;
}
public String getImage() {
return this.image;
}
public void setImage(String image) {
this.image = image;
}
public Long getId() {
return this.id;
}
public void setId(Long id) {
this.id = id;
}
}
| NestedWorld/NestedWorld-Android | app/src/main/java/com/nestedworld/nestedworld/data/database/entities/ShopItem.java | Java | mit | 2,768 |
package fi.guagua.pixrayandroid.models;
import java.io.Serializable;
import java.util.ArrayList;
public class ScoreTypes implements Serializable {
private ArrayList<Integer> mIds;
private ArrayList<String> mNames;
private ArrayList<String> mColors;
public ScoreTypes(ArrayList<Integer> ids, ArrayList<String> names, ArrayList<String> colors) {
mIds = ids;
mNames = names;
mColors = colors;
}
public ArrayList<Integer> getIds() {
return mIds;
}
public ArrayList<String> getNames() {
return mNames;
}
public ArrayList<String> getColors() {
return mColors;
}
}
| huiningd/PixrayAndroid | app/src/main/java/fi/guagua/pixrayandroid/models/ScoreTypes.java | Java | mit | 657 |
'use strict'
// ensure endpoint starts w/ http:// or https://
module.exports = function normalizeEndpoint (endpoint, version) {
if (endpoint == null) throw new Error('endpoint is required')
if (typeof endpoint !== 'string') throw new Error('endpoint must be a string')
if (endpoint === '') throw new Error('endpoint must not be empty string')
if (version == null || version === 1) {
version = 'v1'
}
if (version !== 'v1') {
throw new Error('Only v1 of the API is currently supported')
}
// if doesn't match http:// or https://, use https://
endpoint = endpoint.trim() + '/api/' + version + '/'
if (!endpoint.match(/^https?:\/\//)) {
endpoint = 'https://' + endpoint
}
return endpoint
}
| nodesource/nsolid-statsd | node_modules/nsolid-apiclient/lib/normalize-endpoint.js | JavaScript | mit | 726 |
"""
Tahmatassu Web Server
~~~~~~~~~~~~~~~~~~~~~
HTTP-status codes containing module
:copyright: (c) 2014 by Teemu Puukko.
:license: MIT, see LICENSE for more details.
"""
from werkzeug.wsgi import LimitedStream
class StreamConsumingMiddleware(object):
def __init__(self, app):
self.app = app
def __call__(self, environ, start_response):
content_length = environ.get('CONTENT_LENGTH',0)
content_length = 0 if content_length is '' else content_length
stream = LimitedStream(environ.get('wsgi.input'),
int(content_length))
environ['wsgi.input'] = stream
app_iter = self.app(environ, start_response)
try:
stream.exhaust()
for event in app_iter:
yield event
finally:
if hasattr(app_iter, 'close'):
app_iter.close() | puumuki/tahmatassu-api | tahmatassu-server/middlewares.py | Python | mit | 813 |
import React, { Component } from 'react'
import cx from 'classnames'
import Collapse from 'react-collapse'
import {
MdAutorenew as IconChecking,
MdNote as IconSimple,
MdViewDay as IconSeparated,
} from 'react-icons/md'
import fetchGallery from 'helpers/fetchGallery'
import Tabbable from 'components/Tabbable'
class TemplateChooser extends Component {
state = {
// can be basic | gallery
source: 'basic',
isFetching: false,
isError: false,
gallery: [],
}
handleChangeSource = async source => {
this.setState({ source })
if (source === 'gallery') {
if (this.state.isFetching) {
return
}
this.setState({ isFetching: true })
try {
const gallery = await fetchGallery()
this.setState({
isFetching: false,
isError: false,
gallery,
})
this.handleSelectGalleryTemplate(0)
} catch (err) {
this.setState({
isFetching: false,
isError: true,
})
}
} else {
this.props.onSelect('singleBasic')
}
}
handleSelectGalleryTemplate = i => {
this.props.onSelect(this.state.gallery[i])
}
render() {
const { template, onSelect } = this.props
const { source, isFetching, isError, gallery } = this.state
return (
<div className="flow-v-20">
<div className="d-f TemplateChooserTabs">
<Tabbable
onClick={() => this.handleChangeSource('basic')}
className={cx('TemplateChooserTabs--tab f-1 cu-d', {
isActive: source === 'basic',
})}
>
{'Basic'}
</Tabbable>
<Tabbable
onClick={() => this.handleChangeSource('gallery')}
className={cx('TemplateChooserTabs--tab f-1 cu-d', {
isActive: source === 'gallery',
})}
>
{'Gallery'}
</Tabbable>
</div>
<Collapse isOpened springConfig={{ stiffness: 300, damping: 30 }}>
{source === 'basic' ? (
<div className="d-f">
<TabItem
onClick={() => onSelect('singleBasic')}
isSelected={template === 'singleBasic'}
label="Single file, basic layout"
>
<IconSimple size={80} />
</TabItem>
<TabItem
onClick={() => onSelect('headerFooter')}
isSelected={template === 'headerFooter'}
label="Header & Footer"
>
<IconSeparated size={80} />
</TabItem>
</div>
) : source === 'gallery' ? (
<div>
{isFetching ? (
<div className="z" style={{ height: 250 }}>
<IconChecking className="rotating mb-20" size={30} />
{'Fetching templates...'}
</div>
) : isError ? (
<div>{'Error'}</div>
) : (
<div className="r" style={{ height: 450 }}>
<div className="sticky o-y-a Gallery">
{gallery.map((tpl, i) => (
<Tabbable
key={tpl.name}
onClick={() => this.handleSelectGalleryTemplate(i)}
className={cx('Gallery-Item-wrapper', {
isSelected: template.name === tpl.name,
})}
>
<div
className="Gallery-Item"
style={{
backgroundImage: `url(${tpl.thumbnail})`,
}}
>
<div className="Gallery-item-label small">{tpl.name}</div>
</div>
</Tabbable>
))}
</div>
</div>
)}
</div>
) : null}
</Collapse>
</div>
)
}
}
function TabItem({ onClick, isSelected, thumbnail, children, label }) {
return (
<Tabbable
onClick={onClick}
className={cx('Gallery-Item-wrapper', {
isSelected,
})}
>
<div
className="Gallery-Item"
style={{
backgroundImage: thumbnail ? `url(${thumbnail})` : undefined,
}}
>
{children}
<div className="Gallery-item-label small">{label}</div>
</div>
</Tabbable>
)
}
export default TemplateChooser
| mjmlio/mjml-app | src/components/NewProjectModal/TemplateChooser.js | JavaScript | mit | 4,575 |
$(document).ready(function () {
$('.eacc-change-photo-btn').bind('click', function () {
$('#eacc-change-photo-file').click();
return false;
});
$('.icon-menu').on('click', function () {
var is_active = $('#main-menu').hasClass('active');
if (is_active) {
$('#main-menu').slideUp();
$('#main-menu').removeClass('active');
} else {
$('#main-menu').slideDown();
$('#main-menu').addClass('active');
}
});
$('#name-field').blur(function () {
var value = $('#name-field').val();
if (value) {
$('.hello').html('miło Cię poznać!');
} else {
$('.hello').empty();
}
});
$('.login').on('click', function () {
var is_open = $('.auth-form-wrapper').hasClass('open');
if (!is_open) {
$('.auth-login-wrapper').addClass('open');
fullscreenlogin('.auth-login-wrapper');
}
});
$('.close-login').on('click', function () {
$('.auth-login-wrapper').removeClass('open');
})
});
function fullscreenlogin(element) {
var windowheight = $(window).height();
$(element).css('height', windowheight);
$(element).css('height', "touch");
var loginwrapperheight = $('.login-form-wrapper').outerHeight();
if (windowheight > loginwrapperheight) {
$('.login-form-wrapper').css('margin-top', (windowheight - loginwrapperheight) / 2);
}
} | wzywno/tescopl_ng | js/test.js | JavaScript | mit | 1,483 |
import { Component, Input, OnInit } from '@angular/core';
import { LangChangeEvent, TranslateService } from '@ngx-translate/core';
import { Observable } from 'rxjs/Observable';
import { ImagesService } from '../../shared/shared.module';
import { ISkill } from '../../models/skill.model';
import { ITranslation, IWork } from '../../models/work.model';
import { WorksService } from '../../shared/shared.module';
@Component({
selector: 'app-skill',
templateUrl: './skill.component.html',
styleUrls: [ './skill.component.scss' ]
})
export class SkillComponent implements OnInit {
@Input() skill: ISkill;
view: any[] = [ 200, 100 ];
years = '';
proficiency = '';
$worksRelated: Observable<IWork[]>;
imagesService = ImagesService;
constructor(private translate: TranslateService,
private worksService: WorksService) {
}
ngOnInit() {
this.$worksRelated = this.worksService.findWorksBySkill(this.skill.slug);
this.translate.getTranslation(this.translate.currentLang)
.subscribe(translation => this.translateChartsUnits(translation));
this.translate.onLangChange
.switchMap((e: LangChangeEvent) => this.translate.getTranslation(e.lang))
.subscribe(translation => this.translateChartsUnits(translation));
}
formatProficiency(proficiency) {
return `${proficiency}%`;
}
translateChartsUnits(translation) {
this.proficiency = translation.WHO.proficiency;
this.years = translation.WHO.years;
}
getRemoteTranslation(item: ITranslation): string {
return item[ this.translate.currentLang ];
}
}
| plastikaweb/plastikaweb2017 | src/app/who-module/skill/skill.component.ts | TypeScript | mit | 1,587 |
import Route from '@ember/routing/route';
import { inject as service } from '@ember/service';
export default class AttributeRoute extends Route {
@service cognito;
async model({ name }) {
if (name) {
const attrs = await this.cognito.user.getUserAttributesHash();
const value = attrs[name];
return { name, value };
}
return { isNew: true };
}
}
| paulcwatts/ember-cognito | tests/dummy/app/routes/attribute.js | JavaScript | mit | 382 |
import React from 'react';
import clsx from 'clsx';
import { useSelector } from 'react-redux';
import { makeStyles } from '@material-ui/core/styles';
import NoSsr from '@material-ui/core/NoSsr';
import Divider from '@material-ui/core/Divider';
import Grid from '@material-ui/core/Grid';
import Container from '@material-ui/core/Container';
import Button from '@material-ui/core/Button';
import Typography from '@material-ui/core/Typography';
const users = [
{
logo: 'nasa.svg',
logoWidth: 49,
logoHeight: 40,
caption: 'NASA',
},
{
logo: 'walmart-labs.svg',
logoWidth: 205,
logoHeight: 39,
caption: 'Walmart Labs',
class: 'walmart',
},
{
logo: 'capgemini.svg',
logoWidth: 180,
logoHeight: 40,
caption: 'Capgemini',
},
{
logo: 'uniqlo.svg',
logoWidth: 40,
logoHeight: 40,
caption: 'Uniqlo',
},
{
logo: 'bethesda.svg',
logoWidth: 196,
logoHeight: 29,
caption: 'Bethesda',
},
{
logo: 'jpmorgan.svg',
logoWidth: 198,
logoHeight: 40,
caption: 'J.P. Morgan',
},
{
logo: 'shutterstock.svg',
caption: 'Shutterstock',
logoWidth: 205,
logoHeight: 29,
},
{
logo: 'netflix.svg',
logoWidth: 111,
logoHeight: 29,
caption: 'Netflix',
},
{
logo: 'amazon.svg',
logoWidth: 119,
logoHeight: 36,
caption: 'Amazon',
class: 'amazon',
},
{
logo: 'unity.svg',
logoWidth: 138,
logoHeight: 50,
caption: 'Unity',
class: 'unity',
},
{
logo: 'spotify.svg',
logoWidth: 180,
logoHeight: 54,
caption: 'Spotify',
class: 'spotify',
},
];
const useStyles = makeStyles(
(theme) => ({
root: {
padding: theme.spacing(2),
minHeight: 160,
paddingTop: theme.spacing(5),
},
container: {
marginBottom: theme.spacing(4),
},
users: {
padding: theme.spacing(10, 6, 0),
},
grid: {
marginTop: theme.spacing(5),
marginBottom: theme.spacing(5),
},
img: {
margin: theme.spacing(1.5, 3),
},
amazon: {
margin: theme.spacing(2.4, 3, 1.5),
},
unity: {
margin: theme.spacing(0.5, 3, 1.5),
},
spotify: {
margin: theme.spacing(0, 3, 1.5),
},
walmart: {
margin: '13px 4px 12px',
},
button: {
margin: theme.spacing(2, 0, 0),
},
}),
{ name: 'Users' },
);
export default function Users() {
const classes = useStyles();
const t = useSelector((state) => state.options.t);
return (
<div className={classes.root}>
<NoSsr defer>
<Container maxWidth="md" className={classes.container} disableGutters>
<Divider />
<div className={classes.users}>
<Typography variant="h4" component="h2" align="center" gutterBottom>
{t('whosUsing')}
</Typography>
<Typography variant="body1" align="center" gutterBottom>
{t('joinThese')}
</Typography>
<Grid container justify="center" className={classes.grid}>
{users.map((user) => (
<img
key={user.caption}
src={`/static/images/users/${user.logo}`}
alt={user.caption}
className={clsx(classes.img, classes[user.class])}
loading="lazy"
width={user.logoWidth}
height={user.logoHeight}
/>
))}
</Grid>
<Typography variant="body1" align="center" gutterBottom>
{t('usingMui')}
</Typography>
<Grid container justify="center">
<Button
variant="outlined"
href="https://github.com/mui-org/material-ui/issues/22426"
rel="noopener nofollow"
target="_blank"
className={classes.button}
>
{t('letUsKnow')}
</Button>
</Grid>
</div>
</Container>
</NoSsr>
</div>
);
}
| lgollut/material-ui | docs/src/pages/landing/Users.js | JavaScript | mit | 4,076 |
import { LavaJsOptions } from "./types";
export const DefaultOptions: LavaJsOptions = {
autodraw: false,
autoloadGoogle: true,
debug: false,
language: "en",
mapsApiKey: "",
responsive: true,
// datetimeFormat: "",
debounceTimeout: 250,
chartPackages: ["corechart"],
timezone: "America/Los_Angeles"
};
| lavacharts/lava.js | src/DefaultOptions.ts | TypeScript | mit | 322 |
/*
Dorm Room Control Server
July 28, 2014
notify.js
Sends notifications through Pushover's notification API
Copyright (c) 2014 by Tristan Honscheid
<MIT License>
*/
var req = require("request");
var app_token = "abwQbZzfMK7v2GvJcnFy8h1bNYHrTj";
/* Send a POST request to the Pushover
* msgData object:
* {
* "title" : string, message title (opt),
* "priority" : int, -2 = no alert, -1 = quiet, 1 = high priority, 2 = emergency (opt),
* "timestamp" : int, unix timestamp (opt),
* "sound" : string, a supported sound name to play (opt),
* "url" : string, a URL to bundle with the message (opt),
* "url_title" : string, the URL's title (opt)
* }
*/
exports.SendNotification = function(userKey, message, msgData, callback) {
if(typeof userKey !== "string" || typeof message !== "string") {
return false;
}
var postData = {
"token" : app_token,
"user" : userKey,
"message" : message,
"title" : msgData.title,
"url" : msgData.url,
"url_title" : msgData.url_title,
"priority" : msgData.priority,
"timestamp" : msgData.timestamp,
"sound" : msgData.sound
};
var post_options = {
uri : "https://api.pushover.net/1/messages.json",
method : "POST",
form : postData,
headers : {
"User-Agent" : "nodejs"
}
};
req(post_options, function(error, response, body) {
if(!error && response.statusCode==200) {
var data = JSON.parse(body);
if(data.status == 1) {
callback({"error" : false, "error_msg" : "", "code" : data.request});
} else {
callback({"error" : true, "error_msg" : ("Pushover error, status " + response.statusCode + ", " + body)});
}
} else {
callback({"error" : true, "error_msg" : ("HTTP error, status " + response.statusCode + ", " + body)});
}
});
};
| tristantech/Dorm-Room-Automation | NodeServer/lib/notify.js | JavaScript | mit | 1,918 |
// you can use includes, for example:
#include <algorithm>
#include <vector>
using namespace std;
// you can write to stdout for debugging purposes, e.g.
// cout << "this is a debug message" << endl;
int solution(vector<int> &A);
int solution(vector<int> &A) {
// write your code in C++14 (g++ 6.2.0)
sort(A.begin(), A.end());
int n = A.size()-1;
return max(A[0] * A[1] * A[n], A[n] * A[n-1] * A[n-2]);
}
| gonini/Codility-Lesson | Lesson6/MaxProductOfThree/maxProductOfThree.cpp | C++ | mit | 424 |
require 'chef_runner'
require_relative '../../../lib/chef_runner/windows/bootstrap'
require_relative '../../../lib/chef_runner/windows/solo'
require_relative 'spec_helper'
describe ChefRunner::Windows::Solo do
it 'should provision machine using chef-solo' do
ChefRunner.bootstrap(params)
ChefRunner.solo(params)
end
end
def params
{
platform: :windows,
user: 'vagrant',
password: 'vagrant',
chef: {
version: '12.4.1',
repo: 'spec/integration/test-files/repository.tar.gz',
json_file: 'spec/integration/test-files/node.json',
secret_file: 'spec/integration/test-files/secret_file'
},
server: {
host: '10.0.10.253',
port: 5985
},
show_output: false
}
end
| MYOB-Technology/chef_runner | spec/integration/windows/windows_solo_spec.rb | Ruby | mit | 754 |
//..............................................................................
//
// This file is part of the Jancy toolkit.
//
// Jancy is distributed under the MIT license.
// For details see accompanying license.txt file,
// the public copy of which is also available at:
// http://tibbo.com/downloads/archive/jancy/license.txt
//
//..............................................................................
#include "pch.h"
#include "jnc_ct_Closure.h"
#include "jnc_ct_DeclTypeCalc.h"
#include "jnc_ct_ArrayType.h"
#include "jnc_ct_UnionType.h"
#include "jnc_ct_DynamicLibClassType.h"
#include "jnc_ct_DynamicLibNamespace.h"
#include "jnc_ct_ExtensionNamespace.h"
#include "jnc_ct_AsyncLauncherFunction.h"
#include "jnc_ct_ReactorClassType.h"
#include "jnc_ct_Parser.llk.h"
#include "jnc_ct_Parser.llk.cpp"
namespace jnc {
namespace ct {
//..............................................................................
Parser::Parser(
Module* module,
const PragmaSettings* pragmaSettings,
Mode mode
):
m_doxyParser(&module->m_doxyModule) {
m_module = module;
m_mode = mode;
if (pragmaSettings)
m_pragmaSettings = *pragmaSettings;
m_cachedPragmaSettings = pragmaSettings;
m_storageKind = StorageKind_Undefined;
m_accessKind = AccessKind_Undefined;
m_attributeBlock = NULL;
m_lastDeclaredItem = NULL;
m_lastNamedType = NULL;
m_lastPropertyGetterType = NULL;
m_lastPropertyTypeModifiers = 0;
m_reactorType = NULL;
m_reactionIdx = 0;
m_constructorType = NULL;
m_constructorProperty = NULL;
m_topDeclarator = NULL;
}
bool Parser::checkUnusedAttributeBlock() {
if (m_attributeBlock) {
err::setFormatStringError("unused attribute block in declaration");
return false;
}
return true;
}
bool
Parser::tokenizeBody(
sl::BoxList<Token>* tokenList,
const lex::LineColOffset& pos,
const sl::StringRef& body
) {
Unit* unit = m_module->m_unitMgr.getCurrentUnit();
ASSERT(unit);
Lexer lexer(m_mode == Mode_Parse ? LexerMode_Parse : LexerMode_Compile);
if ((m_module->getCompileFlags() & ModuleCompileFlag_Documentation) && !unit->getLib())
lexer.m_channelMask = TokenChannelMask_All; // also include doxy-comments (but not for libs!)
lexer.create(unit->getFilePath(), body);
lexer.setLineColOffset(pos);
char buffer[256];
sl::Array<Token*> scopeAnchorTokenStack(rc::BufKind_Stack, buffer, sizeof(buffer));
bool isScopeFlagMarkupRequired = m_mode != Mode_Parse;
for (;;) {
const Token* token = lexer.getToken();
switch (token->m_token) {
case TokenKind_Eof: // don't add EOF token (parseTokenList adds one automatically)
return true;
case TokenKind_Error:
err::setFormatStringError("invalid character '\\x%02x'", (uchar_t) token->m_data.m_integer);
lex::pushSrcPosError(unit->getFilePath(), token->m_pos);
return false;
}
tokenList->insertTail(*token);
lexer.nextToken();
Token* anchorToken;
if (isScopeFlagMarkupRequired)
switch (token->m_token) {
case '{':
anchorToken = tokenList->getTail().p();
anchorToken->m_data.m_integer = 0; // tokens can be reused, ensure 0
scopeAnchorTokenStack.append(anchorToken);
break;
case '}':
scopeAnchorTokenStack.pop();
break;
case TokenKind_NestedScope:
case TokenKind_Case:
case TokenKind_Default:
if (!scopeAnchorTokenStack.isEmpty()) {
anchorToken = tokenList->getTail().p();
anchorToken->m_data.m_integer = 0; // tokens can be reused, ensure 0
scopeAnchorTokenStack.getBack() = anchorToken;
}
break;
case TokenKind_Catch:
if (!scopeAnchorTokenStack.isEmpty())
scopeAnchorTokenStack.getBack()->m_data.m_integer |= ScopeFlag_CatchAhead | ScopeFlag_HasCatch;
break;
case TokenKind_Finally:
if (!scopeAnchorTokenStack.isEmpty())
scopeAnchorTokenStack.getBack()->m_data.m_integer |= ScopeFlag_FinallyAhead | ScopeFlag_Finalizable;
break;
}
}
}
bool
Parser::pragma(
const sl::StringRef& name,
int value
) {
Pragma pragmaKind = PragmaMap::findValue(name, Pragma_Undefined);
switch (pragmaKind) {
case Pragma_Alignment:
if (value < 0)
m_pragmaSettings.m_fieldAlignment = PragmaDefault_Alignment;
else if (sl::isPowerOf2(value) && value <= 16)
m_pragmaSettings.m_fieldAlignment = value;
else {
err::setFormatStringError("invalid alignment %d", value);
return false;
}
break;
case Pragma_ThinPointers:
m_pragmaSettings.m_pointerModifiers = value > 0 ? (uint_t)TypeModifier_Thin : PragmaDefault_PointerModifiers;
break;
case Pragma_ExposedEnums:
m_pragmaSettings.m_enumFlags = value > 0 ? (uint_t)EnumTypeFlag_Exposed : PragmaDefault_EnumFlags;
break;
default:
err::setFormatStringError("unknown pragma '%s'", name.sz());
return false;
}
m_cachedPragmaSettings = NULL;
return true;
}
void
Parser::addDoxyComment(const Token& token) {
uint_t compileFlags = m_module->getCompileFlags();
if (compileFlags & (ModuleCompileFlag_DisableDoxyComment1 << (token.m_token - TokenKind_DoxyComment1)))
return;
sl::StringRef comment = token.m_data.m_string;
ModuleItem* lastDeclaredItem = NULL;
lex::LineCol pos = token.m_pos;
pos.m_col += 3; // doxygen comments always start with 3 characters: ///, //!, /** /*!
if (!comment.isEmpty() && comment[0] == '<') {
lastDeclaredItem = m_lastDeclaredItem;
comment = comment.getSubString(1);
pos.m_col++;
}
m_doxyParser.addComment(
comment,
pos,
token.m_token <= TokenKind_DoxyComment2, // only concat single-line comments
lastDeclaredItem
);
}
bool
Parser::parseBody(
SymbolKind symbol,
const lex::LineColOffset& pos,
const sl::StringRef& body
) {
sl::BoxList<Token> tokenList;
bool result = tokenizeBody(&tokenList, pos, body);
if (!result)
return false;
return !tokenList.isEmpty() ?
parseTokenList(symbol, tokenList) :
create(m_module->m_unitMgr.getCurrentUnit()->getFilePath(), symbol) &&
parseEofToken(pos, body.getLength());
}
bool
Parser::parseTokenList(
SymbolKind symbol,
const sl::ConstBoxList<Token>& tokenList
) {
ASSERT(!tokenList.isEmpty());
Unit* unit = m_module->m_unitMgr.getCurrentUnit();
create(unit->getFilePath(), symbol);
Token::Pos lastTokenPos = tokenList.getTail()->m_pos;
if (!m_module->m_codeAssistMgr.getCodeAssistKind() ||
!unit->isRootUnit() ||
!isOffsetInsideTokenList(tokenList, m_module->m_codeAssistMgr.getOffset())) {
sl::ConstBoxIterator<Token> token = tokenList.getHead();
for (; token; token++) {
bool result = parseToken(&*token);
if (!result) {
lex::ensureSrcPosError(m_module->m_unitMgr.getCurrentUnit()->getFilePath(), token->m_pos);
return false;
}
}
return parseEofToken(lastTokenPos, lastTokenPos.m_length); // might trigger actions
} else {
size_t offset = m_module->m_codeAssistMgr.getOffset();
size_t autoCompleteFallbackOffset = offset;
bool result = true;
sl::ConstBoxIterator<Token> token = tokenList.getHead();
for (; token; token++) {
bool isCodeAssist = markCodeAssistToken((Token*)token.p(), offset);
if (isCodeAssist) {
if (token->m_tokenKind == TokenKind_Identifier && (token->m_flags & TokenFlag_CodeAssist))
autoCompleteFallbackOffset = token->m_pos.m_offset;
if (token->m_flags & TokenFlag_PostCodeAssist) {
m_module->m_codeAssistMgr.prepareAutoCompleteFallback(autoCompleteFallbackOffset);
if (m_mode == Mode_Compile) {
lastTokenPos = token->m_pos;
break;
}
offset = -1; // not needed anymore
}
}
result = parseToken(&*token);
if (!result)
break;
}
if (result)
parseEofToken(lastTokenPos, lastTokenPos.m_length); // might trigger actions
if (!m_module->m_codeAssistMgr.getCodeAssist() &&
m_module->m_codeAssistMgr.hasArgumentTipStack())
m_module->m_codeAssistMgr.createArgumentTipFromStack();
return true;
}
}
bool
Parser::parseEofToken(
const lex::LineColOffset& pos,
size_t length
) {
Token eofToken;
eofToken.m_token = 0;
eofToken.m_pos.m_line = pos.m_line;
eofToken.m_pos.m_col = pos.m_col + length;
eofToken.m_pos.m_offset = pos.m_offset + length;
bool result = parseToken(&eofToken);
if (!result) {
lex::ensureSrcPosError(m_module->m_unitMgr.getCurrentUnit()->getFilePath(), pos);
return false;
}
return true;
}
bool
Parser::isTypeSpecified() {
if (m_typeSpecifierStack.isEmpty())
return false;
// if we've seen 'unsigned', assume 'int' is implied.
// checking for 'property' is required for full property syntax e.g.:
// property foo { int get (); }
// here 'foo' should be a declarator, not import-type-specifier
// the same logic applies to 'reactor'
TypeSpecifier* typeSpecifier = m_typeSpecifierStack.getBack();
return
typeSpecifier->getType() != NULL ||
typeSpecifier->getTypeModifiers() & (TypeModifier_Unsigned | TypeModifier_Property | TypeModifier_Reactor);
}
NamedImportType*
Parser::getNamedImportType(
const QualifiedName& name,
const lex::LineCol& pos
) {
Namespace* nspace = m_module->m_namespaceMgr.getCurrentNamespace();
NamedImportType* type = m_module->m_typeMgr.getNamedImportType(name, nspace);
if (!type->m_parentUnit) {
type->m_parentUnit = m_module->m_unitMgr.getCurrentUnit();
type->m_pos = pos;
}
return type;
}
Type*
Parser::findType(
size_t baseTypeIdx,
const QualifiedName& name,
const lex::LineCol& pos
) {
Namespace* nspace = m_module->m_namespaceMgr.getCurrentNamespace();
ModuleItem* item;
if (m_mode == Mode_Parse) {
if (baseTypeIdx != -1)
return NULL;
if (!name.isSimple())
return getNamedImportType(name, pos);
sl::String shortName = name.getShortName();
FindModuleItemResult findResult = nspace->findDirectChildItem(shortName);
if (!findResult.m_result)
return NULL;
if (!findResult.m_item)
return getNamedImportType(name, pos);
item = findResult.m_item;
} else {
if (baseTypeIdx != -1) {
DerivableType* baseType = findBaseType(baseTypeIdx);
if (!baseType)
return NULL;
nspace = baseType;
if (name.isEmpty())
return baseType;
}
FindModuleItemResult findResult = nspace->findItemTraverse(name);
if (!findResult.m_item)
return NULL;
item = findResult.m_item;
}
ModuleItemKind itemKind = item->getItemKind();
switch (itemKind) {
case ModuleItemKind_Type:
return (Type*)item;
case ModuleItemKind_Typedef:
return (m_module->getCompileFlags() & ModuleCompileFlag_KeepTypedefShadow) ?
((Typedef*)item)->getShadowType() :
((Typedef*)item)->getType();
default:
return NULL;
}
}
Type*
Parser::getType(
size_t baseTypeIdx,
const QualifiedName& name,
const lex::LineCol& pos
) {
Type* type = findType(baseTypeIdx, name, pos);
if (!type) {
if (baseTypeIdx == -1)
err::setFormatStringError("'%s' is not found or not a type", name.getFullName ().sz());
else if (name.isEmpty())
err::setFormatStringError("'basetype%d' is not found", baseTypeIdx + 1);
else
err::setFormatStringError("'basetype%d.%s' is not found or not a type", baseTypeIdx + 1, name.getFullName ().sz());
return NULL;
}
return type;
}
bool
Parser::setSetAsType(Type* type) {
Namespace* nspace = m_module->m_namespaceMgr.getCurrentNamespace();
if (nspace->getNamespaceKind() != NamespaceKind_Type) {
err::setFormatStringError("invalid setas in '%s'", nspace->getQualifiedName().sz());
return false;
}
DerivableType* derivableType = (DerivableType*)(NamedType*)nspace;
if (derivableType->m_setAsType) {
err::setFormatStringError("setas redefinition for '%s'", derivableType->getTypeString().sz());
return false;
}
derivableType->m_setAsType = type;
if (type->getTypeKindFlags() & TypeKindFlag_Import)
((ImportType*)type)->addFixup(&derivableType->m_setAsType);
return true;
}
bool
Parser::createAttributeBlock(const lex::LineCol& pos) {
ASSERT(!m_attributeBlock);
m_attributeBlock = m_module->m_attributeMgr.createAttributeBlock();
m_attributeBlock->m_parentNamespace = m_module->m_namespaceMgr.getCurrentNamespace();
m_attributeBlock->m_parentUnit = m_module->m_unitMgr.getCurrentUnit();
m_attributeBlock->m_pos = pos;
return true;
}
bool
Parser::createAttribute(
const lex::LineCol& pos,
const sl::StringRef& name,
sl::BoxList<Token>* initializer
) {
ASSERT(m_attributeBlock);
Attribute* attribute = m_attributeBlock->createAttribute(name, initializer);
if (!attribute)
return false;
attribute->m_parentNamespace = m_module->m_namespaceMgr.getCurrentNamespace();
attribute->m_parentUnit = m_module->m_unitMgr.getCurrentUnit();
attribute->m_pos = pos;
return true;
}
void
Parser::preDeclaration() {
m_storageKind = StorageKind_Undefined;
m_accessKind = AccessKind_Undefined;
m_lastDeclaredItem = NULL;
}
bool
Parser::bodylessDeclaration() {
if (m_mode == Mode_Reaction)
return true; // reactor declarations are already processed at this stage
ASSERT(m_lastDeclaredItem);
ModuleItemKind itemKind = m_lastDeclaredItem->getItemKind();
switch (itemKind) {
case ModuleItemKind_Property:
return finalizeLastProperty(false);
case ModuleItemKind_Orphan:
err::setFormatStringError(
"orphan '%s' without a body",
m_lastDeclaredItem->getDecl()->getQualifiedName().sz()
);
return false;
}
return true;
}
bool
Parser::setDeclarationBody(const Token& bodyToken) {
if (!m_lastDeclaredItem) {
err::setFormatStringError("declaration without declarator cannot have a body");
return false;
}
Namespace* nspace = m_module->m_namespaceMgr.getCurrentNamespace();
Function* function;
Orphan* orphan;
Type* type;
ModuleItemKind itemKind = m_lastDeclaredItem->getItemKind();
switch (itemKind) {
case ModuleItemKind_Function:
if (nspace->getNamespaceKind() == NamespaceKind_DynamicLib) {
err::setFormatStringError("dynamiclib function cannot have a body");
return false;
}
function = (Function*)m_lastDeclaredItem;
function->addUsingSet(nspace);
return setBody(function, bodyToken);
case ModuleItemKind_Property:
return parseLastPropertyBody(bodyToken);
case ModuleItemKind_Typedef:
type = ((Typedef*)m_lastDeclaredItem)->getType();
break;
case ModuleItemKind_Type:
type = (Type*)m_lastDeclaredItem;
break;
case ModuleItemKind_Variable:
type = ((Variable*)m_lastDeclaredItem)->getType();
break;
case ModuleItemKind_Field:
type = ((Field*)m_lastDeclaredItem)->getType();
break;
case ModuleItemKind_Orphan:
orphan = (Orphan*)m_lastDeclaredItem;
orphan->addUsingSet(nspace);
return setBody(orphan, bodyToken);
default:
err::setFormatStringError("'%s' cannot have a body", getModuleItemKindString(m_lastDeclaredItem->getItemKind ()));
return false;
}
if (!isClassType(type, ClassTypeKind_Reactor)) {
err::setFormatStringError("only functions and reactors can have bodies, not '%s'", type->getTypeString().sz());
return false;
}
return setBody((ReactorClassType*)type, bodyToken);
}
bool
Parser::setStorageKind(StorageKind storageKind) {
if (m_storageKind) {
err::setFormatStringError(
"more than one storage specifier specifiers ('%s' and '%s')",
getStorageKindString(m_storageKind),
getStorageKindString(storageKind)
);
return false;
}
m_storageKind = storageKind;
return true;
}
bool
Parser::setAccessKind(AccessKind accessKind) {
if (m_accessKind) {
err::setFormatStringError(
"more than one access specifiers ('%s' and '%s')",
getAccessKindString(m_accessKind),
getAccessKindString(accessKind)
);
return false;
}
m_accessKind = accessKind;
return true;
}
void
Parser::postDeclaratorName(Declarator* declarator) {
if (!m_topDeclarator)
m_topDeclarator = declarator;
if (!m_topDeclarator->isQualified() || declarator->m_baseType->getTypeKind() != TypeKind_NamedImport)
return;
// need to re-anchor the import, e.g.:
// A C.foo(); <-- here 'A' should be searched for starting with 'C'
QualifiedName anchorName = m_topDeclarator->m_name;
if (m_topDeclarator->getDeclaratorKind() == DeclaratorKind_Name)
anchorName.removeLastName();
ASSERT(!anchorName.isEmpty());
NamedImportType* importType = m_module->m_typeMgr.getNamedImportType(
((NamedImportType*)declarator->m_baseType)->m_name,
m_module->m_namespaceMgr.getCurrentNamespace(),
anchorName
);
importType->m_parentUnit = m_module->m_unitMgr.getCurrentUnit();
importType->m_pos = declarator->getPos();
declarator->m_baseType = importType;
}
void
Parser::postDeclarator(Declarator* declarator) {
if (declarator == m_topDeclarator)
m_topDeclarator = NULL;
}
GlobalNamespace*
Parser::getGlobalNamespace(
GlobalNamespace* parentNamespace,
const sl::StringRef& name,
const lex::LineCol& pos
) {
GlobalNamespace* nspace;
FindModuleItemResult findResult = parentNamespace->findItem(name);
if (!findResult.m_result)
return NULL;
if (!findResult.m_item) {
nspace = m_module->m_namespaceMgr.createGlobalNamespace(name, parentNamespace);
nspace->m_parentUnit = m_module->m_unitMgr.getCurrentUnit();
nspace->m_pos = pos;
parentNamespace->addItem(nspace);
} else {
if (findResult.m_item->getItemKind() != ModuleItemKind_Namespace) {
err::setFormatStringError("'%s' exists and is not a namespace", parentNamespace->createQualifiedName(name).sz());
return NULL;
}
nspace = (GlobalNamespace*)findResult.m_item;
}
return nspace;
}
GlobalNamespace*
Parser::declareGlobalNamespace(
const lex::LineCol& pos,
const QualifiedName& name,
const Token& bodyToken
) {
Namespace* currentNamespace = m_module->m_namespaceMgr.getCurrentNamespace();
if (currentNamespace->getNamespaceKind() != NamespaceKind_Global) {
err::setFormatStringError("cannot open global namespace in '%s'", getNamespaceKindString(currentNamespace->getNamespaceKind ()));
return NULL;
}
GlobalNamespace* nspace = getGlobalNamespace((GlobalNamespace*)currentNamespace, name.getFirstName(), pos);
if (!nspace)
return NULL;
sl::ConstBoxIterator<sl::StringRef> it = name.getNameList().getHead();
for (; it; it++) {
nspace = getGlobalNamespace(nspace, *it, pos);
if (!nspace)
return NULL;
}
nspace->addBody(
m_module->m_unitMgr.getCurrentUnit(),
getCachedPragmaSettings(),
bodyToken.m_pos,
bodyToken.m_data.m_string
);
if (bodyToken.m_flags & TokenFlag_CodeAssist)
m_module->m_codeAssistMgr.m_containerItem = nspace;
return nspace;
}
ExtensionNamespace*
Parser::declareExtensionNamespace(
const lex::LineCol& pos,
const sl::StringRef& name,
Type* type,
const Token& bodyToken
) {
Namespace* currentNamespace = m_module->m_namespaceMgr.getCurrentNamespace();
ExtensionNamespace* nspace = m_module->m_namespaceMgr.createGlobalNamespace<ExtensionNamespace>(
name,
currentNamespace
);
nspace->m_type = (DerivableType*)type; // force-cast
if (type->getTypeKindFlags() & TypeKindFlag_Import)
((ImportType*)type)->addFixup(&nspace->m_type);
assignDeclarationAttributes(nspace, nspace, pos);
bool result = currentNamespace->addItem(nspace);
if (!result)
return NULL;
result = nspace->setBody(
getCachedPragmaSettings(),
bodyToken.m_pos,
bodyToken.m_data.m_string
);
ASSERT(result);
if (bodyToken.m_flags & TokenFlag_CodeAssist)
m_module->m_codeAssistMgr.m_containerItem = nspace;
return nspace;
}
bool
Parser::useNamespace(
const sl::BoxList<QualifiedName>& nameList,
NamespaceKind namespaceKind,
const lex::LineCol& pos
) {
bool result;
Namespace* nspace = m_module->m_namespaceMgr.getCurrentNamespace();
sl::ConstBoxIterator<QualifiedName> it = nameList.getHead();
for (; it; it++) {
result = nspace->m_usingSet.addNamespace(nspace, namespaceKind, *it);
if (!result)
return false;
}
return true;
}
AttributeBlock*
Parser::popAttributeBlock() {
AttributeBlock* attributeBlock = m_attributeBlock;
m_attributeBlock = NULL;
return attributeBlock;
}
bool
Parser::declareInReaction(Declarator* declarator) {
ASSERT(m_mode == Mode_Reaction && m_reactorType);
if (!declarator->isSimple()) {
err::setFormatStringError("invalid declarator in reactor");
return false;
}
const sl::StringRef& name = declarator->getName().getShortName();
FindModuleItemResult findResult = m_reactorType->findItem(name);
if (!findResult.m_result)
return false;
if (!findResult.m_item) {
err::setFormatStringError("member '%s' not found in reactor '%s'", name.sz(), m_reactorType->getQualifiedName().sz());
return false;
}
m_lastDeclaredItem = findResult.m_item;
if (declarator->m_initializer.isEmpty())
return true;
// modify initializer so it looks like an assignment expression: name = <initializer>
Token token;
token.m_pos = declarator->m_initializer.getHead()->m_pos;
token.m_tokenKind = (TokenKind) '=';
declarator->m_initializer.insertHead(token);
token.m_tokenKind = TokenKind_Identifier;
token.m_data.m_string = name;
declarator->m_initializer.insertHead(token);
Parser parser(m_module, getCachedPragmaSettings(), Mode_Reaction);
parser.m_reactorType = m_reactorType;
parser.m_reactionIdx = m_reactionIdx;
return parser.parseTokenList(SymbolKind_expression, declarator->m_initializer);
}
bool
Parser::declare(Declarator* declarator) {
if (m_mode == Mode_Reaction)
return declareInReaction(declarator);
m_lastDeclaredItem = NULL;
bool isLibrary = m_module->m_namespaceMgr.getCurrentNamespace()->getNamespaceKind() == NamespaceKind_DynamicLib;
if ((declarator->getTypeModifiers() & TypeModifier_Property) && m_storageKind != StorageKind_Typedef) {
if (isLibrary) {
err::setFormatStringError("only functions can be part of library");
return false;
}
// too early to calctype cause maybe this property has a body
// declare a typeless property for now
return declareProperty(declarator, NULL, 0);
}
uint_t declFlags;
Type* type = declarator->calcType(&declFlags);
if (!type)
return false;
DeclaratorKind declaratorKind = declarator->getDeclaratorKind();
uint_t postModifiers = declarator->getPostDeclaratorModifiers();
TypeKind typeKind = type->getTypeKind();
if (isLibrary && typeKind != TypeKind_Function) {
err::setFormatStringError("only functions can be part of library");
return false;
}
if (postModifiers != 0 && typeKind != TypeKind_Function) {
err::setFormatStringError("unused post-declarator modifier '%s'", getPostDeclaratorModifierString(postModifiers).sz());
return false;
}
switch (m_storageKind) {
case StorageKind_Typedef:
return declareTypedef(declarator, type);
case StorageKind_Alias:
return declareAlias(declarator, type, declFlags);
default:
switch (typeKind) {
case TypeKind_Void:
err::setFormatStringError("illegal use of type 'void'");
return false;
case TypeKind_Function:
return declareFunction(declarator, (FunctionType*)type);
case TypeKind_Property:
return declareProperty(declarator, (PropertyType*)type, declFlags);
default:
return type->getStdType() == StdType_ReactorBase ?
declareReactor(declarator, declFlags) :
declareData(declarator, type, declFlags);
}
}
}
void
Parser::assignDeclarationAttributes(
ModuleItem* item,
ModuleItemDecl* decl,
const lex::LineCol& pos,
AttributeBlock* attributeBlock,
dox::Block* doxyBlock
) {
decl->m_accessKind = m_accessKind ?
m_accessKind :
m_module->m_namespaceMgr.getCurrentAccessKind();
// don't overwrite storage unless explicit
if (m_storageKind)
decl->m_storageKind = m_storageKind;
decl->m_pos = pos;
decl->m_parentUnit = m_module->m_unitMgr.getCurrentUnit();
decl->m_parentNamespace = m_module->m_namespaceMgr.getCurrentNamespace();
decl->m_pragmaSettings = getCachedPragmaSettings();
decl->m_attributeBlock = attributeBlock ? attributeBlock : popAttributeBlock();
if (m_module->getCompileFlags() & ModuleCompileFlag_Documentation)
m_module->m_doxyHost.setItemBlock(item, decl, doxyBlock ? doxyBlock : m_doxyParser.popBlock());
item->m_flags |= ModuleItemFlag_User;
m_lastDeclaredItem = item;
}
bool
Parser::declareTypedef(
Declarator* declarator,
Type* type
) {
ASSERT(m_storageKind == StorageKind_Typedef);
if (!declarator->isSimple()) {
err::setFormatStringError("invalid typedef declarator");
return false;
}
Namespace* nspace = m_module->m_namespaceMgr.getCurrentNamespace();
const sl::StringRef& name = declarator->getName().getShortName();
FindModuleItemResult findResult = nspace->findItem(name);
if (!findResult.m_result)
return false;
if (findResult.m_item) {
ModuleItem* prevItem = findResult.m_item;
if (prevItem->getItemKind() != ModuleItemKind_Typedef ||
((Typedef*)prevItem)->getType()->cmp(type) != 0) {
setRedefinitionError(name);
return false;
}
m_attributeBlock = NULL;
m_lastDeclaredItem = prevItem;
m_doxyParser.popBlock();
return true;
}
sl::String qualifiedName = nspace->createQualifiedName(name);
ModuleItem* item;
ModuleItemDecl* decl;
Typedef* tdef = m_module->m_typeMgr.createTypedef(name, qualifiedName, type);
item = tdef;
decl = tdef;
assignDeclarationAttributes(item, decl, declarator);
return nspace->addItem(name, item);
}
bool
Parser::declareAlias(
Declarator* declarator,
Type* type,
uint_t ptrTypeFlags
) {
bool result;
if (!declarator->m_constructor.isEmpty()) {
err::setFormatStringError("alias cannot have constructor");
return false;
}
if (declarator->m_initializer.isEmpty()) {
err::setFormatStringError("missing alias initializer");
return false;
}
if (!declarator->isSimple()) {
err::setFormatStringError("invalid alias declarator");
return false;
}
if (type->getTypeKind() != TypeKind_Void) {
err::setFormatStringError("alias doesn't need a type");
return false;
}
Namespace* nspace = m_module->m_namespaceMgr.getCurrentNamespace();
const sl::StringRef& name = declarator->getName().getShortName();
sl::String qualifiedName = nspace->createQualifiedName(name);
sl::BoxList<Token>* initializer = &declarator->m_initializer;
Alias* alias = m_module->m_namespaceMgr.createAlias(name, qualifiedName, initializer);
assignDeclarationAttributes(alias, alias, declarator);
if (nspace->getNamespaceKind() == NamespaceKind_Property) {
Property* prop = (Property*)nspace;
if (ptrTypeFlags & PtrTypeFlag_Bindable) {
result = prop->setOnChanged(alias);
if (!result)
return false;
} else if (ptrTypeFlags & PtrTypeFlag_AutoGet) {
result = prop->setAutoGetValue(alias);
if (!result)
return false;
}
}
return nspace->addItem(alias);
}
bool
Parser::declareFunction(
Declarator* declarator,
FunctionType* type
) {
Namespace* nspace = m_module->m_namespaceMgr.getCurrentNamespace();
NamespaceKind namespaceKind = nspace->getNamespaceKind();
DeclaratorKind declaratorKind = declarator->getDeclaratorKind();
uint_t postModifiers = declarator->getPostDeclaratorModifiers();
FunctionKind functionKind = declarator->getFunctionKind();
bool hasArgs = !type->getArgArray().isEmpty();
if (declaratorKind == DeclaratorKind_UnaryBinaryOperator) {
ASSERT(functionKind == FunctionKind_UnaryOperator || functionKind == FunctionKind_BinaryOperator);
functionKind = hasArgs ? FunctionKind_BinaryOperator : FunctionKind_UnaryOperator;
}
ASSERT(functionKind);
uint_t functionKindFlags = getFunctionKindFlags(functionKind);
if ((functionKindFlags & FunctionKindFlag_NoStorage) && m_storageKind) {
err::setFormatStringError("'%s' cannot have storage specifier", getFunctionKindString(functionKind));
return false;
}
if ((functionKindFlags & FunctionKindFlag_NoArgs) && hasArgs) {
err::setFormatStringError("'%s' cannot have arguments", getFunctionKindString(functionKind));
return false;
}
if (!m_storageKind) {
m_storageKind =
functionKind == FunctionKind_StaticConstructor ? StorageKind_Static :
namespaceKind == NamespaceKind_Property ? ((Property*)nspace)->getStorageKind() : StorageKind_Undefined;
}
if (namespaceKind == NamespaceKind_PropertyTemplate) {
if (m_storageKind) {
err::setFormatStringError("invalid storage '%s' in property template", getStorageKindString(m_storageKind));
return false;
}
if (postModifiers) {
err::setFormatStringError("unused post-declarator modifier '%s'", getPostDeclaratorModifierString(postModifiers).sz());
return false;
}
bool result = ((PropertyTemplate*)nspace)->addMethod(functionKind, type);
if (!result)
return false;
m_lastDeclaredItem = type;
return true;
}
ModuleItem* functionItem;
ModuleItemDecl* functionItemDecl;
FunctionName* functionName;
if (declarator->isQualified()) {
Orphan* orphan = m_module->m_namespaceMgr.createOrphan(OrphanKind_Function, type);
orphan->m_functionKind = functionKind;
orphan->m_declaratorName = declarator->getName();
functionItem = orphan;
functionItemDecl = orphan;
functionName = orphan;
nspace->addOrphan(orphan);
} else {
Function* function;
if (type->getFlags() & FunctionTypeFlag_Async) {
function = m_module->m_functionMgr.createFunction<AsyncLauncherFunction>(
sl::StringRef(),
sl::StringRef(),
type
);
} else {
function = m_module->m_functionMgr.createFunction(type);
function->m_functionKind = functionKind;
}
functionItem = function;
functionItemDecl = function;
functionName = function;
if (!declarator->m_initializer.isEmpty())
sl::takeOver(&function->m_initializer, &declarator->m_initializer);
}
assignDeclarationAttributes(functionItem, functionItemDecl, declarator);
if (postModifiers & PostDeclaratorModifier_Const)
functionName->m_thisArgTypeFlags = PtrTypeFlag_Const;
switch (functionKind) {
case FunctionKind_Normal:
functionItemDecl->m_name = declarator->getName().getShortName();
functionItemDecl->m_qualifiedName = nspace->createQualifiedName(functionItemDecl->m_name);
break;
case FunctionKind_UnaryOperator:
functionName->m_unOpKind = declarator->getUnOpKind();
functionItemDecl->m_qualifiedName.format(
"%s.unary operator %s",
nspace->getQualifiedName().sz(),
getUnOpKindString(functionName->m_unOpKind)
);
break;
case FunctionKind_BinaryOperator:
functionName->m_binOpKind = declarator->getBinOpKind();
functionItemDecl->m_qualifiedName.format(
"%s.binary operator %s",
nspace->getQualifiedName().sz(),
getBinOpKindString(functionName->m_binOpKind)
);
break;
case FunctionKind_CastOperator:
functionName->m_castOpType = declarator->getCastOpType();
functionItemDecl->m_qualifiedName.format(
"%s.cast operator %s",
nspace->getQualifiedName().sz(),
functionName->m_castOpType->getTypeString().sz()
);
break;
default:
functionItemDecl->m_qualifiedName.format(
"%s.%s",
nspace->getQualifiedName().sz(),
getFunctionKindString(functionKind)
);
}
if (functionItem->getItemKind() == ModuleItemKind_Orphan) {
if (namespaceKind == NamespaceKind_DynamicLib) {
err::setFormatStringError("illegal orphan in dynamiclib '%s'", nspace->getQualifiedName().sz());
return false;
}
return true;
}
ASSERT(functionItem->getItemKind() == ModuleItemKind_Function);
Function* function = (Function*)functionItem;
TypeKind typeKind;
switch (namespaceKind) {
case NamespaceKind_Extension:
return ((ExtensionNamespace*)nspace)->addMethod(function);
case NamespaceKind_Type:
typeKind = ((NamedType*)nspace)->getTypeKind();
switch (typeKind) {
case TypeKind_Struct:
return ((StructType*)nspace)->addMethod(function);
case TypeKind_Union:
return ((UnionType*)nspace)->addMethod(function);
case TypeKind_Class:
return ((ClassType*)nspace)->addMethod(function);
default:
err::setFormatStringError("method members are not allowed in '%s'", ((NamedType*)nspace)->getTypeString().sz());
return false;
}
case NamespaceKind_Property:
return ((Property*)nspace)->addMethod(function);
case NamespaceKind_DynamicLib:
function->m_libraryTableIndex = ((DynamicLibNamespace*)nspace)->m_functionCount++;
// and fall through
default:
if (postModifiers) {
err::setFormatStringError("unused post-declarator modifier '%s'", getPostDeclaratorModifierString(postModifiers).sz());
return false;
}
if (!m_storageKind) {
function->m_storageKind = StorageKind_Static;
} else if (m_storageKind != StorageKind_Static) {
err::setFormatStringError("invalid storage specifier '%s' for a global function", getStorageKindString(m_storageKind));
return false;
}
}
if (!nspace->getParentNamespace()) // module constructor / destructor
switch (functionKind) {
case FunctionKind_Constructor:
case FunctionKind_StaticConstructor:
return m_module->m_functionMgr.addGlobalCtorDtor(GlobalCtorDtorKind_Constructor, function);
case FunctionKind_Destructor:
return m_module->m_functionMgr.addGlobalCtorDtor(GlobalCtorDtorKind_Destructor, function);
}
if (functionKind != FunctionKind_Normal) {
err::setFormatStringError(
"invalid '%s' at '%s' namespace",
getFunctionKindString(functionKind),
getNamespaceKindString(namespaceKind)
);
return false;
}
size_t result = nspace->addFunction(function);
return result != -1 || m_module->m_codeAssistMgr.getCodeAssistKind(); // when doing code-assist, ignore redefinition errors
}
bool
Parser::declareProperty(
Declarator* declarator,
PropertyType* type,
uint_t flags
) {
if (!declarator->isSimple()) {
err::setFormatStringError("invalid property declarator");
return false;
}
Property* prop = createProperty(declarator);
if (!prop)
return false;
if (type) {
prop->m_flags |= flags;
return prop->create(type);
}
m_lastPropertyTypeModifiers = declarator->getTypeModifiers();
if (m_lastPropertyTypeModifiers & TypeModifier_Const)
prop->m_flags |= PropertyFlag_Const;
if (declarator->getBaseType()->getTypeKind() != TypeKind_Void ||
!declarator->getPointerPrefixList().isEmpty() ||
!declarator->getSuffixList().isEmpty()) {
DeclTypeCalc typeCalc;
m_lastPropertyGetterType = typeCalc.calcPropertyGetterType(declarator);
if (!m_lastPropertyGetterType)
return false;
} else {
m_lastPropertyGetterType = NULL;
}
return true;
}
PropertyTemplate*
Parser::createPropertyTemplate() {
PropertyTemplate* propertyTemplate = m_module->m_functionMgr.createPropertyTemplate();
uint_t modifiers = getTypeSpecifier()->clearTypeModifiers(TypeModifier_Property | TypeModifier_Bindable);
if (modifiers & TypeModifier_Bindable)
propertyTemplate->m_typeFlags = PropertyTypeFlag_Bindable;
return propertyTemplate;
}
Property*
Parser::createProperty(Declarator* declarator) {
bool result;
m_lastDeclaredItem = NULL;
Namespace* nspace = m_module->m_namespaceMgr.getCurrentNamespace();
NamespaceKind namespaceKind = nspace->getNamespaceKind();
if (namespaceKind == NamespaceKind_PropertyTemplate) {
err::setFormatStringError("property templates cannot have property members");
return NULL;
}
const sl::StringRef& name = declarator->getName().getShortName();
sl::String qualifiedName = nspace->createQualifiedName(name);
Property* prop = m_module->m_functionMgr.createProperty(name, qualifiedName);
assignDeclarationAttributes(prop, prop, declarator);
TypeKind typeKind;
switch (namespaceKind) {
case NamespaceKind_Extension:
result = ((ExtensionNamespace*)nspace)->addProperty(prop);
if (!result)
return NULL;
break;
case NamespaceKind_Type:
typeKind = ((NamedType*)nspace)->getTypeKind();
switch (typeKind) {
case TypeKind_Struct:
result = ((StructType*)nspace)->addProperty(prop);
break;
case TypeKind_Union:
result = ((UnionType*)nspace)->addProperty(prop);
break;
case TypeKind_Class:
result = ((ClassType*)nspace)->addProperty(prop);
break;
default:
err::setFormatStringError("property members are not allowed in '%s'", ((NamedType*) nspace)->getTypeString().sz());
return NULL;
}
if (!result)
return NULL;
break;
case NamespaceKind_Property:
result = ((Property*)nspace)->addProperty(prop);
if (!result)
return NULL;
break;
default:
if (m_storageKind && m_storageKind != StorageKind_Static) {
err::setFormatStringError("invalid storage specifier '%s' for a global property", getStorageKindString(m_storageKind));
return NULL;
}
result = nspace->addItem(prop);
if (!result)
return NULL;
prop->m_storageKind = StorageKind_Static;
}
return prop;
}
bool
Parser::parseLastPropertyBody(const Token& bodyToken) {
size_t length = bodyToken.m_data.m_string.getLength();
sl::BoxList<Token> tokenList;
return
tokenizeBody(
&tokenList,
lex::LineColOffset(
bodyToken.m_pos.m_line,
bodyToken.m_pos.m_col + 1,
bodyToken.m_pos.m_offset + 1
),
bodyToken.m_data.m_string.getSubString(1, length - 2)
) &&
parseLastPropertyBody(tokenList);
}
bool
Parser::parseLastPropertyBody(const sl::ConstBoxList<Token>& body) {
ASSERT(m_lastDeclaredItem && m_lastDeclaredItem->getItemKind() == ModuleItemKind_Property);
Parser parser(m_module, getCachedPragmaSettings(), Mode_Parse);
m_module->m_namespaceMgr.openNamespace((Property*)m_lastDeclaredItem);
bool result = parser.parseTokenList(SymbolKind_member_block_declaration_list, body);
if (!result)
return false;
m_module->m_namespaceMgr.closeNamespace();
return finalizeLastProperty(true);
}
bool
Parser::finalizeLastProperty(bool hasBody) {
ASSERT(m_lastDeclaredItem && m_lastDeclaredItem->getItemKind() == ModuleItemKind_Property);
bool result;
Property* prop = (Property*)m_lastDeclaredItem;
if (prop->getType())
return true;
// finalize getter
if (prop->m_getter) {
if (m_lastPropertyGetterType && m_lastPropertyGetterType->cmp(prop->m_getter->getType()) != 0) {
err::setFormatStringError("getter type '%s' does not match property declaration", prop->m_getter->getType ()->getTypeString().sz());
return false;
}
} else if (prop->m_autoGetValue) {
ASSERT(prop->m_autoGetValue->getItemKind() == ModuleItemKind_Alias); // otherwise, getter would have been created
} else {
if (!m_lastPropertyGetterType) {
err::setFormatStringError("incomplete property: no 'get' method or 'autoget' field");
return false;
}
Function* getter = (m_lastPropertyTypeModifiers & TypeModifier_AutoGet) ?
m_module->m_functionMgr.createFunction<Property::AutoGetter>(m_lastPropertyGetterType) :
m_module->m_functionMgr.createFunction(m_lastPropertyGetterType);
getter->m_functionKind = FunctionKind_Getter;
getter->m_flags |= ModuleItemFlag_User;
result = prop->addMethod(getter);
if (!result)
return false;
}
// finalize setter
if (!(m_lastPropertyTypeModifiers & TypeModifier_Const) && !hasBody) {
FunctionType* getterType = prop->m_getter->getType()->getShortType();
sl::Array<FunctionArg*> argArray = getterType->getArgArray();
Type* setterArgType = getterType->getReturnType();
if (setterArgType->getTypeKindFlags() & TypeKindFlag_Derivable) {
Type* setAsType = ((DerivableType*)setterArgType)->getSetAsType();
if (setAsType)
setterArgType = setAsType;
}
argArray.append(setterArgType->getSimpleFunctionArg());
FunctionType* setterType = m_module->m_typeMgr.getFunctionType(argArray);
Function* setter = m_module->m_functionMgr.createFunction(setterType);
setter->m_functionKind = FunctionKind_Setter;
setter->m_flags |= ModuleItemFlag_User;
result = prop->addMethod(setter);
if (!result)
return false;
}
// finalize binder
if (m_lastPropertyTypeModifiers & TypeModifier_Bindable) {
if (!prop->m_onChanged) {
result = prop->createOnChanged();
if (!result)
return false;
}
}
// finalize auto-get value
if (m_lastPropertyTypeModifiers & TypeModifier_AutoGet) {
if (!prop->m_autoGetValue) {
result = prop->createAutoGetValue(prop->m_getter->getType()->getReturnType());
if (!result)
return false;
}
}
if (prop->m_getter)
prop->createType();
return true;
}
bool
Parser::declareReactor(
Declarator* declarator,
uint_t ptrTypeFlags
) {
bool result;
if (declarator->getDeclaratorKind() != DeclaratorKind_Name) {
err::setFormatStringError("invalid reactor declarator");
return false;
}
Namespace* nspace = m_module->m_namespaceMgr.getCurrentNamespace();
NamespaceKind namespaceKind = nspace->getNamespaceKind();
NamedType* parentType = NULL;
switch (namespaceKind) {
case NamespaceKind_Property:
parentType = ((Property*)nspace)->getParentType();
break;
case NamespaceKind_Type:
parentType = (NamedType*)nspace;
break;
}
if (parentType && parentType->getTypeKind() != TypeKind_Class) {
err::setFormatStringError("'%s' cannot contain reactor members", parentType->getTypeString().sz());
return false;
}
const sl::StringRef& name = declarator->getName().getShortName();
sl::String qualifiedName = nspace->createQualifiedName(name);
if (declarator->isQualified()) {
Orphan* orphan = m_module->m_namespaceMgr.createOrphan(OrphanKind_Reactor, NULL);
orphan->m_functionKind = FunctionKind_Normal;
orphan->m_declaratorName = declarator->getName();
assignDeclarationAttributes(orphan, orphan, declarator);
nspace->addOrphan(orphan);
} else {
ReactorClassType* type = m_module->m_typeMgr.createReactorType(name, qualifiedName, (ClassType*)parentType);
assignDeclarationAttributes(type, type, declarator);
result = declareData(declarator, type, ptrTypeFlags);
if (!result)
return false;
}
return true;
}
bool
Parser::declareData(
Declarator* declarator,
Type* type,
uint_t ptrTypeFlags
) {
bool result;
if (!declarator->isSimple()) {
err::setFormatStringError("invalid data declarator");
return false;
}
Namespace* nspace = m_module->m_namespaceMgr.getCurrentNamespace();
NamespaceKind namespaceKind = nspace->getNamespaceKind();
switch (namespaceKind) {
case NamespaceKind_PropertyTemplate:
case NamespaceKind_Extension:
err::setFormatStringError("'%s' cannot have data fields", getNamespaceKindString(namespaceKind));
return false;
}
const sl::StringRef& name = declarator->getName().getShortName();
size_t bitCount = declarator->getBitCount();
sl::BoxList<Token>* constructor = &declarator->m_constructor;
sl::BoxList<Token>* initializer = &declarator->m_initializer;
if (isAutoSizeArrayType(type)) {
if (initializer->isEmpty()) {
err::setFormatStringError("auto-size array '%s' should have initializer", type->getTypeString().sz());
return false;
}
ArrayType* arrayType = (ArrayType*)type;
arrayType->m_elementCount = m_module->m_operatorMgr.parseAutoSizeArrayInitializer(arrayType, *initializer);
if (arrayType->m_elementCount == -1)
return false;
if (m_mode == Mode_Compile) {
result = arrayType->ensureLayout();
if (!result)
return false;
}
}
bool isDisposable = false;
if (namespaceKind != NamespaceKind_Property && (ptrTypeFlags & (PtrTypeFlag_AutoGet | PtrTypeFlag_Bindable))) {
err::setFormatStringError("'%s' can only be used on property field", getPtrTypeFlagString(ptrTypeFlags & (PtrTypeFlag_AutoGet | PtrTypeFlag_Bindable)).sz());
return false;
}
Scope* scope = m_module->m_namespaceMgr.getCurrentScope();
StorageKind storageKind = m_storageKind;
switch (storageKind) {
case StorageKind_Undefined:
switch (namespaceKind) {
case NamespaceKind_Scope:
storageKind = (type->getFlags() & TypeFlag_NoStack) ? StorageKind_Heap : StorageKind_Stack;
break;
case NamespaceKind_Type:
storageKind = StorageKind_Member;
break;
case NamespaceKind_Property:
storageKind = ((Property*)nspace)->getParentType() ? StorageKind_Member : StorageKind_Static;
break;
default:
storageKind = StorageKind_Static;
}
break;
case StorageKind_Static:
break;
case StorageKind_Tls:
if (!scope && (!constructor->isEmpty() || !initializer->isEmpty())) {
err::setFormatStringError("global 'threadlocal' variables cannot have initializers");
return false;
}
break;
case StorageKind_Mutable:
switch (namespaceKind) {
case NamespaceKind_Type:
break;
case NamespaceKind_Property:
if (((Property*)nspace)->getParentType())
break;
default:
err::setFormatStringError("'mutable' can only be applied to member fields");
return false;
}
break;
case StorageKind_Disposable:
if (namespaceKind != NamespaceKind_Scope) {
err::setFormatStringError("'disposable' can only be applied to local variables");
return false;
}
if (!isDisposableType(type)) {
err::setFormatStringError("'%s' is not a disposable type", type->getTypeString().sz());
return false;
}
ASSERT(scope);
if (!(scope->getFlags() & ScopeFlag_Disposable))
scope = m_module->m_namespaceMgr.openScope(
declarator->getPos(),
ScopeFlag_Disposable | ScopeFlag_FinallyAhead | ScopeFlag_Finalizable | ScopeFlag_Nested
);
storageKind = (type->getFlags() & TypeFlag_NoStack) ? StorageKind_Heap : StorageKind_Stack;
m_storageKind = StorageKind_Undefined; // don't overwrite
isDisposable = true;
break;
default:
err::setFormatStringError("invalid storage specifier '%s' for variable", getStorageKindString(storageKind));
return false;
}
if (namespaceKind == NamespaceKind_Property) {
Property* prop = (Property*)nspace;
ModuleItem* dataItem = NULL;
if (storageKind == StorageKind_Member) {
Field* field = prop->createField(name, type, bitCount, ptrTypeFlags, constructor, initializer);
if (!field)
return false;
assignDeclarationAttributes(field, field, declarator);
dataItem = field;
} else {
Variable* variable = m_module->m_variableMgr.createVariable(
storageKind,
name,
nspace->createQualifiedName(name),
type,
ptrTypeFlags,
constructor,
initializer
);
assignDeclarationAttributes(variable, variable, declarator);
result = nspace->addItem(variable);
if (!result)
return false;
prop->m_staticVariableArray.append(variable);
dataItem = variable;
}
if (ptrTypeFlags & PtrTypeFlag_Bindable) {
result = prop->setOnChanged(dataItem);
if (!result)
return false;
} else if (ptrTypeFlags & PtrTypeFlag_AutoGet) {
result = prop->setAutoGetValue(dataItem);
if (!result)
return false;
}
} else if (storageKind != StorageKind_Member && storageKind != StorageKind_Mutable) {
Variable* variable = m_module->m_variableMgr.createVariable(
storageKind,
name,
nspace->createQualifiedName(name),
type,
ptrTypeFlags,
constructor,
initializer
);
assignDeclarationAttributes(variable, variable, declarator);
result = nspace->addItem(variable);
if (!result)
return false;
if (nspace->getNamespaceKind() == NamespaceKind_Type) {
NamedType* namedType = (NamedType*)nspace;
TypeKind namedTypeKind = namedType->getTypeKind();
switch (namedTypeKind) {
case TypeKind_Class:
case TypeKind_Struct:
case TypeKind_Union:
((DerivableType*)namedType)->m_staticVariableArray.append(variable);
break;
default:
err::setFormatStringError("field members are not allowed in '%s'", namedType->getTypeString().sz());
return false;
}
} else if (scope) {
result = m_module->m_variableMgr.allocateVariable(variable);
if (!result)
return false;
if (isDisposable) {
result = m_module->m_variableMgr.finalizeDisposableVariable(variable);
if (!result)
return false;
}
switch (storageKind) {
case StorageKind_Stack:
case StorageKind_Heap:
result = m_module->m_variableMgr.initializeVariable(variable);
if (!result)
return false;
break;
case StorageKind_Static:
case StorageKind_Tls:
if (variable->m_initializer.isEmpty() &&
variable->m_type->getTypeKind() != TypeKind_Class &&
!isConstructibleType(variable->m_type))
break;
OnceStmt stmt;
m_module->m_controlFlowMgr.onceStmt_Create(&stmt, variable->m_pos, storageKind);
result = m_module->m_controlFlowMgr.onceStmt_PreBody(&stmt, variable->m_pos);
if (!result)
return false;
result = m_module->m_variableMgr.initializeVariable(variable);
if (!result)
return false;
m_module->m_controlFlowMgr.onceStmt_PostBody(
&stmt,
!variable->m_initializer.isEmpty() ? variable->m_initializer.getTail()->m_pos :
!variable->m_constructor.isEmpty() ? variable->m_constructor.getTail()->m_pos :
variable->m_pos
);
break;
default:
ASSERT(false);
}
}
} else {
ASSERT(nspace->getNamespaceKind() == NamespaceKind_Type);
NamedType* namedType = (NamedType*)nspace;
TypeKind namedTypeKind = namedType->getTypeKind();
Field* field;
switch (namedTypeKind) {
case TypeKind_Class:
field = ((ClassType*)namedType)->createField(name, type, bitCount, ptrTypeFlags, constructor, initializer);
break;
case TypeKind_Struct:
field = ((StructType*)namedType)->createField(name, type, bitCount, ptrTypeFlags, constructor, initializer);
break;
case TypeKind_Union:
field = ((UnionType*)namedType)->createField(name, type, bitCount, ptrTypeFlags, constructor, initializer);
break;
default:
err::setFormatStringError("field members are not allowed in '%s'", namedType->getTypeString().sz());
return false;
}
if (!field)
return false;
assignDeclarationAttributes(field, field, declarator);
}
return true;
}
bool
Parser::declareUnnamedStructOrUnion(DerivableType* type) {
m_storageKind = StorageKind_Undefined;
m_accessKind = AccessKind_Undefined;
Declarator declarator;
declarator.m_declaratorKind = DeclaratorKind_Name;
declarator.m_pos = type->getPos();
return declareData(&declarator, type, 0);
}
FunctionArg*
Parser::createFormalArg(
DeclFunctionSuffix* argSuffix,
Declarator* declarator
) {
Namespace* nspace = m_module->m_namespaceMgr.getCurrentNamespace();
uint_t ptrTypeFlags = 0;
Type* type = declarator->calcType(&ptrTypeFlags);
if (!type)
return NULL;
TypeKind typeKind = type->getTypeKind();
switch (typeKind) {
case TypeKind_Void:
case TypeKind_Class:
case TypeKind_Function:
case TypeKind_Property:
err::setFormatStringError(
"function cannot accept '%s' as an argument",
type->getTypeString().sz()
);
return NULL;
}
if (m_storageKind) {
err::setFormatStringError("invalid storage '%s' for argument", getStorageKindString(m_storageKind));
return NULL;
}
m_storageKind = StorageKind_Stack;
sl::String name;
if (declarator->isSimple()) {
name = declarator->getName().getShortName();
} else if (declarator->getDeclaratorKind() != DeclaratorKind_Undefined) {
err::setFormatStringError("invalid formal argument declarator");
return NULL;
}
FunctionArg* arg = m_module->m_typeMgr.createFunctionArg(
name,
type,
ptrTypeFlags,
&declarator->m_initializer
);
assignDeclarationAttributes(arg, arg, declarator);
argSuffix->m_argArray.append(arg);
return arg;
}
bool
Parser::addEnumFlag(
uint_t* flags,
EnumTypeFlag flag
) {
if (*flags & flag) {
err::setFormatStringError("modifier '%s' used more than once", getEnumTypeFlagString(flag));
return false;
}
*flags |= flag;
return true;
}
EnumType*
Parser::createEnumType(
const sl::StringRef& name,
Type* baseType,
uint_t flags
) {
Namespace* nspace = m_module->m_namespaceMgr.getCurrentNamespace();
EnumType* enumType = NULL;
if (name.isEmpty()) {
flags |= EnumTypeFlag_Exposed;
enumType = m_module->m_typeMgr.createUnnamedEnumType(baseType, flags);
} else {
sl::String qualifiedName = nspace->createQualifiedName(name);
enumType = m_module->m_typeMgr.createEnumType(name, qualifiedName, baseType, flags);
if (!enumType)
return NULL;
bool result = nspace->addItem(enumType);
if (!result)
return NULL;
}
assignDeclarationAttributes(enumType, enumType, m_lastMatchedToken.m_pos);
return enumType;
}
EnumConst*
Parser::createEnumConst(
const sl::StringRef& name,
const lex::LineCol& pos,
sl::BoxList<Token>* initializer
) {
Namespace* nspace = m_module->m_namespaceMgr.getCurrentNamespace();
ASSERT(nspace->getNamespaceKind() == NamespaceKind_Type);
ASSERT(((NamedType*)nspace)->getTypeKind() == TypeKind_Enum);
EnumType* type = (EnumType*)m_module->m_namespaceMgr.getCurrentNamespace();
EnumConst* enumConst = type->createConst(name, initializer);
if (!enumConst)
return NULL;
assignDeclarationAttributes(enumConst, enumConst, pos);
return enumConst;
}
StructType*
Parser::createStructType(
const sl::StringRef& name,
sl::BoxList<Type*>* baseTypeList,
size_t fieldAlignment,
uint_t flags
) {
bool result;
Namespace* nspace = m_module->m_namespaceMgr.getCurrentNamespace();
StructType* structType = NULL;
if (name.isEmpty()) {
structType = m_module->m_typeMgr.createUnnamedStructType(fieldAlignment, flags);
} else {
sl::String qualifiedName = nspace->createQualifiedName(name);
structType = m_module->m_typeMgr.createStructType(name, qualifiedName, fieldAlignment, flags);
if (!structType)
return NULL;
}
if (baseTypeList) {
sl::BoxIterator<Type*> baseType = baseTypeList->getHead();
for (; baseType; baseType++) {
result = structType->addBaseType(*baseType) != NULL;
if (!result)
return NULL;
}
}
if (!name.isEmpty()) {
result = nspace->addItem(structType);
if (!result)
return NULL;
}
assignDeclarationAttributes(structType, structType, m_lastMatchedToken.m_pos);
return structType;
}
UnionType*
Parser::createUnionType(
const sl::StringRef& name,
size_t fieldAlignment,
uint_t flags
) {
bool result;
if (flags & TypeFlag_Dynamic) {
err::setError("dynamic unions are not supported yet");
return NULL;
}
Namespace* nspace = m_module->m_namespaceMgr.getCurrentNamespace();
UnionType* unionType = NULL;
if (name.isEmpty()) {
unionType = m_module->m_typeMgr.createUnnamedUnionType(fieldAlignment, flags);
} else {
sl::String qualifiedName = nspace->createQualifiedName(name);
unionType = m_module->m_typeMgr.createUnionType(name, qualifiedName, fieldAlignment, flags);
if (!unionType)
return NULL;
result = nspace->addItem(unionType);
if (!result)
return NULL;
}
assignDeclarationAttributes(unionType, unionType, m_lastMatchedToken.m_pos);
return unionType;
}
ClassType*
Parser::createClassType(
const sl::StringRef& name,
sl::BoxList<Type*>* baseTypeList,
size_t fieldAlignment,
uint_t flags
) {
bool result;
Namespace* nspace = m_module->m_namespaceMgr.getCurrentNamespace();
ClassType* classType;
if (name.isEmpty()) {
classType = m_module->m_typeMgr.createUnnamedClassType(fieldAlignment, flags);
} else {
sl::String qualifiedName = nspace->createQualifiedName(name);
classType = m_module->m_typeMgr.createClassType(name, qualifiedName, fieldAlignment, flags);
}
if (baseTypeList) {
sl::BoxIterator<Type*> baseType = baseTypeList->getHead();
for (; baseType; baseType++) {
result = classType->addBaseType(*baseType) != NULL;
if (!result)
return NULL;
}
}
if (!name.isEmpty()) {
result = nspace->addItem(classType);
if (!result)
return NULL;
}
assignDeclarationAttributes(classType, classType, m_lastMatchedToken.m_pos);
return classType;
}
DynamicLibClassType*
Parser::createDynamicLibType(const sl::StringRef& name) {
bool result;
Namespace* nspace = m_module->m_namespaceMgr.getCurrentNamespace();
sl::String qualifiedName = nspace->createQualifiedName(name);
DynamicLibClassType* classType = m_module->m_typeMgr.createClassType<DynamicLibClassType>(name, qualifiedName);
Type* baseType = m_module->m_typeMgr.getStdType(StdType_DynamicLib);
result =
classType->addBaseType(baseType) != NULL &&
nspace->addItem(classType);
if (!result)
return NULL;
assignDeclarationAttributes(classType, classType, m_lastMatchedToken.m_pos);
DynamicLibNamespace* dynamicLibNamespace = classType->createLibNamespace();
dynamicLibNamespace->m_parentUnit = classType->getParentUnit();
return classType;
}
bool
Parser::finalizeDynamicLibType() {
Namespace* nspace = m_module->m_namespaceMgr.getCurrentNamespace();
ASSERT(nspace->getNamespaceKind() == NamespaceKind_DynamicLib);
DynamicLibNamespace* dynamicLibNamespace = (DynamicLibNamespace*)nspace;
DynamicLibClassType* dynamicLibType = dynamicLibNamespace->getLibraryType();
bool result = dynamicLibType->ensureFunctionTable();
if (!result)
return false;
m_module->m_namespaceMgr.closeNamespace();
return true;
}
bool
Parser::addReactionBinding(const Value& value) {
ASSERT(m_mode == Mode_Reaction && m_reactorType);
Function* addBindingFunc = getReactorMethod(m_module, ReactorMethod_AddOnChangedBinding);
Value thisValue = m_module->m_functionMgr.getThisValue();
ASSERT(thisValue);
Value onChangedValue;
return
m_module->m_operatorMgr.getPropertyOnChanged(value, &onChangedValue) &&
m_module->m_operatorMgr.callOperator(addBindingFunc, thisValue, onChangedValue);
}
bool
Parser::resetReactionBindings() {
Function* resetBindingsFunc = getReactorMethod(m_module, ReactorMethod_ResetOnChangedBindings);
Value thisValue = m_module->m_functionMgr.getThisValue();
ASSERT(thisValue);
return m_module->m_operatorMgr.callOperator(resetBindingsFunc, thisValue);
}
bool
Parser::reactorOnEventStmt(
const sl::ConstBoxList<Value>& valueList,
Declarator* declarator,
sl::BoxList<Token>* tokenList
) {
ASSERT(m_mode == Mode_Reaction && m_reactorType);
DeclFunctionSuffix* suffix = declarator->getFunctionSuffix();
ASSERT(suffix);
FunctionType* functionType = m_module->m_typeMgr.getFunctionType(suffix->getArgArray());
Function* handler = m_reactorType->createOnEventHandler(m_reactionIdx, functionType);
handler->m_parentUnit = m_module->m_unitMgr.getCurrentUnit();
handler->setBody(tokenList);
Function* addBindingFunc = getReactorMethod(m_module, ReactorMethod_AddOnEventBinding);
Value thisValue = m_module->m_functionMgr.getThisValue();
ASSERT(thisValue);
sl::ConstBoxIterator<Value> it = valueList.getHead();
for (; it; it++) {
bool result = m_module->m_operatorMgr.callOperator(addBindingFunc, thisValue, *it);
if (!result)
return false;
}
return true;
}
bool
Parser::callBaseTypeMemberConstructor(
const QualifiedName& name,
sl::BoxList<Value>* argList
) {
ASSERT(m_constructorType || m_constructorProperty);
Namespace* nspace = m_module->m_functionMgr.getCurrentFunction()->getParentNamespace();
FindModuleItemResult findResult = nspace->findItemTraverse(name);
if (!findResult.m_result)
return false;
if (!findResult.m_item) {
err::setFormatStringError("name '%s' is not found", name.getFullName ().sz());
return false;
}
Type* type = NULL;
ModuleItem* item = findResult.m_item;
ModuleItemKind itemKind = item->getItemKind();
switch (itemKind) {
case ModuleItemKind_Type:
return callBaseTypeConstructor((Type*)item, argList);
case ModuleItemKind_Typedef:
return callBaseTypeConstructor(((Typedef*)item)->getType(), argList);
case ModuleItemKind_Property:
err::setFormatStringError("property construction is not yet implemented");
return false;
case ModuleItemKind_Field:
return callFieldConstructor((Field*)item, argList);
case ModuleItemKind_Variable:
err::setFormatStringError("static field construction is not yet implemented");
return false;
default:
err::setFormatStringError("'%s' cannot be used in base-type-member construct list");
return false;
}
}
DerivableType*
Parser::findBaseType(size_t baseTypeIdx) {
Function* function = m_module->m_functionMgr.getCurrentFunction();
ASSERT(function); // should not be called at pass
DerivableType* parentType = function->getParentType();
if (!parentType)
return NULL;
BaseTypeSlot* slot = parentType->getBaseTypeByIndex(baseTypeIdx);
if (!slot)
return NULL;
return slot->getType();
}
DerivableType*
Parser::getBaseType(size_t baseTypeIdx) {
DerivableType* type = findBaseType(baseTypeIdx);
if (!type) {
err::setFormatStringError("'basetype%d' is not found", baseTypeIdx + 1);
return NULL;
}
return type;
}
bool
Parser::getBaseType(
size_t baseTypeIdx,
Value* resultValue
) {
DerivableType* type = getBaseType(baseTypeIdx);
if (!type)
return false;
resultValue->setNamespace(type);
return true;
}
bool
Parser::callBaseTypeConstructor(
size_t baseTypeIdx,
sl::BoxList<Value>* argList
) {
ASSERT(m_constructorType || m_constructorProperty);
if (m_constructorProperty) {
err::setFormatStringError("'%s.construct' cannot have base-type constructor calls", m_constructorProperty->getQualifiedName().sz());
return false;
}
BaseTypeSlot* baseTypeSlot = m_constructorType->getBaseTypeByIndex(baseTypeIdx);
if (!baseTypeSlot)
return false;
return callBaseTypeConstructorImpl(baseTypeSlot, argList);
}
bool
Parser::callBaseTypeConstructor(
Type* type,
sl::BoxList<Value>* argList
) {
ASSERT(m_constructorType || m_constructorProperty);
if (m_constructorProperty) {
err::setFormatStringError("'%s.construct' cannot have base-type constructor calls", m_constructorProperty->getQualifiedName().sz());
return false;
}
BaseTypeSlot* baseTypeSlot = m_constructorType->findBaseType(type);
if (!baseTypeSlot) {
err::setFormatStringError(
"'%s' is not a base type of '%s'",
type->getTypeString().sz(),
m_constructorType->getTypeString().sz()
);
return false;
}
return callBaseTypeConstructorImpl(baseTypeSlot, argList);
}
bool
Parser::callBaseTypeConstructorImpl(
BaseTypeSlot* baseTypeSlot,
sl::BoxList<Value>* argList
) {
DerivableType* type = baseTypeSlot->getType();
if (baseTypeSlot->m_flags & ModuleItemFlag_Constructed) {
err::setFormatStringError("'%s' is already constructed", type->getTypeString().sz());
return false;
}
OverloadableFunction constructor = type->getConstructor();
if (!constructor) {
err::setFormatStringError("'%s' has no constructor", type->getTypeString().sz());
return false;
}
Value thisValue = m_module->m_functionMgr.getThisValue();
ASSERT(thisValue);
argList->insertHead(thisValue);
bool result = m_module->m_operatorMgr.callOperator(constructor, argList);
if (!result)
return false;
baseTypeSlot->m_flags |= ModuleItemFlag_Constructed;
return true;
}
bool
Parser::callFieldConstructor(
Field* field,
sl::BoxList<Value>* argList
) {
ASSERT(m_constructorType || m_constructorProperty);
Value thisValue = m_module->m_functionMgr.getThisValue();
ASSERT(thisValue);
bool result;
if (m_constructorProperty) {
err::setFormatStringError("property field construction is not yet implemented");
return false;
}
if (field->getParentNamespace() != m_constructorType) {
err::setFormatStringError(
"'%s' is not an immediate field of '%s'",
field->getName().sz(),
m_constructorType->getTypeString().sz()
);
return false;
}
if (field->getFlags() & ModuleItemFlag_Constructed) {
err::setFormatStringError("'%s' is already constructed", field->getName().sz());
return false;
}
if (!(field->getType()->getTypeKindFlags() & TypeKindFlag_Derivable) ||
!((DerivableType*)field->getType())->getConstructor()) {
err::setFormatStringError("'%s' has no constructor", field->getName().sz());
return false;
}
OverloadableFunction constructor = ((DerivableType*)field->getType())->getConstructor();
Value fieldValue;
result =
m_module->m_operatorMgr.getField(thisValue, field, NULL, &fieldValue) &&
m_module->m_operatorMgr.unaryOperator(UnOpKind_Addr, &fieldValue);
if (!result)
return false;
argList->insertHead(fieldValue);
result = m_module->m_operatorMgr.callOperator(constructor, argList);
if (!result)
return false;
field->m_flags |= ModuleItemFlag_Constructed;
return true;
}
bool
Parser::finalizeBaseTypeMemberConstructBlock() {
ASSERT(m_constructorType || m_constructorProperty);
Function* constructor = m_module->m_functionMgr.getCurrentFunction();
FunctionKind functionKind = constructor->getFunctionKind();
ASSERT(functionKind == FunctionKind_Constructor || functionKind == FunctionKind_StaticConstructor);
if (functionKind == FunctionKind_StaticConstructor) {
MemberBlock* memberBlock = m_constructorProperty ?
(MemberBlock*)m_constructorProperty :
(MemberBlock*)m_constructorType;
memberBlock->primeStaticVariables();
return
memberBlock->initializeStaticVariables() &&
memberBlock->callPropertyStaticConstructors();
} else {
Value thisValue = m_module->m_functionMgr.getThisValue();
if (m_constructorProperty)
return
m_constructorProperty->initializeFields(thisValue) &&
m_constructorProperty->callPropertyConstructors(thisValue);
else
return
m_constructorType->callBaseTypeConstructors(thisValue) &&
m_constructorType->callStaticConstructor() &&
m_constructorType->initializeFields(thisValue) &&
m_constructorType->callPropertyConstructors(thisValue);
}
}
bool
Parser::lookupIdentifier(
const Token& token,
Value* value
) {
bool result;
Namespace* nspace = m_module->m_namespaceMgr.getCurrentNamespace();
MemberCoord coord;
FindModuleItemResult findResult = nspace->findDirectChildItemTraverse(token.m_data.m_string, &coord);
if (!findResult.m_result)
return false;
if (!findResult.m_item) {
err::setFormatStringError("undeclared identifier '%s'", token.m_data.m_string.sz());
lex::pushSrcPosError(m_module->m_unitMgr.getCurrentUnit()->getFilePath(), token.m_pos);
return false;
}
Value thisValue;
ModuleItem* item = findResult.m_item;
ModuleItemKind itemKind = item->getItemKind();
switch (itemKind) {
case ModuleItemKind_Namespace:
value->setNamespace((GlobalNamespace*)item);
break;
case ModuleItemKind_Typedef:
item = ((Typedef*)item)->getType();
// and fall through
case ModuleItemKind_Type:
if (!(((Type*)item)->getTypeKindFlags() & TypeKindFlag_Named)) {
err::setFormatStringError("'%s' cannot be used as expression", ((Type*)item)->getTypeString().sz());
return false;
}
value->setNamespace((NamedType*)item);
break;
case ModuleItemKind_Const:
*value = ((Const*)item)->getValue();
break;
case ModuleItemKind_Variable:
value->setVariable((Variable*)item);
break;
case ModuleItemKind_Function:
result = value->trySetFunction((Function*)item);
if (!result)
return false;
if (((Function*)item)->isMember()) {
result = m_module->m_operatorMgr.createMemberClosure(value, (Function*)item);
if (!result)
return false;
}
break;
case ModuleItemKind_FunctionOverload:
value->setFunctionOverload((FunctionOverload*)item);
if (((FunctionOverload*)item)->getFlags() & FunctionOverloadFlag_HasMembers) {
result = m_module->m_operatorMgr.createMemberClosure(value, (FunctionOverload*)item);
if (!result)
return false;
}
break;
case ModuleItemKind_Property:
value->setProperty((Property*)item);
if (((Property*)item)->isMember()) {
result = m_module->m_operatorMgr.createMemberClosure(value, (Property*)item);
if (!result)
return false;
}
break;
case ModuleItemKind_EnumConst:
result = value->trySetEnumConst((EnumConst*)item);
if (!result)
return false;
break;
case ModuleItemKind_Field:
result =
m_module->m_operatorMgr.getThisValue(&thisValue, (Field*)item) &&
m_module->m_operatorMgr.getField(thisValue, (Field*)item, &coord, value);
if (!result)
return false;
m_module->m_operatorMgr.finalizeDualType(thisValue, (Field*)item, value);
break;
default:
err::setFormatStringError(
"%s '%s' cannot be used as expression",
getModuleItemKindString(item->getItemKind()),
token.m_data.m_string.sz()
);
return false;
};
if (m_module->m_codeAssistMgr.getCodeAssistKind() == CodeAssistKind_QuickInfoTip &&
(token.m_flags & TokenFlag_CodeAssist))
m_module->m_codeAssistMgr.createQuickInfoTip(token.m_pos.m_offset, item);
return true;
}
bool
Parser::prepareCurlyInitializerNamedItem(
CurlyInitializer* initializer,
const sl::StringRef& name
) {
Value memberValue;
bool result = m_module->m_operatorMgr.memberOperator(
initializer->m_targetValue,
name,
&initializer->m_memberValue
);
if (!result)
return false;
initializer->m_index = -1;
m_curlyInitializerTargetValue = initializer->m_memberValue;
return true;
}
bool
Parser::prepareCurlyInitializerIndexedItem(CurlyInitializer* initializer) {
if (initializer->m_index == -1) {
err::setFormatStringError("indexed-based initializer cannot be used after named-based initializer");
return false;
}
bool result = m_module->m_operatorMgr.memberOperator(
initializer->m_targetValue,
initializer->m_index,
&initializer->m_memberValue
);
if (!result)
return false;
m_curlyInitializerTargetValue = initializer->m_memberValue;
return true;
}
bool
Parser::skipCurlyInitializerItem(CurlyInitializer* initializer) {
if (initializer->m_index == -1)
return true; // allow finishing comma(s)
initializer->m_index++;
return true;
}
bool
Parser::assignCurlyInitializerItem(
CurlyInitializer* initializer,
const Value& value
) {
if (initializer->m_index == -1 ||
value.getValueKind() != ValueKind_Const ||
!isCharArrayType(value.getType()) ||
!isCharArrayRefType(initializer->m_targetValue.getType())) {
if (initializer->m_index != -1)
initializer->m_index++;
initializer->m_count++;
return m_module->m_operatorMgr.binaryOperator(BinOpKind_Assign, initializer->m_memberValue, value);
}
ArrayType* srcType = (ArrayType*)value.getType();
ArrayType* dstType = (ArrayType*)((DataPtrType*)initializer->m_targetValue.getType())->getTargetType();
size_t length = srcType->getElementCount();
if (dstType->getElementCount() < initializer->m_index + length) {
err::setFormatStringError("literal initializer is too big to fit inside the target array");
return false;
}
initializer->m_index += length;
initializer->m_count++;
Value memberPtrValue;
return
m_module->m_operatorMgr.unaryOperator(UnOpKind_Addr, initializer->m_memberValue, &memberPtrValue) &&
m_module->m_operatorMgr.memCpy(memberPtrValue, value, length);
}
bool
Parser::addFmtSite(
Literal* literal,
const sl::StringRef& string,
const Value& value,
bool isIndex,
const sl::StringRef& fmtSpecifierString
) {
literal->m_binData.append(string.cp(), string.getLength());
FmtSite* site = AXL_MEM_NEW(FmtSite);
site->m_offset = literal->m_binData.getCount();
site->m_fmtSpecifierString = fmtSpecifierString;
literal->m_fmtSiteList.insertTail(site);
literal->m_isZeroTerminated = true;
if (!isIndex) {
site->m_value = value;
return true;
}
if (value.getValueKind() != ValueKind_Const ||
!(value.getType()->getTypeKindFlags() & TypeKindFlag_Integer)) {
err::setFormatStringError("expression is not integer constant");
return false;
}
site->m_index = 0;
memcpy(&site->m_index, value.getConstData(), value.getType()->getSize());
literal->m_lastIndex = site->m_index;
return true;
}
void
Parser::addFmtSite(
Literal* literal,
const sl::StringRef& string,
size_t index
) {
literal->m_binData.append(string.cp(), string.getLength());
FmtSite* site = AXL_MEM_NEW(FmtSite);
site->m_offset = literal->m_binData.getCount();
site->m_index = index;
literal->m_fmtSiteList.insertTail(site);
literal->m_lastIndex = index;
literal->m_isZeroTerminated = true;
}
void
Parser::addFmtSite(
Literal* literal,
const sl::StringRef& string,
const sl::StringRef& fmtSpecifierString
) {
literal->m_binData.append(string.cp(), string.getLength());
FmtSite* site = AXL_MEM_NEW(FmtSite);
site->m_offset = literal->m_binData.getCount();
site->m_index = ++literal->m_lastIndex;
site->m_fmtSpecifierString = fmtSpecifierString;
literal->m_fmtSiteList.insertTail(site);
literal->m_isZeroTerminated = true;
}
bool
Parser::finalizeLiteral(
Literal* literal,
sl::BoxList<Value>* argValueList,
Value* resultValue
) {
bool result;
if (literal->m_fmtSiteList.isEmpty()) {
if (literal->m_isZeroTerminated)
literal->m_binData.append(0);
resultValue->setCharArray(literal->m_binData, literal->m_binData.getCount(), m_module);
return true;
}
char buffer[256];
sl::Array<Value*> argValueArray(rc::BufKind_Stack, buffer, sizeof(buffer));
size_t argCount = 0;
if (argValueList) {
argCount = argValueList->getCount();
argValueArray.setCount(argCount);
sl::BoxIterator<Value> it = argValueList->getHead();
for (size_t i = 0; i < argCount; i++, it++) {
ASSERT(it);
argValueArray[i] = it.p();
}
}
Type* type = m_module->m_typeMgr.getStdType(StdType_FmtLiteral);
Variable* fmtLiteral = m_module->m_variableMgr.createSimpleStackVariable("fmtLiteral", type);
result = m_module->m_variableMgr.initializeVariable(fmtLiteral);
ASSERT(result);
Value fmtLiteralValue = fmtLiteral;
size_t offset = 0;
sl::BitMap argUsageMap;
argUsageMap.setBitCount(argCount);
sl::Iterator<FmtSite> siteIt = literal->m_fmtSiteList.getHead();
for (; siteIt; siteIt++) {
FmtSite* site = *siteIt;
Value* value;
if (site->m_index == -1) {
value = &site->m_value;
} else {
size_t i = site->m_index - 1;
if (i >= argCount) {
err::setFormatStringError("formatting literal doesn't have argument %%%d", site->m_index);
return false;
}
value = argValueArray[i];
argUsageMap.setBit(i);
}
if (site->m_offset > offset) {
size_t length = site->m_offset - offset;
appendFmtLiteralRawData(
fmtLiteralValue,
literal->m_binData + offset,
length
);
offset += length;
}
if (value->isEmpty()) {
err::setFormatStringError("formatting literals arguments cannot be skipped");
return false;
}
result = appendFmtLiteralValue(fmtLiteralValue, *value, site->m_fmtSpecifierString);
if (!result)
return false;
}
size_t unusedArgIdx = argUsageMap.findBit(0, false);
if (unusedArgIdx < argCount) {
err::setFormatStringError("formatting literal argument %%%d is not used", unusedArgIdx + 1);
return false;
}
size_t endOffset = literal->m_binData.getCount();
if (endOffset > offset) {
size_t length = endOffset - offset;
appendFmtLiteralRawData(
fmtLiteralValue,
literal->m_binData + offset,
length
);
}
DataPtrType* resultType = m_module->m_typeMgr.getPrimitiveType(TypeKind_Char)->getDataPtrType(DataPtrTypeKind_Lean);
if (!m_module->hasCodeGen()) {
resultValue->setType(resultType);
return true;
}
Value fatPtrValue;
Value thinPtrValue;
Value validatorValue;
Type* validatorType = m_module->m_typeMgr.getStdType(StdType_DataPtrValidatorPtr);
m_module->m_llvmIrBuilder.createGep2(fmtLiteralValue, 0, NULL, &fatPtrValue);
m_module->m_llvmIrBuilder.createLoad(fatPtrValue, NULL, &fatPtrValue);
m_module->m_llvmIrBuilder.createExtractValue(fatPtrValue, 0, NULL, &thinPtrValue);
m_module->m_llvmIrBuilder.createExtractValue(fatPtrValue, 1, validatorType, &validatorValue);
resultValue->setLeanDataPtr(thinPtrValue.getLlvmValue(), resultType, validatorValue);
return true;
}
void
Parser::appendFmtLiteralRawData(
const Value& fmtLiteralValue,
const void* p,
size_t length
) {
if (!m_module->hasCodeGen())
return;
Function* append = m_module->m_functionMgr.getStdFunction(StdFunc_AppendFmtLiteral_a);
Value literalValue;
literalValue.setCharArray(p, length, m_module);
bool result = m_module->m_operatorMgr.castOperator(&literalValue, m_module->m_typeMgr.getStdType(StdType_CharConstPtr));
ASSERT(result);
Value lengthValue;
lengthValue.setConstSizeT(length, m_module);
Value resultValue;
m_module->m_llvmIrBuilder.createCall3(
append,
append->getType(),
fmtLiteralValue,
literalValue,
lengthValue,
&resultValue
);
}
bool
Parser::appendFmtLiteralValue(
const Value& fmtLiteralValue,
const Value& rawSrcValue,
const sl::StringRef& fmtSpecifierString
) {
if (fmtSpecifierString == "B") // binary format
return appendFmtLiteralBinValue(fmtLiteralValue, rawSrcValue);
Value srcValue;
bool result = m_module->m_operatorMgr.prepareOperand(rawSrcValue, &srcValue);
if (!result)
return false;
StdFunc appendFunc;
Type* type = srcValue.getType();
TypeKind typeKind = type->getTypeKind();
uint_t typeKindFlags = type->getTypeKindFlags();
if (typeKindFlags & TypeKindFlag_Integer) {
static StdFunc funcTable[2][2] = {
{ StdFunc_AppendFmtLiteral_i32, StdFunc_AppendFmtLiteral_ui32 },
{ StdFunc_AppendFmtLiteral_i64, StdFunc_AppendFmtLiteral_ui64 },
};
size_t i1 = type->getSize() > 4;
size_t i2 = (typeKindFlags & TypeKindFlag_Unsigned) != 0;
appendFunc = funcTable[i1][i2];
} else if (typeKindFlags & TypeKindFlag_Fp) {
appendFunc = StdFunc_AppendFmtLiteral_f;
} else if (typeKind == TypeKind_Variant) {
appendFunc = StdFunc_AppendFmtLiteral_v;
} else if (isCharArrayType(type) || isCharArrayRefType(type) || isCharPtrType(type)) {
appendFunc = StdFunc_AppendFmtLiteral_p;
} else {
err::setFormatStringError("don't know how to format '%s'", type->getTypeString().sz());
return false;
}
Function* append = m_module->m_functionMgr.getStdFunction(appendFunc);
Type* argType = append->getType()->getArgArray() [2]->getType();
Value argValue;
result = m_module->m_operatorMgr.castOperator(srcValue, argType, &argValue);
if (!result)
return false;
Value fmtSpecifierValue;
if (!fmtSpecifierString.isEmpty()) {
fmtSpecifierValue.setCharArray(fmtSpecifierString, m_module);
m_module->m_operatorMgr.castOperator(&fmtSpecifierValue, m_module->m_typeMgr.getStdType(StdType_CharConstPtr));
} else {
fmtSpecifierValue = m_module->m_typeMgr.getStdType(StdType_CharConstPtr)->getZeroValue();
}
return m_module->m_operatorMgr.callOperator(
append,
fmtLiteralValue,
fmtSpecifierValue,
argValue
);
}
bool
Parser::appendFmtLiteralBinValue(
const Value& fmtLiteralValue,
const Value& rawSrcValue
) {
Value srcValue;
bool result = m_module->m_operatorMgr.prepareOperand(rawSrcValue, &srcValue);
if (!result)
return false;
if (!m_module->hasCodeGen())
return true;
Type* type = srcValue.getType();
Function* append = m_module->m_functionMgr.getStdFunction(StdFunc_AppendFmtLiteral_a);
Type* argType = m_module->m_typeMgr.getStdType(StdType_BytePtr);
Value sizeValue(
type->getSize(),
m_module->m_typeMgr.getPrimitiveType(TypeKind_SizeT)
);
Value tmpValue;
Value resultValue;
m_module->m_llvmIrBuilder.createAlloca(type, "tmpFmtValue", NULL, &tmpValue);
m_module->m_llvmIrBuilder.createStore(srcValue, tmpValue);
m_module->m_llvmIrBuilder.createBitCast(tmpValue, argType, &tmpValue);
m_module->m_llvmIrBuilder.createCall3(
append,
append->getType(),
fmtLiteralValue,
tmpValue,
sizeValue,
&resultValue
);
return true;
}
bool
Parser::finalizeReSwitchCaseLiteral(
sl::StringRef* data,
const Value& value,
bool isZeroTerminated
) {
if (value.getValueKind() != ValueKind_Const) {
err::setFormatStringError("not a constant literal expression");
return false;
}
size_t length = value.m_type->getSize();
if (isZeroTerminated) {
ASSERT(length);
length--;
}
*data = sl::StringRef(value.m_constData.getHdr(), value.m_constData.cp(), length);
return true;
}
BasicBlock*
Parser::assertCondition(const sl::BoxList<Token>& tokenList) {
bool result;
Value conditionValue;
result = m_module->m_operatorMgr.parseExpression(tokenList, &conditionValue);
if (!result)
return NULL;
BasicBlock* failBlock = m_module->m_controlFlowMgr.createBlock("assert_fail");
BasicBlock* continueBlock = m_module->m_controlFlowMgr.createBlock("assert_continue");
result = m_module->m_controlFlowMgr.conditionalJump(conditionValue, continueBlock, failBlock, failBlock);
if (!result)
return NULL;
return continueBlock;
}
bool
Parser::finalizeAssertStmt(
const sl::BoxList<Token>& conditionTokenList,
const Value& messageValue,
BasicBlock* continueBlock
) {
ASSERT(!conditionTokenList.isEmpty());
sl::String fileName = m_module->m_unitMgr.getCurrentUnit()->getFilePath();
sl::String conditionString = Token::getTokenListString(conditionTokenList);
Token::Pos pos = conditionTokenList.getHead()->m_pos;
Value fileNameValue;
Value lineValue;
Value conditionValue;
fileNameValue.setCharArray(fileName, m_module);
lineValue.setConstInt32(pos.m_line, m_module);
conditionValue.setCharArray(conditionString, m_module);
Function* assertionFailure = m_module->m_functionMgr.getStdFunction(StdFunc_AssertionFailure);
sl::BoxList<Value> argValueList;
argValueList.insertTail(fileNameValue);
argValueList.insertTail(lineValue);
argValueList.insertTail(conditionValue);
if (messageValue) {
argValueList.insertTail(messageValue);
} else {
Value nullValue;
nullValue.setNull(m_module);
argValueList.insertTail(nullValue);
}
bool result = m_module->m_operatorMgr.callOperator(assertionFailure, &argValueList);
if (!result)
return false;
m_module->m_controlFlowMgr.follow(continueBlock);
return true;
}
void
Parser::addScopeAnchorToken(
StmtPass1* stmt,
const Token& token
) {
sl::BoxIterator<Token> it = stmt->m_tokenList.insertTail(token);
stmt->m_scopeAnchorToken = &*it;
stmt->m_scopeAnchorToken->m_data.m_integer = 0; // tokens can be reused, ensure 0
}
void
Parser::generateAutoComplete(
const Token& token,
const Value& value
) {
Namespace* nspace = m_module->m_operatorMgr.getValueNamespace(value);
if (nspace)
generateAutoComplete(token, nspace);
else
m_module->m_codeAssistMgr.createEmptyCodeAssist(token.m_pos.m_offset);
}
void
Parser::generateMemberInfo(
const Token& token,
const Value& value,
const sl::StringRef& name
) {
Namespace* nspace = m_module->m_operatorMgr.getValueNamespace(value);
if (nspace) {
FindModuleItemResult result = nspace->findDirectChildItemTraverse(name, NULL, TraverseFlag_NoParentNamespace);
if (result.m_item)
m_module->m_codeAssistMgr.createQuickInfoTip(token.m_pos.m_offset, result.m_item);
}
}
void
Parser::generateAutoComplete(
const Token& token,
Namespace* nspace,
uint_t flags
) {
size_t offset = token.m_pos.m_offset;
if (token.m_tokenKind != TokenKind_Identifier)
if (token.m_flags & TokenFlag_CodeAssistRight)
offset += token.m_pos.m_length;
else
return;
m_module->m_codeAssistMgr.createAutoComplete(offset, nspace, flags);
}
void
Parser::prepareAutoCompleteFallback(
const Token& token,
const QualifiedName& prefix,
uint_t flags
) {
size_t offset = token.m_pos.m_offset;
if (token.m_tokenKind != TokenKind_Identifier)
if (token.m_flags & TokenFlag_CodeAssistRight)
offset += token.m_pos.m_length;
else
return;
Namespace* nspace = m_module->m_namespaceMgr.getCurrentNamespace();
m_module->m_codeAssistMgr.m_autoCompleteFallback.m_offset = offset;
m_module->m_codeAssistMgr.m_autoCompleteFallback.m_namespace = nspace;
m_module->m_codeAssistMgr.m_autoCompleteFallback.m_prefix = prefix;
m_module->m_codeAssistMgr.m_autoCompleteFallback.m_flags = flags;
}
//..............................................................................
} // namespace ct
} // namespace jnc
| vovkos/jancy | src/jnc_ct/jnc_ct_Parser/jnc_ct_Parser.cpp | C++ | mit | 82,212 |
/********************************************************************
The Multiverse Platform is made available under the MIT License.
Copyright (c) 2012 The Multiverse Foundation
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify,
merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software
is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
OR OTHER DEALINGS IN THE SOFTWARE.
*********************************************************************/
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:2.0.50727.42
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace TerrainAssembler.Properties {
using System;
/// <summary>
/// A strongly-typed resource class, for looking up localized strings, etc.
/// </summary>
// This class was auto-generated by the StronglyTypedResourceBuilder
// class via a tool like ResGen or Visual Studio.
// To add or remove a member, edit your .ResX file then rerun ResGen
// with the /str option, or rebuild your VS project.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "2.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Resources {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources() {
}
/// <summary>
/// Returns the cached ResourceManager instance used by this class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("TerrainAssembler.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Overrides the current thread's CurrentUICulture property for all
/// resource lookups using this strongly typed resource class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
}
}
| longde123/MultiversePlatform | tools/TerrainAssembler/TerrainAssembler/Properties/Resources.Designer.cs | C# | mit | 4,084 |
import { DataView } from '@antv/data-set';
import { Chart } from '@antv/g2';
const data = [
{
State: 'AL',
'Under 5 Years': 310504,
'5 to 13 Years': 552339,
'14 to 17 Years': 259034,
'18 to 24 Years': 450818,
'25 to 44 Years': 1231572,
'45 to 64 Years': 1215966,
'65 Years and Over': 641667,
},
{
State: 'AK',
'Under 5 Years': 52083,
'5 to 13 Years': 85640,
'14 to 17 Years': 42153,
'18 to 24 Years': 74257,
'25 to 44 Years': 198724,
'45 to 64 Years': 183159,
'65 Years and Over': 50277,
},
{
State: 'AZ',
'Under 5 Years': 515910,
'5 to 13 Years': 828669,
'14 to 17 Years': 362642,
'18 to 24 Years': 601943,
'25 to 44 Years': 1804762,
'45 to 64 Years': 1523681,
'65 Years and Over': 862573,
},
{
State: 'AR',
'Under 5 Years': 202070,
'5 to 13 Years': 343207,
'14 to 17 Years': 157204,
'18 to 24 Years': 264160,
'25 to 44 Years': 754420,
'45 to 64 Years': 727124,
'65 Years and Over': 407205,
},
{
State: 'CA',
'Under 5 Years': 2704659,
'5 to 13 Years': 4499890,
'14 to 17 Years': 2159981,
'18 to 24 Years': 3853788,
'25 to 44 Years': 10604510,
'45 to 64 Years': 8819342,
'65 Years and Over': 4114496,
},
{
State: 'CO',
'Under 5 Years': 358280,
'5 to 13 Years': 587154,
'14 to 17 Years': 261701,
'18 to 24 Years': 466194,
'25 to 44 Years': 1464939,
'45 to 64 Years': 1290094,
'65 Years and Over': 511094,
},
{
State: 'CT',
'Under 5 Years': 211637,
'5 to 13 Years': 403658,
'14 to 17 Years': 196918,
'18 to 24 Years': 325110,
'25 to 44 Years': 916955,
'45 to 64 Years': 968967,
'65 Years and Over': 478007,
},
];
const ages = [
'Under 5 Years',
'5 to 13 Years',
'14 to 17 Years',
'18 to 24 Years',
'25 to 44 Years',
'45 to 64 Years',
'65 Years and Over',
];
const dv = new DataView();
dv.source(data)
.transform({
type: 'fold',
fields: ages,
key: 'age',
value: 'population',
retains: ['State'],
})
.transform({
type: 'map',
callback: (obj) => {
const key = obj.age;
let type;
if (key === 'Under 5 Years' || key === '5 to 13 Years' || key === '14 to 17 Years') {
type = 'a';
} else if (key === '18 to 24 Years') {
type = 'b';
} else if (key === '25 to 44 Years') {
type = 'c';
} else {
type = 'd';
}
obj.type = type;
return obj;
},
});
const colorMap = {
'Under 5 Years': '#E3F4BF',
'5 to 13 Years': '#BEF7C8',
'14 to 17 Years': '#86E6C8',
'18 to 24 Years': '#36CFC9',
'25 to 44 Years': '#209BDD',
'45 to 64 Years': '#1581E6',
'65 Years and Over': '#0860BF',
};
const chart = new Chart({
container: 'container',
autoFit: true,
height: 500,
});
chart.coordinate('polar', {
innerRadius: 0.5,
});
chart.data(dv.rows);
chart.scale({
population: {
tickInterval: 5000000,
nice: true,
},
});
chart.axis('population', {
label: {
formatter: (val) => {
return +val / 1000000 + 'M';
},
},
line: null
});
chart.axis('State', {
tickLine: null,
grid: {
alignTick: false,
line: {
style: {
stroke: '#BFBFBF',
lineWidth: 1,
lineDash: [3, 3],
}
}
}
});
chart.legend({
position: 'right',
});
chart.tooltip({
showMarkers: false,
shared: true,
});
chart
.interval()
.position('State*population')
.color('age', (age) => colorMap[age])
.tooltip('age*population', (age, population) => {
return {
name: age,
value: population,
};
})
.adjust([
{
type: 'dodge',
dodgeBy: 'type', // 按照 type 字段进行分组
marginRatio: 1, // 分组中各个柱子之间不留空隙
},
{
type: 'stack',
},
]);
chart.interaction('active-region');
chart.render();
| antvis/g2 | examples/column/dodge-stack/demo/circular-stacked.ts | TypeScript | mit | 3,914 |
#include "VulkanDebug.h"
#include <windows.h>
#include <math.h>
#include <stdlib.h>
#include <string>
#include <cstring>
#include <fstream>
#include <assert.h>
#include <stdio.h>
#include <vector>
#include <fcntl.h>
#include <io.h>
#include <iostream>
#include <vulkan.h>
namespace VKDebug
{
int validationLayerCount = 1;
const char *validationLayerNames[] =
{
// This is a meta layer that enables all of the standard
// validation layers in the correct order :
// threading, parameter_validation, device_limits, object_tracker, image, core_validation, swapchain, and unique_objects
"VK_LAYER_LUNARG_standard_validation"
};
PFN_vkCreateDebugReportCallbackEXT CreateDebugReportCallback;
PFN_vkDestroyDebugReportCallbackEXT DestroyDebugReportCallback;
PFN_vkDebugReportMessageEXT dbgBreakCallback;
VkDebugReportCallbackEXT msgCallback;
VkBool32 MessageCallback(
VkDebugReportFlagsEXT flags,
VkDebugReportObjectTypeEXT objType,
uint64_t srcObject,
size_t location,
int32_t msgCode,
const char* pLayerPrefix,
const char* pMsg,
void* pUserData)
{
char *message = (char *)malloc(strlen(pMsg) + 100);
assert(message);
if (flags & VK_DEBUG_REPORT_ERROR_BIT_EXT)
{
std::cout << "ERROR: " << "[" << pLayerPrefix << "] Code " << msgCode << " : " << pMsg << "\n";
}
else
if (flags & VK_DEBUG_REPORT_WARNING_BIT_EXT)
{
// Uncomment to see warnings
std::cout << "WARNING: " << "[" << pLayerPrefix << "] Code " << msgCode << " : " << pMsg << "\n";
}
else
{
return false;
}
fflush(stdout);
free(message);
return false;
}
void SetupDebugging(VkInstance instance, VkDebugReportFlagsEXT flags, VkDebugReportCallbackEXT callBack)
{
CreateDebugReportCallback = (PFN_vkCreateDebugReportCallbackEXT)vkGetInstanceProcAddr(instance, "vkCreateDebugReportCallbackEXT");
DestroyDebugReportCallback = (PFN_vkDestroyDebugReportCallbackEXT)vkGetInstanceProcAddr(instance, "vkDestroyDebugReportCallbackEXT");
dbgBreakCallback = (PFN_vkDebugReportMessageEXT)vkGetInstanceProcAddr(instance, "vkDebugReportMessageEXT");
VkDebugReportCallbackCreateInfoEXT dbgCreateInfo = {};
dbgCreateInfo.sType = VK_STRUCTURE_TYPE_DEBUG_REPORT_CREATE_INFO_EXT;
dbgCreateInfo.pfnCallback = (PFN_vkDebugReportCallbackEXT)MessageCallback;
dbgCreateInfo.flags = flags;
VkResult err = CreateDebugReportCallback(
instance,
&dbgCreateInfo,
nullptr,
(callBack != nullptr) ? &callBack : &msgCallback);
assert(!err);
}
void freeDebugCallback(VkInstance instance)
{
if (msgCallback != VK_NULL_HANDLE)
{
DestroyDebugReportCallback(instance, msgCallback, nullptr);
}
}
/*PFN_vkDebugMarkerSetObjectNameEXT DebugMarkerSetObjectName = VK_NULL_HANDLE;
PFN_vkCmdDebugMarkerBeginEXT CmdDebugMarkerBegin = VK_NULL_HANDLE;
PFN_vkCmdDebugMarkerEndEXT CmdDebugMarkerEnd = VK_NULL_HANDLE;
PFN_vkCmdDebugMarkerInsertEXT CmdDebugMarkerInsert = VK_NULL_HANDLE;
// Set up the debug marker function pointers
void SetupDebugMarkers(VkDevice device)
{
DebugMarkerSetObjectName = (PFN_vkDebugMarkerSetObjectNameEXT)vkGetDeviceProcAddr(device, "vkDebugMarkerSetObjectNameEXT");
CmdDebugMarkerBegin = (PFN_vkCmdDebugMarkerBeginEXT)vkGetDeviceProcAddr(device, "vkCmdDebugMarkerBeginEXT");
CmdDebugMarkerEnd = (PFN_vkCmdDebugMarkerEndEXT)vkGetDeviceProcAddr(device, "vkCmdDebugMarkerEndEXT");
CmdDebugMarkerInsert = (PFN_vkCmdDebugMarkerInsertEXT)vkGetDeviceProcAddr(device, "vkCmdDebugMarkerInsertEXT");
}*/
} | yunyinghu/CVCT_Vulkan | source/VulkanDebug.cpp | C++ | mit | 3,485 |
<?php
use ElasticSearcher\Parsers\FragmentParser;
use ElasticSearcher\Fragments\Queries\TermQuery;
use ElasticSearcher\Fragments\Analyzers\StandardAnalyzer;
use ElasticSearcher\Dummy\Fragments\Filters\IDFilter;
class FragmentParserTest extends ElasticSearcherTestCase
{
public function testParsingRootLevel()
{
$parser = new FragmentParser();
$body = [
'query' => new TermQuery('name', 'John'),
];
$expectedBody = [
'query' => [
'term' => [
'name' => 'John',
]
]
];
$this->assertEquals($expectedBody, $parser->parse($body));
}
public function testParsingChildLevel()
{
$parser = new FragmentParser();
$body = [
'query' => [
'bool' => [
'and' => [
new TermQuery('name', 'John'),
new TermQuery('category', 'authors'),
]
]
]
];
$expectedBody = [
'query' => [
'bool' => [
'and' => [
[
'term' => [
'name' => 'John'
]
],
[
'term' => [
'category' => 'authors'
]
],
]
]
]
];
$this->assertEquals($expectedBody, $parser->parse($body));
}
public function testParsingNestedFragments()
{
$parser = new FragmentParser();
$body = [
'query' => [
'bool' => [
'and' => [
new TermQuery('name', new TermQuery('category', 'authors')),
]
]
]
];
$expectedBody = [
'query' => [
'bool' => [
'and' => [
[
'term' => [
'name' => [
'term' => [
'category' => 'authors'
]
]
]
],
]
]
]
];
$this->assertEquals($expectedBody, $parser->parse($body));
}
public function testParsingAndMergingWithParent()
{
$parser = new FragmentParser();
$body = [
'settings' => [
new StandardAnalyzer('myAnalyzer')
]
];
$expectedBody = [
'settings' => [
'myAnalyzer' => [
'type' => 'standard'
]
]
];
$this->assertEquals($expectedBody, $parser->parse($body));
}
public function testParsingAndMergingMultipleFragmentsWithParent()
{
$parser = new FragmentParser();
$body = [
'settings' => [
new StandardAnalyzer('myAnalyzer1'),
new StandardAnalyzer('myAnalyzer2'),
new StandardAnalyzer('myAnalyzer3'),
]
];
$expectedBody = [
'settings' => [
'myAnalyzer1' => [
'type' => 'standard'
],
'myAnalyzer2' => [
'type' => 'standard'
],
'myAnalyzer3' => [
'type' => 'standard'
]
]
];
$this->assertEquals($expectedBody, $parser->parse($body));
}
public function testParsingCustomFragments()
{
$parser = new FragmentParser();
$body = [
'query' => [
new IDFilter(123),
]
];
$expectedBody = [
'query' => [
[
'term' => [
'id' => 123
]
]
]
];
$this->assertEquals($expectedBody, $parser->parse($body));
}
}
| madewithlove/elasticsearcher | tests/Parsers/FragmentParserTest.php | PHP | mit | 2,850 |
using System.Data;
using System.Net;
using OhioTrackStats.API.ServiceModel;
using OhioTrackStats.API.ServiceModel.Types;
using ServiceStack;
using ServiceStack.OrmLite;
namespace OhioTrackStats.API.ServiceInterface
{
public class EventService : Service
{
public IAutoQueryDb AutoQuery { get; set; }
public object Get(QueryEvents query)
{
return AutoQuery.Execute(query, AutoQuery.CreateQuery(query, this.Request));
}
public object Delete(DeleteEvent request)
{
Db.DeleteById<Event>(request.Id);
return new HttpResult(HttpStatusCode.OK);
}
public object Post(CreateEvent request)
{
Db.Insert(request.Event);
return new HttpResult(HttpStatusCode.Created);
}
public static void SeedData(IDbConnection db)
{
db.Insert(new Event { Name = "100M", ShortName = "100m", IsMale = true, IsFemale = true, IsRunning = true, IsField = false, IsRelay = false});
db.Insert(new Event { Name = "200M", ShortName = "200m", IsMale = true, IsFemale = true, IsRunning = true, IsField = false, IsRelay = false });
db.Insert(new Event { Name = "400M", ShortName = "400m", IsMale = true, IsFemale = true, IsRunning = true, IsField = false, IsRelay = false });
db.Insert(new Event { Name = "800M", ShortName = "800m", IsMale = true, IsFemale = true, IsRunning = true, IsField = false, IsRelay = false });
db.Insert(new Event { Name = "1600M", ShortName = "1600m", IsMale = true, IsFemale = true, IsRunning = true, IsField = false, IsRelay = false });
db.Insert(new Event { Name = "3200M", ShortName = "3200m", IsMale = true, IsFemale = true, IsRunning = true, IsField = false, IsRelay = false });
db.Insert(new Event { Name = "100M Hurdles", ShortName = "100m-hurdles", IsMale = false, IsFemale = true, IsRunning = true, IsField = false, IsRelay = false });
db.Insert(new Event { Name = "110M Hurdles", ShortName = "110m-hurdles", IsMale = true, IsFemale = false, IsRunning = true, IsField = false, IsRelay = false });
db.Insert(new Event { Name = "300M Hurdles", ShortName = "300m-hurdles", IsMale = true, IsFemale = true, IsRunning = true, IsField = false, IsRelay = false });
db.Insert(new Event { Name = "4x100M Relay", ShortName = "4x100m-relay", IsMale = true, IsFemale = true, IsRunning = true, IsField = false, IsRelay = true });
db.Insert(new Event { Name = "4x200M Relay", ShortName = "4x200m-relay", IsMale = true, IsFemale = true, IsRunning = true, IsField = false, IsRelay = true });
db.Insert(new Event { Name = "4x400M Relay", ShortName = "4x400m-relay", IsMale = true, IsFemale = true, IsRunning = true, IsField = false, IsRelay = true });
db.Insert(new Event { Name = "4x800M Relay", ShortName = "4x800m-relay", IsMale = true, IsFemale = true, IsRunning = true, IsField = false, IsRelay = true });
db.Insert(new Event { Name = "Shot Put", ShortName = "shot-put", IsMale = true, IsFemale = true, IsRunning = false, IsField = true, IsRelay = false });
db.Insert(new Event { Name = "Discus", ShortName = "discus", IsMale = true, IsFemale = true, IsRunning = false, IsField = true, IsRelay = false });
db.Insert(new Event { Name = "Long Jump", ShortName = "long-jump", IsMale = true, IsFemale = true, IsRunning = false, IsField = true, IsRelay = false });
db.Insert(new Event { Name = "High Jump", ShortName = "high-jump", IsMale = true, IsFemale = true, IsRunning = false, IsField = true, IsRelay = false });
db.Insert(new Event { Name = "Pole Vault", ShortName = "pole-vault", IsMale = true, IsFemale = true, IsRunning = false, IsField = true, IsRelay = false });
}
}
}
| OhioTrackStats/OhioTrackStats.API | src/OhioTrackStats.API.ServiceInterface/EventService.cs | C# | mit | 3,859 |
var fs = require('fs');
var path = require('path');
var config = require('rc')('easy-workflow', {
projectName: process.cwd().split(path.sep).pop()
});
module.exports = function (gulp) {
fs.readdirSync(__dirname).filter(function (file) {
return (file.indexOf(".") !== 0) && (file.indexOf('task_') === 0);
}).forEach(function (file) {
var registerTask = require(path.join(__dirname, file));
registerTask(gulp, config);
});
};
| grassmu/easy-workflow | templates/tasks/index.js | JavaScript | mit | 465 |
require 'open3'
Given(/^that a queue parent directory exists$/) do
td = TestDir.new('features/fixtures/setup/queue')
td.nuke
td.create_root
end
When(/^I setup the queue$/) do
_, e, s = Open3.capture3('rake git_transactor:setup:queue QUEUE_ROOT=features/fixtures/setup/queue/work')
raise RuntimeError.new(e)unless s == 0
end
Then(/^I should be able to use the queue$/) do
GitTransactor::QueueManager.open('features/fixtures/setup/queue/work')
end
| NYULibraries/git_transactor | features/step_definitions/setup_queue_steps.rb | Ruby | mit | 461 |
class CreateRooms < ActiveRecord::Migration[5.0]
def change
create_table :rooms do |t|
t.string :code
t.string :name
t.integer :capacity
t.boolean :active
t.integer :time_grid_id
t.references :department, foreign_key: true
t.belongs_to :building, index: true
t.timestamps
end
end
end
| fga-gpp-mds/2017.1-SIGS | SIGS/db/migrate/20170414134440_create_rooms.rb | Ruby | mit | 345 |
function readCookie(name) {
var nameEQ = encodeURIComponent(name) + "=";
var ca = document.cookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) === ' ') c = c.substring(1, c.length);
if (c.indexOf(nameEQ) === 0) return decodeURIComponent(c.substring(nameEQ.length, c.length));
}
return null;
}
$.ajaxPrefilter(function (options, originalOptions, jqXHR) {
var token = readCookie("_xsrf")
// console.log("ajaxPrefilter: _xsrf = ", token)
jqXHR.setRequestHeader('X-Csrftoken', token);
});
//auth_signup.html
//注册发送验证码
$( "#get-authcode-bt" ).bind("click", function() {
// event.preventDefault();
// $(this).attr('disabled', 'true')
$(this).unbind("click");
var email = $("#email")[0].value
var query_string = `mutation MyMutation {
auth {
signup_identifier(type:"email", data: "${email}") {
id
}
}
}`
$.ajax({
url: "/api/graphql",
method: "POST",
// The key needs to match your method's input parameter (case-sensitive).
data: JSON.stringify({"query": query_string }),
contentType: "application/json; charset=utf-8",
dataType: "json",
// dataType:'jsonp',
success: function(data){
// console.log("data",data.errors)
if (data.errors) {
var s = data.errors.map(function(v)
{
$(".error-append").append('<span class="error-message">'+v.message +'</span>');
})
// alert(s)
} else {
$("#auth_key")[0].value = data.data.auth.signup_identifier.id
// console.log('22222=>',$("#auth_key")[0].value)
}
},
failure: function(errMsg) {
alert(errMsg);
}
});
})
//忘记密码发送验证码
$( "#forgetpassord-authcode-bt" ).bind("click", function() {
// event.preventDefault();
// $(this).attr('disabled', 'true')
$(this).unbind("click");
var email = $("#email")[0].value
var query_string = `mutation MyMutation {
auth {
forget_password_identifier(type:"email", data: "${email}") {
id
}
}
}`
$.ajax({
url: "/api/graphql",
method: "POST",
// The key needs to match your method's input parameter (case-sensitive).
data: JSON.stringify({"query": query_string }),
contentType: "application/json; charset=utf-8",
dataType: "json",
// dataType:'jsonp',
success: function(data){
// console.log('1111=>',data)
if (data.errors) {
var s = data.errors.map(function(v)
{
$(".error-append").append('<span class="error-message">'+v.message +'</span>');
})
// alert(s)
} else {
$("#auth_key")[0].value = data.data.auth.forget_password_identifier.id
}
// console.log('22222=>',$("#auth_key")[0].value)
},
failure: function(errMsg) {
alert(errMsg);
}
});
})
$('input').on("keypress", function(e) {
/* ENTER PRESSED*/
if (e.keyCode == 13) {
/* FOCUS ELEMENT */
var inputs = $(this).parents("form").eq(0).find(":input");
var idx = inputs.index(this);
if (idx == inputs.length - 1) {
inputs[0].select()
} else {
inputs[idx + 1].focus(); // handles submit buttons
inputs[idx + 1].select();
}
return false;
}
});
window.blog_menu_init = function blog_menu_init() {
// var $selector = $(".submenu a[href='" + window.location.pathname + "']")
// console.log($selector)
if (window.location.pathname.startsWith("/console/blog")) {
var p_url = window.location.pathname.split("/").slice(0,4).join('/')
var selector = ".submenu a[href='" + p_url + "']"
$(selector).parent().addClass("active")
} else {
var selector = ".submenu a[href='" + window.location.pathname + "']"
$(selector).parent().addClass("active")
}
// $selector.parent().addClass("active")
var s=window.location.pathname
if (!s.startsWith("/console/account")) {
$(selector).closest(".panel-default").find(".panel-title a").first().click()
}
// var $s = $selector.closest(".panel-default").find(".panel-title a").first()
// $s.click()
// $s.removeClass("collapsed")
// console.log($(selector).closest(".panel-default").find(".panel-title a").text())
// console.log($(selector).closest(".panel-default").find("a.collapsed").first())
}
//创建目录
import { success_catalog_change, create_catalog, success_blog_catalog_change } from './catalog'
window.create_catalog = create_catalog
window.success_catalog_change = success_catalog_change
window.success_blog_catalog_change = success_blog_catalog_change
// Tag操作
import { success_tag_change, create_tag, blog_add_tag, set_hidden_input, success_blog_tag_change, delete_tag } from './tag'
window.create_tag = create_tag
window.success_tag_change = success_tag_change
window.success_blog_tag_change = success_blog_tag_change
window.blog_add_tag = blog_add_tag
window.set_hidden_input = set_hidden_input
window.delete_tag = delete_tag
| nuanri/hiblog | src/js-dev/src/blog-home.js | JavaScript | mit | 5,466 |
import {CommonGraphAPI} from '../common/CommonGraphAPI'
import {CommonGraphBuilders} from '../common/CommonGraphBuilders'
import {UndirectedGraphAPI} from './UndirectedGraphAPI'
import {AdjacencyListGraph} from './AdjacencyListGraph'
import {BipartiteBFS} from './BipartiteBFS'
/**
* Factory functions for creating instances of undirected graphs' ADTs.
*/
export namespace UndirectedGraphBuilders {
import Graph = UndirectedGraphAPI.Graph
import Bipartite = UndirectedGraphAPI.Bipartite
import VerticesPair = CommonGraphAPI.VerticesPair
import vertex = CommonGraphBuilders.vertex
/**
* Creates new instance of {@link UndirectedGraphAPI.Graph}.
* @return {UndirectedGraphAPI.Graph<V>} new instance of <tt>Graph</tt>.
*/
export function graph<V>(): Graph<V> {
return new AdjacencyListGraph([])
}
/**
* Creates new instance of <tt>Graph</tt> from given keys of its edges. It means that for every pair like
* ['key1', 'key2'] it creates pair of vertices [V1('key1', 'key1'), V2('key2', 'key2'] and adds this pair of
* vertices as the edge (V1-V2).
* @param {[string , string][]} edges pairs of keys of vertices that describe edges.
* @return {UndirectedGraphAPI.Graph<string>} new graph with given edges.
*/
export function graphFromEdgesKeys(edges: [string, string][]): Graph<string> {
return edges.reduce((acc: Graph<string>, e) => acc.addEdge(vertex(e[0], e[0]), vertex(e[1], e[1])),
new AdjacencyListGraph<string>())
}
/**
* Creates new <tt>Graph</tt> with given edges.
* @param {CommonGraphAPI.VerticesPair<V>[]} edges edges to add into new graph.
* @return {UndirectedGraphAPI.Graph<V>} new <tt>Graph</tt> with given edges.
*/
export function graphFromEdges<V>(edges: VerticesPair<V>[]): Graph<V> {
return new AdjacencyListGraph(edges)
}
/**
* Creates an instance of <code>Bipartite</code> for given graph.
* @param {UndirectedGraphAPI.Graph<V>} g graph to apply the algorithm.
* @return {UndirectedGraphAPI.Bipartite<V>} implementation of <tt>Bipartite</tt>.
*/
export function bipartite<V>(g: Graph<V>): Bipartite<V> {
return new BipartiteBFS(g)
}
}
| prishedko/algorithms-ts | src/graphs/undirected/UndirectedGraphBuilders.ts | TypeScript | mit | 2,254 |
<?php
function _esc($n) {
$ESC = chr(27);
return $ESC . "[{$n}m";
}
$RESET_ALL = _esc(0);
$BRIGHT = _esc(1);
$DIM = _esc(2);
$NORMAL = _esc(2);
$BLACK = _esc(30);
$RED = _esc(31);
$GREEN = _esc(32);
$YELLOW = _esc(33);
$BLUE = _esc(34);
$MAGENTA = _esc(35);
$CYAN = _esc(36);
$WHITE = _esc(37);
$RESET = _esc(39);
$BG_BLACK = _esc(40);
$BG_RED = _esc(41);
$BG_GREEN = _esc(42);
$BG_YELLOW = _esc(43);
$BG_BLUE = _esc(44);
$BG_MAGENTA = _esc(45);
$BG_CYAN = _esc(46);
$BG_WHITE = _esc(47);
$BG_RESET = _esc(49); | basp/lily | style.php | PHP | mit | 603 |
package sample.spring.security.test;
import org.springframework.security.test.context.support.WithSecurityContext;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD, ElementType.TYPE})
@WithSecurityContext(factory=MyTestUserFactory.class)
public @interface MyTestUser {
String name();
String pass();
String authority();
}
| opengl-8080/Samples | java/spring-security/common/src/test/java/sample/spring/security/test/MyTestUser.java | Java | mit | 529 |
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
/*
| -------------------------------------------------------------------------
| URI ROUTING
| -------------------------------------------------------------------------
| This file lets you re-map URI requests to specific controller functions.
|
| Typically there is a one-to-one relationship between a URL string
| and its corresponding controller class/method. The segments in a
| URL normally follow this pattern:
|
| example.com/class/method/id/
|
| In some instances, however, you may want to remap this relationship
| so that a different class/function is called than the one
| corresponding to the URL.
|
| Please see the user guide for complete details:
|
| https://codeigniter.com/user_guide/general/routing.html
|
| -------------------------------------------------------------------------
| RESERVED ROUTES
| -------------------------------------------------------------------------
|
| There are three reserved routes:
|
| $route['default_controller'] = 'welcome';
|
| This route indicates which controller class should be loaded if the
| URI contains no data. In the above example, the "welcome" class
| would be loaded.
|
| $route['404_override'] = 'errors/page_missing';
|
| This route will tell the Router which controller/method to use if those
| provided in the URL cannot be matched to a valid route.
|
| $route['translate_uri_dashes'] = FALSE;
|
| This is not exactly a route, but allows you to automatically route
| controller and method names that contain dashes. '-' isn't a valid
| class or method name character, so it requires translation.
| When you set this option to TRUE, it will replace ALL dashes in the
| controller and method URI segments.
|
| Examples: my-controller/index -> my_controller/index
| my-controller/my-method -> my_controller/my_method
*/
$route['default_controller'] = 'beranda';
// $route['beranda'] = 'beranda';
$route['daftar'] = 'daftar';
// $route['tesc/mulai/(:any)'] = 'tesc/mulai/1';
$route['masuk'] = 'masuk';
// $route['404_override'] = '';
//$route['translate_uri_dashes'] = FALSE;
| 0x4164/olqt-ci | application/config/routes.php | PHP | mit | 2,114 |
using System;
using System.Globalization;
using System.IO;
using Newtonsoft.Json.Linq;
using Skybrud.Umbraco.GridData.Models;
using Skybrud.Umbraco.GridData.Models.Config;
using Skybrud.Umbraco.GridData.Models.Values;
using Umbraco.Cms.Core.Models.PublishedContent;
namespace Skybrud.Umbraco.GridData.Converters {
/// <summary>
/// Abstract base implementation of <see cref="IGridConverter"/>.
/// </summary>
public abstract class GridConverterBase : IGridConverter {
public virtual bool GetConfigType(GridEditor editor, out Type type) {
type = null;
return false;
}
public virtual bool GetValueType(GridControl control, out Type type) {
type = null;
return false;
}
/// <summary>
/// Converts the specified <paramref name="token"/> into an instance of <see cref="IGridControlValue"/>.
/// </summary>
/// <param name="control">A reference to the parent <see cref="GridControl"/>.</param>
/// <param name="token">The instance of <see cref="JToken"/> representing the control value.</param>
/// <param name="value">The converted control value.</param>
public virtual bool ConvertControlValue(GridControl control, JToken token, out IGridControlValue value) {
value = null;
return false;
}
/// <summary>
/// Converts the specified <paramref name="token"/> into an instance of <see cref="IGridEditorConfig"/>.
/// </summary>
/// <param name="editor">A reference to the parent <see cref="GridEditor"/>.</param>
/// <param name="token">The instance of <see cref="JToken"/> representing the editor config.</param>
/// <param name="config">The converted editor config.</param>
public virtual bool ConvertEditorConfig(GridEditor editor, JToken token, out IGridEditorConfig config) {
config = null;
return false;
}
public virtual bool WriteSearchableText(GridContext context, IPublishedElement element, TextWriter writer) {
return false;
}
public virtual bool IsValid(IGridControlValue value, out bool result) {
result = false;
return false;
}
public virtual bool IsValid(IPublishedElement element, out bool result) {
result = false;
return false;
}
/// <summary>
/// Returns whether <paramref name="value"/> is contained in <paramref name="source"/> (case insensitive).
/// </summary>
/// <param name="source">The source string.</param>
/// <param name="value">The value to search for.</param>
/// <returns><c>true</c> if <paramref name="source"/> contains <paramref name="value"/>; otherwise <c>false</c>.</returns>
protected bool ContainsIgnoreCase(string source, string value) {
if (string.IsNullOrWhiteSpace(source)) return false;
if (string.IsNullOrWhiteSpace(value)) return false;
return CultureInfo.InvariantCulture.CompareInfo.IndexOf(source, value, CompareOptions.IgnoreCase) >= 0;
}
/// <summary>
/// Returns whether <paramref name="value"/> is equal <paramref name="source"/> (case insensitive).
/// </summary>
/// <param name="source">The source string.</param>
/// <param name="value">The value to search for.</param>
/// <returns><c>true</c> if <paramref name="value"/> equal to <paramref name="source"/>; otherwise <c>false</c>.</returns>
protected bool EqualsIgnoreCase(string source, string value) {
if (string.IsNullOrWhiteSpace(source)) return false;
if (string.IsNullOrWhiteSpace(value)) return false;
return source.Equals(value, StringComparison.InvariantCultureIgnoreCase);
}
}
} | skybrud/Skybrud.Umbraco.GridData | src/Skybrud.Umbraco.GridData/Converters/GridConverterBase.cs | C# | mit | 3,891 |
namespace OmniXaml
{
public class DefaultInstanceLifeCycleListener : IInstanceLifeCycleListener
{
public void OnBegin(object instance)
{
}
public void OnAfterProperties(object instance)
{
}
public void OnAssociatedToParent(object instance)
{
}
public void OnEnd(object instance)
{
}
}
} | Perspex/OmniXAML | Source/OmniXaml/DefaultInstanceLifeCycleListener.cs | C# | mit | 397 |
// Surface.cpp
#include <stdafx.h>
#include "Surface.h"
#include "Surfaces.h"
#include "Program.h"
#include "HeeksConfig.h"
#include "tinyxml.h"
#include "PropertyLength.h"
#include "PropertyCheck.h"
#include "Reselect.h"
#include "SurfaceDlg.h"
int CSurface::number_for_stl_file = 1;
CSurface::CSurface()
{
ReadDefaultValues();
}
HeeksObj *CSurface::MakeACopy(void)const
{
return new CSurface(*this);
}
void CSurface::WriteXML(TiXmlNode *root)
{
TiXmlElement * element = new TiXmlElement( "Surface" );
wxGetApp().LinkXMLEndChild( root, element );
element->SetDoubleAttribute( "tolerance", m_tolerance);
element->SetDoubleAttribute( "material_allowance", m_material_allowance);
element->SetAttribute( "same_for_posns", m_same_for_each_pattern_position ? 1:0);
// write solid ids
for (std::list<int>::iterator It = m_solids.begin(); It != m_solids.end(); It++)
{
int solid = *It;
TiXmlElement * solid_element = new TiXmlElement( "solid" );
wxGetApp().LinkXMLEndChild( element, solid_element );
solid_element->SetAttribute("id", solid);
}
IdNamedObj::WriteBaseXML(element);
}
// static member function
HeeksObj* CSurface::ReadFromXMLElement(TiXmlElement* element)
{
CSurface* new_object = new CSurface;
element->Attribute("tolerance", &new_object->m_tolerance);
element->Attribute("material_allowance", &new_object->m_material_allowance);
int int_for_bool = 1;
if(element->Attribute( "same_for_posns", &int_for_bool))new_object->m_same_for_each_pattern_position = (int_for_bool != 0);
if(const char* pstr = element->Attribute("title"))new_object->m_title = Ctt(pstr);
// read solid ids
for(TiXmlElement* pElem = TiXmlHandle(element).FirstChildElement().Element() ; pElem; pElem = pElem->NextSiblingElement())
{
std::string name(pElem->Value());
if(name == "solid"){
for(TiXmlAttribute* a = pElem->FirstAttribute(); a; a = a->Next())
{
std::string name(a->Name());
if(name == "id"){
int id = a->IntValue();
new_object->m_solids.push_back(id);
}
}
}
}
new_object->ReadBaseXML(element);
return new_object;
}
void CSurface::WriteDefaultValues()
{
HeeksConfig config;
config.Write(wxString(GetTypeString()) + _T("Tolerance"), m_tolerance);
config.Write(wxString(GetTypeString()) + _T("MatAllowance"), m_material_allowance);
config.Write(wxString(GetTypeString()) + _T("SameForPositions"), m_same_for_each_pattern_position);
}
void CSurface::ReadDefaultValues()
{
HeeksConfig config;
config.Read(wxString(GetTypeString()) + _T("Tolerance"), &m_tolerance, 0.01);
config.Read(wxString(GetTypeString()) + _T("MatAllowance"), &m_material_allowance, 0.0);
config.Read(wxString(GetTypeString()) + _T("SameForPositions"), &m_same_for_each_pattern_position, true);
}
static void on_set_tolerance(double value, HeeksObj* object){((CSurface*)object)->m_tolerance = value; ((CSurface*)object)->WriteDefaultValues();}
static void on_set_material_allowance(double value, HeeksObj* object){((CSurface*)object)->m_material_allowance = value; ((CSurface*)object)->WriteDefaultValues();}
static void on_set_same_for_position(bool value, HeeksObj* object){((CSurface*)object)->m_same_for_each_pattern_position = value; ((CSurface*)object)->WriteDefaultValues();}
void CSurface::GetProperties(std::list<Property *> *list)
{
AddSolidsProperties(list, m_solids);
list->push_back(new PropertyLength(_("tolerance"), m_tolerance, this, on_set_tolerance));
list->push_back(new PropertyLength(_("material allowance"), m_material_allowance, this, on_set_material_allowance));
list->push_back(new PropertyCheck(_("same for each pattern position"), m_same_for_each_pattern_position, this, on_set_same_for_position));
IdNamedObj::GetProperties(list);
}
void CSurface::CopyFrom(const HeeksObj* object)
{
if (object->GetType() == GetType())
{
operator=(*((CSurface*)object));
}
}
bool CSurface::CanAddTo(HeeksObj* owner)
{
return ((owner != NULL) && (owner->GetType() == SurfacesType));
}
const wxBitmap &CSurface::GetIcon()
{
static wxBitmap* icon = NULL;
if(icon == NULL)icon = new wxBitmap(wxImage(wxGetApp().GetResFolder() + _T("/icons/surface.png")));
return *icon;
}
static bool OnEdit(HeeksObj* object)
{
return SurfaceDlg::Do((CSurface*)object);
}
void CSurface::GetOnEdit(bool(**callback)(HeeksObj*))
{
*callback = OnEdit;
}
HeeksObj* CSurface::PreferredPasteTarget()
{
return wxGetApp().m_program->Surfaces();
}
| play113/swer | heekscam-read-only/src/Surface.cpp | C++ | mit | 4,554 |
<?php
/**
Using names.txt, a 46K text file containing over five-thousand first names, begin by
sorting it into alphabetical order. Then working out the alphabetical value for each name,
multiply this value by its alphabetical position in the list to obtain a name score.
For example, when the list is sorted into alphabetical order, COLIN, which is worth
3 + 15 + 12 + 9 + 14 = 53, is the 938th name in the list. So COLIN would obtain a score of
938 * 53 = 49714.
What is the total of all the name scores in the file?
**/
$alpha_values = array(
"A" => 1,
"B" => 2,
"C" => 3,
"D" => 4,
"E" => 5,
"F" => 6,
"G" => 7,
"H" => 8,
"I" => 9,
"J" => 10,
"K" => 11,
"L" => 12,
"M" => 13,
"N" => 14,
"O" => 15,
"P" => 16,
"Q" => 17,
"R" => 18,
"S" => 19,
"T" => 20,
"U" => 21,
"V" => 22,
"W" => 23,
"X" => 24,
"Y" => 25,
"Z" => 26,
);
$file_name = "names.txt";
$contents = file_get_contents($file_name);
$contents = str_replace("\"", "", $contents);
$contents = str_replace(" ", "", $contents);
$contents = str_replace("\n", "", $contents);
$names = explode(",", $contents);
sort($names, SORT_STRING);
$names = &array_unique($names);
$total = 0;
$sorted_index = 1;
foreach($names as $name) {
$rank = 0;
for($c = 0; $c < strlen($name); $c++) {
$rank += $alpha_values[$name[$c]];
}
$rank *= $sorted_index;
$total += $rank;
$sorted_index++;
}
print $total;
?>
| jbaldwin/project_euler | p022/p22.php | PHP | mit | 1,393 |
from setuptools import setup
readme = open('README.md').read()
setup(name='HDFserver',
version='0.1',
author='Yohannes Libanos',
license='MIT',
description='REST service for HDF5 data stores',
py_modules=['HDFserver'],
long_description=readme,) | yohannesHL/HDFserver | setup.py | Python | mit | 281 |
import copy
class ArtifactEmulator:
def __init__(self, random_str, ctx, base_url):
self._random_str = random_str
self._ctx = ctx
self._artifacts = {}
self._artifacts_by_id = {}
self._files = {}
self._base_url = base_url
self._portfolio_links = {}
def create(self, variables):
collection_name = variables["artifactCollectionNames"][0]
state = "PENDING"
aliases = []
latest = None
art_id = variables.get("digest", "")
# Find most recent artifact
versions = self._artifacts.get(collection_name)
if versions:
last_version = versions[-1]
latest = {"id": last_version["digest"], "versionIndex": len(versions) - 1}
art_seq = {"id": art_id, "latestArtifact": latest}
aliases.append(dict(artifactCollectionName=collection_name, alias="latest"))
base_url = self._base_url
direct_url = f"{base_url}/storage?file=wandb_manifest.json"
art_data = {
"id": art_id,
"digest": "abc123",
"state": state,
"labels": [],
"aliases": aliases,
"artifactSequence": art_seq,
"currentManifest": dict(file=dict(directUrl=direct_url)),
}
response = {"data": {"createArtifact": {"artifact": copy.deepcopy(art_data)}}}
# save in artifact emu object
art_seq["name"] = collection_name
art_data["artifactSequence"] = art_seq
art_data["state"] = "COMMITTED"
art_type = variables.get("artifactTypeName")
if art_type:
art_data["artifactType"] = {"id": 1, "name": art_type}
art_save = copy.deepcopy(art_data)
self._artifacts.setdefault(collection_name, []).append(art_save)
self._artifacts_by_id[art_id] = art_save
# save in context
self._ctx["artifacts_created"].setdefault(collection_name, {})
self._ctx["artifacts_created"][collection_name].setdefault("num", 0)
self._ctx["artifacts_created"][collection_name]["num"] += 1
if art_type:
self._ctx["artifacts_created"][collection_name]["type"] = art_type
return response
def link(self, variables):
pfolio_name = variables.get("artifactPortfolioName")
artifact_id = variables.get("artifactID") or variables.get("clientID")
if not pfolio_name or not artifact_id:
raise ValueError(
"query variables must contain artifactPortfolioName and either artifactID or clientID"
)
aliases = variables.get("aliases")
# We automatically create a portfolio for the user if we can't find the one given.
links = self._portfolio_links.setdefault(pfolio_name, [])
if not any(map(lambda x: x["id"] == artifact_id, links)):
art = {"id": artifact_id, "aliases": [a["alias"] for a in aliases]}
links.append(art)
self._ctx["portfolio_links"].setdefault(pfolio_name, {})
num = len(links)
self._ctx["portfolio_links"][pfolio_name]["num"] = num
response = {"data": {"linkArtifact": {"versionIndex": num - 1}}}
return response
def create_files(self, variables):
base_url = self._base_url
response = {
"data": {
"createArtifactFiles": {
"files": {
"edges": [
{
"node": {
"id": idx,
"name": af["name"],
"displayName": af["name"],
"uploadUrl": f"{base_url}/storage?file={af['name']}&id={af['artifactID']}",
"uploadHeaders": [],
"artifact": {"id": af["artifactID"]},
},
}
for idx, af in enumerate(variables["artifactFiles"])
],
},
},
},
}
return response
def query(self, variables, query=None):
public_api_query_str = "query Artifact($id: ID!) {"
public_api_query_str2 = "query ArtifactWithCurrentManifest($id: ID!) {"
art_id = variables.get("id")
art_name = variables.get("name")
assert art_id or art_name
is_public_api_query = query and (
query.startswith(public_api_query_str)
or query.startswith(public_api_query_str2)
)
if art_name:
collection_name, version = art_name.split(":", 1)
artifact = None
artifacts = self._artifacts.get(collection_name)
if artifacts:
if version == "latest":
version_num = len(artifacts)
else:
assert version.startswith("v")
version_num = int(version[1:])
artifact = artifacts[version_num - 1]
# TODO: add alias info?
elif art_id:
artifact = self._artifacts_by_id[art_id]
if is_public_api_query:
response = {"data": {"artifact": artifact}}
else:
response = {"data": {"project": {"artifact": artifact}}}
return response
def file(self, entity, digest):
# TODO?
return "ARTIFACT %s" % digest, 200
def storage(self, request):
fname = request.args.get("file")
if request.method == "PUT":
data = request.get_data(as_text=True)
self._files.setdefault(fname, "")
# TODO: extend? instead of overwrite, possible to differentiate wandb_manifest.json artifactid?
self._files[fname] = data
data = ""
if request.method == "GET":
data = self._files[fname]
return data, 200
| wandb/client | tests/utils/artifact_emu.py | Python | mit | 5,987 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
public class AnimalsTesting
{
public static Random rnd = new Random();
public static void Main()
{
TestCreatures();
Cat[] catArr = FillCatArr();
Dog[] dogArr = FillDogArr();
Frog[] frogArr = FillFrogArr();
Kitten[] kitArr = FillKittenArr();
Tomcat[] tomArr = FillTomArr();
Animal[] animals = new Animal[] { new Cat("cat", 2, true), new Dog("dog", 2, true), new Frog("frog", 2, true) };
Console.WriteLine(animals[1]);
decimal averageAgeCats = Animal.AverageAge(catArr);
decimal averageAgeDogs = Animal.AverageAge(dogArr);
decimal averageAgeFrogs = Animal.AverageAge(frogArr);
decimal averageAgeKittens = Animal.AverageAge(kitArr);
decimal averageAgeTomcats = Animal.AverageAge(tomArr);
Console.WriteLine("---------- Average ages ----------");
Console.WriteLine("Cats " + averageAgeCats);
Console.WriteLine("Dogs " + averageAgeDogs);
Console.WriteLine("Frogs " + averageAgeFrogs);
Console.WriteLine("Kittens " + averageAgeKittens);
Console.WriteLine("Tomcats " + averageAgeTomcats);
}
public static Tomcat[] FillTomArr()
{
var tomArr = new Tomcat[rnd.Next(5, 21)];
for (int i = 0; i < tomArr.Length; i++)
{
tomArr[i] = new Tomcat(GetRandomName(), rnd.Next(1, 16));
}
return tomArr;
}
public static Kitten[] FillKittenArr()
{
var kitArr = new Kitten[rnd.Next(5, 21)];
for (int i = 0; i < kitArr.Length; i++)
{
kitArr[i] = new Kitten(GetRandomName(), rnd.Next(1, 16));
}
return kitArr;
}
public static Frog[] FillFrogArr()
{
var frogArr = new Frog[rnd.Next(5, 21)];
for (int i = 0; i < frogArr.Length; i++)
{
frogArr[i] = new Frog(GetRandomName(), rnd.Next(1, 16), rnd.Next(1, 3) == 1 ? true : false);
}
return frogArr;
}
public static Dog[] FillDogArr()
{
var dogArr = new Dog[rnd.Next(5, 21)];
for (int i = 0; i < dogArr.Length; i++)
{
dogArr[i] = new Dog(GetRandomName(), rnd.Next(1, 16), rnd.Next(1, 3) == 1 ? true : false);
}
return dogArr;
}
public static Cat[] FillCatArr()
{
var catArr = new Cat[rnd.Next(5, 21)];
for (int i = 0; i < catArr.Length; i++)
{
catArr[i] = new Cat(GetRandomName(), rnd.Next(1, 16), rnd.Next(1, 3) == 1 ? true : false);
}
return catArr;
}
public static void TestCreatures()
{
Dog charlie = new Dog("Charlie", 4, true);
Console.WriteLine(charlie);
charlie.ProduceSound();
Console.WriteLine();
Frog quackster = new Frog("Rab", 1, false);
Console.WriteLine(quackster);
quackster.ProduceSound();
Console.WriteLine();
Cat miew = new Cat("Dangleton", 3, false);
Console.WriteLine(miew);
miew.ProduceSound();
Console.WriteLine();
Kitten kitty = new Kitten("KittyCat", 3);
Console.WriteLine(kitty);
kitty.ProduceSound();
Console.WriteLine();
Tomcat tom = new Tomcat("Tom", 2);
Console.WriteLine(tom);
tom.ProduceSound();
}
public static string GetRandomName()
{
StringBuilder name = new StringBuilder();
name.Append((char)rnd.Next(65, 91));
for (int i = 0; i < rnd.Next(2, 6); i++)
{
name.Append((char)rnd.Next(97, 123));
}
return name.ToString();
}
}
| dzhenko/TelerikAcademy | OOP/OOP-4-Object-Oriented-Programming-Principles-Part1/03. Animals/AnimalTesting.cs | C# | mit | 3,715 |
import { Token } from './token';
// -------------------------------------------------------------------------------------------------
// FIXTURES
// -------------------------------------------------------------------------------------------------
const EXAMPLE_ENCODED_TOKEN = 'eyJhbGciOiJSUzI1NiJ9.eyJlbWFpbCI6ImFiZWxAY29va2luZ2ZveC5ubCIsImV4c' +
'CI6MTQ5MTgyMDE0NCwiaWF0IjoxNDkxODE2NTQ0fQ.h9KHlT3W24GRunBMQfK6E7vf6exjMXbW8EejEdMlMOvzb48NmU-R' +
'k717DhPNVXlSIPFi8bJf-jXvoe82pe3_U7x2U_jTBCAGESpkidr1fQlFJpBgRkY4axm32khef8_4a8LQdqwvm4hVe2gnEM' +
'gbXpQFLLCafhtRo16AzIQ1SsvQDCccRWmZ4sG9wUY2qiFr_rRWkopB46OLNhX9pBSuvELe9H7Jo68TEMQU7H2uO3TKPyOt' +
'FqiRALCwRhl371h7ygqI9atrIt1Wmw08Mf_pS4pxWA_z2rZJWu6wgDe3HFNTYJwmr-bh4Awyz2WSXZPvcd1dqkR9jufcvX' +
'c8ZVtv0jvtjiHAR_EHpWKyv012acWlXCN0t7Cb6z1DqkabN0RxMbABOMG5AKcVzQ_Sq80-AJgE7ct2904sgFi7yGMaTjV4' +
'Mpsh5LrJDJ3GZmKTW-aANpA7lgdPgX0V8mxGcO6hpa71pFjrMXZlJtWKi1kz7iIrdM84iwiKfHnnLws_D-jYqtZShzvYbL' +
'dxdG6MgEYQLhrKzyuRVL4x_U4JysH0Px5q09Vo-6W551E9IizZnVTrR6OlDEg5QzA0FKAu4KKFrDSwpQN6KDgAPyNOGd0R' +
'HxBOgkb8sN4lNmcgdLAezv0yxmJVrbymFhJc0p70Nlcf7sZt4QQXfufzHgmr-yptCeA';
const EXAMPLE_ENCODED_HEADER = btoa(JSON.stringify({ 'alg': 'RS256' }));
const EXAMPLE_SIGNATURE = '7lgdPgX0V8mxGcO6hpa71pFjrMXZlJtWKi1kz7iIrdM84iwiKfHnnLws_D-jYqtZShzvYbL';
const EXAMPLE_EXPIRATION_MILLISECONDS = 60 * 60 * 1000; // 1 hour
const EXAMPLE_PAYLOAD = {
'exp': 1491820144,
'iat': 1491816544
};
/**
* Mock encoded token with provided timestamp, which is included in payload.
* @param issuedAt When the token was issued by the server.
* @returns string Encoded token.
*/
function mockEncodedToken(issuedAt: Date): string {
const iatMillis = issuedAt.getTime();
const expMillis = iatMillis + EXAMPLE_EXPIRATION_MILLISECONDS;
const payload = {
exp: Math.round(expMillis / 1000),
iat: Math.round(iatMillis / 1000)
};
const encodedPayloadRaw: string = btoa(JSON.stringify(payload));
const encodedPayload = encodedPayloadRaw.substring(0, encodedPayloadRaw.indexOf('='));
return EXAMPLE_ENCODED_HEADER + '.' + encodedPayload + '.' + EXAMPLE_SIGNATURE;
}
// -------------------------------------------------------------------------------------------------
// TESTS
// -------------------------------------------------------------------------------------------------
describe('Token', () => {
it('should throw when provided value is empty', () => {
expect(() => new Token(null)).toThrow();
});
it('should throw when provided value has unexpected format', () => {
expect(() => new Token('foo-bar')).toThrow();
});
it('should not throw when provided value is JWT encoded token', () => {
expect(() => new Token(EXAMPLE_ENCODED_TOKEN)).not.toThrow();
});
it('should be valid when expected', () => {
const token = new Token(mockEncodedToken(new Date()));
expect(token.isValid()).toEqual(true);
});
it('should not be valid when expired', () => {
// create expired date for mock token
const expired = new Date();
expired.setMilliseconds(expired.getMilliseconds() - EXAMPLE_EXPIRATION_MILLISECONDS - 1000);
const token = new Token(mockEncodedToken(expired));
expect(token.isValid()).toEqual(false);
});
});
| cookingfox/stibble-api-client-angular | src/app/stibble-api-client/token/token.spec.ts | TypeScript | mit | 3,236 |
package ast;
import java.util.*;
/**
* @author GAO RISHENG A0101891L
* This class is mainly for construction of AST nodes representing a constant array in C/Java/Python
* Program and its respective syntax generation
*
*/
public class ASTExpressionUnitLiteralArray extends ASTExpressionUnitLiteral{
private static final String NODE_TYPE = "Array";
private ArrayList<ASTExpression> entries;
private int size;
public ASTExpressionUnitLiteralArray(){
super();
initialize();
}
public void addValue(String value){
ASTExpressionUnitLiteral temp = new ASTExpressionUnitLiteral(value);
this.entries.add(temp);
temp.parent = this;
}
public void addValue(ASTExpression exp){
this.entries.add(exp);
exp.parent = this;
}
private void initialize() {
this.entries = new ArrayList<ASTExpression>();
this.size = entries.size();
}
public String typeof(){
return super.typeof()+"->"+NODE_TYPE;
}
public String toSyntax(int programmingLanguageSyntax) throws Exception{
switch(programmingLanguageSyntax){
case INDEX_C:
case INDEX_JAVA:
{
this.result = "";
this.result += "{";
int index = 0;
for(;index<size-1;index++){
this.result+= this.entries.get(index).toSyntax();
this.result+= ", ";
}
this.result+= this.entries.get(index).toSyntax();
this.result += "}";
return this.result;
}
case INDEX_PYTHON:
{
this.result = "";
this.result += "[";
int index = 0;
for(;index<size-1;index++){
this.result+= this.entries.get(index).toSyntax();
this.result+= ", ";
}
this.result+= this.entries.get(index).toSyntax();
this.result += "]";
return this.result;
}
default:
throw new Exception("Not supported Programming Language.");
}
}
}
| MartinGaoR/talk-to-code | src/ast/ASTExpressionUnitLiteralArray.java | Java | mit | 1,741 |
package com.mdb255.wedding.test.config;
import java.util.List;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import com.fasterxml.jackson.databind.ObjectMapper;
@Configuration
@EnableWebMvc
@ComponentScan({ "com.mdb255.wedding.test.controller", "com.mdb255.wedding.shared.filter" })
public class ServletConfig extends WebMvcConfigurerAdapter {
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
MappingJackson2HttpMessageConverter jacksonConverter = new MappingJackson2HttpMessageConverter();
jacksonConverter.setObjectMapper(new ObjectMapper());
converters.add(jacksonConverter);
}
// Allows serving of standard web content, e.g., .html, .jsp
@Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
// If interceptors are needed
// @Override
// public void addInterceptors(InterceptorRegistry registry){
// }
}
| mdb255/wedding | wedding-test-ws/src/main/java/com/mdb255/wedding/test/config/ServletConfig.java | Java | mit | 1,444 |
/**
* @since 15-08-13 11:38
* @author vivaxy
*/
import Url from './index.js';
let assert = chai.assert;
describe('new Url()', function () {
it('should return link', function () {
let link = 'https://www.test.com:8080/vivaxy/test/url?name=vivaxy&year=2015#some',
urlLink = new Url(link);
assert.equal(urlLink, link);
});
it('should return full link, when link is not complete', function () {
let link = '/vivaxy/test/url?name=vivaxy&year=2015#some',
urlLink = new Url(link).toString();
assert.equal(urlLink, location.origin + link);
});
it('should return full link, when link is not complete', function () {
let link = '?name=vivaxy&year=2015#some',
urlLink = new Url(link).toString();
assert.equal(urlLink, location.origin + location.pathname + link);
});
it('should return full link, when link is not complete', function () {
let link = '#some',
urlLink = new Url(link).toString();
assert.equal(urlLink, location.origin + location.pathname + link);
});
});
describe('.get(\'href\')', function () {
it('should return href', function () {
let link = 'https://www.test.com:8080/vivaxy/test/url?name=vivaxy&year=2015#some',
href = new Url(link).get('href');
assert.equal(href, link);
});
it('should return full href, when link is not complete', function () {
let link = '/vivaxy/test/url?name=vivaxy&year=2015#some',
urlLink = new Url(link).toString();
assert.equal(urlLink, location.origin + link);
});
it('should return full href, when link is not complete', function () {
let link = '?name=vivaxy&year=2015#some',
urlLink = new Url(link).toString();
assert.equal(urlLink, location.origin + location.pathname + link);
});
it('should return full href, when link is not complete', function () {
let link = '#some',
urlLink = new Url(link).toString();
assert.equal(urlLink, location.origin + location.pathname + link);
});
});
describe('.get(\'protocol\')', function () {
it('should return protocol', function () {
let link = 'https://www.test.com:8080/vivaxy/test/url?name=vivaxy&year=2015#some',
protocol = new Url(link).get('protocol');
assert.equal(protocol, 'https:');
});
it('should return protocol', function () {
let link = 'http://www.test.com:8080/vivaxy/test/url?name=vivaxy&year=2015#some',
protocol = new Url(link).get('protocol');
assert.equal(protocol, 'http:');
});
it('should return current protocol, when protocol is not supplied', function () {
let link = '//www.test.com:8080/vivaxy/test/url?name=vivaxy&year=2015#some',
protocol = new Url(link).get('protocol');
assert.equal(protocol, location.protocol);
});
it('should return current protocol, when protocol is not supplied', function () {
let link = '/vivaxy/test/url?name=vivaxy&year=2015#some',
protocol = new Url(link).get('protocol');
assert.equal(protocol, location.protocol);
});
});
describe('.get(\'host\')', function () {
it('should return host', function () {
let link = 'https://www.test.com:8080/vivaxy/test/url?name=vivaxy&year=2015#some',
host = new Url(link).get('host');
assert.equal(host, 'www.test.com:8080');
});
it('should return host', function () {
let link = 'https://www.test.com/vivaxy/test/url?name=vivaxy&year=2015#some',
host = new Url(link).get('host');
assert.equal(host, 'www.test.com');
});
it('should return current host, when host is not supplied', function () {
let link = '/vivaxy/test/url?name=vivaxy&year=2015#some',
host = new Url(link).get('host');
assert.equal(host, location.host);
});
});
describe('.get(\'hostname\')', function () {
it('should return hostname', function () {
let link = 'https://www.test.com:8080/vivaxy/test/url?name=vivaxy&year=2015#some',
hostname = new Url(link).get('hostname');
assert.equal(hostname, 'www.test.com');
});
it('should return hostname', function () {
let link = 'https://www.test.com/vivaxy/test/url?name=vivaxy&year=2015#some',
hostname = new Url(link).get('hostname');
assert.equal(hostname, 'www.test.com');
});
it('should return current hostname, when hostname is not supplied', function () {
let link = '/vivaxy/test/url?name=vivaxy&year=2015#some',
hostname = new Url(link).get('hostname');
assert.equal(hostname, location.hostname);
});
});
describe('.get(\'port\')', function () {
it('should return port', function () {
let link = 'https://www.test.com:8080/vivaxy/test/url?name=vivaxy&year=2015#some',
port = new Url(link).get('port');
assert.equal(port, '8080');
});
it('should return port', function () {
let link = 'https://www.test.com/vivaxy/test/url?name=vivaxy&year=2015#some',
port = new Url(link).get('port');
assert.equal(port, '');
});
it('should return current port, when port is not supplied', function () {
let link = '/vivaxy/test/url?name=vivaxy&year=2015#some',
port = new Url(link).get('port');
assert.equal(port, location.port);
});
});
describe('.get(\'path\')', function () {
it('should return path', function () {
let link = 'https://www.test.com:8080/vivaxy/test/url?name=vivaxy&year=2015#some',
path = new Url(link).get('path');
assert.equal(path, '/vivaxy/test/url?name=vivaxy&year=2015');
});
it('should return path', function () {
let link = 'https://www.test.com/vivaxy/test/url#some',
path = new Url(link).get('path');
assert.equal(path, '/vivaxy/test/url');
});
it('should return current path, when path is not supplied', function () {
let link = '?name=vivaxy&year=2015#some',
path = new Url(link).get('path');
assert.equal(path, location.pathname + '?name=vivaxy&year=2015');
});
it('should return current path, when path is not supplied', function () {
let link = '#some',
path = new Url(link).get('path');
assert.equal(path, location.pathname + location.search);
});
});
describe('.get(\'pathname\')', function () {
it('should return pathname', function () {
let link = 'https://www.test.com:8080/vivaxy/test/url?name=vivaxy&year=2015#some',
pathname = new Url(link).get('pathname');
assert.equal(pathname, '/vivaxy/test/url');
});
it('should return pathname', function () {
let link = 'https://www.test.com/vivaxy/test/url#some',
pathname = new Url(link).get('pathname');
assert.equal(pathname, '/vivaxy/test/url');
});
it('should return current pathname, when pathname is not supplied', function () {
let link = '?name=vivaxy&year=2015#some',
pathname = new Url(link).get('pathname');
assert.equal(pathname, location.pathname);
});
it('should return current pathname, when pathname is not supplied', function () {
let link = '#some',
pathname = new Url(link).get('pathname');
assert.equal(pathname, location.pathname);
});
});
describe('.get(\'search\')', function () {
it('should return search', function () {
let link = 'https://www.test.com:8080/vivaxy/test/url?name=vivaxy&year=2015#some',
search = new Url(link).get('search');
assert.equal(search, '?name=vivaxy&year=2015');
});
it('should return search', function () {
let link = 'https://www.test.com/vivaxy/test/url#some',
search = new Url(link).get('search');
assert.equal(search, '');
});
it('should return current search, when search is not supplied', function () {
let link = '#some',
search = new Url(link).get('search');
assert.equal(search, location.search);
});
});
describe('.get(\'query\')', function () {
it('should return query', function () {
let link = 'https://www.test.com:8080/vivaxy/test/url?name=vivaxy&year=2015#some',
query = new Url(link).get('query');
assert.equal(query, 'name=vivaxy&year=2015');
});
it('should return query', function () {
let link = 'https://www.test.com/vivaxy/test/url#some',
query = new Url(link).get('query');
assert.equal(query, '');
});
it('should return current query, when query is not supplied', function () {
let link = '#some',
query = new Url(link).get('query');
assert.equal(query, location.search.slice(1));
});
});
describe('.get(\'parameters\')', function () {
it('should return parameters', function () {
let link = 'https://www.test.com:8080/vivaxy/test/url?name=vivaxy&year=2015#some',
parameters = new Url(link).get('parameters');
assert.equal(parameters.name, 'vivaxy');
assert.equal(parameters.year, '2015');
});
it('should return parameters', function () {
let link = 'https://www.test.com/vivaxy/test/url#some',
parameters = new Url(link).get('parameters'),
parameterCount = 0;
for (let i in parameters) {
parameterCount++;
}
assert.equal(parameterCount, 0);
});
});
describe('.get(\'hash\')', function () {
it('should return hash', function () {
let link = 'https://www.test.com:8080/vivaxy/test/url?name=vivaxy&year=2015#some',
hash = new Url(link).get('hash');
assert.equal(hash, '#some');
});
it('should return hash', function () {
let link = 'https://www.test.com/vivaxy/test/url',
hash = new Url(link).get('hash');
assert.equal(hash, '');
});
});
describe('.parameter()', function () {
it('should return all parameters', function () {
let link = 'https://www.test.com:8080/vivaxy/test/url?name=vivaxy&year=2015#some',
parameters = new Url(link).parameter();
assert.equal(parameters.name, 'vivaxy');
assert.equal(parameters.year, '2015');
});
it('should return all parameters', function () {
let link = 'https://www.test.com/vivaxy/test/url',
parameters = new Url(link).parameter(),
parameterCount = 0;
for (let i in parameters) {
parameterCount++;
}
assert.equal(parameterCount, 0);
});
});
describe('.parameter(`key`)', function () {
it('should return parameter', function () {
let link = 'https://www.test.com:8080/vivaxy/test/url?name=vivaxy&year=2015#some',
url = new Url(link),
name = url.parameter('name'),
year = url.parameter('year'),
other = url.parameter('other');
assert.equal(name, 'vivaxy');
assert.equal(year, '2015');
assert.equal(other, undefined);
});
});
describe('.parameter(`key`, `value`)', function () {
it('should set parameter and return `url`', function () {
let link = 'https://www.test.com:8080/vivaxy/test/url?name=vivaxy&year=2015#some',
url = new Url(link);
url.parameter('year', 2016);
url.parameter('other', 'test');
let year = url.parameter('year'),
other = url.parameter('other');
assert.equal(year, '2016');
assert.equal(other, 'test');
});
});
describe('.parameter(`object`)', function () {
it('should set parameter and return `url`', function () {
let link = 'https://www.test.com:8080/vivaxy/test/url?name=vivaxy&year=2015#some',
url = new Url(link);
url.parameter('year', 2016);
url.parameter('other', 'test');
let year = url.parameter('year'),
other = url.parameter('other');
assert.equal(year, '2016');
assert.equal(other, 'test');
});
});
describe('.removeParameter(`key`)', function () {
it('should remove parameter and return `url`', function () {
let link = 'https://www.test.com:8080/vivaxy/test/url?name=vivaxy&year=2015#some',
url = new Url(link);
url.removeParameter('year');
url.removeParameter('other');
let year = url.parameter('year'),
other = url.parameter('other');
assert.equal(year, undefined);
assert.equal(other, undefined);
});
});
describe('.set(`key`, `value`)', function () {
it('should set `url` and return `url`', function () {
let link = 'https://www.test.com:8080/vivaxy/test/url?name=vivaxy&year=2015#some',
url = new Url(link);
try {
url.set('year', '2015');
} catch (e) {
assert(e.message, 'Url: `year` cannot be set to url');
}
});
it('should set `url` and return `url`', function () {
let link = 'https://www.test.com:8080/vivaxy/test/url?name=vivaxy&year=2015#some',
url = new Url(link);
try {
url.set('parameters', 'test');
} catch (e) {
assert(e.message, 'Url: use `parameter` instead');
}
});
it('should set `url` and return `url`', function () {
let link = 'https://www.test.com:8080/vivaxy/test/url?name=vivaxy&year=2015#some',
url = new Url(link);
url.set('query', 'test=1');
assert(url.get('query'), 'test=1');
});
it('should set `url` and return `url`', function () {
let link = 'https://www.test.com:8080/vivaxy/test/url?name=vivaxy&year=2015#some',
url = new Url(link);
url.set('search', '?test=1');
assert(url.get('search'), '?test=1');
try {
url.set('search', 'test=1');
} catch (e) {
assert(e.message, 'Url: `search` must starts with `?`');
}
});
it('should set `url` and return `url`', function () {
let link = 'https://www.test.com:8080/vivaxy/test/url?name=vivaxy&year=2015#some',
url = new Url(link);
url.set('pathname', 'foo-bar');
assert(url.get('pathname'), 'foo-bar');
});
it('should set `url` and return `url`', function () {
let link = 'https://www.test.com:8080/vivaxy/test/url?name=vivaxy&year=2015#some',
url = new Url(link);
url.set('port', 'foo-bar');
assert(url.get('port'), 'foo-bar');
});
it('should set `url` and return `url`', function () {
let link = 'https://www.test.com:8080/vivaxy/test/url?name=vivaxy&year=2015#some',
url = new Url(link);
url.set('port', 3000);
assert(url.get('port'), '3000');
});
it('should set `url` and return `url`', function () {
let link = 'https://www.test.com:8080/vivaxy/test/url?name=vivaxy&year=2015#some',
url = new Url(link);
url.set('hostname', 'foo-bar.com');
assert(url.get('hostname'), 'foo-bar.com');
});
it('should set `url` and return `url`', function () {
let link = 'https://www.test.com:8080/vivaxy/test/url?name=vivaxy&year=2015#some',
url = new Url(link);
url.set('hash', '#foo-bar');
assert(url.get('hash'), '#foo-bar');
try {
url.set('hash', 'other');
} catch (e) {
assert(e.message, 'Url: `hash` must starts with `#`');
}
});
});
| vivaxy/url | src/test.js | JavaScript | mit | 15,592 |
import React from 'react/addons';
import BaseComponent from './BaseComponent';
import Note from './Note';
/*
* @class Note
* @extends React.Component
*/
class Board extends BaseComponent {
constructor(props) {
super(props);
this.state = {
notes: []
}
this._bind(
'update',
'add',
'remove',
'nextId',
'eachNote'
);
}
nextId () {
this.uniqueId = this.uniqueId || 0;
return this.uniqueId++;
}
componentWillMount () {
var self = this;
if(this.props.count) {
$.getJSON("http://baconipsum.com/api/?type=all-meat&sentences=" +
this.props.count + "&start-with-lorem=1&callback=?", function(results){
results[0].split('. ').forEach(function(sentence){
self.add(sentence.substring(0,40));
});
});
}
}
add (text) {
var arr = this.state.notes;
arr.push({
id: this.nextId(),
note: text
});
this.setState({notes: arr});
}
update (newText, i) {
var arr = this.state.notes;
arr[i].note = newText;
this.setState({notes:arr});
}
remove (i) {
var arr = this.state.notes;
arr.splice(i, 1);
this.setState({notes: arr});
}
eachNote (note, i) {
return (
<Note key={note.id}
index={i}
onChange={this.update}
onRemove={this.remove}
>{note.note}</Note>
);
}
render () {
return (<div className="board">
{this.state.notes.map(this.eachNote)}
<button className="btn btn-sm btn-success glyphicon glyphicon-plus"
onClick={this.add.bind(null, "New Note")}></button>
</div>
);
}
}
// Prop types validation
Board.propTypes = {
//cart: React.PropTypes.object.isRequired,
count: function(props, propName) {
if (typeof props[propName] !== "number"){
return new Error('The count property must be a number');
}
if (props[propName] > 100) {
return new Error("Creating " + props[propName] + " notes is ridiculous");
}
}
};
export default Board;
| carmouche/es6-react-stickynotes | src/app/components/Board.js | JavaScript | mit | 2,320 |
namespace BlizzardAPI.Wow.Item
{
public class ItemSource
{
public int SourceId { get; set; }
public string SourceType { get; set; }
}
}
| EcadryM/BlizzardAPI | BlizzardAPI/BlizzardAPI.Wow/Item/ItemSource.cs | C# | mit | 167 |
<div class="content-wrapper">
<!-- Content Header (Page header) -->
<section class="content-header">
<h1>
Input Sediaan Baru
</h1>
</section>
<section class="content">
<div class="row">
<!-- left column -->
<div class="col-md-12">
<!-- general form elements -->
<div class="box box-primary">
<div class="box-header with-border">
<h3 class="box-title">Data Master Sediaan</h3>
</div><!-- /.box-header -->
<!-- form start -->
<form role="form" id="form_input" action="<?=base_url()?>Sediaan/Insert" method="post">
<div class="box-body">
<div class="form-group">
<label for="id_sediaan">ID</label>
<input type="text" class="form-control required" id="id_sediaan" name="id_sediaan" placeholder="ID untuk Sediaan Baru">
</div>
<div class="form-group">
<label for="sediaan">Sediaan</label>
<input type="text" class="form-control required" id="nama_sediaan" name="nama_sediaan" placeholder="Masukkan Nama Sediaan">
</div>
<div class="form-group">
<label for="keterangan">Keterangan</label>
<textarea class="form-control required" id="keterangan" name="keterangan" placeholder="Masukkan Keterangan Sediaan"></textarea>
</div>
</div><!-- /.box-body -->
<div class="box-footer">
<input type="submit" class="btn btn-primary" value="Submit" />
</div>
</form>
</div><!-- /.box -->
</div> <!-- /.row -->
</section>
</div>
| Quallcode/forkes | application/views/body/master/sediaan/create_dsp.php | PHP | mit | 1,683 |
var path = require('path');
var md5 = require('./../lib/md5file');
describe('md5file', function() {
it('should return md5 of file', function(done) {
var testFile = path.join(__dirname, 'data', 'a');
md5(testFile, function(hash) {
hash.should.be.eql('9195d0beb2a889e1be05ed6bb1954837');
done();
});
});
});
| seandou/koa-assets-minify | test/md5file.test.js | JavaScript | mit | 337 |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HilbertTransformationTests.Data.NetflixReviews
{
public class Probe
{
/// <summary>
/// The key is a movie id, the value, a list of reviewer ids for reviewers whose movie review
/// for the corresponding movie we must guess.
/// </summary>
public Dictionary<int, List<int>> ReviewersByMovie { get; private set; } = new Dictionary<int, List<int>>();
public Probe(string filename)
{
LoadFromFile(filename);
}
/// <summary>
/// Load the probe set from a file.
///
/// Lines that end with a colon contain a movie id. (The colon is removed.)
/// All other lines contain a single reviewer id.
/// </summary>
/// <param name="filename"></param>
private void LoadFromFile(string filename)
{
var lines = File.ReadLines(filename);
List<int> currentMovieReviewList = null;
foreach(var line in lines.Select(s => s.Trim()).Where(s => s.Length > 0))
{
if (line.EndsWith(":"))
{
var currentMovieId = int.Parse(line.Replace(":", ""));
currentMovieReviewList = new List<int>();
ReviewersByMovie[currentMovieId] = currentMovieReviewList;
}
else
{
currentMovieReviewList.Add(int.Parse(line));
}
}
}
}
}
| paulchernoch/HilbertTransformation | HilbertTransformationTests/Data/NetflixReviews/Probe.cs | C# | mit | 1,639 |
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package logica;
import javax.swing.ImageIcon;
import bibliothek.gui.dock.common.action.CButton;
import java.awt.Image;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreeModel;
/**
*
* @author dark
*/
public class CargarArchivoArbol extends CButton {
private CodePanel panel;
private Core base;
DefaultMutableTreeNode carpetaRaiz = new DefaultMutableTreeNode("Carpeta");
DefaultTreeModel modelo = new DefaultTreeModel(carpetaRaiz);
private ArrayList<DesArbol> nodos = new ArrayList<>();
public CargarArchivoArbol(CodePanel panel) {
this.panel = panel;
setText("Abrir archivo");
setTooltip("Cargado de archivo");
Image image = null;
try {
File sourceimage = new File("/home/dark/NetBeansProjects/tesis-final/src/data/tutorial/icons/copy.png");
image = ImageIO.read(sourceimage);
} catch (IOException e) {
e.printStackTrace();
}
ImageIcon icon = new ImageIcon(image);
setIcon(icon);
}
public CargarArchivoArbol(Core panel) {
this.base = panel;
setText("Abrir archivo");
setTooltip("Cargado de archivo");
Image image = null;
try {
// File sourceimage = new File("C:\\Users\\eugenio\\Documents\\proyectos\\CoreTesis\\Desarrollo\\Core\\src\\ima\\ico\\copy.png");
File sourceimage = new File("/home/exile/Documentos/github/java/CoreTesis/Desarrollo/Core/src/ima/ico/copy.png");
image = ImageIO.read(sourceimage);
} catch (IOException e) {
e.printStackTrace();
}
ImageIcon icon = new ImageIcon(image);
setIcon(icon);
}
@Override
protected void action() {
//panel.copy();
//create the root node
JFileChooser fc = new JFileChooser();
fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
//FileNameExtensionFilter filter = new FileNameExtensionFilter("Archivos", "java");
int res = fc.showOpenDialog(this.getBase());
if (res == JFileChooser.APPROVE_OPTION) {
System.out.println(fc.getSelectedFile().getAbsolutePath());
File dir = new File(fc.getSelectedFile().getAbsolutePath());
String archivos[] = dir.list();
System.err.println(archivos.length);
leerDirectorio(archivos, fc.getSelectedFile().getAbsolutePath(),carpetaRaiz,0);
}
this.getBase().getTree().setModel(modelo);
}
public CodePanel getPanel() {
return panel;
}
public void setPanel(CodePanel panel) {
this.panel = panel;
}
public Core getBase() {
return base;
}
public void setBase(Core base) {
this.base = base;
}
public void leerDirectorio(String[] r, String path,DefaultMutableTreeNode padre,int i) {
for (String f : r) {
if (f.contains(".")) {
String ruta = path + "/" + f;
DefaultMutableTreeNode carpeta = new DefaultMutableTreeNode(f);
getNodos().add(new DesArbol(new File(ruta),f));
modelo.insertNodeInto(carpeta, padre, i++);
} else {
String ruta = path + "/" + f;
System.out.println(ruta);
File dir = new File(ruta);
String archivos[] = dir.list();
DefaultMutableTreeNode carpeta = new DefaultMutableTreeNode(f);
modelo.insertNodeInto(carpeta, padre, i++);
leerDirectorio(archivos, ruta,carpeta,0);
}
}
}
public DefaultMutableTreeNode getCarpetaRaiz() {
return carpetaRaiz;
}
public DefaultTreeModel getModelo() {
return modelo;
}
public ArrayList<DesArbol> getNodos() {
return nodos;
}
public DesArbol getNodo(String nom){
for(DesArbol d : getNodos()){
if(d.getNombre().equals(nom))
return d;
}
return null;
}
public boolean validarExistencia(String ruta){
System.err.println("ruta q llega : "+ruta);
System.out.println("esta es la respuesta: "+ruta.split("\\.").length);
System.out.println();
return ruta.split("\\.").length>0?true:false;
}
public String producirContenido(DesArbol a) {
try {
try {
return this.getCode(a.getFile().getAbsolutePath());
}catch (NullPointerException e){
}
} catch (IOException ex) {
}
return "n/a";
}
public String getCode(String ruta) throws IOException{
InputStream in = new FileInputStream(ruta);
if( in == null ){
return "n/a";
}
if( in != null ){
StringBuilder builder = new StringBuilder();
InputStreamReader reader = new InputStreamReader( in, "UTF-8" );
int next;
while( (next = reader.read()) != -1 ){
if( next == '\t' ){
builder.append( " " );
}
else{
builder.append( (char)next );
}
}
reader.close();
return builder.toString();
}
return "n/a";
}
}
| darkdrei/CoreTesis | Desarrollo/Core/src/logica/CargarArchivoArbol.java | Java | mit | 5,774 |
migration_file = `ls #{RAILS_ROOT}/db/migrate/*create_sic_uk_tables.rb`
if migration_file && migration_file[/[^\d](\d+)_create_sic_uk_tables.rb/]
version = $1
puts `cd #{RAILS_ROOT}; rake db:migrate:down VERSION=#{version} --trace`
puts "removing: #{migration_file}"
puts `rm #{migration_file}`
end
| robmckinnon/sic_uk | uninstall.rb | Ruby | mit | 308 |
#include "clustermove.h"
#include "aux/eigensupport.h"
namespace Faunus {
namespace Move {
double Cluster::clusterProbability(const Cluster::Tgroup &g1, const Cluster::Tgroup &g2) const {
if (spc.geo.sqdist(g1.cm, g2.cm) <= thresholdsq(g1.id, g2.id))
return 1.0;
return 0.0;
}
void Cluster::_to_json(json &j) const {
using namespace u8;
j = {{"dir", dir},
{"dp", dptrans},
{"dprot", dprot},
{"spread", spread},
{"dirrot", dirrot},
{rootof + bracket("r" + squared), std::sqrt(msqd.avg())},
{rootof + bracket(theta + squared) + "/" + degrees, std::sqrt(msqd_angle.avg()) / 1.0_deg},
{bracket("N"), N.avg()},
{"bias rejection rate", double(bias_rejected) / cnt},
{"clusterdistribution", clusterSizeDistribution}};
_roundjson(j, 3);
// print threshold matrix
auto &_j = j["threshold"];
for (auto i : ids)
for (auto j : ids)
if (i >= j) {
auto str = Faunus::molecules[i].name + " " + Faunus::molecules[j].name;
_j[str] = std::sqrt(thresholdsq(i, j));
_roundjson(_j[str], 3);
}
// print satellite molecules
if (not satellites.empty()) {
auto &_j = j["satellites"];
_j = json::array();
for (auto id : satellites)
_j.push_back(Faunus::molecules[id].name);
}
}
void Cluster::_from_json(const json &j) {
assertKeys(j, {"dp", "dprot", "dir", "threshold", "molecules", "repeat", "satellites", "dirrot"});
dptrans = j.at("dp");
dir = j.value("dir", Point(1, 1, 1));
dirrot = j.value("dirrot", Point(0, 0, 0)); // predefined axis of rotation
dprot = j.at("dprot");
spread = j.value("spread", true);
names = j.at("molecules").get<decltype(names)>(); // molecule names
ids = names2ids(molecules, names); // names --> molids
index.clear();
for (auto &g : spc.groups) // loop over all groups
if (not g.atomic) // only molecular groups
if (g.size() == g.capacity()) // only active particles
if (std::find(ids.begin(), ids.end(), g.id) != ids.end())
index.push_back(&g - &spc.groups.front());
if (repeat < 0)
repeat = index.size();
// read satellite ids (molecules NOT to be considered as cluster centers)
auto satnames = j.value("satellites", std::vector<std::string>()); // molecule names
auto vec = names2ids(Faunus::molecules, satnames); // names --> molids
satellites = std::set<int>(vec.begin(), vec.end());
for (auto id : satellites)
if (std::find(ids.begin(), ids.end(), id) == ids.end())
throw std::runtime_error("satellite molecules must be defined in `molecules`");
// read cluster thresholds
if (j.count("threshold") == 1) {
auto &_j = j.at("threshold");
// threshold is given as a single number
if (_j.is_number()) {
for (auto i : ids)
for (auto j : ids)
if (i >= j)
thresholdsq.set(i, j, std::pow(_j.get<double>(), 2));
}
// threshold is given as pairs of clustering molecules
else if (_j.is_object()) {
for (auto it = _j.begin(); it != _j.end(); ++it) {
auto v = words2vec<std::string>(it.key());
if (v.size() == 2) {
auto it1 = findName(Faunus::molecules, v[0]);
auto it2 = findName(Faunus::molecules, v[1]);
if (it1 == Faunus::molecules.end() or it2 == Faunus::molecules.end())
throw std::runtime_error("unknown molecule(s): ["s + v[0] + " " + v[1] + "]");
thresholdsq.set(it1->id(), it2->id(), std::pow(it.value().get<double>(), 2));
} else
throw std::runtime_error("threshold requires exactly two space-separated molecules");
}
} else
throw std::runtime_error("threshold must be a number or object");
}
}
void Cluster::findCluster(Space &spc, size_t first, std::set<size_t> &cluster) {
assert(first < spc.p.size());
std::set<size_t> pool(index.begin(), index.end());
assert(pool.count(first) > 0);
cluster.clear();
cluster.insert(first);
pool.erase(first);
size_t n;
do { // find cluster (not very clever...)
start:
n = cluster.size();
for (size_t i : cluster)
if (not spc.groups.at(i).empty()) // check if group is inactive
for (size_t j : pool)
if (i != j)
if (not spc.groups.at(j).empty()) { // check if group is inactive
// probability to cluster
double P = clusterProbability(spc.groups.at(i), spc.groups.at(j));
if (Movebase::slump() <= P) {
cluster.insert(j);
pool.erase(j);
if(spread)
goto start; // wow, first goto ever!
}
}
} while (cluster.size() != n);
// check if cluster is too large
double max = spc.geo.getLength().minCoeff() / 2;
for (auto i : cluster)
for (auto j : cluster)
if (j > i)
if (spc.geo.sqdist(spc.groups.at(i).cm, spc.groups.at(j).cm) >= max * max)
rotate = false; // skip rotation if cluster larger than half the box length
}
void Cluster::_move(Change &change) {
_bias = 0;
rotate = true;
if (not index.empty()) {
std::set<size_t> cluster; // all group index in cluster
// find "nuclei" or cluster center and exclude any molecule id listed as "satellite".
size_t first;
do {
first = *slump.sample(index.begin(), index.end()); // random molecule (nuclei)
} while (satellites.count(spc.groups[first].id) != 0);
findCluster(spc, first, cluster); // find cluster around first
N += cluster.size(); // average cluster size
clusterSizeDistribution[cluster.size()]++; // update cluster size distribution
Change::data d;
d.all = true;
dp = ranunit(slump, dir) * dptrans * slump();
if (rotate)
angle = dprot * (slump() - 0.5);
else
angle = 0;
auto boundary = spc.geo.getBoundaryFunc();
// lambda function to calculate cluster COM
auto clusterCOM = [&]() {
double sum_m = 0;
Point cm(0, 0, 0);
Point O = spc.groups[*cluster.begin()].cm;
for (auto i : cluster) {
auto &g = spc.groups[i];
Point t = g.cm - O;
boundary(t);
double m = g.mass();
cm += m * t;
sum_m += m;
}
cm = cm / sum_m + O;
boundary(cm);
return cm;
};
Point COM = clusterCOM(); // org. cluster center
Eigen::Quaterniond Q;
Point u = ranunit(slump);
if (dirrot.count() > 0)
u = dirrot;
Q = Eigen::AngleAxisd(angle, u); // quaternion
for (auto i : cluster) { // loop over molecules in cluster
auto &g = spc.groups[i];
if (rotate) {
Geometry::rotate(g.begin(), g.end(), Q, boundary, -COM);
g.cm = g.cm - COM;
boundary(g.cm);
g.cm = Q * g.cm + COM;
boundary(g.cm);
}
g.translate(dp, boundary);
d.index = i;
change.groups.push_back(d);
}
change.moved2moved = false; // do not calc. internal cluster energy
// Reject if cluster composition changes during move
// Note: this only works for the binary 0/1 probability function
// currently implemented in `findCluster()`.
std::set<size_t> aftercluster; // all group index in cluster _after_move
findCluster(spc, first, aftercluster); // find cluster around first
if (aftercluster == cluster)
_bias = 0;
else {
_bias = pc::infty; // bias is infinite --> reject
bias_rejected++; // count how many time we reject due to bias
}
#ifndef NDEBUG
// check if cluster mass center movement matches displacement
if (_bias == 0) {
Point newCOM = clusterCOM(); // org. cluster center
Point d = spc.geo.vdist(COM, newCOM); // distance between new and old COM
double _zero = (d + dp).norm(); // |d+dp| should ideally be zero...
assert(std::fabs(_zero) < 1e-6 && "cluster likely too large");
}
#endif
}
}
double Cluster::bias(Change &, double, double) { return _bias; }
void Cluster::_reject(Change &) {
msqd += 0;
msqd_angle += 0;
}
void Cluster::_accept(Change &) {
msqd += dp.squaredNorm();
msqd_angle += angle * angle;
}
Cluster::Cluster(Space &spc) : spc(spc) {
cite = "doi:10/cj9gnn";
name = "cluster";
repeat = -1; // meaning repeat N times
}
} // namespace Move
} // namespace Faunus
| gitesei/faunus | src/clustermove.cpp | C++ | mit | 9,289 |
/**
* Created by osboxes on 21/02/17.
*/
export * from './notes.component';
export * from './notes.routes';
| origamyllc/Mangular | src/client/app/notes/index.ts | TypeScript | mit | 110 |
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _htmlPdf = require('html-pdf');
var _htmlPdf2 = _interopRequireDefault(_htmlPdf);
var _handlebars = require('handlebars');
var _handlebars2 = _interopRequireDefault(_handlebars);
var _fs = require('fs');
var _fs2 = _interopRequireDefault(_fs);
var _path = require('path');
var _path2 = _interopRequireDefault(_path);
var _constants = require('../lib/constants');
var _constants2 = _interopRequireDefault(_constants);
var _moment = require('moment');
var _moment2 = _interopRequireDefault(_moment);
var _lodash = require('lodash');
var _lodash2 = _interopRequireDefault(_lodash);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function generateReport(reportName, data, res) {
var filePath = _path2.default.join(__dirname, '../views/' + reportName + '.html');
var html = _fs2.default.readFileSync(filePath, 'utf8');
var compiledTemplate = _handlebars2.default.compile(html);
var withData = compiledTemplate(data);
var options = { format: 'Letter' };
_htmlPdf2.default.create(withData, options).toBuffer(function (err, buffer) {
if (err) return console.log(err);
res.contentType("application/pdf");
return res.end(buffer, 'binary');
//console.log(res); // { filename: '/app/businesscard.pdf' }
});
}
function buildReportDataFromColumns(columns, skillData) {
console.log(_constants2.default.dateTypes);
return _lodash2.default.map(skillData, function (skillDatum) {
var dataObject = {
skillData: skillDatum,
columns: []
};
_lodash2.default.each(columns, function (column) {
var keys = column.key.split('.');
var value = skillDatum;
_lodash2.default.each(keys, function (key) {
if (value) value = value[key];
});
if (column.isDate) {
value = (0, _moment2.default)(value).format(_constants2.default.dateTypes.altDateFormat);
}
dataObject.columns.push({
value: value
});
});
return dataObject;
});
}
exports.default = { generateReport: generateReport, buildReportDataFromColumns: buildReportDataFromColumns };
//# sourceMappingURL=reportHelper.js.map | manuelnelson/patient-pal | dist/lib/reportHelper.js | JavaScript | mit | 2,378 |
<?php
class CommentWidget extends CWidget
{
public $type;
public $id;
public $limit;
public $uid;
public function init()
{
}
public function run()
{
$criteria=new CDbCriteria();
if($this->type==0)
$criteria->addCondition('dpid='.$this->id);
else
$criteria->addCondition('fdid='.$this->id);
//分页
$count=Comment::model()->count($criteria);
$paper=new CPagination($count);
$paper->pageSize=$this->limit;
$paper->applyLimit($criteria);
//列表
$criteria->limit=$this->limit;
$criteria->with='commentreply';
$criteria->order='id desc';
$list=Comment::model()->findAll($criteria);
$data=$list;
//用户信息
if($data)
{
foreach ($list as $v)
{
$uid[]=$v->uid;
if($v->commentreply)
foreach ($v->commentreply as $val)
$uid[]=$val->uid;
}
}
if($uid)
{
$uid=array_unique($uid);
$u=Member::model()->getUserInfo($uid);
}
$this->render('comment',array(
'data'=>$data,
'u'=>$u,
'pages'=>$paper,
'count'=>$count,
'type'=>$this->type,
'id'=>$this->id,
));
}
} | laijingsong/lacms | protected/widget/CommentWidget.php | PHP | mit | 1,135 |
// development configuration
// author: Kirk Austin
module.exports = {
environment: 'development',
server: {
name: 'Node Scratch',
port: 3001
},
log: {
name: 'node-scratch',
path: 'node-scratch.log'
}
}
| kirkaustin/node-scratch | config/development.js | JavaScript | mit | 225 |
import warnings
from collections import defaultdict
from queryset import QuerySet, QuerySetManager
from queryset import DoesNotExist, MultipleObjectsReturned
from queryset import DO_NOTHING
from mongoengine import signals
import sys
import pymongo
from bson import ObjectId
import operator
from functools import partial
from bson.dbref import DBRef
class NotRegistered(Exception):
pass
class InvalidDocumentError(Exception):
pass
class ValidationError(AssertionError):
"""Validation exception.
May represent an error validating a field or a
document containing fields with validation errors.
:ivar errors: A dictionary of errors for fields within this
document or list, or None if the error is for an
individual field.
"""
errors = {}
field_name = None
_message = None
def __init__(self, message="", **kwargs):
self.errors = kwargs.get('errors', {})
self.field_name = kwargs.get('field_name')
self.message = message
def __str__(self):
return self.message
def __repr__(self):
return '%s(%s,)' % (self.__class__.__name__, self.message)
def __getattribute__(self, name):
message = super(ValidationError, self).__getattribute__(name)
if name == 'message':
if self.field_name:
message = '%s' % message
if self.errors:
message = '%s(%s)' % (message, self._format_errors())
return message
def _get_message(self):
return self._message
def _set_message(self, message):
self._message = message
message = property(_get_message, _set_message)
def to_dict(self):
"""Returns a dictionary of all errors within a document
Keys are field names or list indices and values are the
validation error messages, or a nested dictionary of
errors for an embedded document or list.
"""
def build_dict(source):
errors_dict = {}
if not source:
return errors_dict
if isinstance(source, dict):
for field_name, error in source.iteritems():
errors_dict[field_name] = build_dict(error)
elif isinstance(source, ValidationError) and source.errors:
return build_dict(source.errors)
else:
return unicode(source)
return errors_dict
if not self.errors:
return {}
return build_dict(self.errors)
def _format_errors(self):
"""Returns a string listing all errors within a document"""
def generate_key(value, prefix=''):
if isinstance(value, list):
value = ' '.join([generate_key(k) for k in value])
if isinstance(value, dict):
value = ' '.join(
[generate_key(v, k) for k, v in value.iteritems()])
results = "%s.%s" % (prefix, value) if prefix else value
return results
error_dict = defaultdict(list)
for k, v in self.to_dict().iteritems():
error_dict[generate_key(v)].append(k)
return ' '.join(["%s: %s" % (k, v) for k, v in error_dict.iteritems()])
_document_registry = {}
def get_document(name):
doc = _document_registry.get(name, None)
if not doc:
# Possible old style names
end = ".%s" % name
possible_match = [k for k in _document_registry.keys() if k.endswith(end)]
if len(possible_match) == 1:
doc = _document_registry.get(possible_match.pop(), None)
if not doc:
raise NotRegistered("""
`%s` has not been registered in the document registry.
Importing the document class automatically registers it, has it
been imported?
""".strip() % name)
return doc
class BaseField(object):
"""A base class for fields in a MongoDB document. Instances of this class
may be added to subclasses of `Document` to define a document's schema.
.. versionchanged:: 0.5 - added verbose and help text
"""
name = None
# Fields may have _types inserted into indexes by default
_index_with_types = True
_geo_index = False
# These track each time a Field instance is created. Used to retain order.
# The auto_creation_counter is used for fields that MongoEngine implicitly
# creates, creation_counter is used for all user-specified fields.
creation_counter = 0
auto_creation_counter = -1
def __init__(self, db_field=None, name=None, required=False, default=None,
unique=False, unique_with=None, primary_key=False,
validation=None, choices=None, verbose_name=None, help_text=None):
self.db_field = (db_field or name) if not primary_key else '_id'
if name:
msg = "Fields' 'name' attribute deprecated in favour of 'db_field'"
warnings.warn(msg, DeprecationWarning)
self.name = None
self.required = required or primary_key
self.default = default
self.unique = bool(unique or unique_with)
self.unique_with = unique_with
self.primary_key = primary_key
self.validation = validation
self.choices = choices
self.verbose_name = verbose_name
self.help_text = help_text
# Adjust the appropriate creation counter, and save our local copy.
if self.db_field == '_id':
self.creation_counter = BaseField.auto_creation_counter
BaseField.auto_creation_counter -= 1
else:
self.creation_counter = BaseField.creation_counter
BaseField.creation_counter += 1
def __get__(self, instance, owner):
"""Descriptor for retrieving a value from a field in a document. Do
any necessary conversion between Python and MongoDB types.
"""
if instance is None:
# Document class being used rather than a document object
return self
# Get value from document instance if available, if not use default
value = instance._data.get(self.name)
if value is None:
value = self.default
# Allow callable default values
if callable(value):
value = value()
return value
def __set__(self, instance, value):
"""Descriptor for assigning a value to a field in a document.
"""
instance._data[self.name] = value
instance._mark_as_changed(self.name)
def error(self, message="", errors=None, field_name=None):
"""Raises a ValidationError.
"""
field_name = field_name if field_name else self.name
raise ValidationError(message, errors=errors, field_name=field_name)
def to_python(self, value):
"""Convert a MongoDB-compatible type to a Python type.
"""
return value
def to_mongo(self, value):
"""Convert a Python type to a MongoDB-compatible type.
"""
return self.to_python(value)
def prepare_query_value(self, op, value):
"""Prepare a value that is being used in a query for PyMongo.
"""
return value
def validate(self, value):
"""Perform validation on a value.
"""
pass
def _validate(self, value):
from mongoengine import Document, EmbeddedDocument
# check choices
if self.choices:
is_cls = isinstance(value, (Document, EmbeddedDocument))
value_to_check = value.__class__ if is_cls else value
err_msg = 'an instance' if is_cls else 'one'
if isinstance(self.choices[0], (list, tuple)):
option_keys = [option_key for option_key, option_value in self.choices]
if value_to_check not in option_keys:
self.error('Value must be %s of %s' % (err_msg, unicode(option_keys)))
elif value_to_check not in self.choices:
self.error('Value must be %s of %s' % (err_msg, unicode(self.choices)))
# check validation argument
if self.validation is not None:
if callable(self.validation):
if not self.validation(value):
self.error('Value does not match custom validation method')
else:
raise ValueError('validation argument for "%s" must be a '
'callable.' % self.name)
self.validate(value)
class ComplexBaseField(BaseField):
"""Handles complex fields, such as lists / dictionaries.
Allows for nesting of embedded documents inside complex types.
Handles the lazy dereferencing of a queryset by lazily dereferencing all
items in a list / dict rather than one at a time.
.. versionadded:: 0.5
"""
field = None
_dereference = False
def __get__(self, instance, owner):
"""Descriptor to automatically dereference references.
"""
if instance is None:
# Document class being used rather than a document object
return self
from fields import GenericReferenceField, ReferenceField
dereference = self.field is None or isinstance(self.field,
(GenericReferenceField, ReferenceField))
if not self._dereference and instance._initialised and dereference:
from dereference import DeReference
self._dereference = DeReference() # Cached
instance._data[self.name] = self._dereference(
instance._data.get(self.name), max_depth=1, instance=instance,
name=self.name
)
value = super(ComplexBaseField, self).__get__(instance, owner)
# Convert lists / values so we can watch for any changes on them
if isinstance(value, (list, tuple)) and not isinstance(value, BaseList):
value = BaseList(value, instance, self.name)
instance._data[self.name] = value
elif isinstance(value, dict) and not isinstance(value, BaseDict):
value = BaseDict(value, instance, self.name)
instance._data[self.name] = value
if self._dereference and instance._initialised and \
isinstance(value, (BaseList, BaseDict)) and not value._dereferenced:
value = self._dereference(
value, max_depth=1, instance=instance, name=self.name
)
value._dereferenced = True
instance._data[self.name] = value
return value
def __set__(self, instance, value):
"""Descriptor for assigning a value to a field in a document.
"""
instance._data[self.name] = value
instance._mark_as_changed(self.name)
def to_python(self, value):
"""Convert a MongoDB-compatible type to a Python type.
"""
from mongoengine import Document
if isinstance(value, basestring):
return value
if hasattr(value, 'to_python'):
return value.to_python()
is_list = False
if not hasattr(value, 'items'):
try:
is_list = True
value = dict([(k, v) for k, v in enumerate(value)])
except TypeError: # Not iterable return the value
return value
if self.field:
value_dict = dict([(key, self.field.to_python(item)) for key, item in value.items()])
else:
value_dict = {}
for k, v in value.items():
if isinstance(v, Document):
# We need the id from the saved object to create the DBRef
if v.pk is None:
self.error('You can only reference documents once they'
' have been saved to the database')
collection = v._get_collection_name()
value_dict[k] = DBRef(collection, v.pk)
elif hasattr(v, 'to_python'):
value_dict[k] = v.to_python()
else:
value_dict[k] = self.to_python(v)
if is_list: # Convert back to a list
return [v for k, v in sorted(value_dict.items(), key=operator.itemgetter(0))]
return value_dict
def to_mongo(self, value):
"""Convert a Python type to a MongoDB-compatible type.
"""
from mongoengine import Document
if isinstance(value, basestring):
return value
if hasattr(value, 'to_mongo'):
return value.to_mongo()
is_list = False
if not hasattr(value, 'items'):
try:
is_list = True
value = dict([(k, v) for k, v in enumerate(value)])
except TypeError: # Not iterable return the value
return value
if self.field:
value_dict = dict([(key, self.field.to_mongo(item)) for key, item in value.items()])
else:
value_dict = {}
for k, v in value.items():
if isinstance(v, Document):
# We need the id from the saved object to create the DBRef
if v.pk is None:
self.error('You can only reference documents once they'
' have been saved to the database')
# If its a document that is not inheritable it won't have
# _types / _cls data so make it a generic reference allows
# us to dereference
meta = getattr(v, 'meta', getattr(v, '_meta', {}))
if meta and not meta.get('allow_inheritance', True) and not self.field:
from fields import GenericReferenceField
value_dict[k] = GenericReferenceField().to_mongo(v)
else:
collection = v._get_collection_name()
value_dict[k] = DBRef(collection, v.pk)
elif hasattr(v, 'to_mongo'):
value_dict[k] = v.to_mongo()
else:
value_dict[k] = self.to_mongo(v)
if is_list: # Convert back to a list
return [v for k, v in sorted(value_dict.items(), key=operator.itemgetter(0))]
return value_dict
def validate(self, value):
"""If field is provided ensure the value is valid.
"""
errors = {}
if self.field:
if hasattr(value, 'iteritems'):
sequence = value.iteritems()
else:
sequence = enumerate(value)
for k, v in sequence:
try:
self.field._validate(v)
except ValidationError, error:
errors[k] = error.errors or error
except (ValueError, AssertionError), error:
errors[k] = error
if errors:
field_class = self.field.__class__.__name__
self.error('Invalid %s item (%s)' % (field_class, value),
errors=errors)
# Don't allow empty values if required
if self.required and not value:
self.error('Field is required and cannot be empty')
def prepare_query_value(self, op, value):
return self.to_mongo(value)
def lookup_member(self, member_name):
if self.field:
return self.field.lookup_member(member_name)
return None
def _set_owner_document(self, owner_document):
if self.field:
self.field.owner_document = owner_document
self._owner_document = owner_document
def _get_owner_document(self, owner_document):
self._owner_document = owner_document
owner_document = property(_get_owner_document, _set_owner_document)
class ObjectIdField(BaseField):
"""An field wrapper around MongoDB's ObjectIds.
"""
def to_python(self, value):
return value
def to_mongo(self, value):
if not isinstance(value, ObjectId):
try:
return ObjectId(unicode(value))
except Exception, e:
# e.message attribute has been deprecated since Python 2.6
self.error(unicode(e))
return value
def prepare_query_value(self, op, value):
return self.to_mongo(value)
def validate(self, value):
try:
ObjectId(unicode(value))
except:
self.error('Invalid Object ID')
class DocumentMetaclass(type):
"""Metaclass for all documents.
"""
def __new__(cls, name, bases, attrs):
def _get_mixin_fields(base):
attrs = {}
attrs.update(dict([(k, v) for k, v in base.__dict__.items()
if issubclass(v.__class__, BaseField)]))
# Handle simple mixin's with meta
if hasattr(base, 'meta') and not isinstance(base, DocumentMetaclass):
meta = attrs.get('meta', {})
meta.update(base.meta)
attrs['meta'] = meta
for p_base in base.__bases__:
#optimize :-)
if p_base in (object, BaseDocument):
continue
attrs.update(_get_mixin_fields(p_base))
return attrs
metaclass = attrs.get('__metaclass__')
super_new = super(DocumentMetaclass, cls).__new__
if metaclass and issubclass(metaclass, DocumentMetaclass):
return super_new(cls, name, bases, attrs)
doc_fields = {}
class_name = [name]
superclasses = {}
simple_class = True
for base in bases:
# Include all fields present in superclasses
if hasattr(base, '_fields'):
doc_fields.update(base._fields)
# Get superclasses from superclass
superclasses[base._class_name] = base
superclasses.update(base._superclasses)
else: # Add any mixin fields
attrs.update(_get_mixin_fields(base))
if hasattr(base, '_meta') and not base._meta.get('abstract'):
# Ensure that the Document class may be subclassed -
# inheritance may be disabled to remove dependency on
# additional fields _cls and _types
class_name.append(base._class_name)
if not base._meta.get('allow_inheritance_defined', True):
warnings.warn(
"%s uses inheritance, the default for allow_inheritance "
"is changing to off by default. Please add it to the "
"document meta." % name,
FutureWarning
)
if base._meta.get('allow_inheritance', True) == False:
raise ValueError('Document %s may not be subclassed' %
base.__name__)
else:
simple_class = False
doc_class_name = '.'.join(reversed(class_name))
meta = attrs.get('_meta', {})
meta.update(attrs.get('meta', {}))
if 'allow_inheritance' not in meta:
meta['allow_inheritance'] = True
# Only simple classes - direct subclasses of Document - may set
# allow_inheritance to False
if not simple_class and not meta['allow_inheritance'] and not meta['abstract']:
raise ValueError('Only direct subclasses of Document may set '
'"allow_inheritance" to False')
attrs['_meta'] = meta
attrs['_class_name'] = doc_class_name
attrs['_superclasses'] = superclasses
# Add the document's fields to the _fields attribute
field_names = {}
for attr_name, attr_value in attrs.items():
if hasattr(attr_value, "__class__") and \
issubclass(attr_value.__class__, BaseField):
attr_value.name = attr_name
if not attr_value.db_field:
attr_value.db_field = attr_name
doc_fields[attr_name] = attr_value
field_names[attr_value.db_field] = field_names.get(attr_value.db_field, 0) + 1
duplicate_db_fields = [k for k, v in field_names.items() if v > 1]
if duplicate_db_fields:
raise InvalidDocumentError("Multiple db_fields defined for: %s " % ", ".join(duplicate_db_fields))
attrs['_fields'] = doc_fields
attrs['_db_field_map'] = dict([(k, v.db_field) for k, v in doc_fields.items() if k != v.db_field])
attrs['_reverse_db_field_map'] = dict([(v, k) for k, v in attrs['_db_field_map'].items()])
from mongoengine import Document, EmbeddedDocument, DictField
new_class = super_new(cls, name, bases, attrs)
for field in new_class._fields.values():
field.owner_document = new_class
delete_rule = getattr(field, 'reverse_delete_rule', DO_NOTHING)
f = field
if isinstance(f, ComplexBaseField) and hasattr(f, 'field'):
delete_rule = getattr(f.field, 'reverse_delete_rule', DO_NOTHING)
if isinstance(f, DictField) and delete_rule != DO_NOTHING:
raise InvalidDocumentError("Reverse delete rules are not supported for %s (field: %s)" % (field.__class__.__name__, field.name))
f = field.field
if delete_rule != DO_NOTHING:
if issubclass(new_class, EmbeddedDocument):
raise InvalidDocumentError("Reverse delete rules are not supported for EmbeddedDocuments (field: %s)" % field.name)
f.document_type.register_delete_rule(new_class, field.name, delete_rule)
if field.name and hasattr(Document, field.name) and EmbeddedDocument not in new_class.mro():
raise InvalidDocumentError("%s is a document method and not a valid field name" % field.name)
module = attrs.get('__module__')
base_excs = tuple(base.DoesNotExist for base in bases
if hasattr(base, 'DoesNotExist')) or (DoesNotExist,)
exc = subclass_exception('DoesNotExist', base_excs, module)
new_class.add_to_class('DoesNotExist', exc)
base_excs = tuple(base.MultipleObjectsReturned for base in bases
if hasattr(base, 'MultipleObjectsReturned'))
base_excs = base_excs or (MultipleObjectsReturned,)
exc = subclass_exception('MultipleObjectsReturned', base_excs, module)
new_class.add_to_class('MultipleObjectsReturned', exc)
global _document_registry
_document_registry[doc_class_name] = new_class
return new_class
def add_to_class(self, name, value):
setattr(self, name, value)
class TopLevelDocumentMetaclass(DocumentMetaclass):
"""Metaclass for top-level documents (i.e. documents that have their own
collection in the database.
"""
def __new__(cls, name, bases, attrs):
super_new = super(TopLevelDocumentMetaclass, cls).__new__
# Classes defined in this package are abstract and should not have
# their own metadata with DB collection, etc.
# __metaclass__ is only set on the class with the __metaclass__
# attribute (i.e. it is not set on subclasses). This differentiates
# 'real' documents from the 'Document' class
#
# Also assume a class is abstract if it has abstract set to True in
# its meta dictionary. This allows custom Document superclasses.
if (attrs.get('__metaclass__') == TopLevelDocumentMetaclass or
('meta' in attrs and attrs['meta'].get('abstract', False))):
# Make sure no base class was non-abstract
non_abstract_bases = [b for b in bases
if hasattr(b, '_meta') and not b._meta.get('abstract', False)]
if non_abstract_bases:
raise ValueError("Abstract document cannot have non-abstract base")
return super_new(cls, name, bases, attrs)
collection = ''.join('_%s' % c if c.isupper() else c for c in name).strip('_').lower()
id_field = None
abstract_base_indexes = []
base_indexes = []
base_meta = {}
# Subclassed documents inherit collection from superclass
for base in bases:
if hasattr(base, '_meta'):
if 'collection' in attrs.get('meta', {}) and not base._meta.get('abstract', False):
import warnings
msg = "Trying to set a collection on a subclass (%s)" % name
warnings.warn(msg, SyntaxWarning)
del(attrs['meta']['collection'])
if base._get_collection_name():
collection = base._get_collection_name()
# Propagate inherited values
keys_to_propogate = (
'index_background', 'index_drop_dups', 'index_opts',
'allow_inheritance', 'queryset_class', 'db_alias',
)
for key in keys_to_propogate:
if key in base._meta:
base_meta[key] = base._meta[key]
id_field = id_field or base._meta.get('id_field')
if base._meta.get('abstract', False):
abstract_base_indexes += base._meta.get('indexes', [])
else:
base_indexes += base._meta.get('indexes', [])
try:
base_meta['objects'] = base.__getattribute__(base, 'objects')
except TypeError:
pass
except AttributeError:
pass
# defaults
meta = {
'abstract': False,
'collection': collection,
'max_documents': None,
'max_size': None,
'ordering': [], # default ordering applied at runtime
'indexes': [], # indexes to be ensured at runtime
'id_field': id_field,
'index_background': False,
'index_drop_dups': False,
'index_opts': {},
'queryset_class': QuerySet,
'delete_rules': {},
'allow_inheritance': True
}
allow_inheritance_defined = ('allow_inheritance' in base_meta or
'allow_inheritance'in attrs.get('meta', {}))
meta['allow_inheritance_defined'] = allow_inheritance_defined
meta.update(base_meta)
# Apply document-defined meta options
meta.update(attrs.get('meta', {}))
attrs['_meta'] = meta
# Set up collection manager, needs the class to have fields so use
# DocumentMetaclass before instantiating CollectionManager object
new_class = super_new(cls, name, bases, attrs)
collection = attrs['_meta'].get('collection', None)
if callable(collection):
new_class._meta['collection'] = collection(new_class)
# Provide a default queryset unless one has been manually provided
manager = attrs.get('objects', meta.get('objects', QuerySetManager()))
if hasattr(manager, 'queryset_class'):
meta['queryset_class'] = manager.queryset_class
new_class.objects = manager
indicies = list(meta['indexes']) + abstract_base_indexes
user_indexes = [QuerySet._build_index_spec(new_class, spec)
for spec in indicies] + base_indexes
new_class._meta['indexes'] = user_indexes
unique_indexes = cls._unique_with_indexes(new_class)
new_class._meta['unique_indexes'] = unique_indexes
for field_name, field in new_class._fields.items():
# Check for custom primary key
if field.primary_key:
current_pk = new_class._meta['id_field']
if current_pk and current_pk != field_name:
raise ValueError('Cannot override primary key field')
if not current_pk:
new_class._meta['id_field'] = field_name
# Make 'Document.id' an alias to the real primary key field
new_class.id = field
if not new_class._meta['id_field']:
new_class._meta['id_field'] = 'id'
new_class._fields['id'] = ObjectIdField(db_field='_id')
new_class.id = new_class._fields['id']
return new_class
@classmethod
def _unique_with_indexes(cls, new_class, namespace=""):
unique_indexes = []
for field_name, field in new_class._fields.items():
# Generate a list of indexes needed by uniqueness constraints
if field.unique:
field.required = True
unique_fields = [field.db_field]
# Add any unique_with fields to the back of the index spec
if field.unique_with:
if isinstance(field.unique_with, basestring):
field.unique_with = [field.unique_with]
# Convert unique_with field names to real field names
unique_with = []
for other_name in field.unique_with:
parts = other_name.split('.')
# Lookup real name
parts = QuerySet._lookup_field(new_class, parts)
name_parts = [part.db_field for part in parts]
unique_with.append('.'.join(name_parts))
# Unique field should be required
parts[-1].required = True
unique_fields += unique_with
# Add the new index to the list
index = [("%s%s" % (namespace, f), pymongo.ASCENDING) for f in unique_fields]
unique_indexes.append(index)
# Grab any embedded document field unique indexes
if field.__class__.__name__ == "EmbeddedDocumentField" and field.document_type != new_class:
field_namespace = "%s." % field_name
unique_indexes += cls._unique_with_indexes(field.document_type,
field_namespace)
return unique_indexes
class BaseDocument(object):
_dynamic = False
_created = True
_dynamic_lock = True
_initialised = False
def __init__(self, **values):
signals.pre_init.send(self.__class__, document=self, values=values)
self._data = {}
# Assign default values to instance
for attr_name, field in self._fields.items():
value = getattr(self, attr_name, None)
setattr(self, attr_name, value)
# Set passed values after initialisation
if self._dynamic:
self._dynamic_fields = {}
dynamic_data = {}
for key, value in values.items():
if key in self._fields or key == '_id':
setattr(self, key, value)
elif self._dynamic:
dynamic_data[key] = value
else:
for key, value in values.items():
key = self._reverse_db_field_map.get(key, key)
setattr(self, key, value)
# Set any get_fieldname_display methods
self.__set_field_display()
if self._dynamic:
self._dynamic_lock = False
for key, value in dynamic_data.items():
setattr(self, key, value)
# Flag initialised
self._initialised = True
signals.post_init.send(self.__class__, document=self)
def __setattr__(self, name, value):
# Handle dynamic data only if an initialised dynamic document
if self._dynamic and not self._dynamic_lock:
field = None
if not hasattr(self, name) and not name.startswith('_'):
from fields import DynamicField
field = DynamicField(db_field=name)
field.name = name
self._dynamic_fields[name] = field
if not name.startswith('_'):
value = self.__expand_dynamic_values(name, value)
# Handle marking data as changed
if name in self._dynamic_fields:
self._data[name] = value
if hasattr(self, '_changed_fields'):
self._mark_as_changed(name)
if not self._created and name in self._meta.get('shard_key', tuple()):
from queryset import OperationError
raise OperationError("Shard Keys are immutable. Tried to update %s" % name)
super(BaseDocument, self).__setattr__(name, value)
def __expand_dynamic_values(self, name, value):
"""expand any dynamic values to their correct types / values"""
if not isinstance(value, (dict, list, tuple)):
return value
is_list = False
if not hasattr(value, 'items'):
is_list = True
value = dict([(k, v) for k, v in enumerate(value)])
if not is_list and '_cls' in value:
cls = get_document(value['_cls'])
value = cls(**value)
value._dynamic = True
value._changed_fields = []
return value
data = {}
for k, v in value.items():
key = name if is_list else k
data[k] = self.__expand_dynamic_values(key, v)
if is_list: # Convert back to a list
data_items = sorted(data.items(), key=operator.itemgetter(0))
value = [v for k, v in data_items]
else:
value = data
# Convert lists / values so we can watch for any changes on them
if isinstance(value, (list, tuple)) and not isinstance(value, BaseList):
value = BaseList(value, self, name)
elif isinstance(value, dict) and not isinstance(value, BaseDict):
value = BaseDict(value, self, name)
return value
def validate(self):
"""Ensure that all fields' values are valid and that required fields
are present.
"""
# Get a list of tuples of field names and their current values
fields = [(field, getattr(self, name))
for name, field in self._fields.items()]
# Ensure that each field is matched to a valid value
errors = {}
for field, value in fields:
if value is not None:
try:
field._validate(value)
except ValidationError, error:
errors[field.name] = error.errors or error
except (ValueError, AttributeError, AssertionError), error:
errors[field.name] = error
elif field.required:
errors[field.name] = ValidationError('Field is required',
field_name=field.name)
if errors:
raise ValidationError('ValidationError', errors=errors)
def to_mongo(self):
"""Return data dictionary ready for use with MongoDB.
"""
data = {}
for field_name, field in self._fields.items():
value = getattr(self, field_name, None)
if value is not None:
data[field.db_field] = field.to_mongo(value)
# Only add _cls and _types if allow_inheritance is not False
if not (hasattr(self, '_meta') and
self._meta.get('allow_inheritance', True) == False):
data['_cls'] = self._class_name
data['_types'] = self._superclasses.keys() + [self._class_name]
if '_id' in data and data['_id'] is None:
del data['_id']
if not self._dynamic:
return data
for name, field in self._dynamic_fields.items():
data[name] = field.to_mongo(self._data.get(name, None))
return data
@classmethod
def _get_collection_name(cls):
"""Returns the collection name for this class.
"""
return cls._meta.get('collection', None)
@classmethod
def _from_son(cls, son):
"""Create an instance of a Document (subclass) from a PyMongo SON.
"""
# get the class name from the document, falling back to the given
# class if unavailable
class_name = son.get('_cls', cls._class_name)
data = dict(("%s" % key, value) for key, value in son.items())
if '_types' in data:
del data['_types']
if '_cls' in data:
del data['_cls']
# Return correct subclass for document type
if class_name != cls._class_name:
cls = get_document(class_name)
changed_fields = []
errors_dict = {}
for field_name, field in cls._fields.items():
if field.db_field in data:
value = data[field.db_field]
try:
data[field_name] = (value if value is None
else field.to_python(value))
if field_name != field.db_field:
del data[field.db_field]
except (AttributeError, ValueError), e:
errors_dict[field_name] = e
elif field.default:
default = field.default
if callable(default):
default = default()
if isinstance(default, BaseDocument):
changed_fields.append(field_name)
if errors_dict:
errors = "\n".join(["%s - %s" % (k, v) for k, v in errors_dict.items()])
raise InvalidDocumentError("""
Invalid data to create a `%s` instance.\n%s""".strip() % (cls._class_name, errors))
obj = cls(**data)
obj._changed_fields = changed_fields
obj._created = False
return obj
def _mark_as_changed(self, key):
"""Marks a key as explicitly changed by the user
"""
if not key:
return
key = self._db_field_map.get(key, key)
if hasattr(self, '_changed_fields') and key not in self._changed_fields:
self._changed_fields.append(key)
def _get_changed_fields(self, key='', inspected=None):
"""Returns a list of all fields that have explicitly been changed.
"""
from mongoengine import EmbeddedDocument, DynamicEmbeddedDocument
_changed_fields = []
_changed_fields += getattr(self, '_changed_fields', [])
inspected = inspected or set()
if hasattr(self, 'id'):
if self.id in inspected:
return _changed_fields
inspected.add(self.id)
field_list = self._fields.copy()
if self._dynamic:
field_list.update(self._dynamic_fields)
for field_name in field_list:
db_field_name = self._db_field_map.get(field_name, field_name)
key = '%s.' % db_field_name
field = self._data.get(field_name, None)
if hasattr(field, 'id'):
if field.id in inspected:
continue
inspected.add(field.id)
if isinstance(field, (EmbeddedDocument, DynamicEmbeddedDocument)) and db_field_name not in _changed_fields: # Grab all embedded fields that have been changed
_changed_fields += ["%s%s" % (key, k) for k in field._get_changed_fields(key, inspected) if k]
elif isinstance(field, (list, tuple, dict)) and db_field_name not in _changed_fields: # Loop list / dict fields as they contain documents
# Determine the iterator to use
if not hasattr(field, 'items'):
iterator = enumerate(field)
else:
iterator = field.iteritems()
for index, value in iterator:
if not hasattr(value, '_get_changed_fields'):
continue
list_key = "%s%s." % (key, index)
_changed_fields += ["%s%s" % (list_key, k) for k in value._get_changed_fields(list_key, inspected) if k]
return _changed_fields
def _delta(self):
"""Returns the delta (set, unset) of the changes for a document.
Gets any values that have been explicitly changed.
"""
# Handles cases where not loaded from_son but has _id
doc = self.to_mongo()
set_fields = self._get_changed_fields()
set_data = {}
unset_data = {}
parts = []
if hasattr(self, '_changed_fields'):
set_data = {}
# Fetch each set item from its path
for path in set_fields:
parts = path.split('.')
d = doc
new_path = []
for p in parts:
if isinstance(d, DBRef):
break
elif p.isdigit():
d = d[int(p)]
elif hasattr(d, 'get'):
d = d.get(p)
new_path.append(p)
path = '.'.join(new_path)
set_data[path] = d
else:
set_data = doc
if '_id' in set_data:
del(set_data['_id'])
# Determine if any changed items were actually unset.
for path, value in set_data.items():
if value or isinstance(value, bool):
continue
# If we've set a value that ain't the default value dont unset it.
default = None
if self._dynamic and len(parts) and parts[0] in self._dynamic_fields:
del(set_data[path])
unset_data[path] = 1
continue
elif path in self._fields:
default = self._fields[path].default
else: # Perform a full lookup for lists / embedded lookups
d = self
parts = path.split('.')
db_field_name = parts.pop()
for p in parts:
if p.isdigit():
d = d[int(p)]
elif hasattr(d, '__getattribute__') and not isinstance(d, dict):
real_path = d._reverse_db_field_map.get(p, p)
d = getattr(d, real_path)
else:
d = d.get(p)
if hasattr(d, '_fields'):
field_name = d._reverse_db_field_map.get(db_field_name,
db_field_name)
if field_name in d._fields:
default = d._fields.get(field_name).default
else:
default = None
if default is not None:
if callable(default):
default = default()
if default != value:
continue
del(set_data[path])
unset_data[path] = 1
return set_data, unset_data
@classmethod
def _geo_indices(cls, inspected=None):
inspected = inspected or []
geo_indices = []
inspected.append(cls)
from fields import EmbeddedDocumentField, GeoPointField
for field in cls._fields.values():
if not isinstance(field, (EmbeddedDocumentField, GeoPointField)):
continue
if hasattr(field, 'document_type'):
field_cls = field.document_type
if field_cls in inspected:
continue
if hasattr(field_cls, '_geo_indices'):
geo_indices += field_cls._geo_indices(inspected)
elif field._geo_index:
geo_indices.append(field)
return geo_indices
def __getstate__(self):
removals = ["get_%s_display" % k for k, v in self._fields.items() if v.choices]
for k in removals:
if hasattr(self, k):
delattr(self, k)
return self.__dict__
def __setstate__(self, __dict__):
self.__dict__ = __dict__
self.__set_field_display()
def __set_field_display(self):
for attr_name, field in self._fields.items():
if field.choices: # dynamically adds a way to get the display value for a field with choices
setattr(self, 'get_%s_display' % attr_name, partial(self.__get_field_display, field=field))
def __get_field_display(self, field):
"""Returns the display value for a choice field"""
value = getattr(self, field.name)
if field.choices and isinstance(field.choices[0], (list, tuple)):
return dict(field.choices).get(value, value)
return value
def __iter__(self):
return iter(self._fields)
def __getitem__(self, name):
"""Dictionary-style field access, return a field's value if present.
"""
try:
if name in self._fields:
return getattr(self, name)
except AttributeError:
pass
raise KeyError(name)
def __setitem__(self, name, value):
"""Dictionary-style field access, set a field's value.
"""
# Ensure that the field exists before settings its value
if name not in self._fields:
raise KeyError(name)
return setattr(self, name, value)
def __contains__(self, name):
try:
val = getattr(self, name)
return val is not None
except AttributeError:
return False
def __len__(self):
return len(self._data)
def __repr__(self):
try:
u = unicode(self).encode('utf-8')
except (UnicodeEncodeError, UnicodeDecodeError):
u = '[Bad Unicode data]'
return '<%s: %s>' % (self.__class__.__name__, u)
def __str__(self):
if hasattr(self, '__unicode__'):
return unicode(self).encode('utf-8')
return '%s object' % self.__class__.__name__
def __eq__(self, other):
if isinstance(other, self.__class__) and hasattr(other, 'id'):
if self.id == other.id:
return True
return False
def __ne__(self, other):
return not self.__eq__(other)
def __hash__(self):
if self.pk is None:
# For new object
return super(BaseDocument, self).__hash__()
else:
return hash(self.pk)
class BaseList(list):
"""A special list so we can watch any changes
"""
_dereferenced = False
_instance = None
_name = None
def __init__(self, list_items, instance, name):
self._instance = instance
self._name = name
return super(BaseList, self).__init__(list_items)
def __setitem__(self, *args, **kwargs):
self._mark_as_changed()
return super(BaseList, self).__setitem__(*args, **kwargs)
def __delitem__(self, *args, **kwargs):
self._mark_as_changed()
return super(BaseList, self).__delitem__(*args, **kwargs)
def __getstate__(self):
self.observer = None
return self
def __setstate__(self, state):
self = state
return self
def append(self, *args, **kwargs):
self._mark_as_changed()
return super(BaseList, self).append(*args, **kwargs)
def extend(self, *args, **kwargs):
self._mark_as_changed()
return super(BaseList, self).extend(*args, **kwargs)
def insert(self, *args, **kwargs):
self._mark_as_changed()
return super(BaseList, self).insert(*args, **kwargs)
def pop(self, *args, **kwargs):
self._mark_as_changed()
return super(BaseList, self).pop(*args, **kwargs)
def remove(self, *args, **kwargs):
self._mark_as_changed()
return super(BaseList, self).remove(*args, **kwargs)
def reverse(self, *args, **kwargs):
self._mark_as_changed()
return super(BaseList, self).reverse(*args, **kwargs)
def sort(self, *args, **kwargs):
self._mark_as_changed()
return super(BaseList, self).sort(*args, **kwargs)
def _mark_as_changed(self):
if hasattr(self._instance, '_mark_as_changed'):
self._instance._mark_as_changed(self._name)
class BaseDict(dict):
"""A special dict so we can watch any changes
"""
_dereferenced = False
_instance = None
_name = None
def __init__(self, dict_items, instance, name):
self._instance = instance
self._name = name
return super(BaseDict, self).__init__(dict_items)
def __setitem__(self, *args, **kwargs):
self._mark_as_changed()
return super(BaseDict, self).__setitem__(*args, **kwargs)
def __delete__(self, *args, **kwargs):
self._mark_as_changed()
return super(BaseDict, self).__delete__(*args, **kwargs)
def __delitem__(self, *args, **kwargs):
self._mark_as_changed()
return super(BaseDict, self).__delitem__(*args, **kwargs)
def __delattr__(self, *args, **kwargs):
self._mark_as_changed()
return super(BaseDict, self).__delattr__(*args, **kwargs)
def __getstate__(self):
self.instance = None
self._dereferenced = False
return self
def __setstate__(self, state):
self = state
return self
def clear(self, *args, **kwargs):
self._mark_as_changed()
return super(BaseDict, self).clear(*args, **kwargs)
def pop(self, *args, **kwargs):
self._mark_as_changed()
return super(BaseDict, self).pop(*args, **kwargs)
def popitem(self, *args, **kwargs):
self._mark_as_changed()
return super(BaseDict, self).popitem(*args, **kwargs)
def update(self, *args, **kwargs):
self._mark_as_changed()
return super(BaseDict, self).update(*args, **kwargs)
def _mark_as_changed(self):
if hasattr(self._instance, '_mark_as_changed'):
self._instance._mark_as_changed(self._name)
if sys.version_info < (2, 5):
# Prior to Python 2.5, Exception was an old-style class
import types
def subclass_exception(name, parents, unused):
import types
return types.ClassType(name, parents, {})
else:
def subclass_exception(name, parents, module):
return type(name, parents, {'__module__': module})
| newvem/mongoengine | mongoengine/base.py | Python | mit | 50,511 |
import Users from 'meteor/vulcan:users';
import { Utils, addGraphQLMutation, addGraphQLResolvers } from 'meteor/vulcan:core';
/**
* @summary Verify that the un/subscription can be performed
* @param {String} action
* @param {Collection} collection
* @param {String} itemId
* @param {Object} user
* @returns {Object} collectionName, fields: object, item, hasSubscribedItem: boolean
*/
const prepareSubscription = (action, collection, itemId, user) => {
// get item's collection name
const collectionName = collection._name.slice(0,1).toUpperCase() + collection._name.slice(1);
// get item data
const item = collection.findOne(itemId);
// there no user logged in or no item, abort process
if (!user || !item) {
return false;
}
// edge case: Users collection
if (collectionName === 'Users') {
// someone can't subscribe to themself, abort process
if (item._id === user._id) {
return false;
}
} else {
// the item's owner is the subscriber, abort process
if (item.userId && item.userId === user._id) {
return false;
}
}
// assign the right fields depending on the collection
const fields = {
subscribers: 'subscribers',
subscriberCount: 'subscriberCount',
};
// return true if the item has the subscriber's id in its fields
const hasSubscribedItem = !!_.deep(item, fields.subscribers) && _.deep(item, fields.subscribers) && _.deep(item, fields.subscribers).indexOf(user._id) !== -1;
// assign the right update operator and count depending on the action type
const updateQuery = action === 'subscribe' ? {
findOperator: '$ne', // where 'IT' isn't...
updateOperator: '$addToSet', // ...add 'IT' to the array...
updateCount: 1, // ...and log the addition +1
} : {
findOperator: '$eq', // where 'IT' is...
updateOperator: '$pull', // ...remove 'IT' from the array...
updateCount: -1, // ...and log the subtraction -1
};
// return the utility object to pursue
return {
collectionName,
fields,
item,
hasSubscribedItem,
...updateQuery,
};
};
/**
* @summary Perform the un/subscription after verification: update the collection item & the user
* @param {String} action
* @param {Collection} collection
* @param {String} itemId
* @param {Object} user: current user (xxx: legacy, to replace with this.userId)
* @returns {Boolean}
*/
const performSubscriptionAction = (action, collection, itemId, user) => {
// subscription preparation to verify if can pursue and give shorthand variables
const subscription = prepareSubscription(action, collection, itemId, user);
// Abort process if the situation matches one of these cases:
// - subscription preparation failed (ex: no user, no item, subscriber is author's item, ... see all cases above)
// - the action is subscribe but the user has already subscribed to this item
// - the action is unsubscribe but the user hasn't subscribed to this item
if (!subscription || (action === 'subscribe' && subscription.hasSubscribedItem) || (action === 'unsubscribe' && !subscription.hasSubscribedItem)) {
throw Error(Utils.encodeIntlError({id: 'app.mutation_not_allowed', value: 'Already subscribed'}))
}
// shorthand for useful variables
const { collectionName, fields, item, findOperator, updateOperator, updateCount } = subscription;
// Perform the action, eg. operate on the item's collection
const result = collection.update({
_id: itemId,
// if it's a subscription, find where there are not the user (ie. findOperator = $ne), else it will be $in
[fields.subscribers]: { [findOperator]: user._id }
}, {
// if it's a subscription, add a subscriber (ie. updateOperator = $addToSet), else it will be $pull
[updateOperator]: { [fields.subscribers]: user._id },
// if it's a subscription, the count is incremented of 1, else decremented of 1
$inc: { [fields.subscriberCount]: updateCount },
});
// log the operation on the subscriber if it has succeeded
if (result > 0) {
// id of the item subject of the action
let loggedItem = {
itemId: item._id,
};
// in case of subscription, log also the date
if (action === 'subscribe') {
loggedItem = {
...loggedItem,
subscribedAt: new Date()
};
}
// update the user's list of subscribed items
Users.update({
_id: user._id
}, {
[updateOperator]: { [`subscribedItems.${collectionName}`]: loggedItem }
});
const updatedUser = Users.findOne({_id: user._id}, {fields: {_id:1, subscribedItems: 1}});
return updatedUser;
} else {
throw Error(Utils.encodeIntlError({id: 'app.something_bad_happened'}))
}
};
/**
* @summary Generate mutations 'collection.subscribe' & 'collection.unsubscribe' automatically
* @params {Array[Collections]} collections
*/
const subscribeMutationsGenerator = (collection) => {
// generic mutation function calling the performSubscriptionAction
const genericMutationFunction = (collectionName, action) => {
// return the method code
return function(root, { documentId }, context) {
// extract the current user & the relevant collection from the graphql server context
const { currentUser, [Utils.capitalize(collectionName)]: collection } = context;
// permission check
if (!Users.canDo(context.currentUser, `${collectionName}.${action}`)) {
throw new Error(Utils.encodeIntlError({id: "app.noPermission"}));
}
// do the actual subscription action
return performSubscriptionAction(action, collection, documentId, currentUser);
};
};
const collectionName = collection._name;
// add mutations to the schema
addGraphQLMutation(`${collectionName}Subscribe(documentId: String): User`),
addGraphQLMutation(`${collectionName}Unsubscribe(documentId: String): User`);
// create an object of the shape expected by mutations resolvers
addGraphQLResolvers({
Mutation: {
[`${collectionName}Subscribe`]: genericMutationFunction(collectionName, 'subscribe'),
[`${collectionName}Unsubscribe`]: genericMutationFunction(collectionName, 'unsubscribe'),
},
});
};
// Finally. Add the mutations to the Meteor namespace 🖖
// vulcan:users is a dependency of this package, it is alreay imported
subscribeMutationsGenerator(Users);
// note: leverage weak dependencies on packages
const Posts = Package['vulcan:posts'] ? Package['vulcan:posts'].default : null;
// check if vulcan:posts exists, if yes, add the mutations to Posts
if (!!Posts) {
subscribeMutationsGenerator(Posts);
}
// check if vulcan:categories exists, if yes, add the mutations to Categories
const Categories = Package['vulcan:categories'] ? Package['vulcan:categories'].default : null;
if (!!Categories) {
subscribeMutationsGenerator(Categories);
}
export default subscribeMutationsGenerator;
| acidsound/Telescope | packages/vulcan-subscribe/lib/mutations.js | JavaScript | mit | 6,946 |
<?php
defined('BASEPATH') or exit('No direct script access allowed');
class MY_Loader extends CI_Loader{
public function _construct(){
parent::_construct();
}
public function view($view, $vars = array(), $layout='', $return = FALSE)
{
$layout=($layout=='')?config_item('layout'):$layout;
$vars['contenido']=$this->_ci_load(array('_ci_view' => $view, '_ci_vars' => $this->_ci_object_to_array($vars), '_ci_return' => TRUE));
return $this->_ci_load(array('_ci_view' => $layout, '_ci_vars' => $this->_ci_object_to_array($vars), '_ci_return' => $return));
}
}
?> | maxdarkx/batalla_naval | application/core/MY_Loader.php | PHP | mit | 575 |
<?php
/**
* Webiny Platform (http://www.webiny.com/)
*
* @copyright Copyright Webiny LTD
*/
namespace Apps\Webiny\Php\Lib\UserProvider;
use Apps\Webiny\Php\Entities\ApiToken;
use Apps\Webiny\Php\Entities\SystemApiTokenUser;
use Apps\Webiny\Php\Entities\User;
use Apps\Webiny\Php\Lib\WebinyTrait;
/**
* This class handles `Webiny.User.Provide` event and returns one if the platform user entities.
*
* It is registered with the default event priority of 300.
* To add your own user provider, register an event handler with higher priority (ex: 310).
*/
class UserProviderEventHandler
{
use WebinyTrait;
public function handle(UserProviderEvent $event)
{
$data = $event->getData();
$token = $data['meta']['apiToken'] ?? null;
if ($token === 'system') {
return SystemApiTokenUser::load();
}
if ($this->wDatabase()->isId($token)) {
/* @var $apiToken ApiToken */
$apiToken = ApiToken::findById($token);
if ($apiToken) {
return $apiToken->user;
}
}
return isset($data['id']) ? User::findById($data['id']) : null;
}
} | Webiny/Webiny | Php/Lib/UserProvider/UserProviderEventHandler.php | PHP | mit | 1,174 |
<?php
namespace MailchimpTests\Lists;
use MailchimpAPI\Resources\Lists\SignupForms;
use MailchimpAPI\Resources\Lists;
use MailchimpTests\MailChimpTestCase;
/**
* Class SignupFormsTest
* @package MailchimpTests\Lists
*/
class SignupFormsTest extends MailChimpTestCase
{
/**
* @throws \MailchimpAPI\MailchimpException
*/
public function testCollectionUrl()
{
$this->endpointUrlBuildTest(
Lists::URL_COMPONENT . 1 . SignupForms::URL_COMPONENT,
$this->mailchimp->lists(1)->signupForms(),
"The Signup Forms collection endpoint should be constructed correctly"
);
}
/**
* @throws \MailchimpAPI\MailchimpException
*/
public function testInstanceUrl()
{
$this->endpointUrlBuildTest(
Lists::URL_COMPONENT . 1 . SignupForms::URL_COMPONENT . 1,
$this->mailchimp->lists(1)->signupForms(1),
"The Signup Forms instance endpoint should be constructed correctly"
);
}
}
| Jhut89/Mailchimp-API-3.0-PHP | tests/Lists/SignupFormsTest.php | PHP | mit | 1,017 |
package kamil09875.bfparser.syntax;
import java.io.IOException;
import kamil09875.bfparser.BFMemory;
import kamil09875.bfparser.Translator;
public enum BFISet implements BFInstruction{
LEFT{
@Override
public void execute(final BFMemory memory, final boolean debug){
if(debug){
System.out.println("Moving left");
memory.dump();
}
memory.left();
if(debug){
System.out.println(" vvv");
memory.dump();
System.out.println();
BFMemory.waitForUser();
}
}
@Override
public String translate(final Translator translator){
return translator.left();
}
},
RIGHT{
@Override
public void execute(final BFMemory memory, final boolean debug){
if(debug){
System.out.println("Moving right");
memory.dump();
}
memory.right();
if(debug){
System.out.println(" vvv");
memory.dump();
System.out.println();
BFMemory.waitForUser();
}
}
@Override
public String translate(final Translator translator){
return translator.right();
}
},
ADD{
@Override
public void execute(final BFMemory memory, final boolean debug){
if(debug){
System.out.println("Increasing current value");
memory.dump();
}
memory.add();
if(debug){
System.out.println(" vvv");
memory.dump();
System.out.println();
BFMemory.waitForUser();
}
}
@Override
public String translate(final Translator translator){
return translator.add();
}
},
SUB{
@Override
public void execute(final BFMemory memory, final boolean debug){
if(debug){
System.out.println("Decreasing current value");
memory.dump();
}
memory.sub();
if(debug){
System.out.println(" vvv");
memory.dump();
System.out.println();
BFMemory.waitForUser();
}
}
@Override
public String translate(final Translator translator){
return translator.sub();
}
},
OUTPUT{
@Override
public void execute(final BFMemory memory, final boolean debug){
if(debug){
System.out.println("Outputting current value");
memory.dump();
System.out.print("Output: " + memory.get() + " = ");
}
System.out.print((char)memory.get());
if(debug){
System.out.println(" vvv");
memory.dump();
System.out.println();
BFMemory.waitForUser();
}
}
@Override
public String translate(final Translator translator){
return translator.output();
}
},
INPUT{
@Override
public void execute(final BFMemory memory, final boolean debug){
if(debug){
System.out.println("Setting current value to user input");
memory.dump();
}
try{
memory.set(System.in.read());
}catch(IOException e){
memory.set(-1);
}
if(debug){
System.out.println(" vvv");
memory.dump();
System.out.println();
BFMemory.waitForUser();
}
}
@Override
public String translate(final Translator translator){
return translator.input();
}
};
}
| kamil09875/brainfuck-parser | src/kamil09875/bfparser/syntax/BFISet.java | Java | mit | 2,972 |
import test from 'ava';
import { defaultColors } from './defaultColors.js';
const tests = [
{
name: 'Dark background color defined in theme',
theme: {
colors: {
background: '#333333'
}
},
expectedResult: {
tickText: {
secondary: '#9d9d9d',
primary: '#d9d9d9'
},
series: '#f1f1f1',
value: '#d9d9d9',
axis: '#f1f1f1',
gridline: '#707070',
fallbackBaseColor: '#f1f1f1'
}
},
{
name: 'Custom chart element basecolor,background & blend ratios defined in theme',
theme: {
colors: {
background: '#FCB716',
chartContentBaseColor: '#ffffff',
bgBlendRatios: {
gridline: 0.5,
tickText: {
primary: 0,
secondary: 0
}
}
}
},
expectedResult: {
tickText: {
secondary: '#ffffff',
primary: '#ffffff'
},
series: '#ffffff',
value: '#fef2e4',
axis: '#ffffff',
gridline: '#fedeb5',
fallbackBaseColor: '#ffffff'
}
},
{
name: "No fail when theme doesn't have any data",
theme: {},
expectedResult: {
tickText: {
secondary: '#a6a6a6',
primary: '#7b7b7b'
},
series: '#333333',
value: '#7b7b7b',
axis: '#333333',
gridline: '#e8e8e8',
fallbackBaseColor: '#333333'
}
}
];
tests.forEach(({ theme, name, expectedResult }) => {
test(name, t => {
t.deepEqual(defaultColors(theme), expectedResult);
});
});
| datawrapper/datawrapper | libs/shared/defaultColors.test.js | JavaScript | mit | 1,909 |
// Common test code
var chai = require('chai');
exports.chai = chai;
exports.expect = chai.expect;
exports.should = chai.should();
exports.request = require('request'); | Huskie/ScottishPremiershipData | test/common.js | JavaScript | mit | 169 |
// Cloud normal
module.exports = function updateRole(params) {
/*
█████╗ ███████╗██╗ ██╗███╗ ██╗ ██████╗ ██╗ █████╗ ██╗ ██╗ █████╗ ██╗ ██╗
██╔══██╗██╔════╝╚██╗ ██╔╝████╗ ██║██╔════╝ ██╔╝██╔══██╗██║ ██║██╔══██╗╚██╗ ██╔╝
███████║███████╗ ╚████╔╝ ██╔██╗ ██║██║ ██╔╝ ███████║██║ █╗ ██║███████║ ╚████╔╝
██╔══██║╚════██║ ╚██╔╝ ██║╚██╗██║██║ ██╔╝ ██╔══██║██║███╗██║██╔══██║ ╚██╔╝
██║ ██║███████║ ██║ ██║ ╚████║╚██████╗██╔╝ ██║ ██║╚███╔███╔╝██║ ██║ ██║
╚═╝ ╚═╝╚══════╝ ╚═╝ ╚═╝ ╚═══╝ ╚═════╝╚═╝ ╚═╝ ╚═╝ ╚══╝╚══╝ ╚═╝ ╚═╝ ╚═╝
*/
Parse.Cloud.define("testAsync", (req, res) => {
(async () => {
try {
let isQueryAll = req.params.all !== undefined ? true : false;
let userName =
req.params.userName !== undefined
? req.params.userName
: req.user.get("username");
let roleName = req.params.roleName || req.params.role || req.params.r;
!isQueryAll &&
roleName === undefined &&
res.error("Vui lòng nhập tên role");
var userResult = await new Parse.Query(Parse.User)
.equalTo("username", userName)
.find({ useMasterKey: true });
var roleResult = isQueryAll
? await new Parse.Query(Parse.Role)
.equalTo("users", userResult[0])
.find()
: await new Parse.Query(Parse.Role)
.equalTo("name", roleName)
.equalTo("users", userResult[0])
.find();
res.success(
isQueryAll ? res.success(roleResult) : res.success(roleResult[0])
);
} catch (error) {
res.error(error.message);
}
})(); //end async
}); //end define test Async
//NEW
Parse.Cloud.define("isInRole", (req, res) => {
console.log(req);
req.user === undefined && res.error("Vui lòng đăng nhập ");
let roleName = req.params.roleName || req.params.role || req.params.r;
roleName === undefined && res.error("Vui lòng nhập tên role");
(async () => {
var roleResult = await new Parse.Query(Parse.Role)
.equalTo("name", roleName)
.equalTo("users", req.user)
.find();
roleResult.length !== 0 ? res.success(true) : res.success(false);
})();
}); //kết thúc isInRole function.
}; //end cloud
| cuduy197/parse-express | cloud/dev.js | JavaScript | mit | 3,221 |
using System.Collections.Generic;
using GraphLib.CommonOperations;
using GraphLib.VertexCreation;
using GraphLib.Vertices;
using GraphLib.Visiting;
namespace GraphLib.SccDetection
{
public class SccDetector
{
private readonly Graph _graph;
public SccDetector(Graph graph)
{
_graph = graph;
}
public List<List<IVertex>> Process()
{
var reversedGraph = ReverseVertex.Execute(_graph);
FinishingTimeVisitor finishingTimeVisitor = new FinishingTimeVisitor(reversedGraph.VertexCount);
reversedGraph.Visit(new DfsVisitAlgorighm(), finishingTimeVisitor);
SccVisitor sccVisitor = new SccVisitor();
_graph.Visit(new DfsVisitAlgorighm(), sccVisitor, finishingTimeVisitor.SortedVertexTags);
return sccVisitor.Result;
}
public static GraphOptions OptimizedOptions(IVertexTagFactory vertexTagFactory = null)
{
return new GraphOptions(GraphDirection.Directed, VerticesStoreMode.Outcome, GraphPreferedUsage.OptimizedForInsert, false, vertexTagFactory);
}
}
}
| tihilv/GraphLib | GraphLib/SccDetection/SccDetector.cs | C# | mit | 1,143 |
namespace GeckoUBL.Ubl21.Cac
{
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.33440")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2")]
[System.Xml.Serialization.XmlRootAttribute("BillingReference", Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2", IsNullable=false)]
public class BillingReferenceType {
/// <remarks/>
public DocumentReferenceType InvoiceDocumentReference { get; set; }
/// <remarks/>
public DocumentReferenceType SelfBilledInvoiceDocumentReference { get; set; }
/// <remarks/>
public DocumentReferenceType CreditNoteDocumentReference { get; set; }
/// <remarks/>
public DocumentReferenceType SelfBilledCreditNoteDocumentReference { get; set; }
/// <remarks/>
public DocumentReferenceType DebitNoteDocumentReference { get; set; }
/// <remarks/>
public DocumentReferenceType ReminderDocumentReference { get; set; }
/// <remarks/>
public DocumentReferenceType AdditionalDocumentReference { get; set; }
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("BillingReferenceLine")]
public BillingReferenceLineType[] BillingReferenceLine { get; set; }
}
} | JohnGrekso/GeckoUBL | src/GeckoUBL/Ubl21/Cac/BillingReferenceType.cs | C# | mit | 1,419 |
import composeWithTracker from 'compose-with-tracker'
import { Meteor } from 'meteor/meteor'
export default composeWithTracker((props, onData) => {
onData(null, {
isLoggingIn: Meteor.loggingIn(),
user: Meteor.user() || {},
})
})
| FractalFlows/Emergence | app/imports/client/Pages/User/container.js | JavaScript | mit | 242 |
var ipc = require('ipc_utils')
var id = 1;
var binding = {
getCurrent: function () {
var cb, getInfo;
if (arguments.length == 1) {
cb = arguments[0]
} else {
getInfo = arguments[0]
cb = arguments[1]
}
var responseId = ++id
ipc.once('chrome-windows-get-current-response-' + responseId, function(evt, win) {
cb(win)
})
ipc.send('chrome-windows-get-current', responseId, getInfo)
},
getAll: function (getInfo, cb) {
if (arguments.length == 1) {
cb = arguments[0]
} else {
getInfo = arguments[0]
cb = arguments[1]
}
var responseId = ++id
ipc.once('chrome-windows-get-all-response-' + responseId, function(evt, win) {
cb(win)
})
ipc.send('chrome-windows-get-all', responseId, getInfo)
},
create: function (createData, cb) {
console.warn('chrome.windows.create is not supported yet')
},
update: function (windowId, updateInfo, cb) {
var responseId = ++id
cb && ipc.once('chrome-windows-update-response-' + responseId, function (evt, win) {
cb(win)
})
ipc.send('chrome-windows-update', responseId, windowId, updateInfo)
},
WINDOW_ID_NONE: -1,
WINDOW_ID_CURRENT: -2
};
exports.binding = binding;
| posix4e/electron | atom/common/api/resources/windows_bindings.js | JavaScript | mit | 1,251 |
package main
import (
"flag"
"fmt"
"log"
"net/http"
"github.com/julienschmidt/httprouter"
"github.com/yuriadams/smssender/api/controllers"
)
var (
logOn *bool
port *int
urlBase string
)
func init() {
domain := flag.String("d", "localhost", "domain")
port = flag.Int("p", 8888, "port")
logOn = flag.Bool("l", true, "log on/off")
flag.Parse()
urlBase = fmt.Sprintf("http://%s:%d", *domain, *port)
}
func main() {
smsc := controllers.NewSMSController()
r := httprouter.New()
r.GET("/", smsc.GetSMSHandler)
r.POST("/api/sendSMS", smsc.SendSMSHandler)
logging("Starting server %d...", *port)
log.Fatal(http.ListenAndServe(fmt.Sprintf(":%d", *port), r))
}
func logging(format string, v ...interface{}) {
if *logOn {
log.Printf(fmt.Sprintf("%s\n", format), v...)
}
}
| yuriadams/smssender | server.go | GO | mit | 797 |
// Template Source: BaseMethodRequestBuilder.java.tt
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
package com.microsoft.graph.requests;
import com.microsoft.graph.requests.ReportRootGetYammerActivityCountsRequest;
import com.microsoft.graph.models.ReportRoot;
import com.microsoft.graph.models.Report;
import com.microsoft.graph.http.BaseFunctionRequestBuilder;
import com.microsoft.graph.models.ReportRootGetYammerActivityCountsParameterSet;
import com.microsoft.graph.core.IBaseClient;
import com.google.gson.JsonElement;
import javax.annotation.Nullable;
import javax.annotation.Nonnull;
// **NOTE** This file was generated by a tool and any changes will be overwritten.
/**
* The class for the Report Root Get Yammer Activity Counts Request Builder.
*/
public class ReportRootGetYammerActivityCountsRequestBuilder extends BaseFunctionRequestBuilder<Report> {
/**
* The request builder for this ReportRootGetYammerActivityCounts
*
* @param requestUrl the request URL
* @param client the service client
* @param requestOptions the options for this request
*/
public ReportRootGetYammerActivityCountsRequestBuilder(@Nonnull final String requestUrl, @Nonnull final IBaseClient<?> client, @Nullable final java.util.List<? extends com.microsoft.graph.options.Option> requestOptions) {
super(requestUrl, client, requestOptions);
}
/**
* The request builder for this ReportRootGetYammerActivityCounts
*
* @param requestUrl the request URL
* @param client the service client
* @param requestOptions the options for this request
* @param parameters the parameters for the service method
*/
public ReportRootGetYammerActivityCountsRequestBuilder(@Nonnull final String requestUrl, @Nonnull final IBaseClient<?> client, @Nullable final java.util.List<? extends com.microsoft.graph.options.Option> requestOptions, @Nonnull final ReportRootGetYammerActivityCountsParameterSet parameters) {
super(requestUrl, client, requestOptions);
if(parameters != null) {
functionOptions = parameters.getFunctionOptions();
}
}
/**
* Creates the ReportRootGetYammerActivityCountsRequest
*
* @param requestOptions the options for the request
* @return the ReportRootGetYammerActivityCountsRequest instance
*/
@Nonnull
public ReportRootGetYammerActivityCountsRequest buildRequest(@Nullable final com.microsoft.graph.options.Option... requestOptions) {
return buildRequest(getOptions(requestOptions));
}
/**
* Creates the ReportRootGetYammerActivityCountsRequest with specific requestOptions instead of the existing requestOptions
*
* @param requestOptions the options for the request
* @return the ReportRootGetYammerActivityCountsRequest instance
*/
@Nonnull
public ReportRootGetYammerActivityCountsRequest buildRequest(@Nonnull final java.util.List<? extends com.microsoft.graph.options.Option> requestOptions) {
final ReportRootGetYammerActivityCountsRequest request = new ReportRootGetYammerActivityCountsRequest(
getRequestUrl(),
getClient(),
requestOptions);
for (com.microsoft.graph.options.FunctionOption option : functionOptions) {
request.addFunctionOption(option);
}
return request;
}
}
| microsoftgraph/msgraph-sdk-java | src/main/java/com/microsoft/graph/requests/ReportRootGetYammerActivityCountsRequestBuilder.java | Java | mit | 3,693 |
"use strict";
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var _this = this;
var _1 = require("../../../");
describe("StatefulAccessor", function () {
beforeEach(function () {
_1.Utils.guidCounter = 0;
var SomeAccessor = (function (_super) {
__extends(SomeAccessor, _super);
function SomeAccessor() {
_super.apply(this, arguments);
this.state = new _1.ValueState();
}
return SomeAccessor;
}(_1.StatefulAccessor));
_this.accessor = new SomeAccessor("genres.raw");
_this.searchkit = new _1.SearchkitManager("/");
_this.searchkit.addAccessor(_this.accessor);
});
it("constructor()", function () {
expect(_this.accessor.uuid).toBe("genres.raw1");
expect(_this.accessor.key).toEqual("genres.raw");
expect(_this.accessor.urlKey).toEqual("genres_raw");
});
it("setSearchkitManager()", function () {
expect(_this.accessor.searchkit).toBe(_this.searchkit);
expect(_this.accessor.state).toBe(_this.accessor.resultsState);
});
it("translate()", function () {
_this.searchkit.translate = function (key) {
return { a: 'b' }[key];
};
expect(_this.accessor.translate("a")).toBe("b");
});
it("onStateChange()", function () {
expect(function () { return _this.accessor.onStateChange({}); })
.not.toThrow();
});
it("fromQueryObject", function () {
var queryObject = {
genres_raw: [1, 2],
authors_raw: [3, 4]
};
_this.accessor.fromQueryObject(queryObject);
expect(_this.accessor.state.getValue())
.toEqual([1, 2]);
});
it("getQueryObject()", function () {
_this.accessor.state = new _1.ValueState([1, 2]);
expect(_this.accessor.getQueryObject())
.toEqual({ genres_raw: [1, 2] });
});
it("getResults()", function () {
_this.accessor.results = [1, 2];
expect(_this.accessor.getResults()).toEqual([1, 2]);
});
it("getAggregations()", function () {
expect(_this.accessor.getAggregations(["foo"], 10))
.toEqual(10);
_this.accessor.results = {
aggregations: {
some_count: { value: 11 }
}
};
expect(_this.accessor.getAggregations(["some_count", "value"], 10))
.toEqual(11);
});
it("setResultsState()", function () {
delete _this.accessor.resultsState;
expect(_this.accessor.state)
.not.toBe(_this.accessor.resultsState);
_this.accessor.setResultsState();
expect(_this.accessor.state)
.toBe(_this.accessor.resultsState);
});
it("resetState()", function () {
_this.accessor.state = _this.accessor.state.setValue("foo");
expect(_this.accessor.state.getValue()).toBe("foo");
_this.accessor.resetState();
expect(_this.accessor.state.getValue()).toBe(null);
});
it("buildSharedQuery", function () {
var query = new _1.ImmutableQuery();
expect(_this.accessor.buildSharedQuery(query))
.toBe(query);
});
it("buildOwnQuery", function () {
var query = new _1.ImmutableQuery();
expect(_this.accessor.buildOwnQuery(query))
.toBe(query);
});
});
//# sourceMappingURL=StatefulAccessorSpec.js.map | viktorkh/elastickit_express | node_modules/searchkit/lib/src/__test__/core/accessors/StatefulAccessorSpec.js | JavaScript | mit | 3,647 |
<?php
namespace LiveData\Bundle\ShopBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Customer
*
* @ORM\Table()
* @ORM\Entity(repositoryClass="LiveData\Bundle\ShopBundle\Entity\CustomerRepository")
*/
class Customer
{
/**
* @var integer
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @var string
*
* @ORM\Column(name="lastname", type="string", length=32)
*/
private $lastname;
/**
* @var string
*
* @ORM\Column(name="firstname", type="string", length=32)
*/
private $firstname;
/**
* @var \DateTime
*
* @ORM\Column(name="birthday", type="date")
*/
private $birthday;
/**
* @var string
*
* @ORM\Column(name="address", type="string", length=128, nullable=true)
*/
private $address;
/**
* @var integer
*
* @ORM\Column(name="zipCode", type="integer", nullable=true)
*/
private $zipCode;
/**
* @ORM\ManyToOne(targetEntity="City", inversedBy="customers")
* @ORM\JoinColumn(name="city_id", referencedColumnName="id", onDelete="set null")
*/
private $city;
/**
* @var integer
*
* @ORM\Column(name="sex", type="integer", nullable=true)
*/
private $sex;
/**
* @ORM\OneToMany(targetEntity="Sale", mappedBy="customer")
*/
private $sales;
/**
* Get id
*
* @return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set lastname
*
* @param string $lastname
* @return Customer
*/
public function setLastname($lastname)
{
$this->lastname = $lastname;
return $this;
}
/**
* Get lastname
*
* @return string
*/
public function getLastname()
{
return $this->lastname;
}
/**
* Set firstname
*
* @param string $firstname
* @return Customer
*/
public function setFirstname($firstname)
{
$this->firstname = $firstname;
return $this;
}
/**
* Get firstname
*
* @return string
*/
public function getFirstname()
{
return $this->firstname;
}
/**
* Set birthday
*
* @param \DateTime $birthday
* @return Customer
*/
public function setBirthday($birthday)
{
$this->birthday = $birthday;
return $this;
}
/**
* Get birthday
*
* @return \DateTime
*/
public function getBirthday()
{
return $this->birthday;
}
/**
* Set address
*
* @param string $address
* @return Customer
*/
public function setAddress($address)
{
$this->address = $address;
return $this;
}
/**
* Get address
*
* @return string
*/
public function getAddress()
{
return $this->address;
}
/**
* Set zipCode
*
* @param integer $zipCode
* @return Customer
*/
public function setZipCode($zipCode)
{
$this->zipCode = $zipCode;
return $this;
}
/**
* Get zipCode
*
* @return integer
*/
public function getZipCode()
{
return $this->zipCode;
}
/**
* Set city
*
* @param \stdClass $city
* @return Customer
*/
public function setCity($city)
{
$this->city = $city;
return $this;
}
/**
* Get city
*
* @return \stdClass
*/
public function getCity()
{
return $this->city;
}
/**
* Set sex
*
* @param integer $sex
* @return Customer
*/
public function setSex($sex)
{
$this->sex = $sex;
return $this;
}
/**
* Get sex
*
* @return integer
*/
public function getSex()
{
return $this->sex;
}
/**
* Constructor
*/
public function __construct()
{
$this->sales = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* Add sales
*
* @param \LiveData\Bundle\ShopBundle\Entity\Sale $sales
* @return Customer
*/
public function addSale(\LiveData\Bundle\ShopBundle\Entity\Sale $sales)
{
$this->sales[] = $sales;
return $this;
}
/**
* Remove sales
*
* @param \LiveData\Bundle\ShopBundle\Entity\Sale $sales
*/
public function removeSale(\LiveData\Bundle\ShopBundle\Entity\Sale $sales)
{
$this->sales->removeElement($sales);
}
/**
* Get sales
*
* @return \Doctrine\Common\Collections\Collection
*/
public function getSales()
{
return $this->sales;
}
public function getGender() {
if($this->sex ==1)
return 'M';
return 'F';
}
}
| MDBK/LiveData | src/LiveData/Bundle/ShopBundle/Entity/Customer.php | PHP | mit | 4,980 |
const {
SearchkitManager,SearchkitProvider,
SearchBox, Hits, RefinementListFilter, Pagination,
CheckboxFilter,
HierarchicalMenuFilter, HitsStats, SortingSelector, NoHits,
GroupedSelectedFilters, SelectedFilters, ResetFilters,
RangeFilter, NumericRefinementListFilter,
ViewSwitcherHits, ViewSwitcherToggle, Select, Toggle,
ItemList, CheckboxItemList, ItemHistogramList, Tabs, TagCloud, MenuFilter,
renderComponent, PageSizeSelector, RangeSliderHistogramInput, Panel, PaginationSelect,
InputFilter, TagFilter, TagFilterList, TagFilterConfig,
TermQuery, RangeQuery, BoolMust,
Layout, LayoutBody, LayoutResults, SideBar, TopBar, ActionBar, ActionBarRow
} = require("../../../../../src")
const host = "http://demo.searchkit.co/api/movies"
import * as ReactDOM from "react-dom";
import * as React from "react";
const searchkit = new SearchkitManager(host)
const _ = require("lodash")
const map = require("lodash/map")
const isUndefined = require("lodash/isUndefined")
import { TogglePanel } from './TogglePanel'
require("../../../../../theming/theme.scss")
require("./customisations.scss")
const MovieHitsGridItem = (props)=> {
const {bemBlocks, result} = props
let url = "http://www.imdb.com/title/" + result._source.imdbId
const source:any = _.extend({}, result._source, result.highlight)
return (
<div className={bemBlocks.item().mix(bemBlocks.container("item"))} data-qa="hit">
<a href={url} target="_blank">
<img data-qa="poster" className={bemBlocks.item("poster")} src={result._source.poster} width="170" height="240"/>
<div data-qa="title" className={bemBlocks.item("title")} dangerouslySetInnerHTML={{__html:source.title}}>
</div>
</a>
</div>
)
}
const MovieHitsListItem = (props)=> {
const {bemBlocks, result} = props
let url = "http://www.imdb.com/title/" + result._source.imdbId
const source:any = _.extend({}, result._source, result.highlight)
const { title, poster, writers = [], actors = [], genres = [], plot, released, rated } = source;
return (
<div className={bemBlocks.item().mix(bemBlocks.container("item"))} data-qa="hit">
<div className={bemBlocks.item("poster")}>
<img data-qa="poster" src={result._source.poster}/>
</div>
<div className={bemBlocks.item("details")}>
<a href={url} target="_blank"><h2 className={bemBlocks.item("title")} dangerouslySetInnerHTML={{__html:source.title}}></h2></a>
<h3 className={bemBlocks.item("subtitle")}>Released in {source.year}, rated {source.imdbRating}/10</h3>
<ul className={bemBlocks.item("tags")}>
<li>Genres: <TagFilterList field="genres.raw" values={genres} /></li>
<li>Writers: <TagFilterList field="writers.raw" values={writers} /></li>
<li>Actors: <TagFilterList field="actors.raw" values={actors} /></li>
</ul>
<div className={bemBlocks.item("text")} dangerouslySetInnerHTML={{__html:source.plot}}></div>
</div>
</div>
)
}
export class MovieHitsCell extends React.Component<any, {}> {
render(){
const { hit, columnKey, columnIdx } = this.props
if (columnKey === "poster"){
return (
<td key={columnIdx + '-' + columnKey} style={{margin: 0, padding: 0, width: 40}}>
<img data-qa="poster" src={hit._source.poster} style={{width: 40}}/>
</td>
)
} else {
return <td key={columnIdx + '-' + columnKey}>{hit._source[columnKey]}</td>
}
}
}
export class HitsTable extends React.Component<any, {}>{
constructor(props){
super(props)
this.renderHeader = this.renderHeader.bind(this)
this.renderCell = this.renderCell.bind(this)
}
renderHeader(column, idx){
if ((typeof column) === "string"){
return <th key={idx + "-" + column}>{column}</th>
} else {
const label = isUndefined(column.label) ? column.key : column.label
return <th key={idx + "-" + column.key} style={column.style}>{label}</th>
}
}
renderCell(hit, column, idx){
const { cellComponent } = this.props
const key = ((typeof column) === "string") ? column : column.key
var element;
if (cellComponent){
return renderComponent(cellComponent, {hit, columnKey: key, key, column, columnIdx: idx})
} else {
return <td key={idx + '-' + key}>{hit._source[key]}</td>
}
}
render(){
const { columns, hits } = this.props
return (
<div style={{width: '100%', boxSizing: 'border-box', padding: 8}}>
<table className="sk-table sk-table-striped" style={{width: '100%', boxSizing: 'border-box'}}>
<thead>
<tr>{map(columns, this.renderHeader)}</tr>
</thead>
<tbody>
{map(hits, hit => (
<tr key={hit._id}>
{map(columns, (col, idx) => this.renderCell(hit, col, idx))}
</tr>
))}
</tbody>
</table>
</div>
)
}
}
class MovieHitsTable extends React.Component<any, {}> {
render(){
const { hits } = this.props
return (
<div style={{width: '100%', boxSizing: 'border-box', padding: 8}}>
<table className="sk-table sk-table-striped" style={{width: '100%', boxSizing: 'border-box'}}>
<thead>
<tr>
<th></th>
<th>Title</th>
<th>Year</th>
<th>Rating</th>
</tr>
</thead>
<tbody>
{map(hits, hit => (
<tr key={hit._id}>
<td style={{margin: 0, padding: 0, width: 40}}>
<img data-qa="poster" src={hit._source.poster} style={{width: 40}}/>
</td>
<td>{hit._source.title}</td>
<td>{hit._source.year}</td>
<td>{hit._source.imdbRating}</td>
</tr>
))}
</tbody>
</table>
</div>
)
}
}
const listComponents = {
list: ItemList,
checkbox: CheckboxItemList,
histogram: ItemHistogramList,
select: Select,
tabs: (props) => <Tabs {...props} showCount={false}/>,
tags: (props) => <TagCloud {...props} showCount={false} />,
toggle: (props) => <Toggle {...props} showCount={false}/>
}
class App extends React.Component<any, any> {
constructor(props){
super(props)
this.state = {
viewMode: "list"
}
}
handleViewModeChange(e){
this.setState({viewMode: e.target.value})
}
render(){
return (
<SearchkitProvider searchkit={searchkit}>
<Layout>
<TopBar>
<SearchBox autofocus={true} searchOnChange={false} prefixQueryFields={["actors^1","type^2","languages","title^10"]}/>
</TopBar>
<LayoutBody>
<SideBar>
<Panel title="Selected Filters" collapsable={true} defaultCollapsed={false}>
<SelectedFilters/>
</Panel>
<CheckboxFilter id="rated-r" title="Rating" label="Rated R" filter={TermQuery("rated.raw", 'R')} />
<CheckboxFilter id="recent" title="Date" label="Recent" filter={RangeQuery("year", {gt: 2012})} />
<CheckboxFilter id="old-movies" title="Movile filter" label="Old movies" filter={
BoolMust([
RangeQuery("year", {lt: 1970}),
TermQuery("type.raw", "Movie")
])} />
<InputFilter id="author_q" title="Actors filter" placeholder="Search actors" searchOnChange={false} blurAction="search" queryFields={["actors"]}/>
<InputFilter id="writer_q" title="Writers filter" placeholder="Search writers" searchOnChange={false} blurAction="restore" queryFields={["writers"]}/>
<MenuFilter field={"type.raw"} size={10} title="Movie Type" id="types" listComponent={listComponents[this.state.viewMode]}
containerComponent={
(props) => (
<TogglePanel {...props} rightComponent={(
<select value={this.state.listMode} onChange={this.handleViewModeChange.bind(this) }>
<option value="list">List</option>
<option value="checkbox">Checkbox</option>
<option value="histogram">Histogram</option>
<option value="select">Select</option>
<option value="tabs">Tabs</option>
<option value="tags">TagCloud</option>
<option value="toggle">Toggle</option>
</select>
)} />
)
}/>
<HierarchicalMenuFilter fields={["type.raw", "genres.raw"]} title="Categories" id="categories"/>
<RangeFilter min={0} max={100} field="metaScore" id="metascore" title="Metascore" showHistogram={true}/>
<RangeFilter min={0} max={10} field="imdbRating" id="imdbRating" title="IMDB Rating" showHistogram={true} rangeComponent={RangeSliderHistogramInput}/>
<TagFilterConfig id="genres" title="Genres" field="genres.raw" />
<RefinementListFilter id="actors" title="Actors" field="actors.raw" size={10}/>
<RefinementListFilter translations={{"facets.view_more":"View more writers"}} id="writers" title="Writers" field="writers.raw" operator="OR" size={10}/>
<RefinementListFilter id="countries" title="Countries" field="countries.raw" operator="OR" size={10}/>
<NumericRefinementListFilter countFormatter={(count)=>"#"+count} listComponent={Select} id="runtimeMinutes" title="Length" field="runtimeMinutes" options={[
{title:"All"},
{title:"up to 20", from:0, to:20},
{title:"21 to 60", from:21, to:60},
{title:"60 or more", from:61, to:1000}
]}/>
</SideBar>
<LayoutResults>
<ActionBar>
<ActionBarRow>
<HitsStats translations={{
"hitstats.results_found":"{hitCount} results found"
}}/>
<ViewSwitcherToggle/>
{/*<ViewSwitcherToggle listComponent={Select}/>*/}
<PageSizeSelector options={[4,12,25]} listComponent={Toggle }/>
<SortingSelector options={[
{label:"Relevance", field:"_score", order:"desc"},
{label:"Latest Releases", field:"released", order:"desc"},
{label:"Earliest Releases", field:"released", order:"asc"}
]}/>
{/*<SortingSelector options={[
{label:"Relevance", field:"_score", order:"desc"},
{label:"Latest Releases", field:"released", order:"desc"},
{label:"Earliest Releases", field:"released", order:"asc"}
]} listComponent={Toggle}/>*/}
</ActionBarRow>
<ActionBarRow>
<GroupedSelectedFilters/>
<ResetFilters/>
</ActionBarRow>
</ActionBar>
<ViewSwitcherHits
hitsPerPage={12} highlightFields={["title","plot"]}
sourceFilter={["plot", "title", "poster", "imdbId", "imdbRating", "year", "genres", "writers", "actors"]}
hitComponents = {[
{key:"grid", title:"Grid", itemComponent:MovieHitsGridItem},
{key:"list", title:"List", itemComponent:MovieHitsListItem},
{key:"movie-table", title:"Movies", listComponent:MovieHitsTable, defaultOption:true},
{key:"table", title:"Table", listComponent:<HitsTable
cellComponent={MovieHitsCell}
columns={[
{key: 'poster', label: '', style:{ width: 40}},
'title',
'year',
{key: 'imdbRating', label: 'rating'}
]} />}
]}
scrollTo="body"
/>
<NoHits suggestionsField={"title"}/>
<Pagination showNumbers={true}/>
<PaginationSelect/>
</LayoutResults>
</LayoutBody>
</Layout>
</SearchkitProvider>
)
}
}
ReactDOM.render(<App/>, document.getElementById("root"))
| viktorkh/elastickit_express | node_modules/searchkit/test/e2e/server/apps/playground/index.tsx | TypeScript | mit | 12,381 |
/*
The MIT License
Copyright (c) 2010-2021 Paul R. Holser, Jr.
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package com.pholser.junit.quickcheck.runner;
import static java.lang.String.format;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.fail;
import static org.junit.experimental.results.PrintableResult.testResult;
import static org.junit.experimental.results.ResultMatchers.hasFailureContaining;
import com.pholser.junit.quickcheck.From;
import com.pholser.junit.quickcheck.Property;
import com.pholser.junit.quickcheck.UtilityClassesUninstantiabilityHarness;
import com.pholser.junit.quickcheck.test.generator.AnInt;
import org.junit.Test;
import org.junit.runner.RunWith;
public class PropertyFalsifiedUtilityClassTest
extends UtilityClassesUninstantiabilityHarness {
public PropertyFalsifiedUtilityClassTest() {
super(PropertyFalsified.class);
}
@Test public void counterexampleFoundWithAllParameters() {
String propertyName = "mySuperProperty";
String[] arguments = {"first", "second", "third"};
long[] seeds = {12345, 8842};
String assertionName = "assertion name";
AssertionError error = new AssertionError(assertionName);
AssertionError actual =
PropertyFalsified.counterexampleFound(
propertyName,
arguments,
seeds,
error);
String expected =
format(
"Property named 'mySuperProperty' failed (assertion name)%n"
+ "With arguments: [first, second, third]%n"
+ "Seeds for reproduction: [12345, 8842]");
assertThat(actual.getMessage(), equalTo(expected));
}
@Test
public void counterexampleFoundWhenAssertionErrorPassedHasNoMessage() {
String propertyName = "mySuperProperty";
String[] arguments = {"first", "second", "third"};
long[] seeds = {12345, 8842};
AssertionError error = new AssertionError();
AssertionError actual =
PropertyFalsified.counterexampleFound(
propertyName,
arguments,
seeds,
error);
String expected =
format(
"Property named 'mySuperProperty' failed:%n"
+ "With arguments: [first, second, third]%n"
+ "Seeds for reproduction: [12345, 8842]");
assertThat(actual.getMessage(), equalTo(expected));
}
@Test public void smallerCounterexampleFoundWithAllParameters() {
String propertyName = "mySuperProperty";
String[] originalArguments = {"first", "second", "third"};
String[] arguments = {"first"};
long[] seeds = {12345, 8842};
String smallerFailureName = "smaller name";
AssertionError smallerFailure = new AssertionError(smallerFailureName);
String assertionName = "assertion name";
AssertionError originalFailure = new AssertionError(assertionName);
AssertionError actual =
PropertyFalsified.smallerCounterexampleFound(
propertyName,
originalArguments,
arguments,
seeds,
smallerFailure,
originalFailure);
String expected =
format(
"Property named 'mySuperProperty' failed (smaller name):%n"
+ "With arguments: [first]%n"
+ "Original failure message: assertion name%n"
+ "First arguments found to also provoke a failure: "
+ "[first, second, third]%n"
+ "Seeds for reproduction: [12345, 8842]");
assertThat(actual.getMessage(), equalTo(expected));
}
@Test
public void smallerCounterexampleFoundEvenIfSmallerFailureIsNotNamed() {
String propertyName = "mySuperProperty";
String[] originalArguments = {"first", "second", "third"};
String[] arguments = {"first"};
long[] seeds = {12345, 8842};
AssertionError smallerFailure = new AssertionError();
String assertionName = "assertion name";
AssertionError originalFailure = new AssertionError(assertionName);
AssertionError actual =
PropertyFalsified.smallerCounterexampleFound(
propertyName,
originalArguments,
arguments,
seeds,
smallerFailure,
originalFailure);
String expected =
format(
"Property named 'mySuperProperty' failed:%n"
+ "With arguments: [first]%n"
+ "Original failure message: assertion name%n"
+ "First arguments found to also provoke a failure: "
+ "[first, second, third]%n"
+ "Seeds for reproduction: [12345, 8842]");
assertThat(actual.getMessage(), equalTo(expected));
}
@Test
public void smallerCounterexampleFoundEvenIfOriginalFailureIsNotNamed() {
String propertyName = "mySuperProperty";
String[] originalArguments = {"first", "second", "third"};
String[] arguments = {"first"};
long[] seeds = {12345, 8842};
AssertionError smallerFailure = new AssertionError();
AssertionError originalFailure = new AssertionError();
AssertionError actual =
PropertyFalsified.smallerCounterexampleFound(
propertyName,
originalArguments,
arguments,
seeds,
smallerFailure,
originalFailure);
String expected =
format(
"Property named 'mySuperProperty' failed:%n"
+ "With arguments: [first]%n"
+ "First arguments found to also provoke a failure: "
+ "[first, second, third]%n"
+ "Seeds for reproduction: [12345, 8842]");
assertThat(actual.getMessage(), equalTo(expected));
}
@Test public void github_212_failWithIllegalFormatSpecifierInMessage() {
assertThat(
testResult(Failing.class),
hasFailureContaining("Failure with a %D in the text"));
}
@RunWith(JUnitQuickcheck.class)
public static class Failing {
@Property public void prop(@From(AnInt.class) int n) {
fail("Failure with a %D in the text");
}
}
}
| pholser/junit-quickcheck | core/src/test/java/com/pholser/junit/quickcheck/runner/PropertyFalsifiedUtilityClassTest.java | Java | mit | 7,581 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace BorderControl
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
}
| schumann2k/BorderControl | BorderControl/Program.cs | C# | mit | 514 |
<?php
/*
* Peasant
* Copyright 2015 Norbert Zakariás (A.K.A. ZackRave-N). All Rights Reserved.
* This program is free software. You can redistribute and/or modify it in
* accordance with the terms of the accompanying license agreement.
*/
require_once('lib/com/zrnprojects/peasant/renderer/IRenderer.php');
require_once('lib/com/zrnprojects/peasant/renderer/renderers/JsonRenderer.php');
/**
* Test class for the JsonRenderer class.
*
* @author ZackRave-N
*/
class JsonRendererTest extends PHPUnit_Framework_TestCase
{
/**
* @var IRenderer $renderer ;
*/
private $renderer;
public function setUp()
{
$this->renderer = new JsonRenderer();
}
public function testRendering()
{
$data = array('lorem' => 'ipsum', 'dolor' => array('sit', 'amet'));
ob_start();
$this->renderer->render($data);
$result = ob_get_clean();
$this->assertTrue($result == json_encode($data));
}
}
| ZackRave-N/Peasant | unitTests/JsonRendererTest.php | PHP | mit | 940 |
package openblocks.client.model;
import cpw.mods.fml.common.eventhandler.SubscribeEvent;
import net.minecraft.client.Minecraft;
import net.minecraft.client.entity.EntityOtherPlayerMP;
import net.minecraft.client.model.ModelBiped;
import net.minecraft.client.model.ModelRenderer;
import net.minecraft.client.renderer.entity.RenderManager;
import net.minecraft.client.renderer.texture.TextureManager;
import net.minecraft.entity.Entity;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.util.MathHelper;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.client.event.RenderPlayerEvent;
import net.minecraftforge.client.event.RenderWorldLastEvent;
import net.minecraftforge.common.MinecraftForge;
import openblocks.common.CraneRegistry;
import openblocks.common.entity.EntityMagnet;
import openblocks.common.item.ItemCraneBackpack;
import org.lwjgl.opengl.GL11;
public class ModelCraneBackpack extends ModelBiped {
public static final ModelCraneBackpack instance = new ModelCraneBackpack();
private static final ResourceLocation texture = new ResourceLocation(ItemCraneBackpack.TEXTURE_CRANE);
private static final float DEG_TO_RAD = (float)Math.PI / 180;
private final ModelRenderer arm;
public ModelCraneBackpack() {
textureWidth = 128;
textureHeight = 64;
bipedBody = new ModelRenderer(this, 0, 0);
bipedBody.setTextureSize(textureWidth, textureHeight);
bipedBody.setRotationPoint(0, 0, 0);
// main body
bipedBody.addBox(-4, 0, -2, 8, 12, 8);
// support
bipedBody.setTextureOffset(32, 0);
bipedBody.addBox(-1, -16, 6, 2, 24, 2);
// arm
arm = new ModelRenderer(this, 0, 0);
arm.setTextureSize(textureWidth, textureHeight);
arm.setRotationPoint(0, -16, 7);
arm.addBox(-1, 0, 1, 2, 2, 42);
}
@Override
public void setRotationAngles(float swingTime, float swingAmpl, float rightArmAngle, float headAngleX, float headAngleY, float scale, Entity entity) {
super.setRotationAngles(swingTime, swingAmpl, rightArmAngle, headAngleX, headAngleY, scale, entity);
if (isSneak) {
arm.rotationPointZ = -0.15f; // good enough values
arm.offsetY = -0.125f;
} else {
arm.rotationPointZ = 7;
arm.offsetY = 0;
}
}
@Override
public void render(Entity entity, float swingTime, float swingAmpl, float rightArmAngle, float headAngleX, float headAngleY, float scale) {
isSneak = entity != null && entity.isSneaking();
setRotationAngles(swingTime, swingAmpl, rightArmAngle, headAngleX, headAngleY, scale, entity);
bipedBody.render(scale);
arm.rotateAngleY = (float)Math.PI + bipedHead.rotateAngleY;
arm.render(scale);
}
private static float interpolateAngle(float current, float prev, float partialTickTime) {
float interpolated = prev + partialTickTime * (current - prev);
return (90 + interpolated) * DEG_TO_RAD;
}
private static double interpolatePos(double current, double prev, float partialTickTime) {
return prev + partialTickTime * (current - prev);
}
@SubscribeEvent
public void renderLines(RenderPlayerEvent.Pre evt) {
final EntityPlayer player = evt.entityPlayer;
if (!ItemCraneBackpack.isWearingCrane(player)) return;
final EntityMagnet magnet = CraneRegistry.instance.getMagnetForPlayer(player);
if (magnet == null) return;
double playerX = interpolatePos(player.posX, player.lastTickPosX, evt.partialRenderTick)
- RenderManager.renderPosX;
double playerY = interpolatePos(player.posY, player.lastTickPosY, evt.partialRenderTick)
- RenderManager.renderPosY;
double playerZ = interpolatePos(player.posZ, player.lastTickPosZ, evt.partialRenderTick)
- RenderManager.renderPosZ;
if (player instanceof EntityOtherPlayerMP) playerY += 1.62;
final float offset = interpolateAngle(player.renderYawOffset, player.prevRenderYawOffset, evt.partialRenderTick);
final float head = interpolateAngle(player.rotationYawHead, player.prevRotationYawHead, evt.partialRenderTick);
double armX = playerX;
double armY = playerY;
double armZ = playerZ;
double armLength;
if (player.isSneaking()) {
armY += 0.70;
armLength = 2;
} else {
armX += -0.45 * MathHelper.cos(offset);
armY += 0.65;
armZ += -0.45 * MathHelper.sin(offset);
armLength = 2.4;
}
armX += armLength * MathHelper.cos(head);
armZ += armLength * MathHelper.sin(head);
final double magnetX = interpolatePos(magnet.posX, magnet.lastTickPosX, evt.partialRenderTick) - RenderManager.renderPosX;
final double magnetY = interpolatePos(magnet.posY, magnet.lastTickPosY, evt.partialRenderTick) - RenderManager.renderPosY + magnet.height - 0.1;
final double magnetZ = interpolatePos(magnet.posZ, magnet.lastTickPosZ, evt.partialRenderTick) - RenderManager.renderPosZ;
GL11.glLineWidth(2);
GL11.glDisable(GL11.GL_TEXTURE_2D);
GL11.glDisable(GL11.GL_LIGHTING);
GL11.glEnable(GL11.GL_LINE_STIPPLE);
GL11.glColor3f(1, 1, 0);
GL11.glLineStipple(3, (short)0x0555);
GL11.glBegin(GL11.GL_LINES);
GL11.glVertex3d(armX, armY, armZ);
GL11.glVertex3d(magnetX, magnetY, magnetZ);
GL11.glEnd();
GL11.glDisable(GL11.GL_LINE_STIPPLE);
GL11.glEnable(GL11.GL_LIGHTING);
GL11.glEnable(GL11.GL_TEXTURE_2D);
drawLine(magnetX, magnetY, magnetZ, armX, armY, armZ);
}
private static void drawLineFPP(EntityPlayer player, float partialTickTime) {
EntityMagnet magnet = CraneRegistry.instance.getMagnetForPlayer(player);
if (magnet == null) return;
final float yaw = interpolateAngle(player.rotationYaw, player.prevRotationYaw, partialTickTime);
final double posX = 1.9 * MathHelper.cos(yaw);
final double posZ = 1.9 * MathHelper.sin(yaw);
final double centerX = interpolatePos(player.posX, player.lastTickPosX, partialTickTime);
final double centerY = interpolatePos(player.posY, player.lastTickPosY, partialTickTime);
final double centerZ = interpolatePos(player.posZ, player.lastTickPosZ, partialTickTime);
final double magnetX = interpolatePos(magnet.posX, magnet.lastTickPosX, partialTickTime) - centerX;
final double magnetY = interpolatePos(magnet.posY, magnet.lastTickPosY, partialTickTime) - centerY + magnet.height - 0.05;
final double magnetZ = interpolatePos(magnet.posZ, magnet.lastTickPosZ, partialTickTime) - centerZ;
drawLine(magnetX, magnetY, magnetZ, posX, 0.6, posZ);
}
private static void drawLine(double x1, double y1, double z1, double x2, double y2, double z2) {
GL11.glLineWidth(2);
GL11.glDisable(GL11.GL_TEXTURE_2D);
GL11.glDisable(GL11.GL_LIGHTING);
GL11.glEnable(GL11.GL_LINE_STIPPLE);
GL11.glColor3f(0, 0, 0);
GL11.glLineStipple(5, (short)0x5555);
GL11.glBegin(GL11.GL_LINES);
GL11.glVertex3d(x1, y1, z1);
GL11.glVertex3d(x2, y2, z2);
GL11.glEnd();
GL11.glColor3f(1, 1, 0);
GL11.glLineStipple(5, (short)0xAAAA);
GL11.glBegin(GL11.GL_LINES);
GL11.glVertex3d(x1, y1, z1);
GL11.glVertex3d(x2, y2, z2);
GL11.glEnd();
GL11.glDisable(GL11.GL_LINE_STIPPLE);
GL11.glEnable(GL11.GL_LIGHTING);
GL11.glEnable(GL11.GL_TEXTURE_2D);
}
private void drawArm(RenderWorldLastEvent evt, final EntityPlayer player) {
final TextureManager tex = Minecraft.getMinecraft().getTextureManager();
tex.bindTexture(texture);
GL11.glColor3f(1, 1, 1);
GL11.glDisable(GL11.GL_LIGHTING);
GL11.glPushMatrix();
// values adjusted to roughly match TPP crane position
GL11.glRotated(-player.rotationYaw, 0, 1, 0);
GL11.glTranslatef(0, 1.6f, -1f);
arm.rotateAngleY = 0;
arm.render(1.0f / 16.0f);
GL11.glPopMatrix();
GL11.glEnable(GL11.GL_LIGHTING);
}
@SubscribeEvent
public void renderFppArm(RenderWorldLastEvent evt) {
final Minecraft mc = Minecraft.getMinecraft();
if (mc.gameSettings.thirdPersonView != 0) return;
final Entity rve = mc.renderViewEntity;
if (!(rve instanceof EntityPlayer)) return;
final EntityPlayer player = (EntityPlayer)rve;
if (!ItemCraneBackpack.isWearingCrane(player)) return;
drawArm(evt, player);
drawLineFPP(player, evt.partialTicks);
}
public void init() {
MinecraftForge.EVENT_BUS.register(this);
}
}
| emmertf/OpenBlocks | src/main/java/openblocks/client/model/ModelCraneBackpack.java | Java | mit | 8,011 |
class TimeUtil
def self.timestamp_to_seconds(timestamp)
hours, minutes, seconds = timestamp.split(':').map(&:to_i)
hours * 3600 + minutes * 60 + seconds
end
def self.seconds_to_timestamp(seconds)
hours, remainder = seconds.divmod(3600)
minutes, seconds = remainder.divmod(60)
"#{hours}:#{minutes}"
end
end
| burennto/tennis-highlights-maker | src/util/time_util.rb | Ruby | mit | 338 |
/**
* @license
* Copyright UIUX Engineering All Rights Reserved.
*/
import { createIndexDict } from './create-indexed-dict';
import { IIndexedItem, IIndexedItemDict, IIndexedTableItem } from './interfaces';
import { createTableItem } from './create-table-item';
import { hasValue } from '@uiux/cdk/value';
describe('createTableItem', () => {
it('should create item', () => {
const object: any = { a: { b: { foo: 'bar' } } };
const mockTable: any = {};
const _dict: IIndexedItemDict = createIndexDict(object);
const itemB: IIndexedItem = _dict['b'];
itemB.search = ['searchB'];
const tItem: IIndexedTableItem = createTableItem(mockTable, itemB);
expect(tItem.hashKey).toBe('b');
expect(tItem.path).toBe('a.b');
expect(tItem.search).toEqual(['searchB']);
expect(tItem.parent.hashKey).toBe('a');
expect(tItem.parent.path).toBe('a');
// expect(tItem.subject.getValue()).toEqual({foo: 'bar'});
expect(hasValue(tItem['_createdAt'])).toBeTruthy();
expect(hasValue(tItem['_updatedAt'])).toBeTruthy();
expect(hasValue(tItem['_timestamp'])).toBeTruthy();
});
// it('should create item', () => {
// let object: any = {a: {b: {foo: 'bar'}}};
//
// let _dict: IIndexedItemDict = createIndexDict(object);
// let itemB: IIndexedItem = _dict['b'];
// itemB.search = ['searchB'];
//
// let _tableItemB: IIndexedTableItem = createTableItem({}, clone(itemB));
// _tableItemB.subject = new BehaviorSubject({foo: 'baz'});
//
// let mockTable: any = {
// b: _tableItemB
// };
//
// itemB.path = 'z';
// itemB.search = ['searchB', 'searchC'];
// itemB.parent = {
// hashKey: 'foo',
// path: 'bar'
// };
// itemB.value = {foo: 'baz'};
//
// let tItem: IIndexedTableItem = createTableItem(mockTable, itemB);
//
// expect(tItem.hashKey).toBe('b');
// expect(tItem.path).toBe('z');
// expect(tItem.search).toEqual(['searchB', 'searchC']);
// expect(tItem.parent.hashKey).toBe('foo');
// expect(tItem.parent.path).toBe('bar');
// expect(tItem.subject.getValue()).toEqual({foo: 'baz'});
// expect(tItem['_createdAt']).toEqual(_tableItemB['_createdAt']);
// expect(hasValue(tItem['_updatedAt'])).toBeTruthy();
// expect(hasValue(tItem['_timestamp'])).toBeTruthy();
// });
});
| UIUXEngineering/ix-material | libs/z_deprecated-cdk/store/src/indexed-table/reducers/create-table-item.spec.ts | TypeScript | mit | 2,343 |
package edu.buffalo.cse.maybeclient.rest;
import retrofit.GsonConverterFactory;
import retrofit.Retrofit;
/**
* Created by xcv58 on 10/15/15.
*/
public class ServiceFactory {
public static <T> T createRetrofitService(final Class<T> clazz, final String endPoint) {
final Retrofit retrofit = new Retrofit.Builder()
.baseUrl(endPoint)
.addConverterFactory(GsonConverterFactory.create())
.build();
return retrofit.create(clazz);
}
}
| blue-systems-group/project.maybe.java.client | src/main/java/edu/buffalo/cse/maybeclient/rest/ServiceFactory.java | Java | mit | 505 |
<?php
//-------------------------------------------------------------
// * Name: PHP-PostGIS2GeoJSON v2
// * Purpose: GeoLab
// * Date: 2018/10/18
// * Author: Chingchai Humhong (chingchaih@nu.ac.th)
// * Acknowledgement:
//-------------------------------------------------------------
// Database connection settings
define("PG_DB" , "yourdb");
define("PG_HOST", "localhost");
define("PG_USER", "postgres");
define("PG_PORT", "5432");
define("PG_PASS", "yourpass");
define("TABLE", "hospital");
// Retrieve start point
// Connect to database
$con = pg_connect("dbname=".PG_DB." host=".PG_HOST." port=".PG_PORT." password=".PG_PASS." user=".PG_USER);
$sql = "select gid, provcode, maincode, bed, name, lat, lon, ST_AsGeoJSON(geom) AS geojson from ".TABLE."; ";
// Perform database query
$query = pg_query($con,$sql);
//echo $sql;
// Return route as GeoJSON
$geojson = array(
'type' => 'FeatureCollection',
'features' => array()
);
// Add geom to GeoJSON array
while($edge=pg_fetch_assoc($query)) {
$feature = array(
'type' => 'Feature',
'geometry' => json_decode($edge['geojson'], true),
'crs' => array(
'type' => 'EPSG',
'properties' => array('code' => '4326')
),
'properties' => array(
'gid' => $edge['gid'],
'provcode' => $edge['provcode'],
'maincode' => $edge['maincode'],
'bed' => $edge['bed'],
'name' => $edge['name'],
'lat' => $edge['lat'],
'lon' => $edge['lon']
)
);
// Add feature array to feature collection array
array_push($geojson['features'], $feature);
}
// Close database connection
pg_close($con);
// Return routing result
// header('Content-type: application/json',true);
echo json_encode($geojson);
?> | chingchai/workshop | leaflet/condata.php | PHP | mit | 1,942 |
import os
import sys
import numpy as np
import properties
svm = properties.svm_path
model = properties.svm_model_path
output = properties.svm_output_path
config = []
config.append("bsvm-train.exe")
config.append("bsvm-predict.exe")
t = " -t 1 "
c = " -c 1 "
m = " -m 1024 "
w0 = " -w0 0.0384 "
w1 = " -w1 1.136 "
w2 = " -w2 0.37 "
w3 = " -w3 0.33 "
w4 = " -w4 0.20 "
w5 = " -w5 0.0164 "
d = " -d 4 "
predictFile = properties.test_features_file_path
def SVMTrain(feature):
print 'SVM training started...\n'
cmd = "\""+svm+config[0]+"\""+ t + c + m + w0 + w1 + w2 + w3 + w4 + w5 +d +feature+" "+model
print cmd
os.system(cmd)
print 'SVM training finished\n'
def SVMPreditct():
cmd = "\""+svm+config[1]+"\""+" "+predictFile+" "+model+" "+output
print cmd
os.system(cmd)
if __name__=="__main__":
#SVMTrain(properties.feature_file_path)
SVMPreditct() | sureshbvn/nlpProject | SVM_A/svm.py | Python | mit | 891 |
import { curry } from 'lodash/fp';
const checkIfClickedOutSideContainer = (containerEle, element) => {
if (!element) {
return true;
} else if (element === containerEle) {
return false;
} else {
return checkIfClickedOutSideContainer(containerEle, element.parentNode);
}
}
const onDocumentClick = curry((containerEle, { getState, setState }, { target }) => {
const { options } = getState();
if (options.length && checkIfClickedOutSideContainer(containerEle, target)) {
setState({ options: [], dismissed: true });
}
});
export default onDocumentClick;
| Attrash-Islam/infinite-autocomplete | src/onDocumentClick/index.js | JavaScript | mit | 612 |
load 'setup/undefine.rb'
require 'elasticsearch/model/extensions/all'
ActiveRecord::Schema.define(:version => 1) do
create_table :articles do |t|
t.string :title
t.datetime :created_at, :default => 'NOW()'
end
create_table :comments do |t|
t.integer :article_id
t.string :body
t.datetime :created_at, :default => 'NOW()'
end
end
class ::Article < ActiveRecord::Base
has_many :comments
accepts_nested_attributes_for :comments
include Elasticsearch::Model
include Elasticsearch::Model::Callbacks
include Elasticsearch::Model::Extensions::IndexOperations
include Elasticsearch::Model::Extensions::BatchUpdating
include Elasticsearch::Model::Extensions::PartialUpdating
include Elasticsearch::Model::Extensions::DependencyTracking
tracks_attributes_dependencies %w| comments | => %w| num_comments |
settings index: {number_of_shards: 1, number_of_replicas: 0} do
mapping do
indexes :title, type: 'string', analyzer: (ENV['TITLE_ANALYZER'] || 'snowball')
indexes :created_at, type: 'date'
indexes :comments, type: 'object' do
indexes :body, type: 'string', include_in_all: true
end
indexes :num_comments, type: 'long'
end
end
def num_comments
comments.count
end
# Required by Comment's `OuterDocumentUpdating`
include Elasticsearch::Model::Extensions::MappingReflection
end
class ::Comment < ActiveRecord::Base
include Elasticsearch::Model
include Elasticsearch::Model::Callbacks
include Elasticsearch::Model::Extensions::IndexOperations
include Elasticsearch::Model::Extensions::BatchUpdating
include Elasticsearch::Model::Extensions::PartialUpdating
include Elasticsearch::Model::Extensions::OuterDocumentUpdating
partially_updates_document_of ::Article, records_to_update_documents: -> comment { Article.find(comment.article_id) } do |t, changed_fields|
t.partially_update_document(*changed_fields)
end
end
Article.delete_all
Article.__elasticsearch__.create_index! force: true
::Article.create! title: 'Test'
::Article.create! title: 'Testing Coding'
::Article.create! title: 'Coding', comments_attributes: [{ body: 'Comment1' }]
Article.__elasticsearch__.refresh_index!
| crowdworks/elasticsearch-model-extensions | spec/setup/articles_with_comments.rb | Ruby | mit | 2,214 |
import pandas as pd
import os
import subprocess as sub
import re
import sys
from Bio import SeqUtils
import matplotlib.pyplot as plt
import numpy as np
from scipy import stats
path = os.path.join(os.path.expanduser('~'),'GENOMES_BACTER_RELEASE69/genbank')
# ['DbxRefs','Description','FeaturesNum','GenomicID','GenomicLen','GenomicName','Keywords','NucsPresent','Organism_des',
# 'SourceDbxRefs','SourceOrganism','SourcePlasmid','SourceStrain','Taxonomy','BioProject','TaxonID','Organism_env',
# 'OptimumTemperature','TemperatureRange','OxygenReq','Habitat','Salinity','crit_NC','crit_WGS','crit_genlen',
# 'crit_features','crit_comp_genome','crit_plasmid']
env_dat = pd.read_csv(os.path.join(path,"env_catalog_compgenome.dat"))
#['GenomicID','cDNA','fid','pid','product','protein','status','table','ribosomal','CAI','TrOp']
gen_dat = pd.read_csv(os.path.join(path,"complete_CDS_CAI_DNA.dat"))
# PROTEOME LEVEL AMINO ACID FREQUENCIES ...
# "proteome_all.dat"
# # file with the organisms of interest
# dat_fname = os.path.join(bib2_scr_path,'catalog_with_accesion.dat')
# dat = pd.read_csv(dat_fname)
aacids = sorted(list('CMFILVWYAGTSNQDEHRKP'))
cost_vec_path = path
akashi = os.path.join(cost_vec_path,'akashi-cost.d')
argentina = os.path.join(cost_vec_path,'argentina-cost.d')
akashi_cost = pd.read_csv(akashi,header=None,sep=' ')
argentina_cost = pd.read_csv(argentina,header=None,sep=' ')
thermo_freq = pd.read_csv(os.path.join(path,'thermo.dat'),header=None,sep=' ')
akashi_cost.set_index(0,inplace=True)
argentina_cost.set_index(0,inplace=True)
thermo_freq.set_index(0,inplace=True)
akashi_cost.sort_index(inplace=True)
argentina_cost.sort_index(inplace=True)
thermo_freq.sort_index(inplace=True)
#################################################
# after we processed all organism's genomes, we would need to
# pull out proteins with top XXX percent CAI, to analyse their amino acid compositions ...
#################################################################
#################################################################
# (1) for each asm - open protein detail file, sort by CAI and analyse proteins with top 10% CAI ...
# (2) output analysis results to external file ...
#################################################################
#################################################################
# def get_aausage_proteome(seqrec):
# # seqrec = db[seqrec_id]
# features = seqrec.features
# proteome = []
# for feature in features:
# qualifiers = feature.qualifiers
# if (feature.type == 'CDS')and('translation' in qualifiers):
# proteome.append(qualifiers['translation'][0])
# #return the results ...
# proteome = ''.join(proteome)
# prot_len = float(len(proteome))
# aa_freq = tuple(proteome.count(aa)/prot_len for aa in aacids)
# #
# return (int(prot_len),) + aa_freq
# def analyse_genome(db,seqrec_id):
# seqrec = db[seqrec_id]
# pl_aa_freq = get_aausage_proteome(seqrec)
# gc = SeqUtils.GC(seqrec.seq)
# id = seqrec.id
# return (id,gc) + pl_aa_freq
# PERCENTILE = 0.1
# accounted_GC = []
# aafs = {}
# for aa in aacids:
# aafs[aa] = []
# genome_length = []
# proteome_length = []
# and for each assembley it goes ...
######################
# fname = os.path.join(path_CAI,'%s_genes.dat'%asm)
######################
#
#
gen_dat_org = gen_dat.groupby('GenomicID')
# genom_id = orgs.groups.keys() # env_dat['GenomicID'] ...
# gen_dat_grouped.get_group(idx)
#
# how to get quantile ...
# q75 = pid_cai['CAI'].quantile(q=0.75)
#
#
num_of_quantiles = 5
#
stat_dat = {'GenomicID':[],
'OptimumTemperature':[],
'TrOp':[]}
for i in range(num_of_quantiles):
stat_dat['q%d'%i] = []
stat_dat['R20_q%d'%i] = []
stat_dat['Akashi_q%d'%i] = []
#
#
for idx,topt in env_dat[['GenomicID','OptimumTemperature']].itertuples(index=False):
cds_cai_dat = gen_dat_org.get_group(idx)
# is it a translationally optimized organism ?
all,any = cds_cai_dat['TrOp'].all(),cds_cai_dat['TrOp'].any()
if all == any:
trans_opt = all
else: #any != all
print "%s@T=%f: Something wrong is happening: TrOp flag is not same for all ..."%(idx,topt)
# THIS IS just a stupid precaution measure, in case we messed something upstream ...
# not that stupid after all, because NaN is behaving badly here ...
if cds_cai_dat['TrOp'].notnull().all():
#
# we can use this 'qcut' function from pandas to divide our proteins by the quantiles ...
category,bins = pd.qcut(cds_cai_dat['CAI'],q=num_of_quantiles,retbins=True,labels=False)
#
stat_dat['GenomicID'].append(idx)
stat_dat['OptimumTemperature'].append(topt)
stat_dat['TrOp'].append(trans_opt)
#
# then we could iterate over proteins/cDNAs in these categories ...
for cat in range(num_of_quantiles):
cds_cai_category = cds_cai_dat[category==cat]
total_length = cds_cai_category['protein'].str.len().sum()
IVYWREL = sum(cds_cai_category['protein'].str.count(aa).sum() for aa in list('IVYWREL'))
# IVYWREL = cds_cai_category['protein'].str.count('|'.join("IVYWREL")).sum() # tiny bit slower ...
f_IVYWREL = float(IVYWREL)/float(total_length)
# 20-vector for of amino acid composition ...
aa_freq_20 = np.true_divide([cds_cai_category['protein'].str.count(aa).sum() for aa in aacids],float(total_length))
# slope, intercept, r_value, p_value, std_err = stats.linregress(x,y)
_1,_2,R20,_4,_5 = stats.linregress(aa_freq_20, thermo_freq[1])
# Akashi ...
cost = np.dot(aa_freq_20,akashi_cost[1])
# appending ...
#
#
stat_dat['q%d'%cat].append(f_IVYWREL)
stat_dat['R20_q%d'%cat].append(R20)
stat_dat['Akashi_q%d'%cat].append(cost)
#
#
#
cai_stats_quant = pd.DataFrame(stat_dat)
#
cai_stats_quant_TrOp = cai_stats_quant[cai_stats_quant.TrOp]
cai_stats_quant_noTrOp = cai_stats_quant[~cai_stats_quant.TrOp]
plt.clf()
bins = np.linspace(-0.05,0.05,50)
plt.hist(list(cai_stats_quant_TrOp.q4 - cai_stats_quant_TrOp.q1),bins=bins,color='blue')
plt.hist(list(cai_stats_quant_noTrOp.q4 - cai_stats_quant_noTrOp.q1),bins=bins,color='red',alpha=0.8)
plt.show()
plt.clf()
bins = np.linspace(-0.15,0.15,50)
# bins=50
plt.hist(list(cai_stats_quant[cai_stats_quant.OptimumTemperature<=50].R20_q4 - cai_stats_quant[cai_stats_quant.OptimumTemperature<=50].R20_q1),bins=bins,color='black',cumulative=False)
plt.hist(list(cai_stats_quant_noTrOp[cai_stats_quant_noTrOp.OptimumTemperature<=50].R20_q4 - cai_stats_quant_noTrOp[cai_stats_quant_noTrOp.OptimumTemperature<=50].R20_q1),bins=bins,color='blue',cumulative=False)
plt.hist(list(cai_stats_quant_TrOp[cai_stats_quant_TrOp.OptimumTemperature<=50].R20_q4 - cai_stats_quant_TrOp[cai_stats_quant_TrOp.OptimumTemperature<=50].R20_q1),bins=bins,color='red',alpha=0.8,cumulative=False)
plt.xlabel('$R^{4}_{T} - R^{1}_{T}$')
# plt.hist(list(cai_stats_quant_TrOp.R20_q4 - cai_stats_quant_TrOp.R20_q1),bins=bins,color='blue')
# plt.hist(list(cai_stats_quant_noTrOp.R20_q4 - cai_stats_quant_noTrOp.R20_q1),bins=bins,color='red',alpha=0.8)
plt.show()
plt.clf()
plt.plot(cai_stats_quant.OptimumTemperature,cai_stats_quant.q1,'bo',alpha=0.8)
plt.plot(cai_stats_quant.OptimumTemperature,cai_stats_quant.q4,'ro',alpha=0.8)
plt.show()
# #
plt.clf()
plt.plot(cai_stats_quant.OptimumTemperature,cai_stats_quant.R20_q1,'bo',alpha=0.8)
plt.plot(cai_stats_quant.OptimumTemperature,cai_stats_quant.R20_q4,'ro',alpha=0.8)
plt.show()
plt.clf()
plt.plot(cai_stats_quant.GC,cai_stats_quant.R20_q1,'bo',alpha=0.8)
plt.plot(cai_stats_quant.GC,cai_stats_quant.R20_q4,'ro',alpha=0.8)
plt.show()
plt.clf()
for i in range(num_of_quantiles):
k1 = 'q%d'%i
k2 = 'R20_q%d'%i
k3 = 'Akashi_q%d'%i
#
plt.plot([i+1,]*cai_stats_quant.shape[0],cai_stats_quant[k1],alpha=0.7)
plt.xlim(0,6)
plt.clf()
for i in range(num_of_quantiles):
k1 = 'q%d'%i
k2 = 'R20_q%d'%i
k3 = 'Akashi_q%d'%i
#
plt.errorbar([i+1,],cai_stats_quant_noTrOp[cai_stats_quant_noTrOp.OptimumTemperature>0][k2].mean(),yerr=cai_stats_quant_noTrOp[cai_stats_quant_noTrOp.OptimumTemperature>0][k2].std(),fmt='o')
plt.xlim(0,6)
plt.show()
# R20 grows on average,
# | meso thermo
# ------+-------------
# TrOp | ++ ~+
# noTrOp| + ~
# Akashi is declining on average
# | meso thermo
# ------+-------------
# TrOp | -- --
# noTrOp| ~- ~-
# IVYWREL is declining on average
# | meso thermo
# ------+-------------
# TrOp | -- ~-
# noTrOp| ~- -
# After reshuffling given CAI, everything becomes flat and 0-centered with much narrower distributions
# #
# # # move on ...
# # # quantiles calculation ...
# # q20,q40,q60,q80 = cds_cai_dat['CAI'].quantile(q=[0.2,0.4,0.6,0.8])
# # #
# # q1_idx = (cds_cai_dat['CAI']<=q20)
# # q2_idx = (q20<cds_cai_dat['CAI'])&(cds_cai_dat['CAI']<=q40)
# # q3_idx = (q40<cds_cai_dat['CAI'])&(cds_cai_dat['CAI']<=q60)
# # q4_idx = (q60<cds_cai_dat['CAI'])&(cds_cai_dat['CAI']<=q80)
# # q5_idx = (q80<cds_cai_dat['CAI'])
# # # q3_idx = q40<cds_cai_dat['CAI']<=q60
# # # q4_idx = q60<cds_cai_dat['CAI']<=q80
# # # q5_idx = q80<cds_cai_dat['CAI']
# # ['q1', 'q2', 'q3', 'q4', 'q5']
# for IndexId,prot_det in dat[['IndexId','protein_details']].get_values():
# ###################
# # in the case of Bacteria, we know for sure that a single accession number refers to related
# if prot_det:
# # open a file with the analysed organismal proteins...
# protein_fname = os.path.join(path_CAI,'%s_genes.dat'%IndexId)
# # load the data ...
# protein_dat = pd.read_csv(protein_fname)
# # "prot_id,cai,gene_product,gene_seq,prot_seq" are the columns ...
# # we'll be taking proteins with top PERCENTILE% CAI in the list ...
# # protein total number is the first dimension of the table here ...
# number_of_proteins,_ = protein_dat.shape
# accounted_proteins = int(number_of_proteins*PERCENTILE)
# # top PERCENTILE proteins will be considered for analysis ...
# accounted_data = protein_dat.sort(columns='cai',ascending=False)[:accounted_proteins]
# # analyse that stuff ...
# cai_proteome = ''.join(accounted_data['prot_seq'])
# cai_proteome_len = float(len(cai_proteome))
# cai_genome = ''.join(accounted_data['gene_seq'])
# #
# accounted_GC.append(SeqUtils.GC(cai_genome))
# #
# for aa in aacids:
# aafs[aa].append(cai_proteome.count(aa)/cai_proteome_len)
# else:
# # no protein details exist, no corresponding file exist at all...
# accounted_GC.append(0.0)
# for aa in aacids:
# aafs[aa].append(0.0)
# dat['GC'] = accounted_GC
# for aa in aacids:
# dat[aa] = aafs[aa]
# dat.to_csv('cai5_bacter.dat',index=False)
| sergpolly/Thermal_adapt_scripts | composition_analysis_Thermo.py | Python | mit | 11,114 |
# Be sure to restart your server when you modify this file.
# Your secret key is used for verifying the integrity of signed cookies.
# If you change this key, all old signed cookies will become invalid!
# Make sure the secret is at least 30 characters and all random,
# no regular words or you'll be exposed to dictionary attacks.
# You can use `rake secret` to generate a secure secret key.
# Make sure your secret_key_base is kept private
# if you're sharing your code publicly.
MachineLearningAsAService::Application.config.secret_key_base = 'ef3fed998116a31dd91f4a7855ec88ce1611b0919e27677ae024c9a8809c4b8f4a13b841e1612c974221d7d0e562ccad7abd5ecdc2c5fcfb1b4fbb1bcd1ef16f'
| dman7/machine-learning-as-a-service | config/initializers/secret_token.rb | Ruby | mit | 679 |
package com.armandgray.seeme.views;
import android.content.BroadcastReceiver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.Fragment;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v4.widget.CursorAdapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import com.armandgray.seeme.NoteEditorActivity;
import com.armandgray.seeme.R;
import com.armandgray.seeme.db.DatabaseHelper;
import com.armandgray.seeme.db.NotesProvider;
import com.armandgray.seeme.models.User;
import com.armandgray.seeme.services.HttpService;
import com.armandgray.seeme.utils.NotesLvAdapter;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import static android.app.Activity.RESULT_OK;
import static com.armandgray.seeme.MainActivity.ACTIVE_USER;
import static com.armandgray.seeme.MainActivity.API_URI;
import static com.armandgray.seeme.network.HttpHelper.sendNotesRequest;
import static com.armandgray.seeme.network.HttpHelper.sendPostRequest;
/**
* A simple {@link Fragment} subclass.
*/
public class NotesFragment extends Fragment
implements LoaderManager.LoaderCallbacks<Cursor> {
private static final String POST_NOTES_URI = API_URI + "/notes/post?";
private static final String GET_NOTES_URI = API_URI + "/notes/get?";
private static final String TAG = "NOTES_FRAGMENT";
private static final int EDITOR_REQUEST_CODE = 1001;
private static final String USER_NOT_FOUND = "User Not Found!";
private CursorAdapter adapter;
private User activeUser;
private final BroadcastReceiver httpBroadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
handleHttpResponse(intent.getStringExtra(HttpService.HTTP_SERVICE_STRING_PAYLOAD),
intent.getStringArrayExtra(HttpService.HTTP_SERVICE_NOTES_PAYLOAD));
}
};
public NotesFragment() {}
public static NotesFragment newInstance(User activeUser) {
Bundle args = new Bundle();
args.putParcelable(ACTIVE_USER, activeUser);
NotesFragment fragment = new NotesFragment();
fragment.setArguments(args);
return fragment;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_notes, container, false);
activeUser = getArguments().getParcelable(ACTIVE_USER);
adapter = new NotesLvAdapter(getContext());
ListView lvNotes = (ListView) rootView.findViewById(R.id.lvNotes);
lvNotes.setAdapter(adapter);
getLoaderManager().initLoader(0, null, this);
lvNotes.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(getContext(), NoteEditorActivity.class);
Uri uri = Uri.parse(NotesProvider.CONTENT_URI + "/" + id);
intent.putExtra(NotesProvider.CONTENT_ITEM_TYPE, uri);
startActivityForResult(intent, EDITOR_REQUEST_CODE);
}
});
FloatingActionButton fabDelete = (FloatingActionButton) rootView.findViewById(R.id.fabDelete);
fabDelete.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivityForResult(new Intent(getContext(), NoteEditorActivity.class), EDITOR_REQUEST_CODE);
}
});
return rootView;
}
@Override
public void onResume() {
super.onResume();
if (getUserVisibleHint()) {
LocalBroadcastManager.getInstance(getActivity().getApplicationContext())
.registerReceiver(httpBroadcastReceiver,
new IntentFilter(HttpService.HTTP_SERVICE_MESSAGE));
sendGetNotesRequest();
}
}
private void sendGetNotesRequest() {
String url = GET_NOTES_URI
+ "username=" + activeUser.getUsername();
sendNotesRequest(url, getContext());
}
private void restartLoader() {
getLoaderManager().restartLoader(0, null, this);
}
private void handleHttpResponse(String response, String[] arrayExtra) {
if (response != null && response.equals(USER_NOT_FOUND)) {
getActivity().getContentResolver().delete(NotesProvider.CONTENT_URI, null, null);
restartLoader();
return;
}
if (arrayExtra != null) {
updateSqliteDatabase(arrayExtra);
}
}
private void updateSqliteDatabase(String[] arrayExtra) {
getActivity().getContentResolver().delete(NotesProvider.CONTENT_URI, null, null);
for (String note : arrayExtra) {
insertNote(note);
}
restartLoader();
}
private void insertNote(String note) {
ContentValues values = new ContentValues();
values.put(DatabaseHelper.NOTE_TEXT, note);
getActivity().getContentResolver().insert(NotesProvider.CONTENT_URI, values);
restartLoader();
}
@Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
return new CursorLoader(getContext(), NotesProvider.CONTENT_URI,
null, null, null, null);
}
@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
adapter.swapCursor(data);
}
@Override
public void onLoaderReset(Loader<Cursor> loader) {
adapter.swapCursor(null);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == EDITOR_REQUEST_CODE && resultCode == RESULT_OK) {
sendPostNotesRequest();
restartLoader();
}
}
private void sendPostNotesRequest() {
JSONObject json = new JSONObject();
JSONArray jsonArray = new JSONArray();
Cursor cursor = getActivity().getContentResolver()
.query(NotesProvider.CONTENT_URI, null, null, null, null);
if (cursor != null) {
cursor.moveToFirst();
String url = POST_NOTES_URI
+ "username=" + activeUser.getUsername();
sendPostRequest(url, getNotesJson(cursor, json, jsonArray), getContext());
}
}
private String getNotesJson(Cursor cursor, JSONObject json, JSONArray jsonArray) {
String noteText;
try {
do {
noteText = cursor.getString(cursor.getColumnIndex(DatabaseHelper.NOTE_TEXT));
jsonArray.put(cursor.getPosition(), noteText);
} while (cursor.moveToNext());
json = new JSONObject();
json.put("notes", jsonArray);
} catch (JSONException e) {
e.printStackTrace();
}
return json.toString();
}
@Override
public void onPause() {
super.onPause();
if (!getUserVisibleHint()) {
LocalBroadcastManager.getInstance(getActivity().getApplicationContext())
.unregisterReceiver(httpBroadcastReceiver);
}
}
}
| armandgray/SeeMe | SeeMe/app/src/main/java/com/armandgray/seeme/views/NotesFragment.java | Java | mit | 7,802 |
/*!
* jquery.analytics.js
* API Analytics agent for jQuery
* https://github.com/Mashape/analytics-jquery-agent
*
* Copyright (c) 2015, Mashape (https://www.mashape.com)
* Released under the @LICENSE license
* https://github.com/Mashape/analytics-jquery-agent/blob/master/LICENSE
*
* @version @VERSION
* @date @DATE
*/
(function (factory) {
if (typeof define === 'function' && define.amd) {
define(['jquery'], factory)
} else if (typeof exports === 'object') {
module.exports = factory(require('jquery'))
} else {
factory(jQuery)
}
})(function (jQuery) {
'use strict'
// Default Constants
var PLUGIN_NAME = 'Analytics'
var PLUGIN_VERSION = '@VERSION'
var PLUGIN_AGENT_NAME = 'mashape-analytics-agent-jquery'
var ANALYTICS_HOST = 'socket.analytics.mashape.com/'
var FALLBACK_IP = '127.0.0.1'
var HTTP_VERSION = 'HTTP/1.1'
var ENVIRONMENT = ''
var PROTOCOL = 'http://'
var ALF_VERSION = '1.0.0'
var CLIENT_IP = FALLBACK_IP
var SERVER_IP = FALLBACK_IP
var DEBUG = false
var READY = false
// This is not a service token.
var TOKEN = 'SKIjLjUcjBmshb733ZqAGiNYu6Qvp1Ue0XGjsnYZRXaI8y1U4O'
// Globals
var $document = jQuery(document)
var queue = []
/**
* Plugin constructor
*
* @param {String} token
* @param {Object} options
*/
function Plugin (token, options) {
// Constants configuration
ANALYTICS_HOST = options.analyticsHost || ANALYTICS_HOST
HTTP_VERSION = options.httpVersion || HTTP_VERSION
FALLBACK_IP = options.fallbackIp || FALLBACK_IP
SERVER_IP = options.serverIp || FALLBACK_IP
CLIENT_IP = options.clientIp || FALLBACK_IP
PROTOCOL = options.ssl ? 'https://' : PROTOCOL
DEBUG = options.debug || DEBUG
// Service token
this.serviceToken = token
this.hostname = options.hostname || (window ? (window.location ? window.location.hostname : false) : false)
this.fetchClientIp = typeof options.fetchClientIp === 'undefined' ? true : options.fetchClientIp
this.fetchServerIp = typeof options.fetchServerIp === 'undefined' ? true : options.fetchServerIp
// Initialize
this.init()
}
// Extend
jQuery.extend(Plugin.prototype, {
init: function () {
var self = this
this.getClientIp(function () {
self.getServerIp(function () {
self.onReady()
})
})
$document.ajaxSend(this.onSend.bind(this))
$document.ajaxComplete(this.onComplete.bind(this))
},
getServerIp: function (next) {
var url = PROTOCOL + 'statdns.p.mashape.com/' + this.hostname + '/a?mashape-key=' + TOKEN
if (this.fetchServerIp && typeof this.hostname === 'string' && this.hostname.length !== 0) {
return jQuery.ajax({
url: url,
type: 'GET',
global: false,
success: function (data) {
SERVER_IP = data.answer[0].rdata
},
complete: function () {
next()
}
})
} else {
return next()
}
},
getClientIp: function (next) {
if (this.fetchClientIp) {
return jQuery.ajax({
url: PROTOCOL + 'httpbin.org/ip',
type: 'GET',
global: false,
success: function (data) {
CLIENT_IP = data.origin
},
complete: function () {
next()
}
})
}
next()
},
onReady: function () {
if (!queue) {
return
}
var entry
// System is ready to send alfs
READY = true
// Send queued alfs
for (var i = 0, length = queue.length; i < length; i++) {
// Obtain entry
entry = queue[i]
// Update addresses
entry.alf.output.har.log.entries[0].serverIpAddress = this.serverIp
entry.alf.output.har.log.entries[0].clientIpAddress = this.clientIp
// Send
entry.alf.send(entry.options)
}
// Clear queue
queue = null
},
onSend: function (event, xhr, options) {
// Save start time
options._startTime = +(new Date())
options._sendTime = options._startTime - event.timeStamp
},
onComplete: function (event, xhr, options, data) {
// Start new alf object
var alf = new Plugin.Alf(this.serviceToken, {
name: PLUGIN_AGENT_NAME,
version: PLUGIN_VERSION
})
// Type
options.type = options.type.toUpperCase()
// Modifiers
var start = options._startTime
var end = event.timeStamp
var difference = end - start
var url = options.url
var responseHeaders = Plugin.getResponseHeaderObject(xhr)
var headers = options.headers
var query = options.type === 'GET' ? options.data : {}
var responseBodySize
var bodySize
var body
// Obtain body
try {
body = options.type === 'GET' ? typeof options.data === 'string' ?
options.data : JSON.stringify(options.data) : ''
} catch (e) {
body = ''
}
// Obtain bytesize of body
bodySize = Plugin.getStringByteSize(body || '')
responseBodySize = Plugin.getStringByteSize(xhr.responseText || '')
// Handle Querystring
if (typeof query === 'string') {
query = Plugin.parseQueryString(query)
}
// Get Querystring from URL
if (url.indexOf('?') !== -1) {
jQuery.extend(query, Plugin.parseQueryString(url))
}
// Insert entry
alf.entry({
startedDateTime: new Date(start).toISOString(),
serverIpAddress: SERVER_IP,
time: difference,
request: {
method: options.type,
url: options.url,
httpVersion: HTTP_VERSION,
queryString: Plugin.marshalObjectToArray(query),
headers: Plugin.marshalObjectToArray(headers),
cookies: [],
headersSize: -1,
bodySize: bodySize
},
response: {
status: xhr.status,
statusText: xhr.statusText,
httpVersion: HTTP_VERSION,
headers: Plugin.marshalObjectToArray(responseHeaders),
cookies: [],
headersSize: -1,
bodySize: responseBodySize,
redirectURL: Plugin.getObjectValue(responseHeaders, 'Location') || '',
content: {
mimeType: Plugin.getObjectValue(responseHeaders, 'Content-Type') || 'application/octet-stream',
size: responseBodySize
}
},
timings: {
blocked: 0,
dns: 0,
connect: 0,
send: options._sendTime,
wait: difference,
receive: 0,
ssl: 0
},
cache: {}
})
if (DEBUG) {
options._alf = alf
}
if (!READY) {
queue.push({
options: DEBUG ? options : undefined,
alf: alf
})
} else {
alf.send(DEBUG ? options : undefined)
}
}
})
/**
* Alf Constructor
*/
Plugin.Alf = function Alf (serviceToken, creator) {
this.output = {
version: ALF_VERSION,
environment: ENVIRONMENT,
serviceToken: serviceToken,
clientIpAddress: CLIENT_IP,
har: {
log: {
version: '1.2',
creator: creator,
entries: []
}
}
}
}
/**
* Push ALF Har-esque entry to entries list
*
* @param {Object} item
*/
Plugin.Alf.prototype.entry = function (item) {
this.output.har.log.entries.push(item)
}
/**
* Send ALF Object to ANALYTICS_HOST
*/
Plugin.Alf.prototype.send = function (options) {
var request = {
url: PROTOCOL + ANALYTICS_HOST + ALF_VERSION + '/single',
global: false,
type: 'POST',
data: JSON.stringify(this.output),
dataType: 'json',
contentType: 'application/json'
}
if (!DEBUG) {
jQuery.ajax(request)
}
if (options) {
options._alfRequest = request
}
}
/**
* Parses XMLHttpRequest getAllResponseHeaders into a key-value map
*
* @param {Object} xhrObject
*/
Plugin.getResponseHeaderObject = function getResponseHeaderObject (xhrObject) {
var headers = xhrObject.getAllResponseHeaders()
var list = {}
var pairs
if (!headers) {
return list
}
pairs = headers.split('\u000d\u000a')
for (var i = 0, length = pairs.length; i < length; i++) {
var pair = pairs[i]
// Can't use split() here because it does the wrong thing
// if the header value has the string ": " in it.
var index = pair.indexOf('\u003a\u0020')
if (index > 0) {
var key = pair.substring(0, index)
var val = pair.substring(index + 2)
list[key] = val
}
}
return list
}
/**
* Returns the specified string as a key-value object.
* Reoccuring keys become array values.
*
* @param {String} string
* @return {Object}
*/
Plugin.parseQueryString = function parseQueryString (string) {
if (!string) {
return {}
}
string = decodeURIComponent(string)
var index = string.indexOf('?')
var result = {}
var pairs
string = (index !== -1 ? string.slice(0, index) : string)
string = string.replace(/&+/g, '&').replace(/^\?*&*|&+$/g, '')
if (!string) {
return result
}
pairs = string.split('&')
for (var i = 0, length = pairs.length; i < length; i++) {
var pair = pairs[i].split('=')
var key = pair[0]
var value = pair[1]
if (key.length) {
if (result[key]) {
if (!result[key].push) {
result[key] = [result[key]]
}
result[key].push(value || '')
}
} else {
result[key] = value || ''
}
}
return result
}
/**
* Returns an Array of Objects containing the properties name, and value.
*
* @param {Object} object Object to be marshalled to an Array
* @return {Array}
*/
Plugin.marshalObjectToArray = function marshalObjectToArray (object) {
var output = []
for (var key in object) {
if (object.hasOwnProperty(key)) {
output.push({
name: key,
value: object[key]
})
}
}
return output
}
/**
* Returns the value associated with the specified key on the specified object.
* Should the key not exist, or the object not have data, a falsy value is returned.
*
* @param {Object} object Specified object to check for existance of key value.
* @param {String} key Object key to obtain value for on specified object.
* @return {Mixed}
*/
Plugin.getObjectValue = function getObjectValue (object, key) {
if (Object.keys(object).length) {
return object[key]
}
return null
}
/**
* Returns the bytesize of the specified UTF-8 string
*
* @param {String} string UTF-8 string to run bytesize calculations on
* @return {Number} Bytesize of the specified string
*/
Plugin.getStringByteSize = function getStringByteSize (string) {
return encodeURI(string).split(/%(?:u[0-9A-F]{2})?[0-9A-F]{2}|./).length - 1
}
// Export plugin
jQuery[PLUGIN_NAME] = function (token, options) {
// Support object style initialization
if (typeof token === 'object') {
options = token
token = options.serviceToken
}
// Setup options
options = options || {}
// Check service token
if (typeof token !== 'string' || token.length === 0) {
throw {
name: 'MissingArgument',
message: 'Service token is missing'
}
}
// Initialize plugin
return new Plugin(token, options)
}
return Plugin
})
| Mashape/analytics-agent-jquery | src/jquery.analytics.js | JavaScript | mit | 11,673 |
include_recipe "markosamuli_workstation::git"
brew "tmux"
brew "reattach-to-user-namespace"
| markosamuli/osx-dev-setup | markosamuli_workstation/recipes/tmux.rb | Ruby | mit | 92 |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("RAPI2TestM")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("RAPI2TestM")]
[assembly: AssemblyCopyright("Copyright © 2008")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("a32d4ddf-6e8f-487a-96e4-199cba2e529a")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| bigfont/2013-128CG-Vendord | HelpfulStuff/rapi2-86240/RAPI2/RAPI2TestM/Properties/AssemblyInfo.cs | C# | mit | 1,395 |