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 |
|---|---|---|---|---|---|
/**
* Layout component that queries for data
* with Gatsby's useStaticQuery component
*
* See: https://www.gatsbyjs.org/docs/use-static-query/
*/
import React from "react"
import PropTypes from "prop-types"
import { useStaticQuery, graphql } from "gatsby"
import "./layout.css"
import "./fonts.css"
import "./james_daydreams.css"
const Layout = ({ children }) => {
const data = useStaticQuery(graphql`
query SiteTitleQuery {
site {
siteMetadata {
title
}
}
}
`)
return (
<>
<div
style={{
margin: `200px 25% 0 30px`,
maxWidth: 960,
padding: `0px 1.0875rem 1.45rem`,
paddingTop: 0,
}}
>
<main>{children}</main>
<footer>
{console.log(data)}
</footer>
</div>
</>
)
}
Layout.propTypes = {
children: PropTypes.node.isRequired,
}
export default Layout
| parisminton/james.da.ydrea.ms | src/components/layout.js | JavaScript | mit | 928 |
#include "GameAnims.h"
#include "gslib/Core/Core.h"
#include "gslib/Game/GameResources.h"
namespace
{
// Helper to easily build an AnimAsset in code
class AnimAssetBuilder
{
public:
typedef AnimAssetBuilder ThisType;
AnimAssetBuilder() : mpAnimAsset(0) { }
ThisType& CreateAndAdd(AnimAssetKey key)
{
//@TODO: This allocation is never deleted! We're ok for now since we only
// allocate anim assets once at Init time, but we should clean this up somewhere.
mpAnimAsset = new AnimAsset();
AnimAssetManager::AddAnimAsset(key, mpAnimAsset);
return *this;
}
ThisType& InitPoses(const uint8* pFrameGfx, uint16 frameSize)
{
mpAnimAsset->mAnimPoses.Init(pFrameGfx, frameSize);
return *this;
}
ThisType& InitTimeline(int firstFrameIndex, int numFrames, AnimTimeType unitsPerFrame, AnimCycle::Type animCycle)
{
mpAnimAsset->mAnimTimeline.Populate(firstFrameIndex, numFrames, unitsPerFrame, animCycle);
return *this;
}
struct TimelineBuilder
{
typedef TimelineBuilder ThisType;
TimelineBuilder(AnimTimeline& timeline) : mpTimeline(&timeline)
{
ASSERT(mpTimeline);
}
ThisType& Looping(bool looping)
{
mpTimeline->SetLooping(looping);
return *this;
}
// Add frames with operator()
ThisType& operator()(int frameIndex, AnimTimeType frameDuration)
{
mpTimeline->AddKeyFrame(frameIndex, frameDuration);
return *this;
}
private:
AnimTimeline* mpTimeline;
};
TimelineBuilder BuildTimeline()
{
return TimelineBuilder(mpAnimAsset->mAnimTimeline);
}
private:
AnimAsset* mpAnimAsset;
};
// Helper to create and add four-directional animations
void CreateAndAddAnimAssets4(
GameActor::Type gameActor,
BaseAnim::Type baseAnim,
const uint8* pFrameGfx,
uint16 frameSize,
int firstRightFrameIndex,
int numFrames,
int framesToSkip,
AnimTimeType unitsPerFrame,
AnimCycle::Type animCycle)
{
AnimAssetBuilder builder;
for (int d=0; d < SpriteDir::NumTypes; ++d)
{
const int firstFrameIndex = firstRightFrameIndex + d * (numFrames + framesToSkip);
builder.CreateAndAdd(MakeAnimAssetKey(gameActor, baseAnim, (SpriteDir::Type)d))
.InitPoses(pFrameGfx, frameSize)
.InitTimeline(firstFrameIndex, numFrames, unitsPerFrame, animCycle);
}
}
// Helper to create and add non-directional animations
void CreateAndAddAnimAssets1(
GameActor::Type gameActor,
BaseAnim::Type baseAnim,
const uint8* pFrameGfx,
uint16 frameSize,
int firstFrameIndex,
int numFrames,
AnimTimeType unitsPerFrame,
AnimCycle::Type animCycle)
{
AnimAssetBuilder builder;
builder.CreateAndAdd(MakeAnimAssetKey(gameActor, baseAnim, SpriteDir::None))
.InitPoses(pFrameGfx, frameSize)
.InitTimeline(firstFrameIndex, numFrames, unitsPerFrame, animCycle);
}
} // anonymous namespace
void LoadAllGameAnimAssets()
{
//@TODO: Externalize into data files
//@TODO: Replace SEC_TO_FRAMES() with actual frames below to reduce noise
using namespace GameActor;
using namespace BaseAnim;
using namespace SpriteDir;
AnimAssetBuilder builder;
// 16x16 characters
{
const uint8* pFrameGfx = ResourceMgr::Instance().GetResource(GameResource::Gfx_Characters16x16).Data();
const int FrameSize = 16 * 16; // 8bpp sprites
const int NumTilesPerRow = 14;
// General spawn anim
CreateAndAddAnimAssets1(GameActor::None, Spawn, pFrameGfx, FrameSize, 178, 4, SEC_TO_FRAMES(0.1f), AnimCycle::Once);
// Manually add the Idle anims (which include a blink frame)
{
builder.CreateAndAdd(MakeAnimAssetKey(Hero, Idle, Right)).InitPoses (pFrameGfx, FrameSize).BuildTimeline().Looping(true)(1, SEC_TO_FRAMES(2.0f))(22, SEC_TO_FRAMES(0.2f));
builder.CreateAndAdd(MakeAnimAssetKey(Hero, Idle, Left )).InitPoses(pFrameGfx, FrameSize).BuildTimeline().Looping(true)(4, SEC_TO_FRAMES(2.0f))(23, SEC_TO_FRAMES(0.2f));
builder.CreateAndAdd(MakeAnimAssetKey(Hero, Idle, Down )).InitPoses(pFrameGfx, FrameSize).BuildTimeline().Looping(true)(7, SEC_TO_FRAMES(2.0f))(24, SEC_TO_FRAMES(0.2f));
builder.CreateAndAdd(MakeAnimAssetKey(Hero, Idle, Up )).InitPoses(pFrameGfx, FrameSize).BuildTimeline().Looping(true)(10, SEC_TO_FRAMES(0.0f));
}
CreateAndAddAnimAssets4(Hero, Move, pFrameGfx, FrameSize, (0 * NumTilesPerRow + 0), 3, 0, SEC_TO_FRAMES(0.15f), AnimCycle::PingPong);
CreateAndAddAnimAssets4(Hero, Attack, pFrameGfx, FrameSize, (1 * NumTilesPerRow + 0), 2, 0, SEC_TO_FRAMES(0.10f), AnimCycle::Once);
CreateAndAddAnimAssets4(Hero, UseItem, pFrameGfx, FrameSize, (1 * NumTilesPerRow + 1), 1, 1, SEC_TO_FRAMES(0.20f), AnimCycle::Once);
// Player Death anim (must face down)
{
// 7: down
// 4: left
// 10: up
// 1: right
builder.CreateAndAdd(MakeAnimAssetKey(Hero, Die, SpriteDir::None))
.InitPoses(pFrameGfx, FrameSize)
.BuildTimeline()
(7, SEC_TO_FRAMES(0.5f))(4, SEC_TO_FRAMES(0.05f))(10, SEC_TO_FRAMES(0.05f))(1, SEC_TO_FRAMES(0.05f))
(7, SEC_TO_FRAMES(0.05f))(4, SEC_TO_FRAMES(0.05f))(10, SEC_TO_FRAMES(0.05f))(1, SEC_TO_FRAMES(0.05f))
(7, SEC_TO_FRAMES(0.05f))(4, SEC_TO_FRAMES(0.05f))(10, SEC_TO_FRAMES(0.05f))(1, SEC_TO_FRAMES(0.05f))
(7, SEC_TO_FRAMES(0.10f))(4, SEC_TO_FRAMES(0.10f))(10, SEC_TO_FRAMES(0.10f))(1, SEC_TO_FRAMES(0.10f))
(7, SEC_TO_FRAMES(0.15f))(4, SEC_TO_FRAMES(0.15f))(10, SEC_TO_FRAMES(0.15f))(1, SEC_TO_FRAMES(0.15f))
(7, SEC_TO_FRAMES(0.15f));
}
// Enemies - note that Idle is used for stunned (enemies don't really idle)
CreateAndAddAnimAssets4(Rope, Idle, pFrameGfx, FrameSize, (2 * NumTilesPerRow + 0), 1, 2, SEC_TO_FRAMES(0.0f), AnimCycle::Once);
CreateAndAddAnimAssets4(Rope, Move, pFrameGfx, FrameSize, (2 * NumTilesPerRow + 0), 3, 0, SEC_TO_FRAMES(0.25f), AnimCycle::PingPong);
CreateAndAddAnimAssets4(Rope, Attack, pFrameGfx, FrameSize, (2 * NumTilesPerRow + 2), 1, 2, SEC_TO_FRAMES(0.25f), AnimCycle::Once);
CreateAndAddAnimAssets4(Darknut, Idle, pFrameGfx, FrameSize, (3 * NumTilesPerRow + 1), 1, 2, SEC_TO_FRAMES(0.25f), AnimCycle::Loop);
CreateAndAddAnimAssets4(Darknut, Move, pFrameGfx, FrameSize, (3 * NumTilesPerRow + 0), 3, 0, SEC_TO_FRAMES(0.25f), AnimCycle::PingPong);
CreateAndAddAnimAssets4(Stalfos, Idle, pFrameGfx, FrameSize, (4 * NumTilesPerRow + 1), 1, 2, SEC_TO_FRAMES(0.25f), AnimCycle::Loop);
CreateAndAddAnimAssets4(Stalfos, Move, pFrameGfx, FrameSize, (4 * NumTilesPerRow + 0), 3, 0, SEC_TO_FRAMES(0.25f), AnimCycle::PingPong);
CreateAndAddAnimAssets4(Goriya, Idle, pFrameGfx, FrameSize, (5 * NumTilesPerRow + 1), 1, 2, SEC_TO_FRAMES(0.0f), AnimCycle::Loop);
CreateAndAddAnimAssets4(Goriya, Move, pFrameGfx, FrameSize, (5 * NumTilesPerRow + 0), 3, 0, SEC_TO_FRAMES(0.25f), AnimCycle::PingPong);
CreateAndAddAnimAssets4(Goriya, Attack, pFrameGfx, FrameSize, (5 * NumTilesPerRow + 12), 1, 0, SEC_TO_FRAMES(0.5f), AnimCycle::Once);
CreateAndAddAnimAssets1(Gel, Idle, pFrameGfx, FrameSize, (6 * NumTilesPerRow + 5), 1, SEC_TO_FRAMES(1.0f), AnimCycle::Loop);
CreateAndAddAnimAssets1(Gel, Move, pFrameGfx, FrameSize, (6 * NumTilesPerRow + 5), 3, SEC_TO_FRAMES(0.25f), AnimCycle::Loop);
CreateAndAddAnimAssets1(Keese, Idle, pFrameGfx, FrameSize, (6 * NumTilesPerRow + 8), 1, SEC_TO_FRAMES(1.0f), AnimCycle::Loop);
CreateAndAddAnimAssets1(Keese, Move, pFrameGfx, FrameSize, (6 * NumTilesPerRow + 8), 3, SEC_TO_FRAMES(0.25f), AnimCycle::Loop);
CreateAndAddAnimAssets1(WallMaster, Idle, pFrameGfx, FrameSize, (6 * NumTilesPerRow + 2), 1, SEC_TO_FRAMES(1.0f), AnimCycle::Loop);
CreateAndAddAnimAssets1(WallMaster, Move, pFrameGfx, FrameSize, (6 * NumTilesPerRow + 2), 3, SEC_TO_FRAMES(0.25f), AnimCycle::Loop);
}
// 32x32 characters
{
const uint8* pFrameGfx = ResourceMgr::Instance().GetResource(GameResource::Gfx_Characters32x32).Data();
const int FrameSize = 32 * 32; // 8bpp sprites
const int NumTilesPerRow = 4;
// Override global Spawn with one that fits 32x32 sprites. What sucks is we need to do this for every 32x32 character.
//@TODO: Rename BaseAnim::Spawn to Spawn16x16, add BaseAnim::Spawn32x32, create its global anim here, and in the Enemy
// state machine, call the specific spawn anim based on the sprite dimenions.
CreateAndAddAnimAssets1(Dragon, Spawn, pFrameGfx, FrameSize, (0 * NumTilesPerRow + 0), 4, SEC_TO_FRAMES(0.1f), AnimCycle::Once);
CreateAndAddAnimAssets1(Dragon, Idle, pFrameGfx, FrameSize, (1 * NumTilesPerRow + 0), 1, SEC_TO_FRAMES(1.0f), AnimCycle::Loop);
CreateAndAddAnimAssets1(Dragon, Move, pFrameGfx, FrameSize, (1 * NumTilesPerRow + 0), 3, SEC_TO_FRAMES(0.25f), AnimCycle::Loop);
}
// 16x16 items
{
const uint8* pFrameGfx = ResourceMgr::Instance().GetResource(GameResource::Gfx_Items).Data();
const int FrameSize = 16 * 16; // 8bpp sprites
// Boomerang
{
const int numFramesPerImage = 5;
builder.CreateAndAdd(MakeAnimAssetKey(Boomerang, ItemDefault, SpriteDir::None))
.InitPoses(pFrameGfx, FrameSize)
.BuildTimeline().Looping(true)(4, numFramesPerImage)(5, numFramesPerImage)(6, numFramesPerImage)(7, numFramesPerImage);
}
}
}
| amaiorano/ZeldaDS | Game/ZeldaDS/arm9/source/gslib/Game/GameAnims.cpp | C++ | mit | 9,026 |
#include <cmath>
#include <cstring>
#include <iostream>
#include <GL/glew.h>
#include <GLFW/glfw3.h>
#include <boost/format.hpp>
#include "../common/util.hpp"
using namespace std;
using namespace boost;
int main(int argc, char* argv[]) {
if (argc < 2) {
cout << format("Usage: %1% <star>") % argv[0]<< endl;
return EXIT_FAILURE;
}
const int star = atoi(argv[1]);
if (!glfwInit()) {
throw runtime_error("Failed to initialize GLFW");
}
glfwWindowHint(GLFW_SAMPLES, 4);
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
GLFWwindow* window = glfwCreateWindow(600, 600, "Hexagram", NULL, NULL);
if (!window) {
throw runtime_error("Failed to open GLFW window");
}
glfwMakeContextCurrent(window);
glfwSetInputMode(window, GLFW_STICKY_KEYS, GL_TRUE);
glewExperimental = GL_TRUE;
if (glewInit() != GLEW_OK) {
throw runtime_error("Failed to initialize GLEW");
}
GLuint programID = buildProgram("vertex.shader", "fragment.shader");
glUseProgram(programID);
glClearColor(25 / 255.0f, 25 / 255.0, 25 / 255.0, 0.0f);
GLuint vertexArrayID;
glGenVertexArrays(1, &vertexArrayID);
glBindVertexArray(vertexArrayID);
GLfloat vertexData[star * 12];
// center vertex
GLfloat centerVertex[2];
centerVertex[0] = 0;
centerVertex[1] = 0;
for (int i = 0; i < star; i++) {
vertexData[12 * i] = cos(2 * i * M_PI / star) / 2;
vertexData[12 * i + 1] = sin(2 * i * M_PI / star) / 2;
vertexData[12 * i + 2] = cos(2 * (i + 1) * M_PI / star) / 2;
vertexData[12 * i + 3] = sin(2 * (i + 1) * M_PI / star) / 2;
memcpy(vertexData + (12 * i + 4), centerVertex, sizeof(GLfloat) * 2);
memcpy(vertexData + (12 * i + 6), vertexData + (12 * i), sizeof(GLfloat) * 4);
vertexData[12 * i + 10] = cos((2 * i + 1) * M_PI / star);
vertexData[12 * i + 11] = sin((2 * i + 1) * M_PI / star);
}
GLfloat colorData[star * 18];
// center color
GLfloat centerColor[3];
centerColor[0] = float(rand()) / RAND_MAX;
centerColor[1] = float(rand()) / RAND_MAX;
centerColor[2] = float(rand()) / RAND_MAX;
/*
* if: most case first
*
* first star => generate 3 random color
* other star => generate 2 random color, copy 1 color
* last star => generate 1 random color, copy 2 color
*
*/
for (int i = 0; i < star; i++) {
if (i != 0) {
memcpy(colorData + (18 * i), colorData + (18 * i - 6), sizeof(GLfloat) * 3);
} else {
colorData[0] = float(rand()) / RAND_MAX;
colorData[1] = float(rand()) / RAND_MAX;
colorData[2] = float(rand()) / RAND_MAX;
}
if (i != (star - 1)) {
colorData[18 * i + 3] = float(rand()) / RAND_MAX;
colorData[18 * i + 4] = float(rand()) / RAND_MAX;
colorData[18 * i + 5] = float(rand()) / RAND_MAX;
} else {
memcpy(colorData + (18 * i + 3), colorData, sizeof(GLfloat) * 3);
}
memcpy(colorData + (18 * i + 6), centerColor, sizeof(centerColor));
memcpy(colorData + (18 * i + 9), colorData + (18 * i), sizeof(GLfloat) * 6);
colorData[18 * i + 15] = float(rand()) / RAND_MAX;
colorData[18 * i + 16] = float(rand()) / RAND_MAX;
colorData[18 * i + 17] = float(rand()) / RAND_MAX;
}
GLuint vertexBuffer;
glGenBuffers(1, &vertexBuffer);
glBindBuffer(GL_ARRAY_BUFFER, vertexBuffer);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertexData), vertexData, GL_STATIC_DRAW);
glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, (void*)0);
glEnableVertexAttribArray(0);
GLuint colorBuffer;
glGenBuffers(1, &colorBuffer);
glBindBuffer(GL_ARRAY_BUFFER, colorBuffer);
glBufferData(GL_ARRAY_BUFFER, sizeof(colorData), colorData, GL_STATIC_DRAW);
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 0, (void*)0);
glEnableVertexAttribArray(1);
do {
glClear(GL_COLOR_BUFFER_BIT);
glDrawArrays(GL_TRIANGLES, 0, star * 12);
glfwSwapBuffers(window);
glfwPollEvents();
} while (glfwGetKey(window, GLFW_KEY_ESCAPE) != GLFW_PRESS && glfwWindowShouldClose(window) == 0);
return EXIT_SUCCESS;
}
| Preffer/learning-opengl | hexagram/main.cpp | C++ | mit | 3,982 |
/**
* System configuration for Angular samples
* Adjust as necessary for your application needs.
*/
(function (global) {
System.config({
paths: {
// paths serve as alias
'npm:': 'node_modules/'
},
// map tells the System loader where to look for things
map: {
// our app is within the app folder
app: 'app',
// angular bundles
'@angular/core': 'npm:@angular/core/bundles/core.umd.js',
'@angular/common': 'npm:@angular/common/bundles/common.umd.js',
'@angular/compiler': 'npm:@angular/compiler/bundles/compiler.umd.js',
'@angular/platform-browser': 'npm:@angular/platform-browser/bundles/platform-browser.umd.js',
'@angular/platform-browser-dynamic': 'npm:@angular/platform-browser-dynamic/bundles/platform-browser-dynamic.umd.js',
'@angular/http': 'npm:@angular/http/bundles/http.umd.js',
'@angular/router': 'npm:@angular/router/bundles/router.umd.js',
'@angular/forms': 'npm:@angular/forms/bundles/forms.umd.js',
// other libraries
'rxjs': 'npm:rxjs',
'angular2-in-memory-web-api': 'npm:angular2-in-memory-web-api',
},
// packages tells the System loader how to load when no filename and/or no extension
packages: {
app: {
main: 'main.js',
defaultExtension: 'js'
},
rxjs: {
defaultExtension: 'js'
},
'angular2-in-memory-web-api': {
main: './index.js',
defaultExtension: 'js'
}
}
});
})(this); | nz-andy/electron-test | systemjs.config.js | JavaScript | mit | 1,529 |
import React,{ Component } from 'react'
import { {{ name }}List } from './list'
export { {{ name }}List }
| team4yf/yf-fpm-admin | src_template/index.js | JavaScript | mit | 107 |
import argparse
import io
import unittest
import mock
import time
from imagemounter.cli import AppendDictAction
class AppendDictActionTest(unittest.TestCase):
def test_with_comma(self):
parser = argparse.ArgumentParser()
parser.add_argument('--test', action=AppendDictAction)
self.assertDictEqual(parser.parse_args(["--test", "x"]).test, {"*": 'x'})
self.assertDictEqual(parser.parse_args(["--test", "y=x"]).test, {"y": 'x'})
self.assertDictEqual(parser.parse_args(["--test", "y=x,z=a"]).test, {"y": 'x', "z": 'a'})
self.assertDictEqual(parser.parse_args(["--test", "*=x"]).test, {"*": 'x'})
self.assertDictEqual(parser.parse_args(["--test", "*=x", "--test", "y=a"]).test, {"*": 'x', 'y': 'a'})
self.assertDictEqual(parser.parse_args(["--test", "x=x", "--test", "x=y"]).test, {'x': 'y'})
self.assertDictEqual(parser.parse_args(["--test", "*=x", "--test", "y"]).test, {"*": 'y'})
self.assertDictEqual(parser.parse_args(["--test", "y", "--test", "*=3"]).test, {"*": '3'})
with self.assertRaises(SystemExit):
parser.parse_args(["--test", "y=x,z"])
def test_with_comma_multiple_times(self):
parser = argparse.ArgumentParser()
parser.add_argument('--test', action=AppendDictAction)
self.assertDictEqual(parser.parse_args(["--test", "*=x", "--test", "y=a"]).test, {"*": 'x', 'y': 'a'})
self.assertDictEqual(parser.parse_args(["--test", "x=x", "--test", "x=y"]).test, {'x': 'y'})
self.assertDictEqual(parser.parse_args(["--test", "*=x", "--test", "y"]).test, {"*": 'y'})
self.assertDictEqual(parser.parse_args(["--test", "y", "--test", "*=3"]).test, {"*": '3'})
with self.assertRaises(SystemExit):
parser.parse_args(["--test", "y=x,z", "--test", "x"])
def test_without_comma(self):
parser = argparse.ArgumentParser()
parser.add_argument('--test', action=AppendDictAction, allow_commas=False)
self.assertDictEqual(parser.parse_args(["--test", "x"]).test, {"*": 'x'})
self.assertDictEqual(parser.parse_args(["--test", "y=x"]).test, {"y": 'x'})
self.assertDictEqual(parser.parse_args(["--test", "y=x,z=a"]).test, {"y": 'x,z=a'})
self.assertDictEqual(parser.parse_args(["--test", "*=x"]).test, {"*": 'x'})
self.assertDictEqual(parser.parse_args(["--test", "y=x,z"]).test, {"y": 'x,z'})
def test_without_comma_multiple_times(self):
parser = argparse.ArgumentParser()
parser.add_argument('--test', action=AppendDictAction, allow_commas=False)
self.assertDictEqual(parser.parse_args(["--test", "x", "--test", "y"]).test, {"*": 'y'})
self.assertDictEqual(parser.parse_args(["--test", "y=x", "--test", "x=y"]).test, {"y": 'x', 'x': 'y'})
self.assertDictEqual(parser.parse_args(["--test", "y=x,z=a", "--test", "b=c"]).test, {"y": 'x,z=a', 'b': 'c'})
def test_with_default(self):
parser = argparse.ArgumentParser()
parser.add_argument('--test', action=AppendDictAction, default={"aa": "bb"})
self.assertDictEqual(parser.parse_args(["--test", "x"]).test, {"*": 'x', 'aa': 'bb'}) | jdossett/imagemounter | tests/cli_test.py | Python | mit | 3,178 |
angular.module('Techtalk')
.factory('socket', function ($rootScope, config) {
if (typeof (io) != "undefined") {
var socket = io.connect(config.Urls.URLService, { reconnection: false });
return {
on: function (eventName, callback) {
socket.on(eventName, function () {
var args = arguments;
$rootScope.$apply(function () {
callback.apply(socket, args);
});
});
},
emit: function (eventName, data, callback) {
socket.emit(eventName, data, function () {
var args = arguments;
$rootScope.$apply(function () {
if (callback) {
callback.apply(socket, args);
}
});
})
}
};
}
return;
})
.directive('serverError', function () {
return {
restrict: 'A',
require: 'ngModel',
link: function (scope, element, attrs, ctrl) {
element.on('keydown', function () {
ctrl.$setValidity('server', true)
});
}
}
})
.directive('ngEnter', function () {
return function (scope, element, attrs) {
element.bind("keydown keypress", function (event) {
if (event.which === 13) {
scope.$apply(function () {
scope.$eval(attrs.ngEnter);
});
var $id = $("." + attrs.ngScrollBottomText);
$id.scrollTop($id[0].scrollHeight + 250);
event.preventDefault();
}
});
};
})
.directive("ngScrollBottom", function () {
return {
link: function (scope, element, attr) {
var $id = $("." + attr.ngScrollBottom);
$(element).on("click", function () {
$id.scrollTop($id[0].scrollHeight + 250);
$('.msg-field').focus();
});
}
}
});
| RafaSousa/techtalk-node | client/app/directives/main-directive.js | JavaScript | mit | 1,844 |
// Regular expression that matches all symbols with the `IDS_Binary_Operator` property as per Unicode v7.0.0:
/[\u2FF0\u2FF1\u2FF4-\u2FFB]/; | mathiasbynens/unicode-data | 7.0.0/properties/IDS_Binary_Operator-regex.js | JavaScript | mit | 140 |
# Import the necessary packages and modules
import matplotlib.pyplot as plt
import numpy as np
# Prepare the data
x = np.linspace(0, 10, 100)
# Plot the data
plt.plot(x, x, label='linear')
# Add a legend
plt.legend()
# Show the plot
plt.show()
print("done")
| vadim-ivlev/STUDY | coding/plot.py | Python | mit | 262 |
(function(){
console.log("Message");
})(); | curvecode/chrome-ext-js | app/helloworld/js/app.js | JavaScript | mit | 46 |
using CompartiMoss.BootCamp.Web.Services;
using Microsoft.AspNet.Mvc;
namespace CompartiMoss.BootCamp.Web.ViewComponents
{
public class ArticulosByAutor : ViewComponent
{
private IArticulos _service;
public ArticulosByAutor(IArticulos service)
{
_service = service;
}
public IViewComponentResult Invoke(string name)
{
var articulosCollection = _service.GetArticulosByAutor(name);
return View(articulosCollection);
}
}
}
| AdrianDiaz81/AzureBootCamp2016 | CompartiMoss.BootCamp/src/CompartiMoss.BootCamp.Web/ViewComponents/ArticulosByAutor.cs | C# | mit | 551 |
using System.Collections.ObjectModel;
// Copyright (c) 2017 Cyotek Ltd.
// http://mantissharp.net/
// Licensed under the MIT License. See LICENSE.txt for the full text.
// If you use this control in your applications, attribution, donations or contributions are welcome.
namespace MantisSharp
{
public class UserCollection : KeyedCollection<int, User>
{
#region Methods
protected override int GetKeyForItem(User item)
{
return item.Id;
}
#endregion
}
}
| cyotek/MantisSharp | src/UserCollection.cs | C# | mit | 493 |
var express = require('express');
var morphine = require('./api');
var app = express();
// Mounts the rpc layer middleware. This will enable remote function calls
app.use(morphine.router);
// Serve static files in this folder
app.use('/', express.static(__dirname + '/'));
// Listen on port 3000
app.listen(3000, function(err) {
if (err) return console.log(err.stack);
// Creates a user when you boot up the server
// This is only to demostrate we can use the same code on server side...
var User = morphine.User;
User.create({ _id: 5, name: 'someone' }, function(err, user) {
if (err) console.error(err.stack);
console.log('App listening on http://127.0.0.1:3000');
});
});
| d-oliveros/isomorphine | examples/barebone/src/server.js | JavaScript | mit | 703 |
#!/usr/bin/env node
require('yargs')
.commandDir('cmd')
.demand(1)
.strict()
.help()
.argv;
| dobbydog/webpack-porter | cli.js | JavaScript | mit | 93 |
package main
import (
"fmt"
"github.com/oreans/virtualizersdk"
"io/ioutil"
"net/http"
)
func main() {
string1 := "This is string1"
virtualizersdk.Macro(virtualizersdk.TIGER_BLACK_START)
string2 := "This is string2"
string3 := string1 + string2
fmt.Println(string3)
resp, err := http.Get("http://google.com")
if err != nil {
fmt.Println(err)
} else {
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
fmt.Println(err)
}
fmt.Println(string(body))
}
virtualizersdk.Macro(virtualizersdk.TIGER_BLACK_END)
string4 := string2 + "...and string 4"
fmt.Println(string4)
}
| ryanskidmore/CodeVirtualizer-Go-Example | main.go | GO | mit | 624 |
<?php
include_once '../application/services/cases/test';
$model = new case_service();
$rs = $model->get_cases_num();
include_once ('global.php'); //调用数据库
include_once ('ofc/open-flash-chart.php'); //调用OFC库文件
//设置图表标题
$title = new title( '各区域单位场所数量分布图'.date('Y-m-d') );
$title->set_style("font-size:12px; font-weight:bold;");
$pie = new pie();
$pie->set_alpha(0.6);
$pie->set_start_angle( 32 );
$pie->add_animation( new pie_fade() );
$pie->set_tooltip( '#val# of #total##percent# of 100%' );
$pie->set_colours( array('#1C9E05','#FF368D','#0099cc','#d853ce','#ff7400','#006e2e',
'#d15600','#4096ee','#c79810') );
//读取各区域信息
$model = new case_service();
$rs = $model->get_cases_num();
var_dump($rs);exit();
$sql="select sum(total) as num from ".$prefix."district";
$query=$db->query($sql);
$rs=$db->fetch_array($query);
$t=$rs[num];
$sql="select name,total from ".$prefix."district";
$query=$db->query($sql);
while($row=$db->fetch_array($query)){
$total=$row[total];
if(!empty($t)){
$v=round($total/$t,4)*100;
}else{
$v=0;
}
$dis[]=array("name"=>$row[name],"total"=>$row[total],"v"=>$v);
}
$len_dis=count($dis);
for($i=0;$i<$len_dis;$i++){
$dis_value[]=new pie_value(intval($dis[$i][total]),$dis[$i][name]."(".$dis[$i][v]."%)");
}
$pie->set_values($dis_value);
$chart = new open_flash_chart();
$chart->set_title( $title );
$chart->add_element( $pie );
$chart->x_axis = null;
echo $chart->toPrettyString(); //生成json数据 | niuzz/ci | static/cases_data.php | PHP | mit | 1,585 |
class CreateRepoUsers < ActiveRecord::Migration
def change
create_table :repo_users do |t|
t.integer :user_id, :null => false
t.integer :repo_id, :null => false
t.timestamps
end
add_index :repo_users, [:user_id, :repo_id], :unique => true
end
end
| prashantrajan/gitstars-oss | db/migrate/20120813015611_create_repo_users.rb | Ruby | mit | 282 |
/*
* JDIVisitor
* Copyright (C) 2014 Adrian Herrera
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
package org.jdivisitor.debugger.event;
import org.jdivisitor.debugger.event.visitor.EventVisitor;
import org.jdivisitor.debugger.event.visitor.Visitable;
import com.sun.jdi.event.ThreadStartEvent;
/**
* Visitable thread start event.
*
* @author Adrian Herrera
* @see ThreadStartEvent
*/
public class VisitableThreadStartEvent implements Visitable {
private final ThreadStartEvent event;
public VisitableThreadStartEvent(ThreadStartEvent event) {
this.event = event;
}
@Override
public void accept(EventVisitor visitor) {
visitor.visit(event);
}
}
| adrianherrera/jdivisitor | src/main/java/org/jdivisitor/debugger/event/VisitableThreadStartEvent.java | Java | mit | 1,378 |
package com.limpoxe.fairy.core;
import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.content.ContextWrapper;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import com.limpoxe.fairy.content.LoadedPlugin;
import com.limpoxe.fairy.content.PluginDescriptor;
import com.limpoxe.fairy.core.android.HackLayoutInflater;
import com.limpoxe.fairy.core.compat.CompatForFragmentClassCache;
import com.limpoxe.fairy.core.compat.CompatForSupportv7ViewInflater;
import com.limpoxe.fairy.core.proxy.systemservice.AndroidAppIActivityManager;
import com.limpoxe.fairy.core.proxy.systemservice.AndroidAppINotificationManager;
import com.limpoxe.fairy.core.proxy.systemservice.AndroidAppIPackageManager;
import com.limpoxe.fairy.core.proxy.systemservice.AndroidOsServiceManager;
import com.limpoxe.fairy.core.proxy.systemservice.AndroidWebkitWebViewFactoryProvider;
import com.limpoxe.fairy.core.proxy.systemservice.AndroidWidgetToast;
import com.limpoxe.fairy.manager.PluginManagerHelper;
import com.limpoxe.fairy.manager.PluginManagerProviderClient;
import com.limpoxe.fairy.manager.mapping.StubActivityMappingProcessor;
import com.limpoxe.fairy.manager.mapping.StubReceiverMappingProcessor;
import com.limpoxe.fairy.manager.mapping.StubServiceMappingProcessor;
import com.limpoxe.fairy.util.FreeReflection;
import com.limpoxe.fairy.util.LogUtil;
import com.limpoxe.fairy.util.ProcessUtil;
public class PluginLoader {
private PluginLoader() {
}
/**
* 初始化loader, 只可调用一次
*
* @param app
*/
public static synchronized void initLoader(Application app) {
if (FairyGlobal.isInited()) {
return;
}
LogUtil.v("插件框架初始化中...");
long t1 = System.currentTimeMillis();
if (Build.VERSION.SDK_INT >= 28) {
boolean ret = FreeReflection.exemptAll(app);
LogUtil.v("hidden api exempt " + ret);
}
FairyGlobal.setApplication(app);
FairyGlobal.registStubMappingProcessor(new StubActivityMappingProcessor());
FairyGlobal.registStubMappingProcessor(new StubServiceMappingProcessor());
FairyGlobal.registStubMappingProcessor(new StubReceiverMappingProcessor());
//这里的isPluginProcess方法需要在安装AndroidAppIActivityManager之前执行一次。
//原因见AndroidAppIActivityManager的getRunningAppProcesses()方法
boolean isPluginProcess = ProcessUtil.isPluginProcess();
if(ProcessUtil.isPluginProcess()) {
AndroidOsServiceManager.installProxy();
AndroidWidgetToast.installProxy();
}
AndroidAppIActivityManager.installProxy();
AndroidAppINotificationManager.installProxy();
AndroidAppIPackageManager.installProxy(FairyGlobal.getHostApplication().getPackageManager());
if (isPluginProcess) {
HackLayoutInflater.installPluginCustomViewConstructorCache();
CompatForSupportv7ViewInflater.installPluginCustomViewConstructorCache();
CompatForFragmentClassCache.installFragmentClassCache();
CompatForFragmentClassCache.installSupportV4FragmentClassCache();
CompatForFragmentClassCache.installAndroidXFragmentClassCache();
//不可在主进程中同步安装,因为此时ActivityThread还没有准备好, 会导致空指针。
new Handler(Looper.getMainLooper()).post(new Runnable() {
@Override
public void run() {
AndroidWebkitWebViewFactoryProvider.installProxy();
}
});
}
PluginInjector.injectHandlerCallback();//本来宿主进程是不需要注入handlecallback的,这里加上是为了对抗360安全卫士等软件,提高Instrumentation的成功率
PluginInjector.injectInstrumentation();
PluginInjector.injectBaseContext(FairyGlobal.getHostApplication());
PluginInjector.injectAppComponentFactory();
if (isPluginProcess) {
if (Build.VERSION.SDK_INT >= 14) {
FairyGlobal.getHostApplication().registerActivityLifecycleCallbacks(new Application.ActivityLifecycleCallbacks() {
@Override
public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
}
@Override
public void onActivityStarted(Activity activity) {
}
@Override
public void onActivityResumed(Activity activity) {
}
@Override
public void onActivityPaused(Activity activity) {
}
@Override
public void onActivityStopped(Activity activity) {
}
@Override
public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
}
@Override
public void onActivityDestroyed(Activity activity) {
Intent intent = activity.getIntent();
if (intent != null && intent.getComponent() != null) {
LogUtil.v("回收绑定关系");
PluginManagerProviderClient.unBindLaunchModeStubActivity(intent.getComponent().getClassName(), activity.getClass().getName());
}
}
});
}
}
FairyGlobal.setIsInited(true);
long t2 = System.currentTimeMillis();
LogUtil.w("插件框架初始化完成", "耗时:" + (t2-t1));
}
public static Context fixBaseContextForReceiver(Context superApplicationContext) {
if (superApplicationContext instanceof ContextWrapper) {
return ((ContextWrapper)superApplicationContext).getBaseContext();
} else {
return superApplicationContext;
}
}
/**
* 根据插件中的classId加载一个插件中的class
*
* @param clazzId
* @return
*/
@SuppressWarnings("rawtypes")
public static Class loadPluginFragmentClassById(String clazzId) {
PluginDescriptor pluginDescriptor = PluginManagerHelper.getPluginDescriptorByFragmentId(clazzId);
if (pluginDescriptor != null) {
String clazzName = pluginDescriptor.getPluginClassNameById(clazzId);
return loadPluginClassByName(pluginDescriptor, clazzName);
} else {
LogUtil.e("PluginDescriptor Not Found for classId ", clazzId);
}
return null;
}
@SuppressWarnings("rawtypes")
public static Class loadPluginClassByName(String clazzName) {
PluginDescriptor pluginDescriptor = PluginManagerHelper.getPluginDescriptorByClassName(clazzName);
return loadPluginClassByName(pluginDescriptor, clazzName);
}
public static Class loadPluginClassByName(PluginDescriptor pluginDescriptor, String clazzName) {
if (pluginDescriptor != null && clazzName != null) {
//插件可能尚未初始化,确保使用前已经初始化
LoadedPlugin plugin = PluginLauncher.instance().startPlugin(pluginDescriptor);
if (plugin != null) {
return plugin.loadClassByName(clazzName);
} else {
LogUtil.e("Plugin is not running", clazzName);
}
} else {
LogUtil.e("loadPluginClass Fail for clazzName ", clazzName, pluginDescriptor==null?"pluginDescriptor = null":"pluginDescriptor not null");
}
return null;
}
/**
* 获取当前class所在插件的Context
* 每个插件只有1个DefaultContext,
* 是当前插件中所有class公用的Context
*
* @param clazz
* @return
*/
public static Context getDefaultPluginContext(@SuppressWarnings("rawtypes") Class clazz) {
Context pluginContext = null;
PluginDescriptor pluginDescriptor = PluginManagerHelper.getPluginDescriptorByClassName(clazz.getName());
if (pluginDescriptor != null) {
LoadedPlugin plugin = PluginLauncher.instance().getRunningPlugin(pluginDescriptor.getPackageName());
if (plugin != null) {
pluginContext = plugin.pluginContext;;
} else {
LogUtil.e("Plugin is not running", clazz.getName());
}
} else {
LogUtil.e("PluginDescriptor Not Found for ", clazz.getName());
}
if (pluginContext == null) {
LogUtil.e("Context Not Found for ", clazz.getName());
}
return pluginContext;
}
}
| limpoxe/Android-Plugin-Framework | FairyPlugin/src/main/java/com/limpoxe/fairy/core/PluginLoader.java | Java | mit | 8,547 |
/**
* @desc express config
* @author awwwesssooooome <chengpengcp9@gmail.com>
* @date 2015-09-21
*/
'use strict';
/**
* Module dependencies
*/
import express from 'express';
import cookieParser from 'cookie-parser';
import bodyParser from 'body-parser';
import favicon from 'serve-favicon';
import compression from 'compression';
import swig from 'swig';
import pkg from '../package.json';
/**
* Expose
*/
export default ((app) => {
// Compression middleware (should be placed before express.static)
app.use(compression({
threshold: 512
}));
// Set favicon
app.use(favicon(`${__dirname}/../public/favicon.ico`));
// Static files middleware
app.use(express.static(`${__dirname}/../public`));
// Set views path, template engine and default layout
app.engine('html', swig.renderFile);
app.set('views', `${__dirname}/../app/views`);
app.set('view engine', 'html');
// For development
app.set('view cache', false);
swig.setDefaults({ cache: false });
// Expose package.json to views
app.use((req, res, next) => {
res.locals.pkg = pkg;
res.locals.env = process.env.NODE_ENV || 'development';
next();
});
// bodyParser should be above methodOverride
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
// CookieParser should be above session
app.use(cookieParser());
//app.use(cookieSession({ secret: 'secret' }));
});
| playwolsey/Robin | config/express.js | JavaScript | mit | 1,492 |
<?php
/*
* This file is part of KoolKode Async.
*
* (c) Martin Schröder <m.schroeder2007@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
declare(strict_types = 1);
namespace KoolKode\Async\Concurrent\Filesystem;
use KoolKode\Async\Context;
use KoolKode\Async\Promise;
use KoolKode\Async\Success;
use KoolKode\Async\Concurrent\Pool\FileDescriptor;
use KoolKode\Async\Concurrent\Pool\FunctionCall;
use KoolKode\Async\Concurrent\Pool\MethodCall;
use KoolKode\Async\Concurrent\Pool\Pool;
use KoolKode\Async\Concurrent\Pool\SyncPool;
use KoolKode\Async\Filesystem\Filesystem;
use KoolKode\Async\Filesystem\FilesystemException;
use KoolKode\Async\Filesystem\TempStream;
use KoolKode\Async\Stream\ReadableStream;
/**
* Async filesystem based on a worker pool.
*
* @author Martin Schröder
*/
class PoolFilesystem implements Filesystem
{
/**
* Pool being used to generate temp file names.
*
* @var Pool
*/
protected $pool;
/**
* Is file descriptor transfer supported by the pool?
*
* @var bool
*/
protected $fileTransferSupported;
/**
* Create an async filesystem backed by the given worker pool.
*
* @param Pool $pool
*/
public function __construct(Pool $pool)
{
$this->pool = $pool;
$this->fileTransferSupported = \KOOLKODE_ASYNC_SCM_RIGHTS_SUPPORTED || $this->pool instanceof SyncPool;
}
/**
* {@inheritdoc}
*/
public function exists(Context $context, string $path): Promise
{
return $this->pool->submit($context, new FunctionCall('@file_exists', $path));
}
/**
* {@inheritdoc}
*/
public function size(Context $context, string $path): Promise
{
return $this->pool->submit($context, new MethodCall(static::class, 'sizeJob', $path));
}
/**
* Get size of a file on the local filesystem.
*
* @param string $path Absolute path to the file.
* @return int Filesize in bytes or 0 when the path does not exist or is not a regular file.
*/
protected static function sizeJob(string $path): int
{
if (\is_file($path)) {
return (int) @\filesize($path);
}
return 0;
}
/**
* {@inheritdoc}
*/
public function isFile(Context $context, string $path): Promise
{
return $this->pool->submit($context, new FunctionCall('@is_file', $path));
}
/**
* {@inheritdoc}
*/
public function isDir(Context $context, string $path): Promise
{
return $this->pool->submit($context, new FunctionCall('@is_dir', $path));
}
/**
* {@inheritdoc}
*/
public function scandir(Context $context, string $path): Promise
{
return $context->task($this->scandirTask($context, \rtrim(\str_replace([
'/',
'\\'
], \DIRECTORY_SEPARATOR, $path), \DIRECTORY_SEPARATOR)));
}
/**
* Scan the given directory for items.
*
* @param Context $context Async execution context.
* @param string $path Absolute path of the directory to be scanned.
* @return array Absolute paths of all scanned items.
*
* @throws FilesystemException When scanning the directory has failed.
*/
protected function scandirTask(Context $context, string $path): \Generator
{
$entries = yield $this->pool->submit($context, new MethodCall(static::class, 'scandirJob', $path));
if ($entries === null) {
throw new FilesystemException(\sprintf('Failed to scan directory: "%s"', $path));
}
return $entries;
}
/**
* Scan the given directory using sync fuctions.
*/
protected static function scandirJob(string $path): ?array
{
if (!\is_dir($path)) {
return null;
}
$entries = @\glob($path . \DIRECTORY_SEPARATOR . '*', \GLOB_NOSORT);
return ($entries === false) ? null : $entries;
}
/**
* {@inheritdoc}
*/
public function readStream(Context $context, string $path): Promise
{
return $context->task($this->readStreamTask($context, $path));
}
/**
* Open a file descriptor stream to be used for reading.
*
* @param Context $context Async execution context.
* @param string $path Absolute path to the target file.
* @return ReadableDescriptorStream Async readable file stream.
*/
protected function readStreamTask(Context $context, string $path): \Generator
{
if (!yield $this->pool->submit($context, new MethodCall(static::class, 'checkFileReadableJob', $path))) {
throw new FilesystemException(\sprintf('File is not readable: "%s"', $path));
}
if (!$this->fileTransferSupported) {
return new ReadableFileStream($this->pool, $path);
}
$file = yield $this->pool->submit($context, new MethodCall(FileDescriptor::class, 'open', $path, 'rb'));
return new ReadableDescriptorStream($this->pool, $path, $file);
}
/**
* Check if the given path is a regular file that is readable.
*/
protected static function checkFileReadableJob(string $path): bool
{
if (!\is_file($path) || !\is_readable($path)) {
return false;
}
return true;
}
/**
* {@inheritdoc}
*/
public function writeStream(Context $context, string $path): Promise
{
return $context->task($this->writeStreamTask($context, $path));
}
/**
* {@inheritdoc}
*/
public function appendStream(Context $context, string $path): Promise
{
return $context->task($this->writeStreamTask($context, $path, true));
}
/**
* {@inheritdoc}
*/
public function tempFile(Context $context, ReadableStream $stream, int $limit = 0x4000000): Promise
{
return $context->task(function (Context $context) use ($stream, $limit) {
try {
$file = yield $this->pool->submit($context, new FunctionCall('tempnam', \sys_get_temp_dir(), 'kkt'));
try {
$temp = yield $this->writeStream($context, $file);
$size = 0;
try {
while (null !== ($chunk = yield $stream->read($context))) {
if (($size + \strlen($chunk)) > $limit) {
throw new FilesystemException('Temp file size exceeded');
}
$size += yield $temp->write($context, $chunk);
}
} finally {
$temp->close();
}
} catch (\Throwable $e) {
yield $this->removeFile($context, $file);
throw $e;
}
} finally {
$stream->close();
}
return $file;
});
}
/**
* {@inheritdoc}
*/
public function tempStream(Context $context, int $memory = 0xFFFF, int $limit = 0x4000000): Promise
{
return new Success($context, new TempStream($context, $this, $memory, $limit));
}
/**
* {@inheritdoc}
*/
public function removeFile(Context $context, string $file): Promise
{
$promise = $this->pool->submit($context, new FunctionCall('@unlink', $file));
$promise->when(function ($e, $v = null) use ($file) {
if (!$v) {
@\unlink($file);
}
});
return $promise;
}
/**
* Open a file descriptor stream to be used for writing.
*
* @param Context $context Async execution context.
* @param string $path Absolute path to the target file.
* @return WritableDescriptorStream Async readable file stream.
*/
protected function writeStreamTask(Context $context, string $path, bool $append = false): \Generator
{
if (!yield $this->pool->submit($context, new MethodCall(static::class, 'checkFileWritableJob', $path, !$append && !$this->fileTransferSupported))) {
throw new FilesystemException(\sprintf('File is not writable: "%s"', $path));
}
if (!$this->fileTransferSupported) {
return new WritableFileStream($this->pool, $path);
}
$file = yield $this->pool->submit($context, new MethodCall(FileDescriptor::class, 'open', $path, $append ? 'ab' : 'wb'));
return new WritableDescriptorStream($this->pool, $path, $file);
}
/**
* Check if the given path is a regular file that is writable.
*/
protected static function checkFileWritableJob(string $path, bool $truncate = false): bool
{
if (\file_exists($path) && (!\is_file($path) || !\is_writable($path))) {
return false;
}
if ($truncate && \is_file($path)) {
@\ftruncate(@\fopen($path, 'wb'), 0);
}
return true;
}
}
| koolkode/async | src/Concurrent/Filesystem/PoolFilesystem.php | PHP | mit | 9,372 |
/***************************************************//**
* @file ProtocolFamilies.cpp
* @date February 2012
* @author Ocean Optics, Inc.
*
* This provides a way to get references to different kinds
* of features (e.g. spectrometer, TEC) generically.
*
* LICENSE:
*
* SeaBreeze Copyright (C) 2014, Ocean Optics Inc
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject
* to the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*******************************************************/
#include "common/globals.h"
#include "api/seabreezeapi/ProtocolFamilies.h"
/* Constants */
#define PROTOCOL_FAMILY_ID_UNDEFINED 0
#define PROTOCOL_FAMILY_ID_VIRTUAL 1
#define PROTOCOL_FAMILY_ID_OOI 2
#define PROTOCOL_FAMILY_ID_OCEAN_BINARY 3
#define PROTOCOL_FAMILY_ID_JAZ_MESSAGING 4
using namespace seabreeze;
using namespace seabreeze::api;
using namespace std;
seabreeze::api::ProtocolFamilies::ProtocolFamilies() {
}
seabreeze::api::ProtocolFamilies::~ProtocolFamilies() {
}
seabreeze::api::UndefinedProtocolFamily::UndefinedProtocolFamily()
: ProtocolFamily("Undefined", PROTOCOL_FAMILY_ID_UNDEFINED) {
}
seabreeze::api::UndefinedProtocolFamily::~UndefinedProtocolFamily() {
}
seabreeze::api::VirtualProtocolFamily::VirtualProtocolFamily()
: ProtocolFamily("Virtual", PROTOCOL_FAMILY_ID_VIRTUAL) {
}
seabreeze::api::VirtualProtocolFamily::~VirtualProtocolFamily() {
}
seabreeze::api::OOIProtocolFamily::OOIProtocolFamily()
: ProtocolFamily("OceanLegacyUSB", PROTOCOL_FAMILY_ID_OOI) {
}
seabreeze::api::OOIProtocolFamily::~OOIProtocolFamily() {
}
seabreeze::api::OceanBinaryProtocolFamily::OceanBinaryProtocolFamily()
: ProtocolFamily("OceanBinary", PROTOCOL_FAMILY_ID_OCEAN_BINARY) {
}
seabreeze::api::OceanBinaryProtocolFamily::~OceanBinaryProtocolFamily() {
}
seabreeze::api::JazMessagingProtocolFamily::JazMessagingProtocolFamily()
: ProtocolFamily("JazMessaging", PROTOCOL_FAMILY_ID_JAZ_MESSAGING) {
}
seabreeze::api::JazMessagingProtocolFamily::~JazMessagingProtocolFamily() {
}
vector<ProtocolFamily *> seabreeze::api::ProtocolFamilies::getAllProtocolFamilies() {
vector<ProtocolFamily *> retval;
/* This creates new instances of these so the class-wide fields do not risk
* having their const flags ignored.
*/
retval.push_back(new OOIProtocolFamily());
retval.push_back(new OceanBinaryProtocolFamily());
retval.push_back(new JazMessagingProtocolFamily());
retval.push_back(new VirtualProtocolFamily());
return retval;
}
| ap--/python-seabreeze | src/libseabreeze/src/api/seabreezeapi/ProtocolFamilies.cpp | C++ | mit | 3,549 |
# frozen_string_literal: true
describe RuboCop::Cop::Rails::IndexTrue, :config do
subject(:cop) { described_class.new(config) }
let(:source) do
<<-RUBY
class ExampleMigration < ActiveRecord::Migration
def change
#{code}
end
end
RUBY
end
shared_examples :accepts do |name, code|
let(:code) { code }
it "accepts usages of #{name}" do
inspect_source(cop, source)
expect(cop.offenses).to be_empty
end
end
shared_examples :offense do |name, code|
let(:code) { code }
it "registers an offense for #{name}" do
inspect_source(cop, source)
expect(cop.messages.any?).to eq(true)
end
end
context 'when add_column statement contains `index: true`' do
let(:code) do
'add_column :books, :author_id, :integer, index: true'
end
it 'adds an offense when an add_column statement contains `index: true`' do
expect_offense(<<-RUBY.strip_indent)
add_column :books, :author_id, :integer, index: true
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ `index: true` does not work in an `add_column` or `change_column` method. Please use `add_index :table, :column`.
RUBY
end
end
context 'when add_column statement does not contain `index: true`' do
let(:source) do
'add_column :books, :author_id, :integer'
end
it 'doest not add any offenses' do
expect_no_offenses(<<-RUBY.strip_indent)
add_column :books, :author_id, :integer
RUBY
end
end
context 'when change_column statement contains `index: true`' do
let(:code) do
'change_column :books, :author_id, :integer, index: true'
end
it 'adds an offense' do
expect_offense(<<-RUBY.strip_indent)
change_column :books, :author_id, :integer, index: true
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ `index: true` does not work in an `add_column` or `change_column` method. Please use `add_index :table, :column`.
RUBY
end
end
context 'when add_column statement does not contain `index: true`' do
let(:source) do
'change_column :books, :author_id, :integer'
end
it 'does not add any offenses' do
expect_no_offenses(<<-RUBY.strip_indent)
change_column :books, :author_id, :integer
RUBY
end
end
end
| alexcstark/rubocop | spec/rubocop/cop/rails/index_true_spec.rb | Ruby | mit | 2,354 |
package br.com.casadocodigo.redis.capitulo4.exemplo02;
import redis.clients.jedis.Jedis;
public class DefinirTempoExpiracaoDeSessaoDoUsuario {
public static void main(String[] args) {
String codigoDoUsuario = "1962";
String chave = "usuario:" + codigoDoUsuario + ":sessao";
int trintaMinutosEmSegundos = 1800;
Jedis jedis = new Jedis("localhost");
long resultado = jedis.expire(chave, trintaMinutosEmSegundos);
System.out.println(resultado);
}
}
| rlazoti/exemplos-livro-redis | src/main/java/br/com/casadocodigo/redis/capitulo4/exemplo02/DefinirTempoExpiracaoDeSessaoDoUsuario.java | Java | mit | 508 |
<?php
/**
* Copyright (C) 2013 Emay Komarudin
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* @author Emay Komarudin
*
**/
namespace Emayk\Ics\Repo\Factory\Order;
use Emayk\Ics\Models\BaseModel;
class Status extends BaseModel
{
protected $table = 'master_pr_status';
}
| emayk/ics | src/Emayk/Ics/Repo/Factory/Order/Status.php | PHP | mit | 880 |
/*
* Copyright (C) 2012 Google Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "core/html/shadow/HTMLShadowElement.h"
#include "HTMLNames.h"
#include "core/dom/shadow/ShadowRoot.h"
namespace WebCore {
class Document;
inline HTMLShadowElement::HTMLShadowElement(Document& document)
: InsertionPoint(HTMLNames::shadowTag, document)
{
ScriptWrappable::init(this);
}
PassRefPtr<HTMLShadowElement> HTMLShadowElement::create(Document& document)
{
return adoptRef(new HTMLShadowElement(document));
}
HTMLShadowElement::~HTMLShadowElement()
{
}
ShadowRoot* HTMLShadowElement::olderShadowRoot()
{
ShadowRoot* containingRoot = containingShadowRoot();
if (!containingRoot)
return 0;
document().updateDistributionForNodeIfNeeded(this);
ShadowRoot* older = containingRoot->olderShadowRoot();
if (!older || !older->shouldExposeToBindings() || older->shadowInsertionPointOfYoungerShadowRoot() != this)
return 0;
ASSERT(older->shouldExposeToBindings());
return older;
}
Node::InsertionNotificationRequest HTMLShadowElement::insertedInto(ContainerNode* insertionPoint)
{
if (insertionPoint->inDocument()) {
// Warn if trying to reproject between user agent and author shadows.
ShadowRoot* root = containingShadowRoot();
if (root && root->olderShadowRoot() && root->type() != root->olderShadowRoot()->type()) {
String message = String::format("<shadow> doesn't work for %s element host.", root->host()->tagName().utf8().data());
document().addConsoleMessage(RenderingMessageSource, WarningMessageLevel, message);
}
}
return InsertionPoint::insertedInto(insertionPoint);
}
} // namespace WebCore
| lordmos/blink | Source/core/html/shadow/HTMLShadowElement.cpp | C++ | mit | 3,228 |
var Type = function(Bookshelf) {
return Bookshelf.Model.extend({
tableName: 'types',
model: function() {
return this.belongsTo('model');
}
});
};
module.exports = Type;
| ericclemmons/bookshelf-manager | test/models/type.js | JavaScript | mit | 193 |
package com.medallia.word2vec;
import com.google.common.base.Function;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Iterables;
import com.google.common.primitives.Doubles;
import com.medallia.word2vec.util.Pair;
import java.nio.DoubleBuffer;
import java.util.Arrays;
import java.util.List;
/** Implementation of {@link Searcher} */
class SearcherImpl implements Searcher {
private final NormalizedWord2VecModel model;
private final ImmutableMap<String, Integer> word2vectorOffset;
SearcherImpl(final NormalizedWord2VecModel model) {
this.model = model;
final ImmutableMap.Builder<String, Integer> result = ImmutableMap.builder();
for (int i = 0; i < model.vocab.size(); i++) {
result.put(model.vocab.get(i), i * model.layerSize);
}
word2vectorOffset = result.build();
}
SearcherImpl(final Word2VecModel model) {
this(NormalizedWord2VecModel.fromWord2VecModel(model));
}
@Override public List<Match> getMatches(String s, int maxNumMatches) throws UnknownWordException {
return getMatches(getVector(s), maxNumMatches);
}
@Override public double cosineDistance(String s1, String s2) throws UnknownWordException {
return calculateDistance(getVector(s1), getVector(s2));
}
@Override public boolean contains(String word) {
return word2vectorOffset.containsKey(word);
}
@Override public List<Match> getMatches(final double[] vec, int maxNumMatches) {
return Match.ORDERING.greatestOf(
Iterables.transform(model.vocab, new Function<String, Match>() {
@Override
public Match apply(String other) {
double[] otherVec = getVectorOrNull(other);
double d = calculateDistance(otherVec, vec);
return new MatchImpl(other, d);
}
}),
maxNumMatches
);
}
public double calculateDistance(double[] otherVec, double[] vec) {
double d = 0;
for (int a = 0; a < model.layerSize; a++)
d += vec[a] * otherVec[a];
return d;
}
public double calculateDistance2(double[] otherVec, double[] vec) {
double d = 0;
for (int a = 0; a < model.layerSize; a++)
d += (vec[a] - otherVec[a]) * (vec[a] - otherVec[a]);
return d;
}
@Override public ImmutableList<Double> getRawVector(String word) throws UnknownWordException {
return ImmutableList.copyOf(Doubles.asList(getVector(word)));
}
/**
* @return Vector for the given word
* @throws UnknownWordException If word is not in the model's vocabulary
*/
private double[] getVector(String word) throws UnknownWordException {
final double[] result = getVectorOrNull(word);
if(result == null)
throw new UnknownWordException(word);
return result;
}
private double[] getVectorOrNull(final String word) {
final Integer index = word2vectorOffset.get(word);
if(index == null)
return null;
final DoubleBuffer vectors = model.vectors.duplicate();
double[] result = new double[model.layerSize];
vectors.position(index);
vectors.get(result);
return result;
}
/** @return Vector difference from v1 to v2 */
private double[] getDifference(double[] v1, double[] v2) {
double[] diff = new double[model.layerSize];
for (int i = 0; i < model.layerSize; i++)
diff[i] = v1[i] - v2[i];
return diff;
}
private double[] getSum(double[] v1, double[] v2) {
double[] sum = new double[model.layerSize];
for (int i = 0; i < model.layerSize; i++)
sum[i] = v1[i] + v2[i];
return sum;
}
private double[] getScaledVector(double[] v1, double k) {
double[] scaled = new double[model.layerSize];
for (int i = 0; i < model.layerSize; i++)
scaled[i] = v1[i] * k;
return scaled;
}
public double[] getVectorFrom3Words(String word1, String word2, String word3) {
try {
double[] v1 = getVector(word1);
double[] v2 = getVector(word2);
double[] diff1 = getDifference(v1, v2);
double[] v3 = getVector(word3);
double[] diff2 = getDifference(v3, diff1);
return diff2;
} catch(UnknownWordException ex) {
ex.printStackTrace();
}
return null;
}
public double[] getAverageVector(String[] words) {
double[] average = new double[model.layerSize];
for(int i = 0; i < model.layerSize; i++)
average[i] = 0;
int seqLength = 0;
try {
for(String word : words) {
// if(model.forSearch().contains(word)) {
double[] v = getVector(word);
average = getSum(v, average);
++ seqLength;
// }
}
} catch(UnknownWordException ex) {
ex.printStackTrace();
}
return getScaledVector(average, 1.0/(double)words.length);
}
@Override public SemanticDifference similarity(String s1, String s2) throws UnknownWordException {
double[] v1 = getVector(s1);
double[] v2 = getVector(s2);
final double[] diff = getDifference(v1, v2);
return new SemanticDifference() {
@Override public List<Match> getMatches(String word, int maxMatches) throws UnknownWordException {
double[] target = getDifference(getVector(word), diff);
return SearcherImpl.this.getMatches(target, maxMatches);
}
};
}
/** Implementation of {@link Match} */
private static class MatchImpl extends Pair<String, Double> implements Match {
private MatchImpl(String first, Double second) {
super(first, second);
}
@Override public String match() {
return first;
}
@Override public double distance() {
return second;
}
@Override public String toString() {
return String.format("%s [%s]", first, second);
}
}
}
| thanhnguyen12/Word2Vec | src/main/java/com/medallia/word2vec/SearcherImpl.java | Java | mit | 5,469 |
using System;
namespace Synergy.Contracts.Requirements
{
public class BusinessRuleViolationException : Exception
{
public Business.Requirement Requirement { get; }
public BusinessRuleViolationException(string message, Business.Requirement requirement) : base(message)
{
this.Requirement = requirement;
}
}
} | synergy-software/synergy.framework | Contracts/Synergy.Contracts/Requirements/BusinessRuleViolationException.cs | C# | mit | 368 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Sdl.Community.GroupShareKit.Helpers
{
public class ExpressionFieldValue
{
public string Name { get; set; }
public string Value { get; set; }
public string Operator { get; set; }
public override string ToString()
{
return "\"" + EscapeString(Name) + "\"" + Operator + "\"" + EscapeString(Value) + "\"";
}
public static string EscapeString(string expression)
{
string str;
var charactersToEscape = "\"\\";
if (!string.IsNullOrEmpty(expression) && !string.IsNullOrEmpty(charactersToEscape))
{
var stringBuilder = new StringBuilder();
for (int i = 0; i < expression.Length; i++)
{
char chr = expression[i];
if (charactersToEscape.IndexOf(chr) >= 0)
{
stringBuilder.Append("\\");
}
stringBuilder.Append(chr);
}
str = stringBuilder.ToString();
}
else
{
str = expression;
}
return str;
}
}
}
| sdl/groupsharekit.net | Sdl.Community.GroupShareKit/Helpers/ExpressionFieldValue.cs | C# | mit | 1,341 |
<?php
/*
* @author M2E Pro Developers Team
* @copyright M2E LTD
* @license Commercial use is forbidden
*/
class Ess_M2ePro_Model_Magento_Quote_Store_Configurator
{
/** @var $_quote Mage_Sales_Model_Quote */
protected $_quote = null;
/** @var $proxy Ess_M2ePro_Model_Order_Proxy */
protected $_proxyOrder = null;
/** @var $_taxConfig Mage_Tax_Model_Config */
protected $_taxConfig = null;
//########################################
public function init(Mage_Sales_Model_Quote $quote, Ess_M2ePro_Model_Order_Proxy $proxyOrder)
{
// we need clear singleton stored instances, because magento caches tax rates in private properties
Mage::unregister('_singleton/tax/calculation');
Mage::unregister('_resource_singleton/tax/calculation');
Mage::unregister('_singleton/sales/quote_address_total_collector');
$this->_quote = $quote;
$this->_proxyOrder = $proxyOrder;
$this->_taxConfig = Mage::getSingleton('tax/config');
}
//########################################
/**
* @return array
*/
public function getOriginalStoreConfig()
{
$keys = array(
Mage_Tax_Model_Config::CONFIG_XML_PATH_PRICE_INCLUDES_TAX,
Mage_Tax_Model_Config::CONFIG_XML_PATH_SHIPPING_INCLUDES_TAX,
Mage_Tax_Model_Config::CONFIG_XML_PATH_SHIPPING_TAX_CLASS,
Mage_Tax_Model_Config::CONFIG_XML_PATH_BASED_ON,
Mage_Customer_Model_Group::XML_PATH_DEFAULT_ID,
Mage_Weee_Helper_Data::XML_PATH_FPT_ENABLED,
$this->getOriginCountryIdXmlPath(),
$this->getOriginRegionIdXmlPath(),
$this->getOriginPostcodeXmlPath()
);
$config = array();
foreach ($keys as $key) {
$config[$key] = $this->getStoreConfig($key);
}
return $config;
}
//########################################
public function prepareStoreConfigForOrder()
{
// catalog prices
// ---------------------------------------
// reset flag, use store config instead
$this->_taxConfig->setNeedUsePriceExcludeTax(false);
$this->setStoreConfig(Mage_Tax_Model_Config::CONFIG_XML_PATH_PRICE_INCLUDES_TAX, $this->isPriceIncludesTax());
// ---------------------------------------
// shipping prices
// ---------------------------------------
$isShippingPriceIncludesTax = $this->isShippingPriceIncludesTax();
if (method_exists($this->_taxConfig, 'setShippingPriceIncludeTax')) {
$this->_taxConfig->setShippingPriceIncludeTax($isShippingPriceIncludesTax);
} else {
$this->setStoreConfig(
Mage_Tax_Model_Config::CONFIG_XML_PATH_SHIPPING_INCLUDES_TAX, $isShippingPriceIncludesTax
);
}
// ---------------------------------------
// Fixed Product Tax settings
// ---------------------------------------
if ($this->_proxyOrder->isTaxModeChannel() ||
($this->_proxyOrder->isTaxModeMixed() && $this->_proxyOrder->hasTax())
) {
$this->setStoreConfig(Mage_Weee_Helper_Data::XML_PATH_FPT_ENABLED, false);
}
// ---------------------------------------
// store origin address
// ---------------------------------------
$this->setStoreConfig($this->getOriginCountryIdXmlPath(), $this->getOriginCountryId());
$this->setStoreConfig($this->getOriginRegionIdXmlPath(), $this->getOriginRegionId());
$this->setStoreConfig($this->getOriginPostcodeXmlPath(), $this->getOriginPostcode());
// ---------------------------------------
// ---------------------------------------
$this->setStoreConfig(Mage_Customer_Model_Group::XML_PATH_DEFAULT_ID, $this->getDefaultCustomerGroupId());
$this->setStoreConfig(Mage_Tax_Model_Config::CONFIG_XML_PATH_BASED_ON, $this->getTaxCalculationBasedOn());
// ---------------------------------------
// store shipping tax class
// ---------------------------------------
$this->setStoreConfig(
Mage_Tax_Model_Config::CONFIG_XML_PATH_SHIPPING_TAX_CLASS, $this->getShippingTaxClassId()
);
// ---------------------------------------
}
//########################################
public function isPriceIncludesTax()
{
if ($this->_proxyOrder->isProductPriceIncludeTax() !== null) {
return $this->_proxyOrder->isProductPriceIncludeTax();
}
return (bool)$this->getStoreConfig(Mage_Tax_Model_Config::CONFIG_XML_PATH_PRICE_INCLUDES_TAX);
}
public function isShippingPriceIncludesTax()
{
if ($this->_proxyOrder->isShippingPriceIncludeTax() !== null) {
return $this->_proxyOrder->isShippingPriceIncludeTax();
}
return (bool)$this->getStoreConfig(Mage_Tax_Model_Config::CONFIG_XML_PATH_SHIPPING_INCLUDES_TAX);
}
//########################################
public function getShippingTaxClassId()
{
$proxyOrder = $this->_proxyOrder;
$hasRatesForCountry = Mage::getSingleton('M2ePro/Magento_Tax_Helper')
->hasRatesForCountry($this->_quote->getShippingAddress()->getCountryId());
$storeShippingTaxRate = Mage::getSingleton('M2ePro/Magento_Tax_Helper')
->getStoreShippingTaxRate($this->getStore());
$calculationBasedOnOrigin = Mage::getSingleton('M2ePro/Magento_Tax_Helper')
->isCalculationBasedOnOrigin($this->getStore());
$shippingPriceTaxRate = $proxyOrder->getShippingPriceTaxRate();
$isTaxSourceChannel = $proxyOrder->isTaxModeChannel()
|| ($proxyOrder->isTaxModeMixed() && $shippingPriceTaxRate > 0);
if ($proxyOrder->isTaxModeNone()
|| ($isTaxSourceChannel && $shippingPriceTaxRate <= 0)
|| ($proxyOrder->isTaxModeMagento() && !$hasRatesForCountry && !$calculationBasedOnOrigin)
) {
return Ess_M2ePro_Model_Magento_Product::TAX_CLASS_ID_NONE;
}
if ($proxyOrder->isTaxModeMagento()
|| $proxyOrder->getShippingPriceTaxRate() <= 0
|| $shippingPriceTaxRate == $storeShippingTaxRate
) {
return $this->_taxConfig->getShippingTaxClass($this->getStore());
}
// Create tax rule according to channel tax rate
// ---------------------------------------
/** @var $taxRuleBuilder Ess_M2ePro_Model_Magento_Tax_Rule_Builder */
$taxRuleBuilder = Mage::getModel('M2ePro/Magento_Tax_Rule_Builder');
$taxRuleBuilder->buildShippingTaxRule(
$shippingPriceTaxRate,
$this->_quote->getShippingAddress()->getCountryId(),
$this->_quote->getCustomerTaxClassId()
);
$taxRule = $taxRuleBuilder->getRule();
$productTaxClasses = $taxRule->getProductTaxClasses();
// ---------------------------------------
return array_shift($productTaxClasses);
}
//########################################
protected function getOriginCountryId()
{
$originCountryId = $this->getStoreConfig($this->getOriginCountryIdXmlPath());
if ($this->_proxyOrder->isTaxModeMagento()) {
return $originCountryId;
}
if ($this->_proxyOrder->isTaxModeMixed() && !$this->_proxyOrder->hasTax()) {
return $originCountryId;
}
if ($this->_proxyOrder->isTaxModeNone()
|| ($this->_proxyOrder->isTaxModeChannel() && !$this->_proxyOrder->hasTax())
) {
return '';
}
return $this->_quote->getShippingAddress()->getCountryId();
}
protected function getOriginRegionId()
{
$originRegionId = $this->getStoreConfig($this->getOriginRegionIdXmlPath());
if ($this->_proxyOrder->isTaxModeMagento()) {
return $originRegionId;
}
if ($this->_proxyOrder->isTaxModeMixed() && !$this->_proxyOrder->hasTax()) {
return $originRegionId;
}
if ($this->_proxyOrder->isTaxModeNone()
|| ($this->_proxyOrder->isTaxModeChannel() && !$this->_proxyOrder->hasTax())
) {
return '';
}
return $this->_quote->getShippingAddress()->getRegionId();
}
protected function getOriginPostcode()
{
$originPostcode = $this->getStoreConfig($this->getOriginPostcodeXmlPath());
if ($this->_proxyOrder->isTaxModeMagento()) {
return $originPostcode;
}
if ($this->_proxyOrder->isTaxModeMixed() && !$this->_proxyOrder->hasTax()) {
return $originPostcode;
}
if ($this->_proxyOrder->isTaxModeNone()
|| ($this->_proxyOrder->isTaxModeChannel() && !$this->_proxyOrder->hasTax())
) {
return '';
}
return $this->_quote->getShippingAddress()->getPostcode();
}
//########################################
protected function getDefaultCustomerGroupId()
{
$defaultCustomerGroupId = $this->getStoreConfig(Mage_Customer_Model_Group::XML_PATH_DEFAULT_ID);
if ($this->_proxyOrder->isTaxModeMagento()) {
return $defaultCustomerGroupId;
}
$currentCustomerTaxClass = Mage::getSingleton('tax/calculation')->getDefaultCustomerTaxClass($this->getStore());
$quoteCustomerTaxClass = $this->_quote->getCustomerTaxClassId();
if ($currentCustomerTaxClass == $quoteCustomerTaxClass) {
return $defaultCustomerGroupId;
}
// ugliest hack ever!
// we have to remove exist singleton instance from the Mage registry
// because Mage_Tax_Model_Calculation::getDefaultCustomerTaxClass() method stores the customer tax class
// after the first call in protected variable and then it doesn't care what store was given to it
Mage::unregister('_singleton/tax/calculation');
// default customer tax class depends on default customer group
// so we override store setting for this with the customer group from the quote
// this is done to make store & address tax requests equal
return $this->_quote->getCustomerGroupId();
}
//########################################
public function getTaxCalculationBasedOn()
{
$basedOn = $this->getStoreConfig(Mage_Tax_Model_Config::CONFIG_XML_PATH_BASED_ON);
if ($this->_proxyOrder->isTaxModeMagento()) {
return $basedOn;
}
if ($this->_proxyOrder->isTaxModeMixed() && !$this->_proxyOrder->hasTax()) {
return $basedOn;
}
return 'shipping';
}
//########################################
protected function getOriginCountryIdXmlPath()
{
// Magento 1.4.x backward compatibility
return @defined('Mage_Shipping_Model_Config::XML_PATH_ORIGIN_COUNTRY_ID')
? Mage_Shipping_Model_Config::XML_PATH_ORIGIN_COUNTRY_ID
: 'shipping/origin/country_id';
}
protected function getOriginRegionIdXmlPath()
{
// Magento 1.4.x backward compatibility
return @defined('Mage_Shipping_Model_Config::XML_PATH_ORIGIN_REGION_ID')
? Mage_Shipping_Model_Config::XML_PATH_ORIGIN_REGION_ID
: 'shipping/origin/region_id';
}
protected function getOriginPostcodeXmlPath()
{
// Magento 1.4.x backward compatibility
return @defined('Mage_Shipping_Model_Config::XML_PATH_ORIGIN_POSTCODE')
? Mage_Shipping_Model_Config::XML_PATH_ORIGIN_POSTCODE
: 'shipping/origin/postcode';
}
//########################################
protected function getStore()
{
return $this->_quote->getStore();
}
// ---------------------------------------
protected function setStoreConfig($key, $value)
{
$this->getStore()->setConfig($key, $value);
}
protected function getStoreConfig($key)
{
return $this->getStore()->getConfig($key);
}
//########################################
} | portchris/NaturalRemedyCompany | src/app/code/community/Ess/M2ePro/Model/Magento/Quote/Store/Configurator.php | PHP | mit | 12,176 |
#!/usr/bin/env python
##################################################################
# Imports
from __future__ import print_function
from random import random
import codecs
import numpy as np
import sys
##################################################################
# Variables and Constants
ENCODING = "utf-8"
POS = {"gut": None, "gute": None}
NEG = {"schlecht": None}
##################################################################
# Methods
def _get_vec_len(a_vec):
"""Return length of the vector
@param a_vec - vector whose length should be computed
@return vector's length
"""
return np.sqrt(sum([i**2 for i in a_vec]))
def _compute_eucl_distance(a_vec1, a_vec2):
"""Compute Euclidean distance between two vectors
@param a_vec1 - first vector
@param a_vec2 - second vector
@return squared Euclidean distance between two vectors
"""
return sum((a_vec1 - a_vec2)**2)
def compute_distance(a_vecs1, a_vecs2):
"""Compute Euclidean distance between all pairs of vectors
Compute \sum_{p^{+} \in P^{+}}\sum_{p^{-} \in P^{-}}||p^{+} - p^{-}||^{2}
@param a_vecs1 - set of positive vectors
@param a_vecs2 - set of negative vectors
@return squared Euclidean distance between all pairs of vectors
"""
return sum([_compute_eucl_distance(ivec1, ivec2) for ivec1 in a_vecs1 \
for ivec2 in a_vecs2])
def _project_vec(a_vec, a_norm, a_prj_line):
"""Project original vector on projection line
@param a_vec - vector whoch should e projected
@param a_norm - square length of projection line
@param a_prj_line - projection line
@return a_vec's projection on a_prj_line
"""
# print("_project_vec: a_vec =", repr(a_vec), file = sys.stderr)
# print("_project_vec: a_prj_line =", repr(a_prj_line), file = sys.stderr)
# print("_project_vec: a_norm =", repr(a_norm), file = sys.stderr)
# print("_project_vec: np.dot() =", repr(np.dot(a_vec, a_prj_line)), file = sys.stderr)
# print("_project_vec: projection =", \
# repr((np.dot(a_vec, a_prj_line) / a_norm) * a_prj_line), file = sys.stderr)
return (np.dot(a_vec, a_prj_line) / a_norm) * a_prj_line
def _project(a_pos_set, a_neg_set, a_prj_line):
"""Project original vector sets on the projection line
@param a_pos_set - set of positive vectors
@param a_neg_set - set of negative vectors
@param a_prj_line - projection line
@return 2-tuple with sets of projected positive and negative vectors
"""
idiv = sum(a_prj_line ** 2)
assert idiv != 0, "Projection vector cannot be zero vector."
vecs1 = [_project_vec(ivec, idiv, a_prj_line) for ivec in a_pos_set]
vecs2 = [_project_vec(ivec, idiv, a_prj_line) for ivec in a_neg_set]
return (vecs1, vecs2)
def _compute_gradient(a_pos_vecs, a_neg_vecs, a_prj_line):
"""Compute gradient of distance function wrt projection line
@param a_pos_vecs - set of positive vectors
@param a_neg_vecs - set of negative vectors
@param a_prj_line - current projection line
@return gradient vector
"""
print("a_prj_line = ", repr(a_prj_line), file=sys.stderr)
# zero-out the gradient vector
dot_prod = diff_vec = None
# prj_squared = a_prj_line ** 2
idiv = 1. # np.float128(sum(a_prj_line ** 2))
idiv_squared = 1. # idiv ** 2
# normalized_prj = a_prj_line / idiv
assert idiv != 0, "Projection vector cannot be zero vector."
gradient = np.array([0 for _ in a_prj_line])
for pos_vec in a_pos_vecs:
for neg_vec in a_neg_vecs:
diff_vec = pos_vec - neg_vec
dot_prod = np.dot(a_prj_line, diff_vec)
print("dot_prod = ", repr(dot_prod), file=sys.stderr)
print("idiv = ", repr(idiv), file=sys.stderr)
print("idiv_squared = ", repr(idiv_squared), file=sys.stderr)
# constant 0.5 below is a dirty hack
gradient += (dot_prod) * (diff_vec - dot_prod * a_prj_line)
# update = multi
# print("0) update =", repr(update), file = sys.stderr)
# update *= (pos_vec * idiv - 2 * np.dot(pos_vec, a_prj_line) * a_prj_line) / idiv_squared + \
# np.dot(pos_vec, a_prj_line) / idiv - \
# (neg_vec * idiv - 2 * np.dot(neg_vec, a_prj_line) * a_prj_line) / idiv_squared - \
# np.dot(neg_vec, a_prj_line) / idiv
# update *= (diff_vec * idiv - 2 * np.dot(a_prj_line, diff_vec) * a_prj_line) * a_prj_line / \
# idiv_squared + np.dot(a_prj_line, diff_vec)/idiv * ones
# print("1) update =", repr(update), file = sys.stderr)
# gradient += update
# since we have a quadratic function, the gradient has coefficient
# two
print("gradient =", repr(gradient), file=sys.stderr)
return 2 * gradient
def find_optimal_prj(a_dim):
"""Find projection line that maximizes distance between vectors
@param a_dim - dimension of vectors
@return 2-tuple with projection line and cost
"""
DELTA = 1e-10 # cost difference
ALPHA = 0.00001 # learning rate
n = 0 # current iteration
max_n = 100000 # maximum number of iterations
inf = float("inf")
ipos = ineg = None
prev_dist = dist = float(inf)
prj_line = np.array([np.float128(1.) for _ in xrange(a_dim)])
# prj_line = np.array([random() for i in xrange(a_dim)])
# gradient = np.array([1 for i in xrange(a_dim)])
while (prev_dist == inf or dist - prev_dist > DELTA) and n < max_n:
prev_dist = dist
# normalize length of projection line
prj_line /= _get_vec_len(prj_line)
# project word vectors on the guessed polarity line
# print("POS = ", repr(POS), file = sys.stderr)
# print("NEG = ", repr(NEG), file = sys.stderr)
ipos, ineg = _project(POS.itervalues(), NEG.itervalues(), prj_line)
# compute distance between posiive and negative vectors
# print("ipos = ", repr(ipos), file = sys.stderr)
# print("ineg = ", repr(ineg), file = sys.stderr)
dist = compute_distance(ipos, ineg)
print("prj_line before = ", prj_line, file = sys.stderr)
print("prev_dist = {:f}".format(prev_dist), file = sys.stderr)
print("dist = {:f}".format(dist), file = sys.stderr)
# update polarity line
prj_line += ALPHA * _compute_gradient(POS.itervalues(), NEG.itervalues(), \
prj_line)
print("prj_line after = ", prj_line, file = sys.stderr)
n += 1
if dist - prev_dist < DELTA:
print("Model converged: delta = {}".format(dist - prev_dist), file = sys.stderr)
return (prj_line, dist)
def parse_vecfile(a_fname):
"""Parse files containing word vectors
@param a_fname - name of the wordvec file
@return \c dimension of the vectors
"""
global POS, NEG
ivec = None
with codecs.open(a_fname, 'r', ENCODING) as ifile:
fnr = True
toks = None
for iline in ifile:
iline = iline.strip()
if fnr:
ndim = int(iline.split()[-1])
fnr = False
continue
elif not iline:
continue
toks = iline.split()
assert (len(toks) - 1) == ndim, "Wrong vector dimension: {:d}".format(\
len(toks) - 1)
if toks[0] in POS:
ivec = np.array([np.float128(i) for i in toks[1:]])
# ivec /= _get_vec_len(ivec)
POS[toks[0]] = ivec
elif toks[0] in NEG:
ivec = np.array([np.float128(i) for i in toks[1:]])
# ivec /= _get_vec_len(ivec)
NEG[toks[0]] = ivec
# prune words for which there were no vectors
POS = {iword: ivec for iword, ivec in POS.iteritems() if ivec is not None}
NEG = {iword: ivec for iword, ivec in NEG.iteritems() if ivec is not None}
return ndim
def main():
"""Main method for finding optimal projection line
@return square sum of the distances between positive and negative
words projected on the line
"""
import argparse
argparser = argparse.ArgumentParser()
argparser.add_argument("vec_file", help = "file containing vectors")
args = argparser.parse_args()
ndim = parse_vecfile(args.vec_file)
prj_line, ret = find_optimal_prj(ndim)
print("ret =", str(ret))
##################################################################
# Main
if __name__ == "__main__":
main()
| WladimirSidorenko/SentiLex | scripts/find_prj_line.py | Python | mit | 8,625 |
namespace PersistentPlanet
{
public class WindowFocusChangedEvent
{
public bool HasFocus { get; set; }
}
} | James226/persistent-planet | PersistentPlanet/WindowFocusChangedEvent.cs | C# | mit | 126 |
exports.BattleMovedex = {
//-----------------------------------------------------------------------------------------------
//Misc changes
//-----------------------------------------------------------------------------------------------
"shellsmash": {
inherit: true,
boosts: {
atk: 2,
spa: 2,
spe: 2,
def: -1,
spd: -1
},
onModifyMove: function(move, user) {
if (user.ability === 'shellarmor') {
move.boosts = {
spa: 1,
atk: 1,
spe: 2,
};
}
}
},
//-----------------------------------------------------------------------------------------------
//The freeze status was removed from the game entirely and replaced by flinch
//-----------------------------------------------------------------------------------------------
icebeam: {
inherit: true,
secondary: {
chance: 10,
volatileStatus: 'flinch'
}
},
icefang: {
inherit: true,
secondary: {
chance: 20,
volatileStatus: 'flinch'
}
},
icepunch: {
inherit: true,
secondary: {
chance: 10,
volatileStatus: 'flinch'
}
},
powdersnow: {
inherit: true,
secondary: {
chance: 10,
volatileStatus: 'flinch'
}
},
blizzard: {
inherit: true,
secondary: {
chance: 10,
volatileStatus: 'flinch'
}
},
triattack: {
inherit: true,
secondary: {
chance: 20,
onHit: function(target, source) {
var result = this.random(3);
if (result===0) {
target.trySetStatus('brn', source);
} else if (result===1) {
target.trySetStatus('par', source);
} else {
target.trySetStatus('tox', source);
}
}
}
},
//-----------------------------------------------------------------------------------------------
//Various nerfed moves
//-----------------------------------------------------------------------------------------------
thunder: {
inherit: true,
secondary: {
chance: 10
}
},
hurricane: {
inherit: true,
secondary: {
chance: 0
}
},
darkvoid: {
inherit: true,
target: "foes"
},
stealthrock: {
inherit: true,
effect: {
// this is a side condition
onStart: function(side) {
this.add('-sidestart',side,'move: Stealth Rock');
},
onSwitchIn: function(pokemon) {
var typeMod = this.getEffectiveness('Rock', pokemon);
var factor = 8;
if (typeMod == 1) factor = 4;
if (typeMod >= 2) factor = 4;
if (typeMod == -1) factor = 16;
if (typeMod <= -2) factor = 32;
var damage = this.damage(pokemon.maxhp/factor);
}
}
},
//-----------------------------------------------------------------------------------------------
//More good critting moves
//-----------------------------------------------------------------------------------------------
explosion: {
inherit: true,
basePower: 200,
willCrit: true
},
selfdestruct: {
inherit: true,
basePower: 125,
willCrit: true
},
twineedle: {
num: 41,
accuracy: 100,
basePower: 20,
willCrit: true,
category: "Physical",
desc: "Deals damage to one adjacent target and hits twice, with each hit having a 20% chance to poison it. If the first hit breaks the target's Substitute, it will take damage for the second hit.",
shortDesc: "Hits 2 times. Each hit has 20% chance to poison.",
id: "twineedle",
name: "Twineedle",
pp: 20,
priority: 0,
multihit: [2,2],
secondary: {
chance: 20,
status: 'psn'
},
target: "normal",
type: "Bug"
},
drillrun: {
inherit: true,
basePower: 40,
accuracy: 90,
willCrit: true
},
frostbreath: {
inherit: true,
power: 50,
accuracy: 100
},
stormthrow: {
inherit: true,
power: 50,
accuracy: 100
},
nightslash: {
inherit: true,
power: 50,
willCrit: true
},
//-----------------------------------------------------------------------------------------------
//Various buffs
//-----------------------------------------------------------------------------------------------
bulldoze: {
num: 523,
accuracy: 100,
basePower: 80,
category: "Physical",
desc: "Deals damage to all adjacent Pokemon with a 100% chance to lower their Speed by 1 stage each.",
shortDesc: "100% chance to lower adjacent Pkmn Speed by 1.",
id: "bulldoze",
name: "Bulldoze",
pp: 20,
priority: 0,
secondary: {
chance: 50,
boosts: {
spe: -1
}
},
target: "adjacent",
type: "Ground"
},
crosspoison: {
inherit: true,
basePower: 90
},
razorshell: {
inherit: true,
basePower: 100,
accuracy: 85
},
glaciate: {
inherit: true,
basePower: 100,
accuracy: 100,
secondary: {
chance: 50,
boosts: {
spe: -1
}
}
},
heatwave: {
inherit: true,
basePower: 90,
accuracy: 100,
secondary: {
chance: 0
},
basePowerCallback: function() {
if (this.isWeather('sunnyday')) {
return 120;
}
return 90;
}
},
poisontail: {
inherit: true,
basePower: 95
},
xscissor: {
inherit: true,
basePower: 90
},
rockslide: {
inherit: true,
basePower: 80,
accuracy: 100
},
stoneedge: {
inherit: true,
accuracy: 85
},
hammerarm: {
inherit: true,
secondary: {
chance: 20,
boosts: {
spe: -1
}
}
},
toxic: {
inherit: true,
accuracy: 100
},
willowisp: {
inherit: true,
accuracy: 100
},
acidspray: {
inherit: true,
target: "adjacent",
power: 70
},
relicsong: {
inherit: true,
secondary: {
chance: 20,
self: {
boosts: {
atk: 1,
spa: 1
}
}
}
},
honeclaws: {
inherit: true,
boosts: {
atk: 1,
accuracy: 2
}
},
shadowpunch: {
inherit: true,
basePower: 85
},
wildcharge: {
inherit: true,
basePower: 100,
},
nightdaze: {
inherit: true,
basePower: 90,
accuracy: 100,
secondary: {
chance: 20,
boosts: {
accuracy: -1
}
}
},
meditate: {
inherit: true,
boosts: {
atk: 1,
spd: 1
}
},
//-----------------------------------------------------------------------------------------------
//Massively changed moves that are pretty much new ones
//-----------------------------------------------------------------------------------------------
"lockon": {
num: 199,
accuracy: true,
basePower: 0,
category: "Status",
desc: "On the following turn, one adjacent target cannot avoid the user's moves, even if the target is in the middle of a two-turn move. Fails if the user tries to use this move again during effect.",
shortDesc: "User's next move will not miss the target.",
id: "lockon",
name: "Lock-On",
pp: 5,
priority: 0,
self: {
boosts: {
spa: 1,
accuracy: 1
}
},
secondary: false,
target: "self",
type: "Normal"
},
lunardance: {
num: 461,
accuracy: true,
basePower: 0,
category: "Status",
desc: "The user faints and the Pokemon brought out to replace it has its HP and PP fully restored along with having any major status condition cured. Fails if the user is the last unfainted Pokemon in its party.",
shortDesc: "User faints. Replacement is fully healed, with PP.",
id: "lunardance",
isViable: true,
name: "Lunar Dance",
pp: 20,
priority: 0,
isSnatchable: true,
boosts: {
spa: 1,
spe: 1
},
secondary: false,
target: "self",
type: "Psychic"
},
rage: {
inherit: true,
basePower: 100,
onHit: function(target, source) {
source.addVolatile('confusion');
}
},
poisonjab: {
inherit: true,
basePower: 40,
priority: 1,
secondary: {
chance: 0
}
},
skyattack: {
num: 143,
accuracy: 90,
basePower: 100,
category: "Physical",
desc: "Deals damage to one adjacent or non-adjacent target with a 30% chance to flinch it and a higher chance for a critical hit. This attack charges on the first turn and strikes on the second. The user cannot make a move between turns. If the user is holding a Power Herb, the move completes in one turn.",
shortDesc: "Charges, then hits turn 2. 30% flinch. High crit.",
id: "skyattack",
name: "Sky Attack",
pp: 15,
isViable: true,
priority: 0,
isTwoTurnMove: false,
isContact: true,
secondary: {
chance: 20,
boosts: {
def: -1
}
},
target: "any",
type: "Flying"
},
electroweb: {
inherit: true,
accuracy: 85,
basePower: 70,
secondary: {
chance: 100,
status: 'par'
}
},
payday: {
inherit: true,
basePower: 25,
multihit: [2,5]
},
barrage: {
inherit: true,
basePower: 25,
type: "Fighting",
multihit: [2,5]
},
doubleslap: {
inherit: true,
basePower: 40,
type: "Fighting",
multihit: [2,2]
},
"hydrocannon": {
num: 308,
accuracy: 100,
basePower: 150,
category: "Special",
desc: "Deals damage to one adjacent target. If this move is successful, the user must recharge on the following turn and cannot make a move.",
shortDesc: "User cannot move next turn.",
id: "hydrocannon",
name: "Hydro Cannon",
pp: 20,
priority: -3,
beforeTurnCallback: function(pokemon) {
pokemon.addVolatile('hydrocannon');
this.add('-message', pokemon.name+" is focusing it's aim!");
},
beforeMoveCallback: function(pokemon) {
if (!pokemon.removeVolatile('hydrocannon')) {
return false;
}
if (pokemon.lastAttackedBy && pokemon.lastAttackedBy.damage && pokemon.lastAttackedBy.thisTurn) {
this.add('cant', pokemon, 'flinch', 'Hydro Cannon');
return true;
}
},
effect: {
duration: 1,
onStart: function(pokemon) {
this.add('-singleturn', pokemon, 'move: Hydro Cannon');
}
},
secondary: false,
target: "normal",
type: "Water"
},
"blastburn": {
inherit: true,
accuracy: 100,
basePower: 60,
pp: 5,
willCrit: true,
selfdestruct: true,
secondary: {
chance: 100,
status: 'brn'
},
target: "allAdjacent",
self: false
},
"frenzyplant": {
inherit: true,
accuracy: 80,
basePower: 100,
category: "Physical",
pp: 5,
volatileStatus: 'partiallytrapped',
self: false
},
"triplekick": {
inherit: true,
basePowerCallback: function(pokemon) {
pokemon.addVolatile('triplekick');
return 5 + (10 * pokemon.volatiles['triplekick'].hit);
},
accuracy: 100
},
"dualchop": {
inherit: true,
accuracy: 100
},
"bonerush": {
inherit: true,
accuracy: 100
},
"feint": {
inherit: true,
basePower: 65
},
"spikecannon": {
num: 131,
accuracy: 80,
basePower: 60,
category: "Physical",
desc: "Deals damage to one adjacent target and hits two to five times. Has a 35% chance to hit two or three times, and a 15% chance to hit four or five times. If one of the hits breaks the target's Substitute, it will take damage for the remaining hits. If the user has the Ability Skill Link, this move will always hit five times.",
shortDesc: "Hits 2-5 times in one turn.",
id: "spikecannon",
name: "Spike Cannon",
pp: 15,
priority: 0,
secondary: false,
sideCondition: 'spikes',
target: "normal",
type: "Ground"
},
"gastroacid": {
inherit: true,
basePower: 50,
category: "Special",
isBounceable: false
},
"naturepower": {
inherit: true,
basePower: 80,
accuracy: 100,
priority: 0,
category: "Physical",
target: "normal",
type: "Ground",
onHit: false,
onModifyMove: function(move, source, target) {
if (source.hasType('Grass')) {
move.basePower = 100;
}
}
},
"electroweb": {
inherit: true,
target: "normal",
},
"leechseed": {
inherit: true,
accuracy: 100,
}
};
| DreMZ/PS | mods/duskmod/moves.js | JavaScript | mit | 18,661 |
<?php
return array(
/*
|--------------------------------------------------------------------------
| Workbench Author Name
|--------------------------------------------------------------------------
|
| When you create new packages via the Artisan "workbench" command your
| name is needed to generate the composer.json file for your package.
| You may specify it now so it is used for all of your workbenches.
|
*/
'name' => 'Marie Hogebrandt',
/*
|--------------------------------------------------------------------------
| Workbench Author E-Mail Address
|--------------------------------------------------------------------------
|
| Like the option above, your e-mail address is used when generating new
| workbench packages. The e-mail is placed in your composer.json file
| automatically after the package is created by the workbench tool.
|
*/
'email' => 'iam@mariehogebrandt.se',
);
| Melindrea/mhcm | app/config/workbench.php | PHP | mit | 987 |
<?php
namespace WowzaRestApi;
class WowzaApplicationSettings
{
public $name;
public $modules = array();
public function __construct($object = null)
{
if (!is_null($object) && is_object($object)) {
$this->modules = array();
foreach ($object->modules->moduleList as $module) {
$this->modules[] = new WowzaModule($module);
}
}
}
} | keyanmca/wowzarestapiclient | src/WowzaApplicationSettings.php | PHP | mit | 417 |
<?php
/*
* 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.
*/
/**
* Description of Stocks
*
* @author rjgodia
*/
class Stocks extends MY_Model
{
//put your code here
function __construct()
{
parent:: __construct('Stocks', 'Value');
}
} | Rawrisaur/comp4711asn1 | application/models/Stocks.php | PHP | mit | 394 |
<?php
namespace ApiGateway;
use ApiGateway\ApiModel;
use ApiGateway\Config\BaseConfig;
use ApiGateway\Config\ArrayConfig;
use ApiGateway\ClassSerialize;
use ApiGateway\Constants;
use ApiGateway\Auth\Signature;
use ApiGateway\Http\HttpHelper;
use ApiGateway\Exception\ServerException;
/**
* Api Service
*
* @author eddycjy <313687982@qq.com>
* @license MIT
*/
class ApiService
{
use ClassSerialize;
//请求路径
protected $url;
//请求参数
protected $params;
public function __construct(ApiModel $modelObject, BaseConfig $configObject = null)
{
if($configObject == null)
{
$configObject = new ArrayConfig();
}
$this->params = $this->getRequestModelParams($modelObject) + $this->getRequestConfigParams($configObject);
$this->url = $this->getRequestUrl($configObject->getRegionHost(), $this->params, $configObject->getAccessKeySecret());
}
/**
* 发起GET请求和解析结果
*
* @param string $format 解析格式
* @return json/xml
*/
public function get($format = Constants::JSON_FORMAT)
{
$response = HttpHelper::curl($this->url);
$body = $this->parseResponse($response->getBody(), $format);
if($response->isSuccess() == false)
{
throw new ServerException($body['Message'], $body['Code'], $response->getStatus(), $body['RequestId']);
}
return $body;
}
/**
* 执行结果解析
*
* @param json/xml $response 请求结果
* @param string $format 解析格式
* @return json/xml
*/
private function parseResponse($body, $format)
{
if ($format == Constants::JSON_FORMAT)
{
$body = json_decode($body, true);
}
else if ($format == Constants::XML_FORMAT)
{
$body = @simplexml_load_string($body);
}
return $body;
}
/**
* 获取请求Model参数
*
* @param object $modelObject Model对象属性
* @return array
*/
private function getRequestModelParams($modelObject)
{
return $this->toArray($modelObject);
}
/**
* 获取请求Config参数
*
* @param object $configObject Config对象属性
* @return array
*/
private function getRequestConfigParams($configObject)
{
return [
'AccessKeyId' => $configObject->getAccessKeyId(),
'AccessKeySecret' => $configObject->getAccessKeySecret(),
'Format' => $configObject->getFormat(),
'Version' => $configObject->getVersion(),
'SignatureMethod' => $configObject->getSignatureMethod(),
'SignatureVersion' => $configObject->getSignatureVersion(),
'SignatureNonce' => $configObject->getSignatureNonce(),
'Timestamp' => $configObject->getTimestamp(),
];
}
/**
* 获取请求路径
*
* @param string $host 域名
* @param array $params 请求参数
* @param string $secret 密钥
* @return string
*/
private function getRequestUrl($host, $params, $secret)
{
$paramString = "";
foreach($params as $key => $value)
{
$paramString .= urlencode($key) . "=" . urlencode($value) . "&";
}
$result = $host . "/?" . $paramString . "Signature=" . $this->getSignature("GET", $params, $secret . "&");
return $result;
}
/**
* 获取签名
*
* @param string $method 方法
* @param array $params 请求参数
* @param string $secret 密钥
* @return string
*/
private function getSignature($method, $params, $secret)
{
$object = new Signature();
return $object->getSignature($method, $params, $secret);
}
} | EDDYCJY/aliyun-api-gateway-sdk | src/ApiService.php | PHP | mit | 3,688 |
<?php
/**
* Carpus Friendly Password Generator.
*
* The Carpus Friendly Password Generator uses a quantitative typing effort model to generate secure
* passwords that are measurably easy-to-type (a.k.a. carpus friendly) on standard QWERTY keyboards.
* Typing effort of the generated passwords is calculated based on the CarpalX Typing Effort Model
* <http://mkweb.bcgsc.ca/carpalx/?typing_effort>. Some of the logic used in CFPG was derived from
* code in CarpalX which is copyright 2002-2009 Martin Krzywinski <martink@bcgsc.ca>.
*
* PHP version 5
*
* @author Jonathan Robson <jnrbsn@gmail.com>
* @copyright 2011 Jonathan Robson
* @license MIT License http://gist.github.com/802399
* @link http://github.com/jnrbsn/cfpg
*/
/**
* Generates a secure, easy-to-type password for QWERTY keyboards.
*
* @param integer $length The number of characters to be in the password.
* @param float $maxEffort The maximum typing effort the password should have.
* @param boolean $returnEffort Whether or not to return the typing effort along with the password.
*
* @return mixed The password or an array containing the password and the effort if $returnEffort
* is set to true.
*/
function cfpg($length=8, $maxEffort=4.362, $returnEffort=false)
{
// Pool of characters from which to generate the password.
$pool = 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnpqrstuvwxyz123456789!@#$%^&*()-=[];,./_+{}:<>?';
// Shift key map. "~" is left shift. "|" is right shift.
$shiftMap = array(
'!' => '~1', '@' => '~2', '#' => '~3', '$' => '~4', '%' => '~5', '^' => '~6', '&' => '|7',
'*' => '|8', '(' => '|9', ')' => '|0', '_' => '|-', '+' => '|=', 'Q' => '~q', 'W' => '~w',
'E' => '~e', 'R' => '~r', 'T' => '~t', 'Y' => '|y', 'U' => '|u', 'P' => '|p', '{' => '|[',
'}' => '|]', 'A' => '~a', 'S' => '~s', 'D' => '~d', 'F' => '~f', 'G' => '~g', 'H' => '|h',
'J' => '|j', 'K' => '|k', 'L' => '|l', ':' => '|;', 'Z' => '~z', 'X' => '~x', 'C' => '~c',
'V' => '~v', 'B' => '~b', 'N' => '|n', 'M' => '|m', '<' => '|,', '>' => '|.', '?' => '|/',
);
// Each element: key => array(distance, penalty, hand, row, finger).
$keyData = array(
'1' => array(5, 3.2606, 0, 0, 1), '2' => array(4, 3.2606, 0, 0, 1),
'3' => array(4, 1.9632, 0, 0, 2), '4' => array(4, 1.9632, 0, 0, 3),
'5' => array(3.5, 1.9632, 0, 0, 3), '6' => array(4.5, 1.9632, 0, 0, 3),
'7' => array(4, 1.9632, 1, 0, 6), '8' => array(4, 1.9632, 1, 0, 7),
'9' => array(4, 1.9632, 1, 0, 7), '0' => array(4, 3.2606, 1, 0, 8),
'-' => array(4, 4.558, 1, 0, 9), '=' => array(4.5, 4.558, 1, 0, 9),
'q' => array(2, 3.2492, 0, 1, 0), 'w' => array(2, 1.9518, 0, 1, 1),
'e' => array(2, 0.6544, 0, 1, 2), 'r' => array(2, 0.6544, 0, 1, 3),
't' => array(2.5, 0.6544, 0, 1, 3), 'y' => array(3, 0.6544, 1, 1, 6),
'u' => array(2, 0.6544, 1, 1, 6), 'i' => array(2, 0.6544, 1, 1, 7),
'p' => array(2, 3.2492, 1, 1, 9), '[' => array(2.5, 3.2492, 1, 1, 9),
']' => array(4, 3.2492, 1, 1, 9), 'a' => array(0, 2.5948, 0, 2, 0),
's' => array(0, 1.2974, 0, 2, 1), 'd' => array(0, 0, 0, 2, 2),
'f' => array(0, 0, 0, 2, 3), 'g' => array(2, 0, 0, 2, 3),
'h' => array(2, 0, 1, 2, 6), 'j' => array(0, 0, 1, 2, 6),
'k' => array(0, 0, 1, 2, 7), 'l' => array(0, 1.2974, 1, 2, 8),
';' => array(0, 2.5948, 1, 2, 9), 'z' => array(2, 3.9036, 0, 3, 0),
'x' => array(2, 2.6062, 0, 3, 1), 'c' => array(2, 1.3088, 0, 3, 2),
'v' => array(2, 1.3088, 0, 3, 3), 'b' => array(3.5, 1.3088, 0, 3, 3),
'n' => array(2, 1.3088, 1, 3, 6), 'm' => array(2, 1.3088, 1, 3, 6),
',' => array(2, 1.3088, 1, 3, 7), '.' => array(2, 2.6062, 1, 3, 8),
'/' => array(2, 3.9036, 1, 3, 9), '~' => array(4, 3.9036, 0, 3, 0),
'|' => array(4, 3.9036, 1, 3, 9),
);
// Generate the first draft of the password.
$password = '';
for ($i = 0; $i < $length; ++$i) {
$password .= $pool[mt_rand(0, 82)];
}
// This will store cached effort calculations for triads to improve efficiency.
$effortCache = array();
do {
// Replace a random character in the password.
$password[mt_rand() % $length] = $pool[mt_rand(0, 82)];
// Translate all the keys that need shift.
$keys = strtr($password, $shiftMap);
// Get the total number of triads.
$numTriads = strlen($keys) - 2;
// This will store the overall effort of the password.
$totalEffort = 0;
for ($i = 0; $i < $numTriads; ++$i) {
$c1 = $keys[$i];
$c2 = $keys[$i + 1];
$c3 = $keys[$i + 2];
$triad = $c1.$c2.$c3;
if (isset($effortCache[$triad])) {
// Don't calculate the effort of this triad if we already know it.
$totalEffort += $effortCache[$triad];
continue;
}
// Base distances and penalties.
$triadEffort = 0.3555 * $keyData[$c1][0] *
(1 + 0.367 * $keyData[$c2][0] * (1 + 0.235 * $keyData[$c3][0]));
$triadEffort += 0.6423 * $keyData[$c1][1] *
(1 + 0.367 * $keyData[$c2][1] * (1 + 0.235 * $keyData[$c3][1]));
// Hand penalty calculation.
if ($keyData[$c1][2] == $keyData[$c3][2]) {
if ($keyData[$c2][2] == $keyData[$c3][2]) {
// Same hand.
$pHand = 2;
} else {
// Alternating.
$pHand = 1;
}
} else {
// Both used, not alternating.
$pHand = 0;
}
// Row penalty calculation.
$row1 = $keyData[$c1][3];
$row2 = $keyData[$c2][3];
$row3 = $keyData[$c3][3];
$dr = array($row1 - $row2, $row1 - $row3, $row2 - $row3);
$drAbs = array(abs($dr[0]), abs($dr[1]), abs($dr[2]));
arsort($drAbs);
// Max delta row absolute value.
$drMaxAbs = reset($drAbs);
// Max delta row.
$drMax = $dr[key($drAbs)];
unset($dr, $drAbs);
if ($row1 < $row2) {
if ($row3 == $row2) {
// Downward progression with repetition: 1 < 2 = 3.
$pRow = 1;
} else if ($row2 < $row3) {
// Downward progression: 1 < 2 < 3.
$pRow = 4;
} else if ($drMaxAbs == 1) {
$pRow = 3;
} else {
// All/some different; delta row > 1.
if ($drMax < 0) {
$pRow = 7;
} else {
$pRow = 5;
}
}
} else if ($row1 > $row2) {
if ($row3 == $row2) {
// Upward progression with repetition: 1 > 2 = 3.
$pRow = 2;
} else if ($row2 > $row3) {
// Upward progression: 1 > 2 > 3.
$pRow = 6;
} else if ($drMaxAbs == 1) {
$pRow = 3;
} else {
if ($drMax < 0) {
$pRow = 7;
} else {
$pRow = 5;
}
}
} else {
if ($row2 > $row3) {
// Upward progression with repetition: 1 = 2 > 3.
$pRow = 2;
} else if ($row2 < $row3) {
// Downward progression with repetition: 1 = 2 < 3.
$pRow = 1;
} else {
// All same.
$pRow = 0;
}
}//end if
unset($drMax, $drMaxAbs);
// Finger penalty calculation.
$finger1 = $keyData[$c1][4];
$finger2 = $keyData[$c2][4];
$finger3 = $keyData[$c3][4];
if ($finger1 > $finger2) {
if ($finger2 > $finger3) {
// Monotonic; all different: 1 > 2 > 3.
$pFinger = 0;
} else if ($finger2 == $finger3) {
// Monotonic; some different: 1 > 2 = 3.
if ($c2 == $c3) {
$pFinger = 1;
} else {
$pFinger = 6;
}
} else if ($finger3 == $finger1) {
$pFinger = 4;
} else if ($finger1 > $finger3 && $finger3 > $finger2) {
// Rolling.
$pFinger = 2;
} else {
// Not monotonic; all different.
$pFinger = 3;
}
} else if ($finger1 < $finger2) {
if ($finger2 < $finger3) {
// Monotonic; all different: 1 < 2 < 3.
$pFinger = 0;
} else if ($finger2 == $finger3) {
if ($c2 == $c3) {
// Monotonic; some different: 1 < 2 = 3.
$pFinger = 1;
} else {
$pFinger = 6;
}
} else if ($finger3 == $finger1) {
// Not monotonic; some different: 1 = 3 < 2.
$pFinger = 4;
} else if ($finger1 < $finger3 && $finger3 < $finger2) {
// Rolling.
$pFinger = 2;
} else {
// Not monotonic; all different.
$pFinger = 3;
}
} else if ($finger1 == $finger2) {
if ($finger2 < $finger3 || $finger3 < $finger1) {
// Monotonic; some different: 1 = 2 < 3, 3 < 1 = 2.
if ($c1 == $c2) {
$pFinger = 1;
} else {
$pFinger = 6;
}
} else if ($finger2 == $finger3) {
if ($c1 != $c2 && $c2 != $c3 && $c1 != $c3) {
$pFinger = 7;
} else {
// All same.
$pFinger = 5;
}
}
}//end if
// Stroke path effort.
$triadEffort += 0.4268 * ($pHand + 0.3 * $pRow + 0.3 * $pFinger);
$effortCache[$triad] = $triadEffort;
$totalEffort += $triadEffort;
}//end for
$totalEffort = $totalEffort / $numTriads;
} while ($totalEffort > $maxEffort
|| !preg_match('/[0-9]/', $password)
|| !preg_match('/[A-Z]/', $password)
|| !preg_match('/[a-z]/', $password)
|| !preg_match('/[^0-9A-Za-z]/', $password));
if ($returnEffort === true) {
return array($password, round($totalEffort, 1));
} else {
return $password;
}
}//end cfpg()
| jnrbsn/cfpg | cfpg.php | PHP | mit | 11,278 |
package org.shkim.codility.lesson.countingelement;
public class FrogRiverOne
{
public static int solution(int X, int A[])
{
int step = X;
int temp[] = new int[step];
for (int i = 0; i < temp.length; i++)
{
temp[i] = i+1;
}
for (int i = 0; i < A.length; i++)
{
if (A[i] > X || temp[A[i]-1] != 0)
{
temp[A[i]-1] = 0;
step --;
}
if (step == 0)
{
return i;
}
}
return -1;
}
}
| KimSiHun/codility | src/org/shkim/codility/lesson/countingelement/FrogRiverOne.java | Java | mit | 437 |
// Admin main
//
// This is the main execution loop of the admin panel. It provides basic
// configuration, routing, and default imports.
require.config({
paths: {
'jquery': 'lib/jquery-1.10.2.min',
'underscore': 'lib/underscore',
'backbone': 'lib/backbone',
'require-css': 'lib/require-css.min',
'require-text': 'lib/require-text',
'pure-min': '//yui.yahooapis.com/pure/0.5.0/pure-min',
'pure-responsive': '//yui.yahooapis.com/pure/0.5.0/grids-responsive-min'
},
shim: {
jquery: {
exports: '$'
},
underscore: {
exports: '_'
},
backbone: {
deps: ['jquery', 'underscore'],
exports: 'Backbone'
}
},
map: {
'*': {
'css': 'require-css',
'text': 'require-text'
}
}
});
require(
[
'jquery',
'backbone',
'css!pure-min',
'css!pure-responsive',
'css!styles/base'
], function($, Backbone) {
var
add_app_header = function(xhr) {
xhr.setRequestHeader(
'x-peanuts-application',
'6752e4b0-8122-4c9a-ad1d-19d703fdfed0'
);
};
// The whole thing is wrapped in the success callback of a GET request for the
// CSRF token. This is necessary since all requests to the peanuts API will
// fail without it.
$.ajax({
url: '/csrf/',
beforeSend: add_app_header,
success: function(data) {
var
add_csrf_token = function(xhr) {
xhr.setRequestHeader(
'x-peanuts-csrf',
data.csrf
);
},
Router = Backbone.Router.extend({
routes: {
'first-use': 'firstUse'
},
render: function(controllerFile) {
var router = this;
require([controllerFile], function(controller) {
router.view = controller();
router.view.render();
$(document).prop(
'title',
$(document).prop('title') + ' - ' + router.view.title
);
});
},
firstUse: function() {
this.render('views/first-use');
}
}),
router = new Router(),
// The old backbone.sync method is retreived here so that the new one
// can call it.
old_sync = Backbone.sync;
// We redefine the global app header here to add in the csrf token.
Backbone.sync = function(method, model, options) {
var beforeSend = options.beforeSend;
options.beforeSend = function(xhr) {
add_app_header(xhr);
add_csrf_token(xhr);
if (beforeSend) {
beforeSend(xhr);
}
};
// Call the default method with our modified options.
old_sync(method, model, options);
};
Backbone.history.start();
}
});
});
| astex/peanuts.admin | static/main.js | JavaScript | mit | 2,817 |
package fr.loganbraga.hogwash.Generator;
public interface Generator {
public String generate();
}
| loganbraga/hogwash | src/main/java/fr/loganbraga/hogwash/Generator/Generator.java | Java | mit | 102 |
import _plotly_utils.basevalidators
class ArrayminussrcValidator(_plotly_utils.basevalidators.SrcValidator):
def __init__(
self, plotly_name="arrayminussrc", parent_name="bar.error_y", **kwargs
):
super(ArrayminussrcValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
edit_type=kwargs.pop("edit_type", "none"),
**kwargs
)
| plotly/plotly.py | packages/python/plotly/plotly/validators/bar/error_y/_arrayminussrc.py | Python | mit | 429 |
module ActiveRecord
class HasManyThroughAssociationNotFoundError < ActiveRecordError #:nodoc:
def initialize(owner_class_name, reflection)
super("Could not find the association #{reflection.options[:through].inspect} in model #{owner_class_name}")
end
end
class HasManyThroughAssociationPolymorphicError < ActiveRecordError #:nodoc:
def initialize(owner_class_name, reflection, source_reflection)
super("Cannot have a has_many :through association '#{owner_class_name}##{reflection.name}' on the polymorphic object '#{source_reflection.class_name}##{source_reflection.name}'.")
end
end
class HasManyThroughAssociationPointlessSourceTypeError < ActiveRecordError #:nodoc:
def initialize(owner_class_name, reflection, source_reflection)
super("Cannot have a has_many :through association '#{owner_class_name}##{reflection.name}' with a :source_type option if the '#{reflection.through_reflection.class_name}##{source_reflection.name}' is not polymorphic. Try removing :source_type on your association.")
end
end
class HasManyThroughSourceAssociationNotFoundError < ActiveRecordError #:nodoc:
def initialize(reflection)
through_reflection = reflection.through_reflection
source_reflection_names = reflection.source_reflection_names
source_associations = reflection.through_reflection.klass.reflect_on_all_associations.collect { |a| a.name.inspect }
super("Could not find the source association(s) #{source_reflection_names.collect(&:inspect).to_sentence(:two_words_connector => ' or ', :last_word_connector => ', or ', :locale => :en)} in model #{through_reflection.klass}. Try 'has_many #{reflection.name.inspect}, :through => #{through_reflection.name.inspect}, :source => <name>'. Is it one of #{source_associations.to_sentence(:two_words_connector => ' or ', :last_word_connector => ', or ', :locale => :en)}?")
end
end
class HasManyThroughSourceAssociationMacroError < ActiveRecordError #:nodoc:
def initialize(reflection)
through_reflection = reflection.through_reflection
source_reflection = reflection.source_reflection
super("Invalid source reflection macro :#{source_reflection.macro}#{" :through" if source_reflection.options[:through]} for has_many #{reflection.name.inspect}, :through => #{through_reflection.name.inspect}. Use :source to specify the source reflection.")
end
end
class HasManyThroughCantAssociateThroughHasManyReflection < ActiveRecordError #:nodoc:
def initialize(owner, reflection)
super("Cannot modify association '#{owner.class.name}##{reflection.name}' because the source reflection class '#{reflection.source_reflection.class_name}' is associated to '#{reflection.through_reflection.class_name}' via :#{reflection.source_reflection.macro}.")
end
end
class HasManyThroughCantAssociateNewRecords < ActiveRecordError #:nodoc:
def initialize(owner, reflection)
super("Cannot associate new records through '#{owner.class.name}##{reflection.name}' on '#{reflection.source_reflection.class_name rescue nil}##{reflection.source_reflection.name rescue nil}'. Both records must have an id in order to create the has_many :through record associating them.")
end
end
class HasManyThroughCantDissociateNewRecords < ActiveRecordError #:nodoc:
def initialize(owner, reflection)
super("Cannot dissociate new records through '#{owner.class.name}##{reflection.name}' on '#{reflection.source_reflection.class_name rescue nil}##{reflection.source_reflection.name rescue nil}'. Both records must have an id in order to delete the has_many :through record associating them.")
end
end
class HasAndBelongsToManyAssociationForeignKeyNeeded < ActiveRecordError #:nodoc:
def initialize(reflection)
super("Cannot create self referential has_and_belongs_to_many association on '#{reflection.class_name rescue nil}##{reflection.name rescue nil}'. :association_foreign_key cannot be the same as the :foreign_key.")
end
end
class EagerLoadPolymorphicError < ActiveRecordError #:nodoc:
def initialize(reflection)
super("Can not eagerly load the polymorphic association #{reflection.name.inspect}")
end
end
class ReadOnlyAssociation < ActiveRecordError #:nodoc:
def initialize(reflection)
super("Can not add to a has_many :through association. Try adding to #{reflection.through_reflection.name.inspect}.")
end
end
# See ActiveRecord::Associations::ClassMethods for documentation.
module Associations # :nodoc:
# These classes will be loaded when associations are created.
# So there is no need to eager load them.
autoload :AssociationCollection, 'active_record/associations/association_collection'
autoload :AssociationProxy, 'active_record/associations/association_proxy'
autoload :BelongsToAssociation, 'active_record/associations/belongs_to_association'
autoload :BelongsToPolymorphicAssociation, 'active_record/associations/belongs_to_polymorphic_association'
autoload :HasAndBelongsToManyAssociation, 'active_record/associations/has_and_belongs_to_many_association'
autoload :HasManyAssociation, 'active_record/associations/has_many_association'
autoload :HasManyThroughAssociation, 'active_record/associations/has_many_through_association'
autoload :HasOneAssociation, 'active_record/associations/has_one_association'
autoload :HasOneThroughAssociation, 'active_record/associations/has_one_through_association'
def self.included(base)
base.extend(ClassMethods)
end
# Clears out the association cache
def clear_association_cache #:nodoc:
self.class.reflect_on_all_associations.to_a.each do |assoc|
instance_variable_set "@#{assoc.name}", nil
end unless self.new_record?
end
private
# Gets the specified association instance if it responds to :loaded?, nil otherwise.
def association_instance_get(name)
association = instance_variable_get("@#{name}")
association if association.respond_to?(:loaded?)
end
# Set the specified association instance.
def association_instance_set(name, association)
instance_variable_set("@#{name}", association)
end
# Associations are a set of macro-like class methods for tying objects together through foreign keys. They express relationships like
# "Project has one Project Manager" or "Project belongs to a Portfolio". Each macro adds a number of methods to the class which are
# specialized according to the collection or association symbol and the options hash. It works much the same way as Ruby's own <tt>attr*</tt>
# methods. Example:
#
# class Project < ActiveRecord::Base
# belongs_to :portfolio
# has_one :project_manager
# has_many :milestones
# has_and_belongs_to_many :categories
# end
#
# The project class now has the following methods (and more) to ease the traversal and manipulation of its relationships:
# * <tt>Project#portfolio, Project#portfolio=(portfolio), Project#portfolio.nil?</tt>
# * <tt>Project#project_manager, Project#project_manager=(project_manager), Project#project_manager.nil?,</tt>
# * <tt>Project#milestones.empty?, Project#milestones.size, Project#milestones, Project#milestones<<(milestone),</tt>
# <tt>Project#milestones.delete(milestone), Project#milestones.find(milestone_id), Project#milestones.find(:all, options),</tt>
# <tt>Project#milestones.build, Project#milestones.create</tt>
# * <tt>Project#categories.empty?, Project#categories.size, Project#categories, Project#categories<<(category1),</tt>
# <tt>Project#categories.delete(category1)</tt>
#
# === A word of warning
#
# Don't create associations that have the same name as instance methods of ActiveRecord::Base. Since the association
# adds a method with that name to its model, it will override the inherited method and break things.
# For instance, +attributes+ and +connection+ would be bad choices for association names.
#
# == Auto-generated methods
#
# === Singular associations (one-to-one)
# | | belongs_to |
# generated methods | belongs_to | :polymorphic | has_one
# ----------------------------------+------------+--------------+---------
# other | X | X | X
# other=(other) | X | X | X
# build_other(attributes={}) | X | | X
# create_other(attributes={}) | X | | X
# other.create!(attributes={}) | | | X
#
# ===Collection associations (one-to-many / many-to-many)
# | | | has_many
# generated methods | habtm | has_many | :through
# ----------------------------------+-------+----------+----------
# others | X | X | X
# others=(other,other,...) | X | X | X
# other_ids | X | X | X
# other_ids=(id,id,...) | X | X | X
# others<< | X | X | X
# others.push | X | X | X
# others.concat | X | X | X
# others.build(attributes={}) | X | X | X
# others.create(attributes={}) | X | X | X
# others.create!(attributes={}) | X | X | X
# others.size | X | X | X
# others.length | X | X | X
# others.count | X | X | X
# others.sum(args*,&block) | X | X | X
# others.empty? | X | X | X
# others.clear | X | X | X
# others.delete(other,other,...) | X | X | X
# others.delete_all | X | X |
# others.destroy_all | X | X | X
# others.find(*args) | X | X | X
# others.find_first | X | |
# others.exists? | X | X | X
# others.uniq | X | X | X
# others.reset | X | X | X
#
# == Cardinality and associations
#
# Active Record associations can be used to describe one-to-one, one-to-many and many-to-many
# relationships between models. Each model uses an association to describe its role in
# the relation. The +belongs_to+ association is always used in the model that has
# the foreign key.
#
# === One-to-one
#
# Use +has_one+ in the base, and +belongs_to+ in the associated model.
#
# class Employee < ActiveRecord::Base
# has_one :office
# end
# class Office < ActiveRecord::Base
# belongs_to :employee # foreign key - employee_id
# end
#
# === One-to-many
#
# Use +has_many+ in the base, and +belongs_to+ in the associated model.
#
# class Manager < ActiveRecord::Base
# has_many :employees
# end
# class Employee < ActiveRecord::Base
# belongs_to :manager # foreign key - manager_id
# end
#
# === Many-to-many
#
# There are two ways to build a many-to-many relationship.
#
# The first way uses a +has_many+ association with the <tt>:through</tt> option and a join model, so
# there are two stages of associations.
#
# class Assignment < ActiveRecord::Base
# belongs_to :programmer # foreign key - programmer_id
# belongs_to :project # foreign key - project_id
# end
# class Programmer < ActiveRecord::Base
# has_many :assignments
# has_many :projects, :through => :assignments
# end
# class Project < ActiveRecord::Base
# has_many :assignments
# has_many :programmers, :through => :assignments
# end
#
# For the second way, use +has_and_belongs_to_many+ in both models. This requires a join table
# that has no corresponding model or primary key.
#
# class Programmer < ActiveRecord::Base
# has_and_belongs_to_many :projects # foreign keys in the join table
# end
# class Project < ActiveRecord::Base
# has_and_belongs_to_many :programmers # foreign keys in the join table
# end
#
# Choosing which way to build a many-to-many relationship is not always simple.
# If you need to work with the relationship model as its own entity,
# use <tt>has_many :through</tt>. Use +has_and_belongs_to_many+ when working with legacy schemas or when
# you never work directly with the relationship itself.
#
# == Is it a +belongs_to+ or +has_one+ association?
#
# Both express a 1-1 relationship. The difference is mostly where to place the foreign key, which goes on the table for the class
# declaring the +belongs_to+ relationship. Example:
#
# class User < ActiveRecord::Base
# # I reference an account.
# belongs_to :account
# end
#
# class Account < ActiveRecord::Base
# # One user references me.
# has_one :user
# end
#
# The tables for these classes could look something like:
#
# CREATE TABLE users (
# id int(11) NOT NULL auto_increment,
# account_id int(11) default NULL,
# name varchar default NULL,
# PRIMARY KEY (id)
# )
#
# CREATE TABLE accounts (
# id int(11) NOT NULL auto_increment,
# name varchar default NULL,
# PRIMARY KEY (id)
# )
#
# == Unsaved objects and associations
#
# You can manipulate objects and associations before they are saved to the database, but there is some special behavior you should be
# aware of, mostly involving the saving of associated objects.
#
# Unless you enable the :autosave option on a <tt>has_one</tt>, <tt>belongs_to</tt>,
# <tt>has_many</tt>, or <tt>has_and_belongs_to_many</tt> association,
# in which case the members are always saved.
#
# === One-to-one associations
#
# * Assigning an object to a +has_one+ association automatically saves that object and the object being replaced (if there is one), in
# order to update their primary keys - except if the parent object is unsaved (<tt>new_record? == true</tt>).
# * If either of these saves fail (due to one of the objects being invalid) the assignment statement returns +false+ and the assignment
# is cancelled.
# * If you wish to assign an object to a +has_one+ association without saving it, use the <tt>association.build</tt> method (documented below).
# * Assigning an object to a +belongs_to+ association does not save the object, since the foreign key field belongs on the parent. It
# does not save the parent either.
#
# === Collections
#
# * Adding an object to a collection (+has_many+ or +has_and_belongs_to_many+) automatically saves that object, except if the parent object
# (the owner of the collection) is not yet stored in the database.
# * If saving any of the objects being added to a collection (via <tt>push</tt> or similar) fails, then <tt>push</tt> returns +false+.
# * You can add an object to a collection without automatically saving it by using the <tt>collection.build</tt> method (documented below).
# * All unsaved (<tt>new_record? == true</tt>) members of the collection are automatically saved when the parent is saved.
#
# === Association callbacks
#
# Similar to the normal callbacks that hook into the lifecycle of an Active Record object, you can also define callbacks that get
# triggered when you add an object to or remove an object from an association collection. Example:
#
# class Project
# has_and_belongs_to_many :developers, :after_add => :evaluate_velocity
#
# def evaluate_velocity(developer)
# ...
# end
# end
#
# It's possible to stack callbacks by passing them as an array. Example:
#
# class Project
# has_and_belongs_to_many :developers, :after_add => [:evaluate_velocity, Proc.new { |p, d| p.shipping_date = Time.now}]
# end
#
# Possible callbacks are: +before_add+, +after_add+, +before_remove+ and +after_remove+.
#
# Should any of the +before_add+ callbacks throw an exception, the object does not get added to the collection. Same with
# the +before_remove+ callbacks; if an exception is thrown the object doesn't get removed.
#
# === Association extensions
#
# The proxy objects that control the access to associations can be extended through anonymous modules. This is especially
# beneficial for adding new finders, creators, and other factory-type methods that are only used as part of this association.
# Example:
#
# class Account < ActiveRecord::Base
# has_many :people do
# def find_or_create_by_name(name)
# first_name, last_name = name.split(" ", 2)
# find_or_create_by_first_name_and_last_name(first_name, last_name)
# end
# end
# end
#
# person = Account.find(:first).people.find_or_create_by_name("David Heinemeier Hansson")
# person.first_name # => "David"
# person.last_name # => "Heinemeier Hansson"
#
# If you need to share the same extensions between many associations, you can use a named extension module. Example:
#
# module FindOrCreateByNameExtension
# def find_or_create_by_name(name)
# first_name, last_name = name.split(" ", 2)
# find_or_create_by_first_name_and_last_name(first_name, last_name)
# end
# end
#
# class Account < ActiveRecord::Base
# has_many :people, :extend => FindOrCreateByNameExtension
# end
#
# class Company < ActiveRecord::Base
# has_many :people, :extend => FindOrCreateByNameExtension
# end
#
# If you need to use multiple named extension modules, you can specify an array of modules with the <tt>:extend</tt> option.
# In the case of name conflicts between methods in the modules, methods in modules later in the array supercede
# those earlier in the array. Example:
#
# class Account < ActiveRecord::Base
# has_many :people, :extend => [FindOrCreateByNameExtension, FindRecentExtension]
# end
#
# Some extensions can only be made to work with knowledge of the association proxy's internals.
# Extensions can access relevant state using accessors on the association proxy:
#
# * +proxy_owner+ - Returns the object the association is part of.
# * +proxy_reflection+ - Returns the reflection object that describes the association.
# * +proxy_target+ - Returns the associated object for +belongs_to+ and +has_one+, or the collection of associated objects for +has_many+ and +has_and_belongs_to_many+.
#
# === Association Join Models
#
# Has Many associations can be configured with the <tt>:through</tt> option to use an explicit join model to retrieve the data. This
# operates similarly to a +has_and_belongs_to_many+ association. The advantage is that you're able to add validations,
# callbacks, and extra attributes on the join model. Consider the following schema:
#
# class Author < ActiveRecord::Base
# has_many :authorships
# has_many :books, :through => :authorships
# end
#
# class Authorship < ActiveRecord::Base
# belongs_to :author
# belongs_to :book
# end
#
# @author = Author.find :first
# @author.authorships.collect { |a| a.book } # selects all books that the author's authorships belong to.
# @author.books # selects all books by using the Authorship join model
#
# You can also go through a +has_many+ association on the join model:
#
# class Firm < ActiveRecord::Base
# has_many :clients
# has_many :invoices, :through => :clients
# end
#
# class Client < ActiveRecord::Base
# belongs_to :firm
# has_many :invoices
# end
#
# class Invoice < ActiveRecord::Base
# belongs_to :client
# end
#
# @firm = Firm.find :first
# @firm.clients.collect { |c| c.invoices }.flatten # select all invoices for all clients of the firm
# @firm.invoices # selects all invoices by going through the Client join model.
#
# === Polymorphic Associations
#
# Polymorphic associations on models are not restricted on what types of models they can be associated with. Rather, they
# specify an interface that a +has_many+ association must adhere to.
#
# class Asset < ActiveRecord::Base
# belongs_to :attachable, :polymorphic => true
# end
#
# class Post < ActiveRecord::Base
# has_many :assets, :as => :attachable # The :as option specifies the polymorphic interface to use.
# end
#
# @asset.attachable = @post
#
# This works by using a type column in addition to a foreign key to specify the associated record. In the Asset example, you'd need
# an +attachable_id+ integer column and an +attachable_type+ string column.
#
# Using polymorphic associations in combination with single table inheritance (STI) is a little tricky. In order
# for the associations to work as expected, ensure that you store the base model for the STI models in the
# type column of the polymorphic association. To continue with the asset example above, suppose there are guest posts
# and member posts that use the posts table for STI. In this case, there must be a +type+ column in the posts table.
#
# class Asset < ActiveRecord::Base
# belongs_to :attachable, :polymorphic => true
#
# def attachable_type=(sType)
# super(sType.to_s.classify.constantize.base_class.to_s)
# end
# end
#
# class Post < ActiveRecord::Base
# # because we store "Post" in attachable_type now :dependent => :destroy will work
# has_many :assets, :as => :attachable, :dependent => :destroy
# end
#
# class GuestPost < Post
# end
#
# class MemberPost < Post
# end
#
# == Caching
#
# All of the methods are built on a simple caching principle that will keep the result of the last query around unless specifically
# instructed not to. The cache is even shared across methods to make it even cheaper to use the macro-added methods without
# worrying too much about performance at the first go. Example:
#
# project.milestones # fetches milestones from the database
# project.milestones.size # uses the milestone cache
# project.milestones.empty? # uses the milestone cache
# project.milestones(true).size # fetches milestones from the database
# project.milestones # uses the milestone cache
#
# == Eager loading of associations
#
# Eager loading is a way to find objects of a certain class and a number of named associations. This is
# one of the easiest ways of to prevent the dreaded 1+N problem in which fetching 100 posts that each need to display their author
# triggers 101 database queries. Through the use of eager loading, the 101 queries can be reduced to 2. Example:
#
# class Post < ActiveRecord::Base
# belongs_to :author
# has_many :comments
# end
#
# Consider the following loop using the class above:
#
# for post in Post.all
# puts "Post: " + post.title
# puts "Written by: " + post.author.name
# puts "Last comment on: " + post.comments.first.created_on
# end
#
# To iterate over these one hundred posts, we'll generate 201 database queries. Let's first just optimize it for retrieving the author:
#
# for post in Post.find(:all, :include => :author)
#
# This references the name of the +belongs_to+ association that also used the <tt>:author</tt> symbol. After loading the posts, find
# will collect the +author_id+ from each one and load all the referenced authors with one query. Doing so will cut down the number of queries from 201 to 102.
#
# We can improve upon the situation further by referencing both associations in the finder with:
#
# for post in Post.find(:all, :include => [ :author, :comments ])
#
# This will load all comments with a single query. This reduces the total number of queries to 3. More generally the number of queries
# will be 1 plus the number of associations named (except if some of the associations are polymorphic +belongs_to+ - see below).
#
# To include a deep hierarchy of associations, use a hash:
#
# for post in Post.find(:all, :include => [ :author, { :comments => { :author => :gravatar } } ])
#
# That'll grab not only all the comments but all their authors and gravatar pictures. You can mix and match
# symbols, arrays and hashes in any combination to describe the associations you want to load.
#
# All of this power shouldn't fool you into thinking that you can pull out huge amounts of data with no performance penalty just because you've reduced
# the number of queries. The database still needs to send all the data to Active Record and it still needs to be processed. So it's no
# catch-all for performance problems, but it's a great way to cut down on the number of queries in a situation as the one described above.
#
# Since only one table is loaded at a time, conditions or orders cannot reference tables other than the main one. If this is the case
# Active Record falls back to the previously used LEFT OUTER JOIN based strategy. For example
#
# Post.find(:all, :include => [ :author, :comments ], :conditions => ['comments.approved = ?', true])
#
# will result in a single SQL query with joins along the lines of: <tt>LEFT OUTER JOIN comments ON comments.post_id = posts.id</tt> and
# <tt>LEFT OUTER JOIN authors ON authors.id = posts.author_id</tt>. Note that using conditions like this can have unintended consequences.
# In the above example posts with no approved comments are not returned at all, because the conditions apply to the SQL statement as a whole
# and not just to the association. You must disambiguate column references for this fallback to happen, for example
# <tt>:order => "author.name DESC"</tt> will work but <tt>:order => "name DESC"</tt> will not.
#
# If you do want eagerload only some members of an association it is usually more natural to <tt>:include</tt> an association
# which has conditions defined on it:
#
# class Post < ActiveRecord::Base
# has_many :approved_comments, :class_name => 'Comment', :conditions => ['approved = ?', true]
# end
#
# Post.find(:all, :include => :approved_comments)
#
# will load posts and eager load the +approved_comments+ association, which contains only those comments that have been approved.
#
# If you eager load an association with a specified <tt>:limit</tt> option, it will be ignored, returning all the associated objects:
#
# class Picture < ActiveRecord::Base
# has_many :most_recent_comments, :class_name => 'Comment', :order => 'id DESC', :limit => 10
# end
#
# Picture.find(:first, :include => :most_recent_comments).most_recent_comments # => returns all associated comments.
#
# When eager loaded, conditions are interpolated in the context of the model class, not the model instance. Conditions are lazily interpolated
# before the actual model exists.
#
# Eager loading is supported with polymorphic associations.
#
# class Address < ActiveRecord::Base
# belongs_to :addressable, :polymorphic => true
# end
#
# A call that tries to eager load the addressable model
#
# Address.find(:all, :include => :addressable)
#
# will execute one query to load the addresses and load the addressables with one query per addressable type.
# For example if all the addressables are either of class Person or Company then a total of 3 queries will be executed. The list of
# addressable types to load is determined on the back of the addresses loaded. This is not supported if Active Record has to fallback
# to the previous implementation of eager loading and will raise ActiveRecord::EagerLoadPolymorphicError. The reason is that the parent
# model's type is a column value so its corresponding table name cannot be put in the +FROM+/+JOIN+ clauses of that query.
#
# == Table Aliasing
#
# Active Record uses table aliasing in the case that a table is referenced multiple times in a join. If a table is referenced only once,
# the standard table name is used. The second time, the table is aliased as <tt>#{reflection_name}_#{parent_table_name}</tt>. Indexes are appended
# for any more successive uses of the table name.
#
# Post.find :all, :joins => :comments
# # => SELECT ... FROM posts INNER JOIN comments ON ...
# Post.find :all, :joins => :special_comments # STI
# # => SELECT ... FROM posts INNER JOIN comments ON ... AND comments.type = 'SpecialComment'
# Post.find :all, :joins => [:comments, :special_comments] # special_comments is the reflection name, posts is the parent table name
# # => SELECT ... FROM posts INNER JOIN comments ON ... INNER JOIN comments special_comments_posts
#
# Acts as tree example:
#
# TreeMixin.find :all, :joins => :children
# # => SELECT ... FROM mixins INNER JOIN mixins childrens_mixins ...
# TreeMixin.find :all, :joins => {:children => :parent}
# # => SELECT ... FROM mixins INNER JOIN mixins childrens_mixins ...
# INNER JOIN parents_mixins ...
# TreeMixin.find :all, :joins => {:children => {:parent => :children}}
# # => SELECT ... FROM mixins INNER JOIN mixins childrens_mixins ...
# INNER JOIN parents_mixins ...
# INNER JOIN mixins childrens_mixins_2
#
# Has and Belongs to Many join tables use the same idea, but add a <tt>_join</tt> suffix:
#
# Post.find :all, :joins => :categories
# # => SELECT ... FROM posts INNER JOIN categories_posts ... INNER JOIN categories ...
# Post.find :all, :joins => {:categories => :posts}
# # => SELECT ... FROM posts INNER JOIN categories_posts ... INNER JOIN categories ...
# INNER JOIN categories_posts posts_categories_join INNER JOIN posts posts_categories
# Post.find :all, :joins => {:categories => {:posts => :categories}}
# # => SELECT ... FROM posts INNER JOIN categories_posts ... INNER JOIN categories ...
# INNER JOIN categories_posts posts_categories_join INNER JOIN posts posts_categories
# INNER JOIN categories_posts categories_posts_join INNER JOIN categories categories_posts_2
#
# If you wish to specify your own custom joins using a <tt>:joins</tt> option, those table names will take precedence over the eager associations:
#
# Post.find :all, :joins => :comments, :joins => "inner join comments ..."
# # => SELECT ... FROM posts INNER JOIN comments_posts ON ... INNER JOIN comments ...
# Post.find :all, :joins => [:comments, :special_comments], :joins => "inner join comments ..."
# # => SELECT ... FROM posts INNER JOIN comments comments_posts ON ...
# INNER JOIN comments special_comments_posts ...
# INNER JOIN comments ...
#
# Table aliases are automatically truncated according to the maximum length of table identifiers according to the specific database.
#
# == Modules
#
# By default, associations will look for objects within the current module scope. Consider:
#
# module MyApplication
# module Business
# class Firm < ActiveRecord::Base
# has_many :clients
# end
#
# class Client < ActiveRecord::Base; end
# end
# end
#
# When <tt>Firm#clients</tt> is called, it will in turn call <tt>MyApplication::Business::Client.find_all_by_firm_id(firm.id)</tt>.
# If you want to associate with a class in another module scope, this can be done by specifying the complete class name.
# Example:
#
# module MyApplication
# module Business
# class Firm < ActiveRecord::Base; end
# end
#
# module Billing
# class Account < ActiveRecord::Base
# belongs_to :firm, :class_name => "MyApplication::Business::Firm"
# end
# end
# end
#
# == Type safety with <tt>ActiveRecord::AssociationTypeMismatch</tt>
#
# If you attempt to assign an object to an association that doesn't match the inferred or specified <tt>:class_name</tt>, you'll
# get an <tt>ActiveRecord::AssociationTypeMismatch</tt>.
#
# == Options
#
# All of the association macros can be specialized through options. This makes cases more complex than the simple and guessable ones
# possible.
module ClassMethods
# Specifies a one-to-many association. The following methods for retrieval and query of
# collections of associated objects will be added:
#
# [collection(force_reload = false)]
# Returns an array of all the associated objects.
# An empty array is returned if none are found.
# [collection<<(object, ...)]
# Adds one or more objects to the collection by setting their foreign keys to the collection's primary key.
# [collection.delete(object, ...)]
# Removes one or more objects from the collection by setting their foreign keys to +NULL+.
# Objects will be in addition destroyed if they're associated with <tt>:dependent => :destroy</tt>,
# and deleted if they're associated with <tt>:dependent => :delete_all</tt>.
# [collection=objects]
# Replaces the collections content by deleting and adding objects as appropriate.
# [collection_singular_ids]
# Returns an array of the associated objects' ids
# [collection_singular_ids=ids]
# Replace the collection with the objects identified by the primary keys in +ids+
# [collection.clear]
# Removes every object from the collection. This destroys the associated objects if they
# are associated with <tt>:dependent => :destroy</tt>, deletes them directly from the
# database if <tt>:dependent => :delete_all</tt>, otherwise sets their foreign keys to +NULL+.
# [collection.empty?]
# Returns +true+ if there are no associated objects.
# [collection.size]
# Returns the number of associated objects.
# [collection.find(...)]
# Finds an associated object according to the same rules as ActiveRecord::Base.find.
# [collection.exists?(...)]
# Checks whether an associated object with the given conditions exists.
# Uses the same rules as ActiveRecord::Base.exists?.
# [collection.build(attributes = {}, ...)]
# Returns one or more new objects of the collection type that have been instantiated
# with +attributes+ and linked to this object through a foreign key, but have not yet
# been saved. <b>Note:</b> This only works if an associated object already exists, not if
# it's +nil+!
# [collection.create(attributes = {})]
# Returns a new object of the collection type that has been instantiated
# with +attributes+, linked to this object through a foreign key, and that has already
# been saved (if it passed the validation). <b>Note:</b> This only works if an associated
# object already exists, not if it's +nil+!
#
# (*Note*: +collection+ is replaced with the symbol passed as the first argument, so
# <tt>has_many :clients</tt> would add among others <tt>clients.empty?</tt>.)
#
# === Example
#
# Example: A Firm class declares <tt>has_many :clients</tt>, which will add:
# * <tt>Firm#clients</tt> (similar to <tt>Clients.find :all, :conditions => ["firm_id = ?", id]</tt>)
# * <tt>Firm#clients<<</tt>
# * <tt>Firm#clients.delete</tt>
# * <tt>Firm#clients=</tt>
# * <tt>Firm#client_ids</tt>
# * <tt>Firm#client_ids=</tt>
# * <tt>Firm#clients.clear</tt>
# * <tt>Firm#clients.empty?</tt> (similar to <tt>firm.clients.size == 0</tt>)
# * <tt>Firm#clients.size</tt> (similar to <tt>Client.count "firm_id = #{id}"</tt>)
# * <tt>Firm#clients.find</tt> (similar to <tt>Client.find(id, :conditions => "firm_id = #{id}")</tt>)
# * <tt>Firm#clients.exists?(:name => 'ACME')</tt> (similar to <tt>Client.exists?(:name => 'ACME', :firm_id => firm.id)</tt>)
# * <tt>Firm#clients.build</tt> (similar to <tt>Client.new("firm_id" => id)</tt>)
# * <tt>Firm#clients.create</tt> (similar to <tt>c = Client.new("firm_id" => id); c.save; c</tt>)
# The declaration can also include an options hash to specialize the behavior of the association.
#
# === Supported options
# [:class_name]
# Specify the class name of the association. Use it only if that name can't be inferred
# from the association name. So <tt>has_many :products</tt> will by default be linked to the Product class, but
# if the real class name is SpecialProduct, you'll have to specify it with this option.
# [:conditions]
# Specify the conditions that the associated objects must meet in order to be included as a +WHERE+
# SQL fragment, such as <tt>price > 5 AND name LIKE 'B%'</tt>. Record creations from the association are scoped if a hash
# is used. <tt>has_many :posts, :conditions => {:published => true}</tt> will create published posts with <tt>@blog.posts.create</tt>
# or <tt>@blog.posts.build</tt>.
# [:order]
# Specify the order in which the associated objects are returned as an <tt>ORDER BY</tt> SQL fragment,
# such as <tt>last_name, first_name DESC</tt>.
# [:foreign_key]
# Specify the foreign key used for the association. By default this is guessed to be the name
# of this class in lower-case and "_id" suffixed. So a Person class that makes a +has_many+ association will use "person_id"
# as the default <tt>:foreign_key</tt>.
# [:primary_key]
# Specify the method that returns the primary key used for the association. By default this is +id+.
# [:dependent]
# If set to <tt>:destroy</tt> all the associated objects are destroyed
# alongside this object by calling their +destroy+ method. If set to <tt>:delete_all</tt> all associated
# objects are deleted *without* calling their +destroy+ method. If set to <tt>:nullify</tt> all associated
# objects' foreign keys are set to +NULL+ *without* calling their +save+ callbacks. *Warning:* This option is ignored when also using
# the <tt>:through</tt> option.
# [:finder_sql]
# Specify a complete SQL statement to fetch the association. This is a good way to go for complex
# associations that depend on multiple tables. Note: When this option is used, +find_in_collection+ is _not_ added.
# [:counter_sql]
# Specify a complete SQL statement to fetch the size of the association. If <tt>:finder_sql</tt> is
# specified but not <tt>:counter_sql</tt>, <tt>:counter_sql</tt> will be generated by replacing <tt>SELECT ... FROM</tt> with <tt>SELECT COUNT(*) FROM</tt>.
# [:extend]
# Specify a named module for extending the proxy. See "Association extensions".
# [:include]
# Specify second-order associations that should be eager loaded when the collection is loaded.
# [:group]
# An attribute name by which the result should be grouped. Uses the <tt>GROUP BY</tt> SQL-clause.
# [:having]
# Combined with +:group+ this can be used to filter the records that a <tt>GROUP BY</tt> returns. Uses the <tt>HAVING</tt> SQL-clause.
# [:limit]
# An integer determining the limit on the number of rows that should be returned.
# [:offset]
# An integer determining the offset from where the rows should be fetched. So at 5, it would skip the first 4 rows.
# [:select]
# By default, this is <tt>*</tt> as in <tt>SELECT * FROM</tt>, but can be changed if you, for example, want to do a join
# but not include the joined columns. Do not forget to include the primary and foreign keys, otherwise it will raise an error.
# [:as]
# Specifies a polymorphic interface (See <tt>belongs_to</tt>).
# [:through]
# Specifies a Join Model through which to perform the query. Options for <tt>:class_name</tt> and <tt>:foreign_key</tt>
# are ignored, as the association uses the source reflection. You can only use a <tt>:through</tt> query through a <tt>belongs_to</tt>
# or <tt>has_many</tt> association on the join model.
# [:source]
# Specifies the source association name used by <tt>has_many :through</tt> queries. Only use it if the name cannot be
# inferred from the association. <tt>has_many :subscribers, :through => :subscriptions</tt> will look for either <tt>:subscribers</tt> or
# <tt>:subscriber</tt> on Subscription, unless a <tt>:source</tt> is given.
# [:source_type]
# Specifies type of the source association used by <tt>has_many :through</tt> queries where the source
# association is a polymorphic +belongs_to+.
# [:uniq]
# If true, duplicates will be omitted from the collection. Useful in conjunction with <tt>:through</tt>.
# [:readonly]
# If true, all the associated objects are readonly through the association.
# [:validate]
# If false, don't validate the associated objects when saving the parent object. true by default.
# [:autosave]
# If true, always save any loaded members and destroy members marked for destruction, when saving the parent object. Off by default.
#
# Option examples:
# has_many :comments, :order => "posted_on"
# has_many :comments, :include => :author
# has_many :people, :class_name => "Person", :conditions => "deleted = 0", :order => "name"
# has_many :tracks, :order => "position", :dependent => :destroy
# has_many :comments, :dependent => :nullify
# has_many :tags, :as => :taggable
# has_many :reports, :readonly => true
# has_many :subscribers, :through => :subscriptions, :source => :user
# has_many :subscribers, :class_name => "Person", :finder_sql =>
# 'SELECT DISTINCT people.* ' +
# 'FROM people p, post_subscriptions ps ' +
# 'WHERE ps.post_id = #{id} AND ps.person_id = p.id ' +
# 'ORDER BY p.first_name'
def has_many(association_id, options = {}, &extension)
reflection = create_has_many_reflection(association_id, options, &extension)
configure_dependency_for_has_many(reflection)
add_association_callbacks(reflection.name, reflection.options)
if options[:through]
collection_accessor_methods(reflection, HasManyThroughAssociation)
else
collection_accessor_methods(reflection, HasManyAssociation)
end
end
# Specifies a one-to-one association with another class. This method should only be used
# if the other class contains the foreign key. If the current class contains the foreign key,
# then you should use +belongs_to+ instead. See also ActiveRecord::Associations::ClassMethods's overview
# on when to use has_one and when to use belongs_to.
#
# The following methods for retrieval and query of a single associated object will be added:
#
# [association(force_reload = false)]
# Returns the associated object. +nil+ is returned if none is found.
# [association=(associate)]
# Assigns the associate object, extracts the primary key, sets it as the foreign key,
# and saves the associate object.
# [build_association(attributes = {})]
# Returns a new object of the associated type that has been instantiated
# with +attributes+ and linked to this object through a foreign key, but has not
# yet been saved. <b>Note:</b> This ONLY works if an association already exists.
# It will NOT work if the association is +nil+.
# [create_association(attributes = {})]
# Returns a new object of the associated type that has been instantiated
# with +attributes+, linked to this object through a foreign key, and that
# has already been saved (if it passed the validation).
#
# (+association+ is replaced with the symbol passed as the first argument, so
# <tt>has_one :manager</tt> would add among others <tt>manager.nil?</tt>.)
#
# === Example
#
# An Account class declares <tt>has_one :beneficiary</tt>, which will add:
# * <tt>Account#beneficiary</tt> (similar to <tt>Beneficiary.find(:first, :conditions => "account_id = #{id}")</tt>)
# * <tt>Account#beneficiary=(beneficiary)</tt> (similar to <tt>beneficiary.account_id = account.id; beneficiary.save</tt>)
# * <tt>Account#build_beneficiary</tt> (similar to <tt>Beneficiary.new("account_id" => id)</tt>)
# * <tt>Account#create_beneficiary</tt> (similar to <tt>b = Beneficiary.new("account_id" => id); b.save; b</tt>)
#
# === Options
#
# The declaration can also include an options hash to specialize the behavior of the association.
#
# Options are:
# [:class_name]
# Specify the class name of the association. Use it only if that name can't be inferred
# from the association name. So <tt>has_one :manager</tt> will by default be linked to the Manager class, but
# if the real class name is Person, you'll have to specify it with this option.
# [:conditions]
# Specify the conditions that the associated object must meet in order to be included as a +WHERE+
# SQL fragment, such as <tt>rank = 5</tt>.
# [:order]
# Specify the order in which the associated objects are returned as an <tt>ORDER BY</tt> SQL fragment,
# such as <tt>last_name, first_name DESC</tt>.
# [:dependent]
# If set to <tt>:destroy</tt>, the associated object is destroyed when this object is. If set to
# <tt>:delete</tt>, the associated object is deleted *without* calling its destroy method. If set to <tt>:nullify</tt>, the associated
# object's foreign key is set to +NULL+. Also, association is assigned.
# [:foreign_key]
# Specify the foreign key used for the association. By default this is guessed to be the name
# of this class in lower-case and "_id" suffixed. So a Person class that makes a +has_one+ association will use "person_id"
# as the default <tt>:foreign_key</tt>.
# [:primary_key]
# Specify the method that returns the primary key used for the association. By default this is +id+.
# [:include]
# Specify second-order associations that should be eager loaded when this object is loaded.
# [:as]
# Specifies a polymorphic interface (See <tt>belongs_to</tt>).
# [:select]
# By default, this is <tt>*</tt> as in <tt>SELECT * FROM</tt>, but can be changed if, for example, you want to do a join
# but not include the joined columns. Do not forget to include the primary and foreign keys, otherwise it will raise an error.
# [:through]
# Specifies a Join Model through which to perform the query. Options for <tt>:class_name</tt> and <tt>:foreign_key</tt>
# are ignored, as the association uses the source reflection. You can only use a <tt>:through</tt> query through a
# <tt>has_one</tt> or <tt>belongs_to</tt> association on the join model.
# [:source]
# Specifies the source association name used by <tt>has_one :through</tt> queries. Only use it if the name cannot be
# inferred from the association. <tt>has_one :favorite, :through => :favorites</tt> will look for a
# <tt>:favorite</tt> on Favorite, unless a <tt>:source</tt> is given.
# [:source_type]
# Specifies type of the source association used by <tt>has_one :through</tt> queries where the source
# association is a polymorphic +belongs_to+.
# [:readonly]
# If true, the associated object is readonly through the association.
# [:validate]
# If false, don't validate the associated object when saving the parent object. +false+ by default.
# [:autosave]
# If true, always save the associated object or destroy it if marked for destruction, when saving the parent object. Off by default.
#
# Option examples:
# has_one :credit_card, :dependent => :destroy # destroys the associated credit card
# has_one :credit_card, :dependent => :nullify # updates the associated records foreign key value to NULL rather than destroying it
# has_one :last_comment, :class_name => "Comment", :order => "posted_on"
# has_one :project_manager, :class_name => "Person", :conditions => "role = 'project_manager'"
# has_one :attachment, :as => :attachable
# has_one :boss, :readonly => :true
# has_one :club, :through => :membership
# has_one :primary_address, :through => :addressables, :conditions => ["addressable.primary = ?", true], :source => :addressable
def has_one(association_id, options = {})
if options[:through]
reflection = create_has_one_through_reflection(association_id, options)
association_accessor_methods(reflection, ActiveRecord::Associations::HasOneThroughAssociation)
else
reflection = create_has_one_reflection(association_id, options)
association_accessor_methods(reflection, HasOneAssociation)
association_constructor_method(:build, reflection, HasOneAssociation)
association_constructor_method(:create, reflection, HasOneAssociation)
configure_dependency_for_has_one(reflection)
end
end
# Specifies a one-to-one association with another class. This method should only be used
# if this class contains the foreign key. If the other class contains the foreign key,
# then you should use +has_one+ instead. See also ActiveRecord::Associations::ClassMethods's overview
# on when to use +has_one+ and when to use +belongs_to+.
#
# Methods will be added for retrieval and query for a single associated object, for which
# this object holds an id:
#
# [association(force_reload = false)]
# Returns the associated object. +nil+ is returned if none is found.
# [association=(associate)]
# Assigns the associate object, extracts the primary key, and sets it as the foreign key.
# [build_association(attributes = {})]
# Returns a new object of the associated type that has been instantiated
# with +attributes+ and linked to this object through a foreign key, but has not yet been saved.
# [create_association(attributes = {})]
# Returns a new object of the associated type that has been instantiated
# with +attributes+, linked to this object through a foreign key, and that
# has already been saved (if it passed the validation).
#
# (+association+ is replaced with the symbol passed as the first argument, so
# <tt>belongs_to :author</tt> would add among others <tt>author.nil?</tt>.)
#
# === Example
#
# A Post class declares <tt>belongs_to :author</tt>, which will add:
# * <tt>Post#author</tt> (similar to <tt>Author.find(author_id)</tt>)
# * <tt>Post#author=(author)</tt> (similar to <tt>post.author_id = author.id</tt>)
# * <tt>Post#author?</tt> (similar to <tt>post.author == some_author</tt>)
# * <tt>Post#build_author</tt> (similar to <tt>post.author = Author.new</tt>)
# * <tt>Post#create_author</tt> (similar to <tt>post.author = Author.new; post.author.save; post.author</tt>)
# The declaration can also include an options hash to specialize the behavior of the association.
#
# === Options
#
# [:class_name]
# Specify the class name of the association. Use it only if that name can't be inferred
# from the association name. So <tt>has_one :author</tt> will by default be linked to the Author class, but
# if the real class name is Person, you'll have to specify it with this option.
# [:conditions]
# Specify the conditions that the associated object must meet in order to be included as a +WHERE+
# SQL fragment, such as <tt>authorized = 1</tt>.
# [:select]
# By default, this is <tt>*</tt> as in <tt>SELECT * FROM</tt>, but can be changed if, for example, you want to do a join
# but not include the joined columns. Do not forget to include the primary and foreign keys, otherwise it will raise an error.
# [:foreign_key]
# Specify the foreign key used for the association. By default this is guessed to be the name
# of the association with an "_id" suffix. So a class that defines a <tt>belongs_to :person</tt> association will use
# "person_id" as the default <tt>:foreign_key</tt>. Similarly, <tt>belongs_to :favorite_person, :class_name => "Person"</tt>
# will use a foreign key of "favorite_person_id".
# [:dependent]
# If set to <tt>:destroy</tt>, the associated object is destroyed when this object is. If set to
# <tt>:delete</tt>, the associated object is deleted *without* calling its destroy method. This option should not be specified when
# <tt>belongs_to</tt> is used in conjunction with a <tt>has_many</tt> relationship on another class because of the potential to leave
# orphaned records behind.
# [:counter_cache]
# Caches the number of belonging objects on the associate class through the use of +increment_counter+
# and +decrement_counter+. The counter cache is incremented when an object of this class is created and decremented when it's
# destroyed. This requires that a column named <tt>#{table_name}_count</tt> (such as +comments_count+ for a belonging Comment class)
# is used on the associate class (such as a Post class). You can also specify a custom counter cache column by providing
# a column name instead of a +true+/+false+ value to this option (e.g., <tt>:counter_cache => :my_custom_counter</tt>.)
# Note: Specifying a counter cache will add it to that model's list of readonly attributes using +attr_readonly+.
# [:include]
# Specify second-order associations that should be eager loaded when this object is loaded.
# [:polymorphic]
# Specify this association is a polymorphic association by passing +true+.
# Note: If you've enabled the counter cache, then you may want to add the counter cache attribute
# to the +attr_readonly+ list in the associated classes (e.g. <tt>class Post; attr_readonly :comments_count; end</tt>).
# [:readonly]
# If true, the associated object is readonly through the association.
# [:validate]
# If false, don't validate the associated objects when saving the parent object. +false+ by default.
# [:autosave]
# If true, always save the associated object or destroy it if marked for destruction, when saving the parent object. Off by default.
# [:touch]
# If true, the associated object will be touched (the updated_at/on attributes set to now) when this record is either saved or
# destroyed. If you specify a symbol, that attribute will be updated with the current time instead of the updated_at/on attribute.
#
# Option examples:
# belongs_to :firm, :foreign_key => "client_of"
# belongs_to :author, :class_name => "Person", :foreign_key => "author_id"
# belongs_to :valid_coupon, :class_name => "Coupon", :foreign_key => "coupon_id",
# :conditions => 'discounts > #{payments_count}'
# belongs_to :attachable, :polymorphic => true
# belongs_to :project, :readonly => true
# belongs_to :post, :counter_cache => true
# belongs_to :company, :touch => true
# belongs_to :company, :touch => :employees_last_updated_at
def belongs_to(association_id, options = {})
reflection = create_belongs_to_reflection(association_id, options)
if reflection.options[:polymorphic]
association_accessor_methods(reflection, BelongsToPolymorphicAssociation)
else
association_accessor_methods(reflection, BelongsToAssociation)
association_constructor_method(:build, reflection, BelongsToAssociation)
association_constructor_method(:create, reflection, BelongsToAssociation)
end
add_counter_cache_callbacks(reflection) if options[:counter_cache]
add_touch_callbacks(reflection, options[:touch]) if options[:touch]
configure_dependency_for_belongs_to(reflection)
end
# Specifies a many-to-many relationship with another class. This associates two classes via an
# intermediate join table. Unless the join table is explicitly specified as an option, it is
# guessed using the lexical order of the class names. So a join between Developer and Project
# will give the default join table name of "developers_projects" because "D" outranks "P". Note that this precedence
# is calculated using the <tt><</tt> operator for String. This means that if the strings are of different lengths,
# and the strings are equal when compared up to the shortest length, then the longer string is considered of higher
# lexical precedence than the shorter one. For example, one would expect the tables "paper_boxes" and "papers"
# to generate a join table name of "papers_paper_boxes" because of the length of the name "paper_boxes",
# but it in fact generates a join table name of "paper_boxes_papers". Be aware of this caveat, and use the
# custom <tt>:join_table</tt> option if you need to.
#
# The join table should not have a primary key or a model associated with it. You must manually generate the
# join table with a migration such as this:
#
# class CreateDevelopersProjectsJoinTable < ActiveRecord::Migration
# def self.up
# create_table :developers_projects, :id => false do |t|
# t.integer :developer_id
# t.integer :project_id
# end
# end
#
# def self.down
# drop_table :developers_projects
# end
# end
#
# Deprecated: Any additional fields added to the join table will be placed as attributes when pulling records out through
# +has_and_belongs_to_many+ associations. Records returned from join tables with additional attributes will be marked as
# readonly (because we can't save changes to the additional attributes). It's strongly recommended that you upgrade any
# associations with attributes to a real join model (see introduction).
#
# Adds the following methods for retrieval and query:
#
# [collection(force_reload = false)]
# Returns an array of all the associated objects.
# An empty array is returned if none are found.
# [collection<<(object, ...)]
# Adds one or more objects to the collection by creating associations in the join table
# (<tt>collection.push</tt> and <tt>collection.concat</tt> are aliases to this method).
# [collection.delete(object, ...)]
# Removes one or more objects from the collection by removing their associations from the join table.
# This does not destroy the objects.
# [collection=objects]
# Replaces the collection's content by deleting and adding objects as appropriate.
# [collection_singular_ids]
# Returns an array of the associated objects' ids.
# [collection_singular_ids=ids]
# Replace the collection by the objects identified by the primary keys in +ids+.
# [collection.clear]
# Removes every object from the collection. This does not destroy the objects.
# [collection.empty?]
# Returns +true+ if there are no associated objects.
# [collection.size]
# Returns the number of associated objects.
# [collection.find(id)]
# Finds an associated object responding to the +id+ and that
# meets the condition that it has to be associated with this object.
# Uses the same rules as ActiveRecord::Base.find.
# [collection.exists?(...)]
# Checks whether an associated object with the given conditions exists.
# Uses the same rules as ActiveRecord::Base.exists?.
# [collection.build(attributes = {})]
# Returns a new object of the collection type that has been instantiated
# with +attributes+ and linked to this object through the join table, but has not yet been saved.
# [collection.create(attributes = {})]
# Returns a new object of the collection type that has been instantiated
# with +attributes+, linked to this object through the join table, and that has already been saved (if it passed the validation).
#
# (+collection+ is replaced with the symbol passed as the first argument, so
# <tt>has_and_belongs_to_many :categories</tt> would add among others <tt>categories.empty?</tt>.)
#
# === Example
#
# A Developer class declares <tt>has_and_belongs_to_many :projects</tt>, which will add:
# * <tt>Developer#projects</tt>
# * <tt>Developer#projects<<</tt>
# * <tt>Developer#projects.delete</tt>
# * <tt>Developer#projects=</tt>
# * <tt>Developer#project_ids</tt>
# * <tt>Developer#project_ids=</tt>
# * <tt>Developer#projects.clear</tt>
# * <tt>Developer#projects.empty?</tt>
# * <tt>Developer#projects.size</tt>
# * <tt>Developer#projects.find(id)</tt>
# * <tt>Developer#clients.exists?(...)</tt>
# * <tt>Developer#projects.build</tt> (similar to <tt>Project.new("project_id" => id)</tt>)
# * <tt>Developer#projects.create</tt> (similar to <tt>c = Project.new("project_id" => id); c.save; c</tt>)
# The declaration may include an options hash to specialize the behavior of the association.
#
# === Options
#
# [:class_name]
# Specify the class name of the association. Use it only if that name can't be inferred
# from the association name. So <tt>has_and_belongs_to_many :projects</tt> will by default be linked to the
# Project class, but if the real class name is SuperProject, you'll have to specify it with this option.
# [:join_table]
# Specify the name of the join table if the default based on lexical order isn't what you want.
# <b>WARNING:</b> If you're overwriting the table name of either class, the +table_name+ method
# MUST be declared underneath any +has_and_belongs_to_many+ declaration in order to work.
# [:foreign_key]
# Specify the foreign key used for the association. By default this is guessed to be the name
# of this class in lower-case and "_id" suffixed. So a Person class that makes a +has_and_belongs_to_many+ association
# to Project will use "person_id" as the default <tt>:foreign_key</tt>.
# [:association_foreign_key]
# Specify the foreign key used for the association on the receiving side of the association.
# By default this is guessed to be the name of the associated class in lower-case and "_id" suffixed.
# So if a Person class makes a +has_and_belongs_to_many+ association to Project,
# the association will use "project_id" as the default <tt>:association_foreign_key</tt>.
# [:conditions]
# Specify the conditions that the associated object must meet in order to be included as a +WHERE+
# SQL fragment, such as <tt>authorized = 1</tt>. Record creations from the association are scoped if a hash is used.
# <tt>has_many :posts, :conditions => {:published => true}</tt> will create published posts with <tt>@blog.posts.create</tt>
# or <tt>@blog.posts.build</tt>.
# [:order]
# Specify the order in which the associated objects are returned as an <tt>ORDER BY</tt> SQL fragment,
# such as <tt>last_name, first_name DESC</tt>
# [:uniq]
# If true, duplicate associated objects will be ignored by accessors and query methods.
# [:finder_sql]
# Overwrite the default generated SQL statement used to fetch the association with a manual statement
# [:counter_sql]
# Specify a complete SQL statement to fetch the size of the association. If <tt>:finder_sql</tt> is
# specified but not <tt>:counter_sql</tt>, <tt>:counter_sql</tt> will be generated by replacing <tt>SELECT ... FROM</tt> with <tt>SELECT COUNT(*) FROM</tt>.
# [:delete_sql]
# Overwrite the default generated SQL statement used to remove links between the associated
# classes with a manual statement.
# [:insert_sql]
# Overwrite the default generated SQL statement used to add links between the associated classes
# with a manual statement.
# [:extend]
# Anonymous module for extending the proxy, see "Association extensions".
# [:include]
# Specify second-order associations that should be eager loaded when the collection is loaded.
# [:group]
# An attribute name by which the result should be grouped. Uses the <tt>GROUP BY</tt> SQL-clause.
# [:having]
# Combined with +:group+ this can be used to filter the records that a <tt>GROUP BY</tt> returns. Uses the <tt>HAVING</tt> SQL-clause.
# [:limit]
# An integer determining the limit on the number of rows that should be returned.
# [:offset]
# An integer determining the offset from where the rows should be fetched. So at 5, it would skip the first 4 rows.
# [:select]
# By default, this is <tt>*</tt> as in <tt>SELECT * FROM</tt>, but can be changed if, for example, you want to do a join
# but not include the joined columns. Do not forget to include the primary and foreign keys, otherwise it will raise an error.
# [:readonly]
# If true, all the associated objects are readonly through the association.
# [:validate]
# If false, don't validate the associated objects when saving the parent object. +true+ by default.
# [:autosave]
# If true, always save any loaded members and destroy members marked for destruction, when saving the parent object. Off by default.
#
# Option examples:
# has_and_belongs_to_many :projects
# has_and_belongs_to_many :projects, :include => [ :milestones, :manager ]
# has_and_belongs_to_many :nations, :class_name => "Country"
# has_and_belongs_to_many :categories, :join_table => "prods_cats"
# has_and_belongs_to_many :categories, :readonly => true
# has_and_belongs_to_many :active_projects, :join_table => 'developers_projects', :delete_sql =>
# 'DELETE FROM developers_projects WHERE active=1 AND developer_id = #{id} AND project_id = #{record.id}'
def has_and_belongs_to_many(association_id, options = {}, &extension)
reflection = create_has_and_belongs_to_many_reflection(association_id, options, &extension)
collection_accessor_methods(reflection, HasAndBelongsToManyAssociation)
# Don't use a before_destroy callback since users' before_destroy
# callbacks will be executed after the association is wiped out.
old_method = "destroy_without_habtm_shim_for_#{reflection.name}"
class_eval <<-end_eval unless method_defined?(old_method)
alias_method :#{old_method}, :destroy_without_callbacks # alias_method :destroy_without_habtm_shim_for_posts, :destroy_without_callbacks
def destroy_without_callbacks # def destroy_without_callbacks
#{reflection.name}.clear # posts.clear
#{old_method} # destroy_without_habtm_shim_for_posts
end # end
end_eval
add_association_callbacks(reflection.name, options)
end
private
# Generates a join table name from two provided table names.
# The names in the join table namesme end up in lexicographic order.
#
# join_table_name("members", "clubs") # => "clubs_members"
# join_table_name("members", "special_clubs") # => "members_special_clubs"
def join_table_name(first_table_name, second_table_name)
if first_table_name < second_table_name
join_table = "#{first_table_name}_#{second_table_name}"
else
join_table = "#{second_table_name}_#{first_table_name}"
end
table_name_prefix + join_table + table_name_suffix
end
def association_accessor_methods(reflection, association_proxy_class)
define_method(reflection.name) do |*params|
force_reload = params.first unless params.empty?
association = association_instance_get(reflection.name)
if association.nil? || force_reload
association = association_proxy_class.new(self, reflection)
retval = association.reload
if retval.nil? and association_proxy_class == BelongsToAssociation
association_instance_set(reflection.name, nil)
return nil
end
association_instance_set(reflection.name, association)
end
association.target.nil? ? nil : association
end
define_method("loaded_#{reflection.name}?") do
association = association_instance_get(reflection.name)
association && association.loaded?
end
define_method("#{reflection.name}=") do |new_value|
association = association_instance_get(reflection.name)
if association.nil? || association.target != new_value
association = association_proxy_class.new(self, reflection)
end
if association_proxy_class == HasOneThroughAssociation
association.create_through_record(new_value)
self.send(reflection.name, new_value)
else
association.replace(new_value)
association_instance_set(reflection.name, new_value.nil? ? nil : association)
end
end
define_method("set_#{reflection.name}_target") do |target|
return if target.nil? and association_proxy_class == BelongsToAssociation
association = association_proxy_class.new(self, reflection)
association.target = target
association_instance_set(reflection.name, association)
end
end
def collection_reader_method(reflection, association_proxy_class)
define_method(reflection.name) do |*params|
force_reload = params.first unless params.empty?
association = association_instance_get(reflection.name)
unless association
association = association_proxy_class.new(self, reflection)
association_instance_set(reflection.name, association)
end
association.reload if force_reload
association
end
define_method("#{reflection.name.to_s.singularize}_ids") do
if send(reflection.name).loaded? || reflection.options[:finder_sql]
send(reflection.name).map(&:id)
else
send(reflection.name).all(:select => "#{reflection.quoted_table_name}.#{reflection.klass.primary_key}").map(&:id)
end
end
end
def collection_accessor_methods(reflection, association_proxy_class, writer = true)
collection_reader_method(reflection, association_proxy_class)
if writer
define_method("#{reflection.name}=") do |new_value|
# Loads proxy class instance (defined in collection_reader_method) if not already loaded
association = send(reflection.name)
association.replace(new_value)
association
end
define_method("#{reflection.name.to_s.singularize}_ids=") do |new_value|
ids = (new_value || []).reject { |nid| nid.blank? }
send("#{reflection.name}=", reflection.class_name.constantize.find(ids))
end
end
end
def association_constructor_method(constructor, reflection, association_proxy_class)
define_method("#{constructor}_#{reflection.name}") do |*params|
attributees = params.first unless params.empty?
replace_existing = params[1].nil? ? true : params[1]
association = association_instance_get(reflection.name)
unless association
association = association_proxy_class.new(self, reflection)
association_instance_set(reflection.name, association)
end
if association_proxy_class == HasOneAssociation
association.send(constructor, attributees, replace_existing)
else
association.send(constructor, attributees)
end
end
end
def add_counter_cache_callbacks(reflection)
cache_column = reflection.counter_cache_column
method_name = "belongs_to_counter_cache_after_create_for_#{reflection.name}".to_sym
define_method(method_name) do
association = send(reflection.name)
association.class.increment_counter(cache_column, send(reflection.primary_key_name)) unless association.nil?
end
after_create(method_name)
method_name = "belongs_to_counter_cache_before_destroy_for_#{reflection.name}".to_sym
define_method(method_name) do
association = send(reflection.name)
association.class.decrement_counter(cache_column, send(reflection.primary_key_name)) unless association.nil?
end
before_destroy(method_name)
module_eval(
"#{reflection.class_name}.send(:attr_readonly,\"#{cache_column}\".intern) if defined?(#{reflection.class_name}) && #{reflection.class_name}.respond_to?(:attr_readonly)"
)
end
def add_touch_callbacks(reflection, touch_attribute)
method_name = "belongs_to_touch_after_save_or_destroy_for_#{reflection.name}".to_sym
define_method(method_name) do
association = send(reflection.name)
if touch_attribute == true
association.touch unless association.nil?
else
association.touch(touch_attribute) unless association.nil?
end
end
after_save(method_name)
after_destroy(method_name)
end
def find_with_associations(options = {})
catch :invalid_query do
join_dependency = JoinDependency.new(self, merge_includes(scope(:find, :include), options[:include]), options[:joins])
rows = select_all_rows(options, join_dependency)
return join_dependency.instantiate(rows)
end
[]
end
# Creates before_destroy callback methods that nullify, delete or destroy
# has_many associated objects, according to the defined :dependent rule.
#
# See HasManyAssociation#delete_records. Dependent associations
# delete children, otherwise foreign key is set to NULL.
#
# The +extra_conditions+ parameter, which is not used within the main
# Active Record codebase, is meant to allow plugins to define extra
# finder conditions.
def configure_dependency_for_has_many(reflection, extra_conditions = nil)
if reflection.options.include?(:dependent)
# Add polymorphic type if the :as option is present
dependent_conditions = []
dependent_conditions << "#{reflection.primary_key_name} = \#{record.quoted_id}"
dependent_conditions << "#{reflection.options[:as]}_type = '#{base_class.name}'" if reflection.options[:as]
dependent_conditions << sanitize_sql(reflection.options[:conditions], reflection.quoted_table_name) if reflection.options[:conditions]
dependent_conditions << extra_conditions if extra_conditions
dependent_conditions = dependent_conditions.collect {|where| "(#{where})" }.join(" AND ")
dependent_conditions = dependent_conditions.gsub('@', '\@')
case reflection.options[:dependent]
when :destroy
method_name = "has_many_dependent_destroy_for_#{reflection.name}".to_sym
define_method(method_name) do
send(reflection.name).each { |o| o.destroy }
end
before_destroy method_name
when :delete_all
module_eval %Q{
before_destroy do |record| # before_destroy do |record|
delete_all_has_many_dependencies(record, # delete_all_has_many_dependencies(record,
"#{reflection.name}", # "posts",
#{reflection.class_name}, # Post,
%@#{dependent_conditions}@) # %@...@) # this is a string literal like %(...)
end # end
}
when :nullify
module_eval %Q{
before_destroy do |record| # before_destroy do |record|
nullify_has_many_dependencies(record, # nullify_has_many_dependencies(record,
"#{reflection.name}", # "posts",
#{reflection.class_name}, # Post,
"#{reflection.primary_key_name}", # "user_id",
%@#{dependent_conditions}@) # %@...@) # this is a string literal like %(...)
end # end
}
else
raise ArgumentError, "The :dependent option expects either :destroy, :delete_all, or :nullify (#{reflection.options[:dependent].inspect})"
end
end
end
# Creates before_destroy callback methods that nullify, delete or destroy
# has_one associated objects, according to the defined :dependent rule.
def configure_dependency_for_has_one(reflection)
if reflection.options.include?(:dependent)
case reflection.options[:dependent]
when :destroy
method_name = "has_one_dependent_destroy_for_#{reflection.name}".to_sym
define_method(method_name) do
association = send(reflection.name)
association.destroy unless association.nil?
end
before_destroy method_name
when :delete
method_name = "has_one_dependent_delete_for_#{reflection.name}".to_sym
define_method(method_name) do
# Retrieve the associated object and delete it. The retrieval
# is necessary because there may be multiple associated objects
# with foreign keys pointing to this object, and we only want
# to delete the correct one, not all of them.
association = send(reflection.name)
association.delete unless association.nil?
end
before_destroy method_name
when :nullify
method_name = "has_one_dependent_nullify_for_#{reflection.name}".to_sym
define_method(method_name) do
association = send(reflection.name)
association.update_attribute(reflection.primary_key_name, nil) unless association.nil?
end
before_destroy method_name
else
raise ArgumentError, "The :dependent option expects either :destroy, :delete or :nullify (#{reflection.options[:dependent].inspect})"
end
end
end
def configure_dependency_for_belongs_to(reflection)
if reflection.options.include?(:dependent)
case reflection.options[:dependent]
when :destroy
method_name = "belongs_to_dependent_destroy_for_#{reflection.name}".to_sym
define_method(method_name) do
association = send(reflection.name)
association.destroy unless association.nil?
end
after_destroy method_name
when :delete
method_name = "belongs_to_dependent_delete_for_#{reflection.name}".to_sym
define_method(method_name) do
association = send(reflection.name)
association.delete unless association.nil?
end
after_destroy method_name
else
raise ArgumentError, "The :dependent option expects either :destroy or :delete (#{reflection.options[:dependent].inspect})"
end
end
end
def delete_all_has_many_dependencies(record, reflection_name, association_class, dependent_conditions)
association_class.delete_all(dependent_conditions)
end
def nullify_has_many_dependencies(record, reflection_name, association_class, primary_key_name, dependent_conditions)
association_class.update_all("#{primary_key_name} = NULL", dependent_conditions)
end
mattr_accessor :valid_keys_for_has_many_association
@@valid_keys_for_has_many_association = [
:class_name, :table_name, :foreign_key, :primary_key,
:dependent,
:select, :conditions, :include, :order, :group, :having, :limit, :offset,
:as, :through, :source, :source_type,
:uniq,
:finder_sql, :counter_sql,
:before_add, :after_add, :before_remove, :after_remove,
:extend, :readonly,
:validate
]
def create_has_many_reflection(association_id, options, &extension)
options.assert_valid_keys(valid_keys_for_has_many_association)
options[:extend] = create_extension_modules(association_id, extension, options[:extend])
create_reflection(:has_many, association_id, options, self)
end
mattr_accessor :valid_keys_for_has_one_association
@@valid_keys_for_has_one_association = [
:class_name, :foreign_key, :remote, :select, :conditions, :order,
:include, :dependent, :counter_cache, :extend, :as, :readonly,
:validate, :primary_key
]
def create_has_one_reflection(association_id, options)
options.assert_valid_keys(valid_keys_for_has_one_association)
create_reflection(:has_one, association_id, options, self)
end
def create_has_one_through_reflection(association_id, options)
options.assert_valid_keys(
:class_name, :foreign_key, :remote, :select, :conditions, :order, :include, :dependent, :counter_cache, :extend, :as, :through, :source, :source_type, :validate
)
create_reflection(:has_one, association_id, options, self)
end
mattr_accessor :valid_keys_for_belongs_to_association
@@valid_keys_for_belongs_to_association = [
:class_name, :foreign_key, :foreign_type, :remote, :select, :conditions,
:include, :dependent, :counter_cache, :extend, :polymorphic, :readonly,
:validate, :touch
]
def create_belongs_to_reflection(association_id, options)
options.assert_valid_keys(valid_keys_for_belongs_to_association)
reflection = create_reflection(:belongs_to, association_id, options, self)
if options[:polymorphic]
reflection.options[:foreign_type] ||= reflection.class_name.underscore + "_type"
end
reflection
end
mattr_accessor :valid_keys_for_has_and_belongs_to_many_association
@@valid_keys_for_has_and_belongs_to_many_association = [
:class_name, :table_name, :join_table, :foreign_key, :association_foreign_key,
:select, :conditions, :include, :order, :group, :having, :limit, :offset,
:uniq,
:finder_sql, :counter_sql, :delete_sql, :insert_sql,
:before_add, :after_add, :before_remove, :after_remove,
:extend, :readonly,
:validate
]
def create_has_and_belongs_to_many_reflection(association_id, options, &extension)
options.assert_valid_keys(valid_keys_for_has_and_belongs_to_many_association)
options[:extend] = create_extension_modules(association_id, extension, options[:extend])
reflection = create_reflection(:has_and_belongs_to_many, association_id, options, self)
if reflection.association_foreign_key == reflection.primary_key_name
raise HasAndBelongsToManyAssociationForeignKeyNeeded.new(reflection)
end
reflection.options[:join_table] ||= join_table_name(undecorated_table_name(self.to_s), undecorated_table_name(reflection.class_name))
reflection
end
def reflect_on_included_associations(associations)
[ associations ].flatten.collect { |association| reflect_on_association(association.to_s.intern) }
end
def guard_against_unlimitable_reflections(reflections, options)
if (options[:offset] || options[:limit]) && !using_limitable_reflections?(reflections)
raise(
ConfigurationError,
"You can not use offset and limit together with has_many or has_and_belongs_to_many associations"
)
end
end
def select_all_rows(options, join_dependency)
connection.select_all(
construct_finder_sql_with_included_associations(options, join_dependency),
"#{name} Load Including Associations"
)
end
def construct_finder_sql_with_included_associations(options, join_dependency)
scope = scope(:find)
sql = "SELECT #{column_aliases(join_dependency)} FROM #{(scope && scope[:from]) || options[:from] || quoted_table_name} "
sql << join_dependency.join_associations.collect{|join| join.association_join }.join
add_joins!(sql, options[:joins], scope)
add_conditions!(sql, options[:conditions], scope)
add_limited_ids_condition!(sql, options, join_dependency) if !using_limitable_reflections?(join_dependency.reflections) && ((scope && scope[:limit]) || options[:limit])
add_group!(sql, options[:group], options[:having], scope)
add_order!(sql, options[:order], scope)
add_limit!(sql, options, scope) if using_limitable_reflections?(join_dependency.reflections)
add_lock!(sql, options, scope)
return sanitize_sql(sql)
end
def add_limited_ids_condition!(sql, options, join_dependency)
unless (id_list = select_limited_ids_list(options, join_dependency)).empty?
sql << "#{condition_word(sql)} #{connection.quote_table_name table_name}.#{primary_key} IN (#{id_list}) "
else
throw :invalid_query
end
end
def select_limited_ids_list(options, join_dependency)
pk = columns_hash[primary_key]
connection.select_all(
construct_finder_sql_for_association_limiting(options, join_dependency),
"#{name} Load IDs For Limited Eager Loading"
).collect { |row| connection.quote(row[primary_key], pk) }.join(", ")
end
def construct_finder_sql_for_association_limiting(options, join_dependency)
scope = scope(:find)
# Only join tables referenced in order or conditions since this is particularly slow on the pre-query.
tables_from_conditions = conditions_tables(options)
tables_from_order = order_tables(options)
all_tables = tables_from_conditions + tables_from_order
distinct_join_associations = all_tables.uniq.map{|table|
join_dependency.joins_for_table_name(table)
}.flatten.compact.uniq
order = options[:order]
if scoped_order = (scope && scope[:order])
order = order ? "#{order}, #{scoped_order}" : scoped_order
end
is_distinct = !options[:joins].blank? || include_eager_conditions?(options, tables_from_conditions) || include_eager_order?(options, tables_from_order)
sql = "SELECT "
if is_distinct
sql << connection.distinct("#{connection.quote_table_name table_name}.#{primary_key}", order)
else
sql << primary_key
end
sql << " FROM #{connection.quote_table_name table_name} "
if is_distinct
sql << distinct_join_associations.collect { |assoc| assoc.association_join }.join
add_joins!(sql, options[:joins], scope)
end
add_conditions!(sql, options[:conditions], scope)
add_group!(sql, options[:group], options[:having], scope)
if order && is_distinct
connection.add_order_by_for_association_limiting!(sql, :order => order)
else
add_order!(sql, options[:order], scope)
end
add_limit!(sql, options, scope)
return sanitize_sql(sql)
end
def tables_in_string(string)
return [] if string.blank?
string.scan(/([\.a-zA-Z_]+).?\./).flatten
end
def conditions_tables(options)
# look in both sets of conditions
conditions = [scope(:find, :conditions), options[:conditions]].inject([]) do |all, cond|
case cond
when nil then all
when Array then all << cond.first
when Hash then all << cond.keys
else all << cond
end
end
tables_in_string(conditions.join(' '))
end
def order_tables(options)
order = [options[:order], scope(:find, :order) ].join(", ")
return [] unless order && order.is_a?(String)
tables_in_string(order)
end
def selects_tables(options)
select = options[:select]
return [] unless select && select.is_a?(String)
tables_in_string(select)
end
def joined_tables(options)
scope = scope(:find)
joins = options[:joins]
merged_joins = scope && scope[:joins] && joins ? merge_joins(scope[:joins], joins) : (joins || scope && scope[:joins])
[table_name] + case merged_joins
when Symbol, Hash, Array
if array_of_strings?(merged_joins)
tables_in_string(merged_joins.join(' '))
else
join_dependency = ActiveRecord::Associations::ClassMethods::InnerJoinDependency.new(self, merged_joins, nil)
join_dependency.join_associations.collect {|join_association| [join_association.aliased_join_table_name, join_association.aliased_table_name]}.flatten.compact
end
else
tables_in_string(merged_joins)
end
end
# Checks if the conditions reference a table other than the current model table
def include_eager_conditions?(options, tables = nil, joined_tables = nil)
((tables || conditions_tables(options)) - (joined_tables || joined_tables(options))).any?
end
# Checks if the query order references a table other than the current model's table.
def include_eager_order?(options, tables = nil, joined_tables = nil)
((tables || order_tables(options)) - (joined_tables || joined_tables(options))).any?
end
def include_eager_select?(options, joined_tables = nil)
(selects_tables(options) - (joined_tables || joined_tables(options))).any?
end
def references_eager_loaded_tables?(options)
joined_tables = joined_tables(options)
include_eager_order?(options, nil, joined_tables) || include_eager_conditions?(options, nil, joined_tables) || include_eager_select?(options, joined_tables)
end
def using_limitable_reflections?(reflections)
reflections.reject { |r| [ :belongs_to, :has_one ].include?(r.macro) }.length.zero?
end
def column_aliases(join_dependency)
join_dependency.joins.collect{|join| join.column_names_with_alias.collect{|column_name, aliased_name|
"#{connection.quote_table_name join.aliased_table_name}.#{connection.quote_column_name column_name} AS #{aliased_name}"}}.flatten.join(", ")
end
def add_association_callbacks(association_name, options)
callbacks = %w(before_add after_add before_remove after_remove)
callbacks.each do |callback_name|
full_callback_name = "#{callback_name}_for_#{association_name}"
defined_callbacks = options[callback_name.to_sym]
if options.has_key?(callback_name.to_sym)
class_inheritable_reader full_callback_name.to_sym
write_inheritable_attribute(full_callback_name.to_sym, [defined_callbacks].flatten)
else
write_inheritable_attribute(full_callback_name.to_sym, [])
end
end
end
def condition_word(sql)
sql =~ /where/i ? " AND " : "WHERE "
end
def create_extension_modules(association_id, block_extension, extensions)
if block_extension
extension_module_name = "#{self.to_s.demodulize}#{association_id.to_s.camelize}AssociationExtension"
silence_warnings do
self.parent.const_set(extension_module_name, Module.new(&block_extension))
end
Array(extensions).push("#{self.parent}::#{extension_module_name}".constantize)
else
Array(extensions)
end
end
class JoinDependency # :nodoc:
attr_reader :joins, :reflections, :table_aliases
def initialize(base, associations, joins)
@joins = [JoinBase.new(base, joins)]
@associations = associations
@reflections = []
@base_records_hash = {}
@base_records_in_order = []
@table_aliases = Hash.new { |aliases, table| aliases[table] = 0 }
@table_aliases[base.table_name] = 1
build(associations)
end
def join_associations
@joins[1..-1].to_a
end
def join_base
@joins[0]
end
def instantiate(rows)
rows.each_with_index do |row, i|
primary_id = join_base.record_id(row)
unless @base_records_hash[primary_id]
@base_records_in_order << (@base_records_hash[primary_id] = join_base.instantiate(row))
end
construct(@base_records_hash[primary_id], @associations, join_associations.dup, row)
end
remove_duplicate_results!(join_base.active_record, @base_records_in_order, @associations)
return @base_records_in_order
end
def remove_duplicate_results!(base, records, associations)
case associations
when Symbol, String
reflection = base.reflections[associations]
if reflection && [:has_many, :has_and_belongs_to_many].include?(reflection.macro)
records.each { |record| record.send(reflection.name).target.uniq! }
end
when Array
associations.each do |association|
remove_duplicate_results!(base, records, association)
end
when Hash
associations.keys.each do |name|
reflection = base.reflections[name]
is_collection = [:has_many, :has_and_belongs_to_many].include?(reflection.macro)
parent_records = records.map do |record|
descendant = record.send(reflection.name)
next unless descendant
descendant.target.uniq! if is_collection
descendant
end.flatten.compact
remove_duplicate_results!(reflection.class_name.constantize, parent_records, associations[name]) unless parent_records.empty?
end
end
end
def join_for_table_name(table_name)
join = (@joins.select{|j|j.aliased_table_name == table_name.gsub(/^\"(.*)\"$/){$1} }.first) rescue nil
return join unless join.nil?
@joins.select{|j|j.is_a?(JoinAssociation) && j.aliased_join_table_name == table_name.gsub(/^\"(.*)\"$/){$1} }.first rescue nil
end
def joins_for_table_name(table_name)
join = join_for_table_name(table_name)
result = nil
if join && join.is_a?(JoinAssociation)
result = [join]
if join.parent && join.parent.is_a?(JoinAssociation)
result = joins_for_table_name(join.parent.aliased_table_name) +
result
end
end
result
end
protected
def build(associations, parent = nil)
parent ||= @joins.last
case associations
when Symbol, String
reflection = parent.reflections[associations.to_s.intern] or
raise ConfigurationError, "Association named '#{ associations }' was not found; perhaps you misspelled it?"
@reflections << reflection
@joins << build_join_association(reflection, parent)
when Array
associations.each do |association|
build(association, parent)
end
when Hash
associations.keys.sort{|a,b|a.to_s<=>b.to_s}.each do |name|
build(name, parent)
build(associations[name])
end
else
raise ConfigurationError, associations.inspect
end
end
# overridden in InnerJoinDependency subclass
def build_join_association(reflection, parent)
JoinAssociation.new(reflection, self, parent)
end
def construct(parent, associations, joins, row)
case associations
when Symbol, String
join = joins.detect{|j| j.reflection.name.to_s == associations.to_s && j.parent_table_name == parent.class.table_name }
raise(ConfigurationError, "No such association") if join.nil?
joins.delete(join)
construct_association(parent, join, row)
when Array
associations.each do |association|
construct(parent, association, joins, row)
end
when Hash
associations.keys.sort{|a,b|a.to_s<=>b.to_s}.each do |name|
join = joins.detect{|j| j.reflection.name.to_s == name.to_s && j.parent_table_name == parent.class.table_name }
raise(ConfigurationError, "No such association") if join.nil?
association = construct_association(parent, join, row)
joins.delete(join)
construct(association, associations[name], joins, row) if association
end
else
raise ConfigurationError, associations.inspect
end
end
def construct_association(record, join, row)
case join.reflection.macro
when :has_many, :has_and_belongs_to_many
collection = record.send(join.reflection.name)
collection.loaded
return nil if record.id.to_s != join.parent.record_id(row).to_s or row[join.aliased_primary_key].nil?
association = join.instantiate(row)
collection.target.push(association)
when :has_one
return if record.id.to_s != join.parent.record_id(row).to_s
return if record.instance_variable_defined?("@#{join.reflection.name}")
association = join.instantiate(row) unless row[join.aliased_primary_key].nil?
record.send("set_#{join.reflection.name}_target", association)
when :belongs_to
return if record.id.to_s != join.parent.record_id(row).to_s or row[join.aliased_primary_key].nil?
association = join.instantiate(row)
record.send("set_#{join.reflection.name}_target", association)
else
raise ConfigurationError, "unknown macro: #{join.reflection.macro}"
end
return association
end
class JoinBase # :nodoc:
attr_reader :active_record, :table_joins
delegate :table_name, :column_names, :primary_key, :reflections, :sanitize_sql, :to => :active_record
def initialize(active_record, joins = nil)
@active_record = active_record
@cached_record = {}
@table_joins = joins
end
def aliased_prefix
"t0"
end
def aliased_primary_key
"#{aliased_prefix}_r0"
end
def aliased_table_name
active_record.table_name
end
def column_names_with_alias
unless defined?(@column_names_with_alias)
@column_names_with_alias = []
([primary_key] + (column_names - [primary_key])).each_with_index do |column_name, i|
@column_names_with_alias << [column_name, "#{aliased_prefix}_r#{i}"]
end
end
@column_names_with_alias
end
def extract_record(row)
column_names_with_alias.inject({}){|record, (cn, an)| record[cn] = row[an]; record}
end
def record_id(row)
row[aliased_primary_key]
end
def instantiate(row)
@cached_record[record_id(row)] ||= active_record.send(:instantiate, extract_record(row))
end
end
class JoinAssociation < JoinBase # :nodoc:
attr_reader :reflection, :parent, :aliased_table_name, :aliased_prefix, :aliased_join_table_name, :parent_table_name
delegate :options, :klass, :through_reflection, :source_reflection, :to => :reflection
def initialize(reflection, join_dependency, parent = nil)
reflection.check_validity!
if reflection.options[:polymorphic]
raise EagerLoadPolymorphicError.new(reflection)
end
super(reflection.klass)
@join_dependency = join_dependency
@parent = parent
@reflection = reflection
@aliased_prefix = "t#{ join_dependency.joins.size }"
@parent_table_name = parent.active_record.table_name
@aliased_table_name = aliased_table_name_for(table_name)
if reflection.macro == :has_and_belongs_to_many
@aliased_join_table_name = aliased_table_name_for(reflection.options[:join_table], "_join")
end
if [:has_many, :has_one].include?(reflection.macro) && reflection.options[:through]
@aliased_join_table_name = aliased_table_name_for(reflection.through_reflection.klass.table_name, "_join")
end
end
def association_join
connection = reflection.active_record.connection
join = case reflection.macro
when :has_and_belongs_to_many
" #{join_type} %s ON %s.%s = %s.%s " % [
table_alias_for(options[:join_table], aliased_join_table_name),
connection.quote_table_name(aliased_join_table_name),
options[:foreign_key] || reflection.active_record.to_s.foreign_key,
connection.quote_table_name(parent.aliased_table_name),
reflection.active_record.primary_key] +
" #{join_type} %s ON %s.%s = %s.%s " % [
table_name_and_alias,
connection.quote_table_name(aliased_table_name),
klass.primary_key,
connection.quote_table_name(aliased_join_table_name),
options[:association_foreign_key] || klass.to_s.foreign_key
]
when :has_many, :has_one
case
when reflection.options[:through]
through_conditions = through_reflection.options[:conditions] ? "AND #{interpolate_sql(sanitize_sql(through_reflection.options[:conditions]))}" : ''
jt_foreign_key = jt_as_extra = jt_source_extra = jt_sti_extra = nil
first_key = second_key = as_extra = nil
if through_reflection.options[:as] # has_many :through against a polymorphic join
jt_foreign_key = through_reflection.options[:as].to_s + '_id'
jt_as_extra = " AND %s.%s = %s" % [
connection.quote_table_name(aliased_join_table_name),
connection.quote_column_name(through_reflection.options[:as].to_s + '_type'),
klass.quote_value(parent.active_record.base_class.name)
]
else
jt_foreign_key = through_reflection.primary_key_name
end
case source_reflection.macro
when :has_many
if source_reflection.options[:as]
first_key = "#{source_reflection.options[:as]}_id"
second_key = options[:foreign_key] || primary_key
as_extra = " AND %s.%s = %s" % [
connection.quote_table_name(aliased_table_name),
connection.quote_column_name("#{source_reflection.options[:as]}_type"),
klass.quote_value(source_reflection.active_record.base_class.name)
]
else
first_key = through_reflection.klass.base_class.to_s.foreign_key
second_key = options[:foreign_key] || primary_key
end
unless through_reflection.klass.descends_from_active_record?
jt_sti_extra = " AND %s.%s = %s" % [
connection.quote_table_name(aliased_join_table_name),
connection.quote_column_name(through_reflection.active_record.inheritance_column),
through_reflection.klass.quote_value(through_reflection.klass.sti_name)]
end
when :belongs_to
first_key = primary_key
if reflection.options[:source_type]
second_key = source_reflection.association_foreign_key
jt_source_extra = " AND %s.%s = %s" % [
connection.quote_table_name(aliased_join_table_name),
connection.quote_column_name(reflection.source_reflection.options[:foreign_type]),
klass.quote_value(reflection.options[:source_type])
]
else
second_key = source_reflection.primary_key_name
end
end
" #{join_type} %s ON (%s.%s = %s.%s%s%s%s) " % [
table_alias_for(through_reflection.klass.table_name, aliased_join_table_name),
connection.quote_table_name(parent.aliased_table_name),
connection.quote_column_name(parent.primary_key),
connection.quote_table_name(aliased_join_table_name),
connection.quote_column_name(jt_foreign_key),
jt_as_extra, jt_source_extra, jt_sti_extra
] +
" #{join_type} %s ON (%s.%s = %s.%s%s) " % [
table_name_and_alias,
connection.quote_table_name(aliased_table_name),
connection.quote_column_name(first_key),
connection.quote_table_name(aliased_join_table_name),
connection.quote_column_name(second_key),
as_extra
]
when reflection.options[:as] && [:has_many, :has_one].include?(reflection.macro)
" #{join_type} %s ON %s.%s = %s.%s AND %s.%s = %s" % [
table_name_and_alias,
connection.quote_table_name(aliased_table_name),
"#{reflection.options[:as]}_id",
connection.quote_table_name(parent.aliased_table_name),
parent.primary_key,
connection.quote_table_name(aliased_table_name),
"#{reflection.options[:as]}_type",
klass.quote_value(parent.active_record.base_class.name)
]
else
foreign_key = options[:foreign_key] || reflection.active_record.name.foreign_key
" #{join_type} %s ON %s.%s = %s.%s " % [
table_name_and_alias,
aliased_table_name,
foreign_key,
parent.aliased_table_name,
reflection.options[:primary_key] || parent.primary_key
]
end
when :belongs_to
" #{join_type} %s ON %s.%s = %s.%s " % [
table_name_and_alias,
connection.quote_table_name(aliased_table_name),
reflection.klass.primary_key,
connection.quote_table_name(parent.aliased_table_name),
options[:foreign_key] || reflection.primary_key_name
]
else
""
end || ''
join << %(AND %s) % [
klass.send(:type_condition, aliased_table_name)] unless klass.descends_from_active_record?
[through_reflection, reflection].each do |ref|
join << "AND #{interpolate_sql(sanitize_sql(ref.options[:conditions], aliased_table_name))} " if ref && ref.options[:conditions]
end
join
end
protected
def aliased_table_name_for(name, suffix = nil)
if !parent.table_joins.blank? && parent.table_joins.to_s.downcase =~ %r{join(\s+\w+)?\s+#{active_record.connection.quote_table_name name.downcase}\son}
@join_dependency.table_aliases[name] += 1
end
unless @join_dependency.table_aliases[name].zero?
# if the table name has been used, then use an alias
name = active_record.connection.table_alias_for "#{pluralize(reflection.name)}_#{parent_table_name}#{suffix}"
table_index = @join_dependency.table_aliases[name]
@join_dependency.table_aliases[name] += 1
name = name[0..active_record.connection.table_alias_length-3] + "_#{table_index+1}" if table_index > 0
else
@join_dependency.table_aliases[name] += 1
end
name
end
def pluralize(table_name)
ActiveRecord::Base.pluralize_table_names ? table_name.to_s.pluralize : table_name
end
def table_alias_for(table_name, table_alias)
"#{reflection.active_record.connection.quote_table_name(table_name)} #{table_alias if table_name != table_alias}".strip
end
def table_name_and_alias
table_alias_for table_name, @aliased_table_name
end
def interpolate_sql(sql)
instance_eval("%@#{sql.gsub('@', '\@')}@")
end
private
def join_type
"LEFT OUTER JOIN"
end
end
end
class InnerJoinDependency < JoinDependency # :nodoc:
protected
def build_join_association(reflection, parent)
InnerJoinAssociation.new(reflection, self, parent)
end
class InnerJoinAssociation < JoinAssociation
private
def join_type
"INNER JOIN"
end
end
end
end
end
end
| alphabetum/saasy | vendor/rails/activerecord/lib/active_record/associations.rb | Ruby | mit | 115,997 |
jest.mock("../../../NativeModules/GraphQLQueryCache")
import * as _cache from "../../../NativeModules/GraphQLQueryCache"
const cache: jest.Mocked<typeof _cache> = _cache as any
import { NetworkError } from "lib/utils/errors"
import { cacheMiddleware } from "../cacheMiddleware"
describe("cacheMiddleware", () => {
const operation = {
id: "SomeQueryID",
operationKind: "query",
}
const variables = {
id: "banksy",
}
const cacheConfig = {
force: false,
}
const request = {
operation,
variables,
cacheConfig,
fetchOpts: {},
}
const response = { json: { artist: { name: "Banksy" } }, status: 200, statusText: "OK" }
beforeEach(() => {
cache.clear.mockClear()
cache.clearAll.mockClear()
cache.get.mockClear()
cache.set.mockClear()
})
const mockedNext = () => {
return new Promise(resolve => {
resolve(response)
})
}
describe("without cached data", () => {
beforeEach(() => {
cache.get.mockImplementation(() => {
return Promise.resolve(null)
})
})
it("performs a fetch", async () => {
const data = await cacheMiddleware()(mockedNext)(request)
expect(data).toEqual(response)
})
it("caches the fetched data", async () => {
await cacheMiddleware()(mockedNext)(request)
expect(cache.set.mock.calls.length).toEqual(2)
expect(cache.set.mock.calls[0][0]).toEqual(operation.id)
})
describe("a response with errors", () => {
it("clears the cache and throws an error", async () => {
const mockedErrorsNext = () => {
return new Promise(resolve => {
resolve({
...response,
json: {
...response.json,
errors: [{ errorCode: 1234 }],
},
})
})
}
await expect(cacheMiddleware()(mockedErrorsNext)(request)).rejects.toEqual(new NetworkError("OK"))
// 1 cache call means we set request as in-flight.
expect(cache.set).toHaveBeenCalledTimes(1)
expect(cache.set).toHaveBeenCalledWith(operation.id, variables, null)
expect(cache.clear).toHaveBeenCalledWith(operation.id, variables)
})
})
})
describe("a 404 response from metaphysics", () => {
beforeAll(() => {
// @ts-ignore
__DEV__ = false
})
afterAll(() => {
// @ts-ignore
__DEV__ = true
})
it(`will be retried if the query id was not recognized by MP`, async () => {
let rejected = false
let retried = false
const mockedErrorsNext = req => {
if (JSON.parse(req.fetchOpts.body).documentID) {
rejected = true
return Promise.reject(new Error("Unable to serve persisted query with ID"))
} else {
retried = true
return Promise.resolve({
status: 200,
json: { data: { success: true }, errors: undefined },
})
}
}
await expect(cacheMiddleware()(mockedErrorsNext)(request)).resolves.toMatchObject({
json: { data: { success: true } },
})
expect(rejected).toBe(true)
expect(retried).toBe(true)
})
it(`will be not be retried if failure was something else`, async () => {
let rejected = false
let retried = false
const mockedErrorsNext = req => {
if (JSON.parse(req.fetchOpts.body).documentID) {
rejected = true
return Promise.reject(new Error("something unrecognized went wrong"))
} else {
retried = true
return Promise.resolve({
status: 200,
json: { data: { success: true }, errors: undefined },
})
}
}
await expect(cacheMiddleware()(mockedErrorsNext)(request)).rejects.toEqual(
new Error("something unrecognized went wrong")
)
expect(rejected).toBe(true)
expect(retried).toBe(false)
})
})
describe("a 500 response from metaphysics", () => {
it("clears the cache and throws an error", async () => {
const mockedErrorsNext = () => {
return new Promise(resolve => {
resolve({
status: 500,
statusText: "some weird 500 HTML page or something",
})
})
}
await expect(cacheMiddleware()(mockedErrorsNext)(request)).rejects.toEqual(
new NetworkError("some weird 500 HTML page or something")
)
// 1 cache call means we set request as in-flight.
expect(cache.set).toHaveBeenCalledTimes(1)
expect(cache.set).toHaveBeenCalledWith(operation.id, variables, null)
expect(cache.clear).toHaveBeenCalledWith(operation.id, variables)
})
})
describe("with cached data", () => {
it("does not perform a fetch by default", async () => {
cache.get.mockImplementation(() => Promise.resolve(JSON.stringify(response)))
expect(await cacheMiddleware()(mockedNext)(request)).toEqual(response)
})
it("does perform a fetch when forced", async () => {
const aRequest = {
operation,
variables,
cacheConfig: { force: true },
}
expect(await cacheMiddleware()(mockedNext)(aRequest)).toEqual(response)
})
it("clears the cache after a mutation", async () => {
const bRequest = {
operation: { id: "SomeMutation", operationKind: "mutation" },
variables,
cacheConfig,
}
await cacheMiddleware()(mockedNext)(bRequest)
expect(cache.clearAll).toHaveBeenCalled()
})
})
})
| artsy/emission | src/lib/relay/middlewares/__tests__/cacheMiddleware-tests.ts | TypeScript | mit | 5,547 |
<?php
// +----------------------------------------------------------------------
// | ShuipFCMS 帐户管理
// +----------------------------------------------------------------------
// | Copyright (c) 2012-2014 http://www.shuipfcms.com, All rights reserved.
// +----------------------------------------------------------------------
// | Author: 水平凡 <admin@abc3210.com>
// +----------------------------------------------------------------------
namespace Member\Controller;
class AccountController extends MemberbaseController {
//互联模型
protected $connect = NULL;
protected function _initialize() {
parent::_initialize();
$this->connect = D('Member/Connect');
}
//个人帐户
public function assets() {
$this->assign('isqqlogin', $this->connect->getUserAuthorize($this->userid, 'qq'));
$this->assign('isweibologin', $this->connect->getUserAuthorize($this->userid, 'sina_weibo'));
$this->display();
}
//取消绑定
public function cancelbind() {
$connectid = I('get.connectid', 0, 'intval');
if (empty($connectid)) {
$this->error('参数不正确!');
}
//查询出绑定信息
$info = $this->connect->where(array('connectid' => $connectid, 'uid' => $this->userid))->find();
if (empty($info)) {
$this->error('该绑定信息不存在,无法解绑!');
}
if ($this->connect->connectDel($connectid, $this->userid)) {
$this->success('解绑成功!');
} else {
$this->error('解绑失败!');
}
}
//授权绑定
public function authorize() {
$type = I('get.type');
if (empty($type)) {
$this->error('请指定授权类型!');
}
switch ($type) {
case 'qq':
$redirect_uri = self::$Cache['Config']['siteurl'] . "index.php?g=Member&m=Account&a=qqbind";
header("location:" . $this->connect->getUrlConnectQQ($redirect_uri));
break;
case 'sina_weibo':
$redirect_uri = self::$Cache['Config']['siteurl'] . "index.php?g=Member&m=Account&a=sinabind";
header("location:" . $this->connect->getUrlConnectSinaWeibo($redirect_uri));
break;
default:
$this->error('授权类型错误!');
break;
}
}
//QQ绑定
public function qqbind() {
$curl = new \Curl();
$sUrl = "https://graph.qq.com/oauth2.0/token";
$aGetParam = array(
"grant_type" => "authorization_code",
"client_id" => $this->memberConfig['qq_akey'],
"client_secret" => $this->memberConfig['qq_skey'],
"code" => $_GET["code"],
"state" => $_GET["state"],
"redirect_uri" => session("redirect_uri")
);
session("redirect_uri", NULL);
//Step2:通过Authorization Code获取Access Token
foreach ($aGetParam as $key => $val) {
$aGet[] = $key . "=" . urlencode($val);
}
$sContent = $curl->get($sUrl . "?" . implode("&", $aGet));
if ($sContent == FALSE) {
$this->error("帐号授权出现错误!");
}
//参数处理
$aTemp = explode("&", $sContent);
$aParam = array();
foreach ($aTemp as $val) {
$aTemp2 = explode("=", $val);
$aParam[$aTemp2[0]] = $aTemp2[1];
}
$sUrl = "https://graph.qq.com/oauth2.0/me";
$aGetParam = array(
"access_token" => $aParam["access_token"]
);
//$sContent = $this->get($sUrl, $aGetParam);
foreach ($aGetParam as $key => $val) {
$aGet[] = $key . "=" . urlencode($val);
}
$sContent = $curl->get($sUrl . "?" . implode("&", $aGet));
if ($sContent == FALSE) {
$this->error("帐号授权出现错误!");
}
$aTemp = array();
//处理授权成功以后,返回的一串类似:callback( {"client_id":"000","openid":"xxx"} );
preg_match('/callback\(\s+(.*?)\s+\)/i', $sContent, $aTemp);
//把json数据转换为数组
$aResult = json_decode($aTemp[1], true);
//合并数组,把access_token和expires_in合并。
$Result = array_merge($aResult, $aParam);
//检查帐号是否已经绑定过了
if ($this->connect->isUserAuthorize($Result['access_token'], 'qq')) {
$this->error('您已经绑定过,不能重复绑定!');
}
//绑定
if ($this->connect->connectAdd(array(
'openid' => $Result['openid'],
'uid' => $this->userid,
'app' => 'qq',
'accesstoken' => $Result['access_token'],
'expires' => time() + (int) $Result['expires_in'],
))) {
$this->success('绑定成功!', U('Account/assets'));
} else {
$this->error($this->connect->getError()?:'绑定失败!');
}
}
//新浪微博绑定
public function sinabind() {
$curl = new \Curl();
$sUrl = "https://api.weibo.com/oauth2/access_token";
$aGetParam = array(
"code" => $_GET["code"], //用于调用access_token,接口获取授权后的access token
"client_id" => $this->memberConfig['sinawb_akey'], //申请应用时分配的AppSecret
"client_secret" => $this->memberConfig['sinawb_skey'], //申请应用时分配的AppSecret
"grant_type" => "authorization_code", //请求的类型,可以为authorization_code、password、refresh_token。
"redirect_uri" => session("redirect_uri"), //回调地址
);
session("redirect_uri", NULL);
$sContent = $curl->post($sUrl, $aGetParam);
if ($sContent == FALSE) {
$this->error("帐号授权出现错误!");
}
//参数处理
$aParam = json_decode($sContent, true);
//检查帐号是否已经绑定过了
if ($this->connect->isUserAuthorize($aParam['access_token'], 'sina_weibo')) {
$this->error('您已经绑定过,不能重复绑定!');
}
//绑定
if ($this->connect->connectAdd(array(
'openid' => $aParam['uid'],
'uid' => $this->userid,
'app' => 'sina_weibo',
'accesstoken' => $aParam['access_token'],
'expires' => time() + (int) $aParam['expires_in'],
))) {
$this->success('绑定成功!', U('Account/assets'));
} else {
$this->error($this->connect->getError()?:'绑定失败!');
}
}
}
| rentianhua/tsf | shuipf/Application/Member/Controller/AccountController.class.php | PHP | mit | 6,831 |
//
// Questo file è stato generato dall'architettura JavaTM per XML Binding (JAXB) Reference Implementation, v2.2.8-b130911.1802
// Vedere <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Qualsiasi modifica a questo file andrà persa durante la ricompilazione dello schema di origine.
// Generato il: 2016.09.12 alle 10:18:45 PM CEST
//
package org.docbook.ns.docbook;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElements;
import javax.xml.bind.annotation.XmlID;
import javax.xml.bind.annotation.XmlIDREF;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlType;
import javax.xml.bind.annotation.adapters.CollapsedStringAdapter;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
/**
* <p>Classe Java per anonymous complex type.
*
* <p>Il seguente frammento di schema specifica il contenuto previsto contenuto in questa classe.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <sequence>
* <choice maxOccurs="unbounded" minOccurs="0">
* <element ref="{http://docbook.org/ns/docbook}title"/>
* <element ref="{http://docbook.org/ns/docbook}titleabbrev"/>
* </choice>
* <element ref="{http://docbook.org/ns/docbook}info" minOccurs="0"/>
* </sequence>
* <choice maxOccurs="unbounded" minOccurs="0">
* <element ref="{http://docbook.org/ns/docbook}itemizedlist"/>
* <element ref="{http://docbook.org/ns/docbook}orderedlist"/>
* <element ref="{http://docbook.org/ns/docbook}procedure"/>
* <element ref="{http://docbook.org/ns/docbook}simplelist"/>
* <element ref="{http://docbook.org/ns/docbook}variablelist"/>
* <element ref="{http://docbook.org/ns/docbook}segmentedlist"/>
* <element ref="{http://docbook.org/ns/docbook}glosslist"/>
* <element ref="{http://docbook.org/ns/docbook}bibliolist"/>
* <element ref="{http://docbook.org/ns/docbook}calloutlist"/>
* <element ref="{http://docbook.org/ns/docbook}qandaset"/>
* <element ref="{http://docbook.org/ns/docbook}example"/>
* <element ref="{http://docbook.org/ns/docbook}figure"/>
* <element ref="{http://docbook.org/ns/docbook}table"/>
* <element ref="{http://docbook.org/ns/docbook}equation"/>
* <element ref="{http://docbook.org/ns/docbook}informalexample"/>
* <element ref="{http://docbook.org/ns/docbook}informalfigure"/>
* <element ref="{http://docbook.org/ns/docbook}informaltable"/>
* <element ref="{http://docbook.org/ns/docbook}informalequation"/>
* <element ref="{http://docbook.org/ns/docbook}sidebar"/>
* <element ref="{http://docbook.org/ns/docbook}blockquote"/>
* <element ref="{http://docbook.org/ns/docbook}address"/>
* <element ref="{http://docbook.org/ns/docbook}epigraph"/>
* <element ref="{http://docbook.org/ns/docbook}mediaobject"/>
* <element ref="{http://docbook.org/ns/docbook}screenshot"/>
* <element ref="{http://docbook.org/ns/docbook}task"/>
* <element ref="{http://docbook.org/ns/docbook}productionset"/>
* <element ref="{http://docbook.org/ns/docbook}constraintdef"/>
* <element ref="{http://docbook.org/ns/docbook}msgset"/>
* <element ref="{http://docbook.org/ns/docbook}screen"/>
* <element ref="{http://docbook.org/ns/docbook}literallayout"/>
* <element ref="{http://docbook.org/ns/docbook}programlistingco"/>
* <element ref="{http://docbook.org/ns/docbook}screenco"/>
* <element ref="{http://docbook.org/ns/docbook}programlisting"/>
* <element ref="{http://docbook.org/ns/docbook}synopsis"/>
* <element ref="{http://docbook.org/ns/docbook}bridgehead"/>
* <element ref="{http://docbook.org/ns/docbook}remark"/>
* <element ref="{http://docbook.org/ns/docbook}revhistory"/>
* <element ref="{http://docbook.org/ns/docbook}indexterm"/>
* <element ref="{http://docbook.org/ns/docbook}funcsynopsis"/>
* <element ref="{http://docbook.org/ns/docbook}classsynopsis"/>
* <element ref="{http://docbook.org/ns/docbook}methodsynopsis"/>
* <element ref="{http://docbook.org/ns/docbook}constructorsynopsis"/>
* <element ref="{http://docbook.org/ns/docbook}destructorsynopsis"/>
* <element ref="{http://docbook.org/ns/docbook}fieldsynopsis"/>
* <element ref="{http://docbook.org/ns/docbook}cmdsynopsis"/>
* <element ref="{http://docbook.org/ns/docbook}caution"/>
* <element ref="{http://docbook.org/ns/docbook}important"/>
* <element ref="{http://docbook.org/ns/docbook}note"/>
* <element ref="{http://docbook.org/ns/docbook}tip"/>
* <element ref="{http://docbook.org/ns/docbook}warning"/>
* <element ref="{http://docbook.org/ns/docbook}anchor"/>
* <element ref="{http://docbook.org/ns/docbook}para"/>
* <element ref="{http://docbook.org/ns/docbook}formalpara"/>
* <element ref="{http://docbook.org/ns/docbook}simpara"/>
* <element ref="{http://docbook.org/ns/docbook}annotation"/>
* </choice>
* <element ref="{http://docbook.org/ns/docbook}listitem" maxOccurs="unbounded"/>
* </sequence>
* <attGroup ref="{http://docbook.org/ns/docbook}db.common.attributes"/>
* <attGroup ref="{http://docbook.org/ns/docbook}db.common.linking.attributes"/>
* <attribute name="role" type="{http://www.w3.org/2001/XMLSchema}anySimpleType" />
* <attribute name="spacing">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}token">
* <enumeration value="compact"/>
* <enumeration value="normal"/>
* </restriction>
* </simpleType>
* </attribute>
* <attribute name="mark" type="{http://www.w3.org/2001/XMLSchema}NMTOKEN" />
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"titlesAndTitleabbrevs",
"info",
"itemizedlistsAndOrderedlistsAndProcedures",
"listitems"
})
@XmlRootElement(name = "itemizedlist")
public class Itemizedlist {
@XmlElements({
@XmlElement(name = "title", type = Title.class),
@XmlElement(name = "titleabbrev", type = Titleabbrev.class)
})
protected List<Object> titlesAndTitleabbrevs;
protected Info info;
@XmlElements({
@XmlElement(name = "itemizedlist", type = Itemizedlist.class),
@XmlElement(name = "orderedlist", type = Orderedlist.class),
@XmlElement(name = "procedure", type = Procedure.class),
@XmlElement(name = "simplelist", type = Simplelist.class),
@XmlElement(name = "variablelist", type = Variablelist.class),
@XmlElement(name = "segmentedlist", type = Segmentedlist.class),
@XmlElement(name = "glosslist", type = Glosslist.class),
@XmlElement(name = "bibliolist", type = Bibliolist.class),
@XmlElement(name = "calloutlist", type = Calloutlist.class),
@XmlElement(name = "qandaset", type = Qandaset.class),
@XmlElement(name = "example", type = Example.class),
@XmlElement(name = "figure", type = Figure.class),
@XmlElement(name = "table", type = Table.class),
@XmlElement(name = "equation", type = Equation.class),
@XmlElement(name = "informalexample", type = Informalexample.class),
@XmlElement(name = "informalfigure", type = Informalfigure.class),
@XmlElement(name = "informaltable", type = Informaltable.class),
@XmlElement(name = "informalequation", type = Informalequation.class),
@XmlElement(name = "sidebar", type = Sidebar.class),
@XmlElement(name = "blockquote", type = Blockquote.class),
@XmlElement(name = "address", type = Address.class),
@XmlElement(name = "epigraph", type = Epigraph.class),
@XmlElement(name = "mediaobject", type = Mediaobject.class),
@XmlElement(name = "screenshot", type = Screenshot.class),
@XmlElement(name = "task", type = Task.class),
@XmlElement(name = "productionset", type = Productionset.class),
@XmlElement(name = "constraintdef", type = Constraintdef.class),
@XmlElement(name = "msgset", type = Msgset.class),
@XmlElement(name = "screen", type = Screen.class),
@XmlElement(name = "literallayout", type = Literallayout.class),
@XmlElement(name = "programlistingco", type = Programlistingco.class),
@XmlElement(name = "screenco", type = Screenco.class),
@XmlElement(name = "programlisting", type = Programlisting.class),
@XmlElement(name = "synopsis", type = Synopsis.class),
@XmlElement(name = "bridgehead", type = Bridgehead.class),
@XmlElement(name = "remark", type = Remark.class),
@XmlElement(name = "revhistory", type = Revhistory.class),
@XmlElement(name = "indexterm", type = Indexterm.class),
@XmlElement(name = "funcsynopsis", type = Funcsynopsis.class),
@XmlElement(name = "classsynopsis", type = Classsynopsis.class),
@XmlElement(name = "methodsynopsis", type = Methodsynopsis.class),
@XmlElement(name = "constructorsynopsis", type = Constructorsynopsis.class),
@XmlElement(name = "destructorsynopsis", type = Destructorsynopsis.class),
@XmlElement(name = "fieldsynopsis", type = Fieldsynopsis.class),
@XmlElement(name = "cmdsynopsis", type = Cmdsynopsis.class),
@XmlElement(name = "caution", type = Caution.class),
@XmlElement(name = "important", type = Important.class),
@XmlElement(name = "note", type = Note.class),
@XmlElement(name = "tip", type = Tip.class),
@XmlElement(name = "warning", type = Warning.class),
@XmlElement(name = "anchor", type = Anchor.class),
@XmlElement(name = "para", type = Para.class),
@XmlElement(name = "formalpara", type = Formalpara.class),
@XmlElement(name = "simpara", type = Simpara.class),
@XmlElement(name = "annotation", type = Annotation.class)
})
protected List<Object> itemizedlistsAndOrderedlistsAndProcedures;
@XmlElement(name = "listitem", required = true)
protected List<Listitem> listitems;
@XmlAttribute(name = "role")
@XmlSchemaType(name = "anySimpleType")
protected String role;
@XmlAttribute(name = "spacing")
@XmlJavaTypeAdapter(CollapsedStringAdapter.class)
protected String spacing;
@XmlAttribute(name = "mark")
@XmlJavaTypeAdapter(CollapsedStringAdapter.class)
@XmlSchemaType(name = "NMTOKEN")
protected String mark;
@XmlAttribute(name = "id", namespace = "http://www.w3.org/XML/1998/namespace")
@XmlJavaTypeAdapter(CollapsedStringAdapter.class)
@XmlID
@XmlSchemaType(name = "ID")
protected String id;
@XmlAttribute(name = "version")
@XmlSchemaType(name = "anySimpleType")
protected String commonVersion;
@XmlAttribute(name = "lang", namespace = "http://www.w3.org/XML/1998/namespace")
@XmlSchemaType(name = "anySimpleType")
protected String xmlLang;
@XmlAttribute(name = "base", namespace = "http://www.w3.org/XML/1998/namespace")
@XmlSchemaType(name = "anySimpleType")
protected String base;
@XmlAttribute(name = "remap")
@XmlSchemaType(name = "anySimpleType")
protected String remap;
@XmlAttribute(name = "xreflabel")
@XmlSchemaType(name = "anySimpleType")
protected String xreflabel;
@XmlAttribute(name = "revisionflag")
@XmlJavaTypeAdapter(CollapsedStringAdapter.class)
protected String revisionflag;
@XmlAttribute(name = "dir")
@XmlJavaTypeAdapter(CollapsedStringAdapter.class)
protected String dir;
@XmlAttribute(name = "arch")
@XmlSchemaType(name = "anySimpleType")
protected String arch;
@XmlAttribute(name = "audience")
@XmlSchemaType(name = "anySimpleType")
protected String audience;
@XmlAttribute(name = "condition")
@XmlSchemaType(name = "anySimpleType")
protected String condition;
@XmlAttribute(name = "conformance")
@XmlSchemaType(name = "anySimpleType")
protected String conformance;
@XmlAttribute(name = "os")
@XmlSchemaType(name = "anySimpleType")
protected String os;
@XmlAttribute(name = "revision")
@XmlSchemaType(name = "anySimpleType")
protected String commonRevision;
@XmlAttribute(name = "security")
@XmlSchemaType(name = "anySimpleType")
protected String security;
@XmlAttribute(name = "userlevel")
@XmlSchemaType(name = "anySimpleType")
protected String userlevel;
@XmlAttribute(name = "vendor")
@XmlSchemaType(name = "anySimpleType")
protected String vendor;
@XmlAttribute(name = "wordsize")
@XmlSchemaType(name = "anySimpleType")
protected String wordsize;
@XmlAttribute(name = "annotations")
@XmlSchemaType(name = "anySimpleType")
protected String annotations;
@XmlAttribute(name = "linkend")
@XmlIDREF
@XmlSchemaType(name = "IDREF")
protected Object linkend;
@XmlAttribute(name = "href", namespace = "http://www.w3.org/1999/xlink")
@XmlSchemaType(name = "anySimpleType")
protected String href;
@XmlAttribute(name = "type", namespace = "http://www.w3.org/1999/xlink")
@XmlSchemaType(name = "anySimpleType")
protected String xlinkType;
@XmlAttribute(name = "role", namespace = "http://www.w3.org/1999/xlink")
@XmlSchemaType(name = "anySimpleType")
protected String xlinkRole;
@XmlAttribute(name = "arcrole", namespace = "http://www.w3.org/1999/xlink")
@XmlSchemaType(name = "anySimpleType")
protected String arcrole;
@XmlAttribute(name = "title", namespace = "http://www.w3.org/1999/xlink")
@XmlSchemaType(name = "anySimpleType")
protected String xlinkTitle;
@XmlAttribute(name = "show", namespace = "http://www.w3.org/1999/xlink")
@XmlJavaTypeAdapter(CollapsedStringAdapter.class)
protected String show;
@XmlAttribute(name = "actuate", namespace = "http://www.w3.org/1999/xlink")
@XmlJavaTypeAdapter(CollapsedStringAdapter.class)
protected String actuate;
/**
* Gets the value of the titlesAndTitleabbrevs property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the titlesAndTitleabbrevs property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getTitlesAndTitleabbrevs().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link Title }
* {@link Titleabbrev }
*
*
*/
public List<Object> getTitlesAndTitleabbrevs() {
if (titlesAndTitleabbrevs == null) {
titlesAndTitleabbrevs = new ArrayList<Object>();
}
return this.titlesAndTitleabbrevs;
}
/**
* Recupera il valore della proprietà info.
*
* @return
* possible object is
* {@link Info }
*
*/
public Info getInfo() {
return info;
}
/**
* Imposta il valore della proprietà info.
*
* @param value
* allowed object is
* {@link Info }
*
*/
public void setInfo(Info value) {
this.info = value;
}
/**
* Gets the value of the itemizedlistsAndOrderedlistsAndProcedures property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the itemizedlistsAndOrderedlistsAndProcedures property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getItemizedlistsAndOrderedlistsAndProcedures().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link Itemizedlist }
* {@link Orderedlist }
* {@link Procedure }
* {@link Simplelist }
* {@link Variablelist }
* {@link Segmentedlist }
* {@link Glosslist }
* {@link Bibliolist }
* {@link Calloutlist }
* {@link Qandaset }
* {@link Example }
* {@link Figure }
* {@link Table }
* {@link Equation }
* {@link Informalexample }
* {@link Informalfigure }
* {@link Informaltable }
* {@link Informalequation }
* {@link Sidebar }
* {@link Blockquote }
* {@link Address }
* {@link Epigraph }
* {@link Mediaobject }
* {@link Screenshot }
* {@link Task }
* {@link Productionset }
* {@link Constraintdef }
* {@link Msgset }
* {@link Screen }
* {@link Literallayout }
* {@link Programlistingco }
* {@link Screenco }
* {@link Programlisting }
* {@link Synopsis }
* {@link Bridgehead }
* {@link Remark }
* {@link Revhistory }
* {@link Indexterm }
* {@link Funcsynopsis }
* {@link Classsynopsis }
* {@link Methodsynopsis }
* {@link Constructorsynopsis }
* {@link Destructorsynopsis }
* {@link Fieldsynopsis }
* {@link Cmdsynopsis }
* {@link Caution }
* {@link Important }
* {@link Note }
* {@link Tip }
* {@link Warning }
* {@link Anchor }
* {@link Para }
* {@link Formalpara }
* {@link Simpara }
* {@link Annotation }
*
*
*/
public List<Object> getItemizedlistsAndOrderedlistsAndProcedures() {
if (itemizedlistsAndOrderedlistsAndProcedures == null) {
itemizedlistsAndOrderedlistsAndProcedures = new ArrayList<Object>();
}
return this.itemizedlistsAndOrderedlistsAndProcedures;
}
/**
* Gets the value of the listitems property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the listitems property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getListitems().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link Listitem }
*
*
*/
public List<Listitem> getListitems() {
if (listitems == null) {
listitems = new ArrayList<Listitem>();
}
return this.listitems;
}
/**
* Recupera il valore della proprietà role.
*
* @return
* possible object is
* {@link String }
*
*/
public String getRole() {
return role;
}
/**
* Imposta il valore della proprietà role.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setRole(String value) {
this.role = value;
}
/**
* Recupera il valore della proprietà spacing.
*
* @return
* possible object is
* {@link String }
*
*/
public String getSpacing() {
return spacing;
}
/**
* Imposta il valore della proprietà spacing.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setSpacing(String value) {
this.spacing = value;
}
/**
* Recupera il valore della proprietà mark.
*
* @return
* possible object is
* {@link String }
*
*/
public String getMark() {
return mark;
}
/**
* Imposta il valore della proprietà mark.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setMark(String value) {
this.mark = value;
}
/**
* Recupera il valore della proprietà id.
*
* @return
* possible object is
* {@link String }
*
*/
public String getId() {
return id;
}
/**
* Imposta il valore della proprietà id.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setId(String value) {
this.id = value;
}
/**
* Recupera il valore della proprietà commonVersion.
*
* @return
* possible object is
* {@link String }
*
*/
public String getCommonVersion() {
return commonVersion;
}
/**
* Imposta il valore della proprietà commonVersion.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setCommonVersion(String value) {
this.commonVersion = value;
}
/**
* Recupera il valore della proprietà xmlLang.
*
* @return
* possible object is
* {@link String }
*
*/
public String getXmlLang() {
return xmlLang;
}
/**
* Imposta il valore della proprietà xmlLang.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setXmlLang(String value) {
this.xmlLang = value;
}
/**
* Recupera il valore della proprietà base.
*
* @return
* possible object is
* {@link String }
*
*/
public String getBase() {
return base;
}
/**
* Imposta il valore della proprietà base.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setBase(String value) {
this.base = value;
}
/**
* Recupera il valore della proprietà remap.
*
* @return
* possible object is
* {@link String }
*
*/
public String getRemap() {
return remap;
}
/**
* Imposta il valore della proprietà remap.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setRemap(String value) {
this.remap = value;
}
/**
* Recupera il valore della proprietà xreflabel.
*
* @return
* possible object is
* {@link String }
*
*/
public String getXreflabel() {
return xreflabel;
}
/**
* Imposta il valore della proprietà xreflabel.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setXreflabel(String value) {
this.xreflabel = value;
}
/**
* Recupera il valore della proprietà revisionflag.
*
* @return
* possible object is
* {@link String }
*
*/
public String getRevisionflag() {
return revisionflag;
}
/**
* Imposta il valore della proprietà revisionflag.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setRevisionflag(String value) {
this.revisionflag = value;
}
/**
* Recupera il valore della proprietà dir.
*
* @return
* possible object is
* {@link String }
*
*/
public String getDir() {
return dir;
}
/**
* Imposta il valore della proprietà dir.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setDir(String value) {
this.dir = value;
}
/**
* Recupera il valore della proprietà arch.
*
* @return
* possible object is
* {@link String }
*
*/
public String getArch() {
return arch;
}
/**
* Imposta il valore della proprietà arch.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setArch(String value) {
this.arch = value;
}
/**
* Recupera il valore della proprietà audience.
*
* @return
* possible object is
* {@link String }
*
*/
public String getAudience() {
return audience;
}
/**
* Imposta il valore della proprietà audience.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setAudience(String value) {
this.audience = value;
}
/**
* Recupera il valore della proprietà condition.
*
* @return
* possible object is
* {@link String }
*
*/
public String getCondition() {
return condition;
}
/**
* Imposta il valore della proprietà condition.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setCondition(String value) {
this.condition = value;
}
/**
* Recupera il valore della proprietà conformance.
*
* @return
* possible object is
* {@link String }
*
*/
public String getConformance() {
return conformance;
}
/**
* Imposta il valore della proprietà conformance.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setConformance(String value) {
this.conformance = value;
}
/**
* Recupera il valore della proprietà os.
*
* @return
* possible object is
* {@link String }
*
*/
public String getOs() {
return os;
}
/**
* Imposta il valore della proprietà os.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setOs(String value) {
this.os = value;
}
/**
* Recupera il valore della proprietà commonRevision.
*
* @return
* possible object is
* {@link String }
*
*/
public String getCommonRevision() {
return commonRevision;
}
/**
* Imposta il valore della proprietà commonRevision.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setCommonRevision(String value) {
this.commonRevision = value;
}
/**
* Recupera il valore della proprietà security.
*
* @return
* possible object is
* {@link String }
*
*/
public String getSecurity() {
return security;
}
/**
* Imposta il valore della proprietà security.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setSecurity(String value) {
this.security = value;
}
/**
* Recupera il valore della proprietà userlevel.
*
* @return
* possible object is
* {@link String }
*
*/
public String getUserlevel() {
return userlevel;
}
/**
* Imposta il valore della proprietà userlevel.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setUserlevel(String value) {
this.userlevel = value;
}
/**
* Recupera il valore della proprietà vendor.
*
* @return
* possible object is
* {@link String }
*
*/
public String getVendor() {
return vendor;
}
/**
* Imposta il valore della proprietà vendor.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setVendor(String value) {
this.vendor = value;
}
/**
* Recupera il valore della proprietà wordsize.
*
* @return
* possible object is
* {@link String }
*
*/
public String getWordsize() {
return wordsize;
}
/**
* Imposta il valore della proprietà wordsize.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setWordsize(String value) {
this.wordsize = value;
}
/**
* Recupera il valore della proprietà annotations.
*
* @return
* possible object is
* {@link String }
*
*/
public String getAnnotations() {
return annotations;
}
/**
* Imposta il valore della proprietà annotations.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setAnnotations(String value) {
this.annotations = value;
}
/**
* Recupera il valore della proprietà linkend.
*
* @return
* possible object is
* {@link Object }
*
*/
public Object getLinkend() {
return linkend;
}
/**
* Imposta il valore della proprietà linkend.
*
* @param value
* allowed object is
* {@link Object }
*
*/
public void setLinkend(Object value) {
this.linkend = value;
}
/**
* Recupera il valore della proprietà href.
*
* @return
* possible object is
* {@link String }
*
*/
public String getHref() {
return href;
}
/**
* Imposta il valore della proprietà href.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setHref(String value) {
this.href = value;
}
/**
* Recupera il valore della proprietà xlinkType.
*
* @return
* possible object is
* {@link String }
*
*/
public String getXlinkType() {
return xlinkType;
}
/**
* Imposta il valore della proprietà xlinkType.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setXlinkType(String value) {
this.xlinkType = value;
}
/**
* Recupera il valore della proprietà xlinkRole.
*
* @return
* possible object is
* {@link String }
*
*/
public String getXlinkRole() {
return xlinkRole;
}
/**
* Imposta il valore della proprietà xlinkRole.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setXlinkRole(String value) {
this.xlinkRole = value;
}
/**
* Recupera il valore della proprietà arcrole.
*
* @return
* possible object is
* {@link String }
*
*/
public String getArcrole() {
return arcrole;
}
/**
* Imposta il valore della proprietà arcrole.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setArcrole(String value) {
this.arcrole = value;
}
/**
* Recupera il valore della proprietà xlinkTitle.
*
* @return
* possible object is
* {@link String }
*
*/
public String getXlinkTitle() {
return xlinkTitle;
}
/**
* Imposta il valore della proprietà xlinkTitle.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setXlinkTitle(String value) {
this.xlinkTitle = value;
}
/**
* Recupera il valore della proprietà show.
*
* @return
* possible object is
* {@link String }
*
*/
public String getShow() {
return show;
}
/**
* Imposta il valore della proprietà show.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setShow(String value) {
this.show = value;
}
/**
* Recupera il valore della proprietà actuate.
*
* @return
* possible object is
* {@link String }
*
*/
public String getActuate() {
return actuate;
}
/**
* Imposta il valore della proprietà actuate.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setActuate(String value) {
this.actuate = value;
}
}
| mcaliman/dochi | src/org/docbook/ns/docbook/Itemizedlist.java | Java | mit | 33,730 |
import angular from 'angular-fix';
import utils from '../other/utils';
export default formlyConfig;
// @ngInject
function formlyConfig(formlyUsabilityProvider, formlyErrorAndWarningsUrlPrefix, formlyApiCheck) {
const typeMap = {};
const templateWrappersMap = {};
const defaultWrapperName = 'default';
const _this = this;
const getError = formlyUsabilityProvider.getFormlyError;
angular.extend(this, {
setType,
getType,
getTypeHeritage,
setWrapper,
getWrapper,
getWrapperByType,
removeWrapperByName,
removeWrappersForType,
disableWarnings: false,
extras: {
disableNgModelAttrsManipulator: false,
fieldTransform: [],
ngModelAttrsManipulatorPreferUnbound: false,
removeChromeAutoComplete: false,
defaultHideDirective: 'ng-if',
getFieldId: null
},
templateManipulators: {
preWrapper: [],
postWrapper: []
},
$get: () => this
});
function setType(options) {
if (angular.isArray(options)) {
const allTypes = [];
angular.forEach(options, item => {
allTypes.push(setType(item));
});
return allTypes;
} else if (angular.isObject(options)) {
checkType(options);
if (options.extends) {
extendTypeOptions(options);
}
typeMap[options.name] = options;
return typeMap[options.name];
} else {
throw getError(`You must provide an object or array for setType. You provided: ${JSON.stringify(arguments)}`);
}
}
function checkType(options) {
formlyApiCheck.throw(formlyApiCheck.formlyTypeOptions, options, {
prefix: 'formlyConfig.setType',
url: 'settype-validation-failed'
});
if (!options.overwriteOk) {
checkOverwrite(options.name, typeMap, options, 'types');
} else {
options.overwriteOk = undefined;
}
}
function extendTypeOptions(options) {
const extendsType = getType(options.extends, true, options);
extendTypeControllerFunction(options, extendsType);
extendTypeLinkFunction(options, extendsType);
extendTypeDefaultOptions(options, extendsType);
utils.reverseDeepMerge(options, extendsType);
extendTemplate(options, extendsType);
}
function extendTemplate(options, extendsType) {
if (options.template && extendsType.templateUrl) {
delete options.templateUrl;
} else if (options.templateUrl && extendsType.template) {
delete options.template;
}
}
function extendTypeControllerFunction(options, extendsType) {
const extendsCtrl = extendsType.controller;
if (!angular.isDefined(extendsCtrl)) {
return;
}
const optionsCtrl = options.controller;
if (angular.isDefined(optionsCtrl)) {
options.controller = function($scope, $controller) {
$controller(extendsCtrl, {$scope});
$controller(optionsCtrl, {$scope});
};
options.controller.$inject = ['$scope', '$controller'];
} else {
options.controller = extendsCtrl;
}
}
function extendTypeLinkFunction(options, extendsType) {
const extendsFn = extendsType.link;
if (!angular.isDefined(extendsFn)) {
return;
}
const optionsFn = options.link;
if (angular.isDefined(optionsFn)) {
options.link = function() {
extendsFn(...arguments);
optionsFn(...arguments);
};
} else {
options.link = extendsFn;
}
}
function extendTypeDefaultOptions(options, extendsType) {
const extendsDO = extendsType.defaultOptions;
if (!angular.isDefined(extendsDO)) {
return;
}
const optionsDO = options.defaultOptions;
const optionsDOIsFn = angular.isFunction(optionsDO);
const extendsDOIsFn = angular.isFunction(extendsDO);
if (extendsDOIsFn) {
options.defaultOptions = function defaultOptions(opts, scope) {
const extendsDefaultOptions = extendsDO(opts, scope);
const mergedDefaultOptions = {};
utils.reverseDeepMerge(mergedDefaultOptions, opts, extendsDefaultOptions);
let extenderOptionsDefaultOptions = optionsDO;
if (optionsDOIsFn) {
extenderOptionsDefaultOptions = extenderOptionsDefaultOptions(mergedDefaultOptions, scope);
}
utils.reverseDeepMerge(extendsDefaultOptions, extenderOptionsDefaultOptions);
return extendsDefaultOptions;
};
} else if (optionsDOIsFn) {
options.defaultOptions = function defaultOptions(opts, scope) {
const newDefaultOptions = {};
utils.reverseDeepMerge(newDefaultOptions, opts, extendsDO);
return optionsDO(newDefaultOptions, scope);
};
}
}
function getType(name, throwError, errorContext) {
if (!name) {
return undefined;
}
const type = typeMap[name];
if (!type && throwError === true) {
throw getError(
`There is no type by the name of "${name}": ${JSON.stringify(errorContext)}`
);
} else {
return type;
}
}
function getTypeHeritage(parent) {
const heritage = [];
let type = parent;
if (angular.isString(type)) {
type = getType(parent);
}
parent = type.extends;
while (parent) {
type = getType(parent);
heritage.push(type);
parent = type.extends;
}
return heritage;
}
function setWrapper(options, name) {
if (angular.isArray(options)) {
return options.map(wrapperOptions => setWrapper(wrapperOptions));
} else if (angular.isObject(options)) {
options.types = getOptionsTypes(options);
options.name = getOptionsName(options, name);
checkWrapperAPI(options);
templateWrappersMap[options.name] = options;
return options;
} else if (angular.isString(options)) {
return setWrapper({
template: options,
name
});
}
}
function getOptionsTypes(options) {
if (angular.isString(options.types)) {
return [options.types];
}
if (!angular.isDefined(options.types)) {
return [];
} else {
return options.types;
}
}
function getOptionsName(options, name) {
return options.name || name || options.types.join(' ') || defaultWrapperName;
}
function checkWrapperAPI(options) {
formlyUsabilityProvider.checkWrapper(options);
if (options.template) {
formlyUsabilityProvider.checkWrapperTemplate(options.template, options);
}
if (!options.overwriteOk) {
checkOverwrite(options.name, templateWrappersMap, options, 'templateWrappers');
} else {
delete options.overwriteOk;
}
checkWrapperTypes(options);
}
function checkWrapperTypes(options) {
const shouldThrow = !angular.isArray(options.types) || !options.types.every(angular.isString);
if (shouldThrow) {
throw getError(`Attempted to create a template wrapper with types that is not a string or an array of strings`);
}
}
function checkOverwrite(property, object, newValue, objectName) {
if (object.hasOwnProperty(property)) {
warn('overwriting-types-or-wrappers', [
`Attempting to overwrite ${property} on ${objectName} which is currently`,
`${JSON.stringify(object[property])} with ${JSON.stringify(newValue)}`,
`To supress this warning, specify the property "overwriteOk: true"`
].join(' '));
}
}
function getWrapper(name) {
return templateWrappersMap[name || defaultWrapperName];
}
function getWrapperByType(type) {
/* eslint prefer-const:0 */
const wrappers = [];
for (let name in templateWrappersMap) {
if (templateWrappersMap.hasOwnProperty(name)) {
if (templateWrappersMap[name].types && templateWrappersMap[name].types.indexOf(type) !== -1) {
wrappers.push(templateWrappersMap[name]);
}
}
}
return wrappers;
}
function removeWrapperByName(name) {
const wrapper = templateWrappersMap[name];
delete templateWrappersMap[name];
return wrapper;
}
function removeWrappersForType(type) {
const wrappers = getWrapperByType(type);
if (!wrappers) {
return undefined;
}
if (!angular.isArray(wrappers)) {
return removeWrapperByName(wrappers.name);
} else {
wrappers.forEach((wrapper) => removeWrapperByName(wrapper.name));
return wrappers;
}
}
function warn() {
if (!_this.disableWarnings && console.warn) {
/* eslint no-console:0 */
const args = Array.prototype.slice.call(arguments);
const warnInfoSlug = args.shift();
args.unshift('Formly Warning:');
args.push(`${formlyErrorAndWarningsUrlPrefix}${warnInfoSlug}`);
console.warn(...args);
}
}
}
| kentcdodds/angular-formly | src/providers/formlyConfig.js | JavaScript | mit | 8,628 |
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
/*
| -------------------------------------------------------------------
| DATABASE CONNECTIVITY SETTINGS
| -------------------------------------------------------------------
| This file will contain the settings needed to access your database.
|
| For complete instructions please consult the 'Database Connection'
| page of the User Guide.
|
| -------------------------------------------------------------------
| EXPLANATION OF VARIABLES
| -------------------------------------------------------------------
|
| ['dsn'] The full DSN string describe a connection to the database.
| ['hostname'] The hostname of your database server.
| ['username'] The username used to connect to the database
| ['password'] The password used to connect to the database
| ['database'] The name of the database you want to connect to
| ['dbdriver'] The database driver. e.g.: mysqli.
| Currently supported:
| cubrid, ibase, mssql, mysql, mysqli, oci8,
| odbc, pdo, postgre, sqlite, sqlite3, sqlsrv
| ['dbprefix'] You can add an optional prefix, which will be added
| to the table name when using the Query Builder class
| ['pconnect'] TRUE/FALSE - Whether to use a persistent connection
| ['db_debug'] TRUE/FALSE - Whether database errors should be displayed.
| ['cache_on'] TRUE/FALSE - Enables/disables query caching
| ['cachedir'] The path to the folder where cache files should be stored
| ['char_set'] The character set used in communicating with the database
| ['dbcollat'] The character collation used in communicating with the database
| NOTE: For MySQL and MySQLi databases, this setting is only used
| as a backup if your server is running PHP < 5.2.3 or MySQL < 5.0.7
| (and in table creation queries made with DB Forge).
| There is an incompatibility in PHP with mysql_real_escape_string() which
| can make your site vulnerable to SQL injection if you are using a
| multi-byte character set and are running versions lower than these.
| Sites using Latin-1 or UTF-8 database character set and collation are unaffected.
| ['swap_pre'] A default table prefix that should be swapped with the dbprefix
| ['encrypt'] Whether or not to use an encrypted connection.
|
| 'mysql' (deprecated), 'sqlsrv' and 'pdo/sqlsrv' drivers accept TRUE/FALSE
| 'mysqli' and 'pdo/mysql' drivers accept an array with the following options:
|
| 'ssl_key' - Path to the private key file
| 'ssl_cert' - Path to the public key certificate file
| 'ssl_ca' - Path to the certificate authority file
| 'ssl_capath' - Path to a directory containing trusted CA certificats in PEM format
| 'ssl_cipher' - List of *allowed* ciphers to be used for the encryption, separated by colons (':')
| 'ssl_verify' - TRUE/FALSE; Whether verify the server certificate or not ('mysqli' only)
|
| ['compress'] Whether or not to use client compression (MySQL only)
| ['stricton'] TRUE/FALSE - forces 'Strict Mode' connections
| - good for ensuring strict SQL while developing
| ['ssl_options'] Used to set various SSL options that can be used when making SSL connections.
| ['failover'] array - A array with 0 or more data for connections if the main should fail.
| ['save_queries'] TRUE/FALSE - Whether to "save" all executed queries.
| NOTE: Disabling this will also effectively disable both
| $this->db->last_query() and profiling of DB queries.
| When you run a query, with this setting set to TRUE (default),
| CodeIgniter will store the SQL statement for debugging purposes.
| However, this may cause high memory usage, especially if you run
| a lot of SQL queries ... disable this to avoid that problem.
|
| The $active_group variable lets you choose which connection group to
| make active. By default there is only one group (the 'default' group).
|
| The $query_builder variables lets you determine whether or not to load
| the query builder class.
*/
$active_group = 'default';
$query_builder = TRUE;
$db['default'] = array(
'dsn' => '',
'hostname' => 'localhost',
'username' => 'root',
'password' => '',
'database' => 'controlx',
'dbdriver' => 'mysqli',
'dbprefix' => '',
'pconnect' => FALSE,
'db_debug' => (ENVIRONMENT !== 'production'),
'cache_on' => FALSE,
'cachedir' => '',
'char_set' => 'utf8',
'dbcollat' => 'utf8_general_ci',
'swap_pre' => '',
'encrypt' => FALSE,
'compress' => FALSE,
'stricton' => FALSE,
'failover' => array(),
'save_queries' => TRUE
);
| leleuvilela/controlx | application/config/database.php | PHP | mit | 4,527 |
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { HomeComponent as Home } from '../components';
import { ProtectedContainer } from '.';
class HomeContainer extends Component {
render () {
return (
<ProtectedContainer>
<Home user={this.props.user} />
</ProtectedContainer>
);
}
}
HomeContainer.navigationOptions = {
title: 'Home',
drawerLabel: 'Home'
};
export default connect(
state => ({
user: state.user
})
)(HomeContainer);
| advantys/workflowgen-templates | integration/azure/authentication/azure-v1/auth-code-pkce/WorkflowGenExample/containers/HomeContainer.js | JavaScript | mit | 515 |
# encoding: utf-8
require 'spec_helper'
describe "Form I Past" do
context "regular past" do
it 'conjugates form I regular past' do
verb = Verb.new({root1: "ك", root2: "ت", root3: "ب", form: "1", tense: "past", pronoun: :she})
expect(verb.conjugate).to eq("كتبت")
end
it 'conjugates form I regular past with first radical hamza' do
verb = Verb.new({root1: "ء", root2: "ك", root3: "ل", form: "1", tense: "past", pronoun: :she})
expect(verb.conjugate).to eq("أكلت")
end
it 'conjugates form I regular past with second radical hamza' do
verb = Verb.new({root1: "س", root2: "ء", root3: "ل", form: "1", tense: "past", pronoun: :they})
expect(verb.conjugate).to eq("سألوا")
end
it 'conjugates form I regular past with third radical hamza' do
verb = Verb.new({root1: "ج", root2: "ر", root3: "ء", form: "1", tense: "past", pronoun: :she})
expect(verb.conjugate).to eq("جرؤت")
end
end
context "defective past" do
it 'conjugates form I defective past with final root waaw, :he' do
verb = Verb.new({root1: "ش", root2: "ك", root3: "و", form: "1", tense: "past", pronoun: :he})
expect(verb.conjugate).to eq("شكا")
end
it 'conjugates form I defective past with final root waaw, :you_m' do
verb = Verb.new({root1: "ش", root2: "ك", root3: "و", form: "1", tense: "past", pronoun: :you_m})
expect(verb.conjugate).to eq("شكوت")
end
it 'conjugates form I defective past, final root waaw, irregular' do
verb = Verb.new({root1: "ر", root2: "ض", root3: "و", form: "1", tense: "past", pronoun: :he})
expect(verb.conjugate).to eq("رضى")
end
it 'conjugates form I defective past with final root yaa' do
verb = Verb.new({root1: "د", root2: "ع", root3: "ي", form: "1", tense: "past", pronoun: :he})
expect(verb.conjugate).to eq("دعى")
end
it 'conjugates form I defective past with final root yaa, you_pl' do
verb = Verb.new({root1: "د", root2: "ع", root3: "ي", form: "1", tense: "past", pronoun: :you_pl})
expect(verb.conjugate).to eq("دعيتم")
end
it 'conjugates form I defective past with final root yaa, irregular' do
verb = Verb.new({root1: "ن", root2: "س", root3: "ي", form: "1", tense: "past", pronoun: :he})
expect(verb.conjugate).to eq("نسي")
end
end
context "hollow-defective past" do
it 'conjugates form I hollow-defective, waaw-yaa' do
verb = Verb.new({root1: "ر", root2: "و", root3: "ي", form: "1", tense: "past", pronoun: :he})
expect(verb.conjugate).to eq("روى")
end
it 'conjugates form I hollow-defective, waaw-yaa, irregular' do
verb = Verb.new({root1: "س", root2: "و", root3: "ي", form: "1", tense: "past", pronoun: :he})
expect(verb.conjugate).to eq("سوي")
end
it 'conjugates form I hollow-defective, yaa-yaa' do
verb = Verb.new({root1: "ح", root2: "ي", root3: "ي", form: "1", tense: "past", pronoun: :he})
expect(verb.conjugate).to eq("حيي")
end
end
context 'assimilated-defective past' do
it 'conjugates form I assimilated-defective, waaw-yaa, :they' do
verb = Verb.new({root1: "و", root2: "ف", root3: "ي", form: "1", tense: "past", pronoun: :they})
expect(verb.conjugate).to eq("وفوا")
end
it 'conjugates form I assimilated-defective, waaw-yaa, :he' do
verb = Verb.new({root1: "و", root2: "ف", root3: "ي", form: "1", tense: "past", pronoun: :he})
expect(verb.conjugate).to eq("وفى")
end
it 'conjugates form I assimilated-defective, waawy-yaa, irregular' do
verb = Verb.new({root1: "و", root2: "ل", root3: "ي", form: "1", tense: "past", pronoun: :he})
expect(verb.conjugate).to eq("ولي")
end
end
context 'hamzated-defective past' do
it 'conjugates form I hamzated-defective, second radical hamza' do
verb = Verb.new({root1: "ر", root2: "ء", root3: "ي", form: "1", tense: "past", pronoun: :he})
expect(verb.conjugate).to eq("رأى")
end
end
context "hollow past" do
it 'conjugates form I hollow past, :he' do
verb = Verb.new({root1: "ق", root2: "و", root3: "ل", form: "1", tense: "past", pronoun: :he})
expect(verb.conjugate).to eq("قال")
end
it 'conjugates form I hollow past, :you_f' do
verb = Verb.new({root1: "ق", root2: "و", root3: "ل", form: "1", tense: "past", pronoun: :you_f})
expect(verb.conjugate).to eq("قلت")
end
it 'conjugates form I hollow past, irregular, :he' do
verb = Verb.new({root1: "ل", root2: "ي", root3: "س", form: "1", tense: "past", pronoun: :he})
expect(verb.conjugate).to eq("ليس")
end
end
context 'hollow-hamzated' do
it 'conjugates form I hollow past with third radical hamza, :he' do
verb = Verb.new({root1: "ج", root2: "ي", root3: "ء", form: "1", tense: "past", pronoun: :he})
expect(verb.conjugate).to eq("جاء")
end
it 'conjugates form I hollow past with third radical hamza, :you_m' do
verb = Verb.new({root1: "ج", root2: "ي", root3: "ء", form: "1", tense: "past", pronoun: :you_m})
expect(verb.conjugate).to eq("جئت")
end
end
context "assimilated past" do
it 'conjugates form I assimilated past with root 1 waaw' do
verb = Verb.new({root1: "و", root2: "ص", root3: "ف", form: "1", tense: "past", pronoun: :she})
expect(verb.conjugate).to eq("وصفت")
end
it 'conjugates form I assimilated past with root 1 yaa' do
verb = Verb.new({root1: "ي", root2: "ق", root3: "ظ", form: "1", tense: "past", pronoun: :you_m})
expect(verb.conjugate).to eq("يقظت")
end
end
context "doubled past" do
it 'conjugates form I doubled past, :you_m' do
verb = Verb.new({root1: "ر", root2: "د", root3: "د", form: "1", tense: "past", pronoun: :you_m})
expect(verb.conjugate).to eq("رددت")
end
it 'conjugates form I doubled past, :she' do
verb = Verb.new({root1: "ر", root2: "د", root3: "د", form: "1", tense: "past", pronoun: :she})
expect(verb.conjugate).to eq("ردّت")
end
it 'conjugates form I doubled assimilated past' do
verb = Verb.new({root1: "و", root2: "د", root3: "د", form: "1", tense: "past", pronoun: :she})
expect(verb.conjugate).to eq("ودّت")
end
end
end | awillborn/Arabic-Conjugator | spec/past_tense/formI_past_spec.rb | Ruby | mit | 6,446 |
# -*- coding: utf-8 -*-
# Define here the models for your scraped items
#
# See documentation in:
# http://doc.scrapy.org/en/latest/topics/items.html
import scrapy
class MeiziItem(scrapy.Item):
# define the fields for your item here like:
# name = scrapy.Field()
page_num = scrapy.Field()
img_url = scrapy.Field()
img_md5 = scrapy.Field()
up_vote = scrapy.Field()
down_vote = scrapy.Field()
image_urls = scrapy.Field()
images = scrapy.Field()
| JMwill/wiki | notebook/tool/spider/meizi_spider/python_spider/meizi/meizi/items.py | Python | mit | 514 |
# encoding: utf-8
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
module Azure::Network::Mgmt::V2018_02_01
module Models
#
# Response for ListPeering API service call retrieves all peerings that
# belong to an ExpressRouteCrossConnection.
#
class ExpressRouteCrossConnectionPeeringList
include MsRestAzure
include MsRest::JSONable
# @return [Array<ExpressRouteCrossConnectionPeering>] The peerings in an
# express route cross connection.
attr_accessor :value
# @return [String] The URL to get the next set of results.
attr_accessor :next_link
# return [Proc] with next page method call.
attr_accessor :next_method
#
# Gets the rest of the items for the request, enabling auto-pagination.
#
# @return [Array<ExpressRouteCrossConnectionPeering>] operation results.
#
def get_all_items
items = @value
page = self
while page.next_link != nil && !page.next_link.strip.empty? do
page = page.get_next_page
items.concat(page.value)
end
items
end
#
# Gets the next page of results.
#
# @return [ExpressRouteCrossConnectionPeeringList] with next page
# content.
#
def get_next_page
response = @next_method.call(@next_link).value! unless @next_method.nil?
unless response.nil?
@next_link = response.body.next_link
@value = response.body.value
self
end
end
#
# Mapper for ExpressRouteCrossConnectionPeeringList class as Ruby Hash.
# This will be used for serialization/deserialization.
#
def self.mapper()
{
client_side_validation: true,
required: false,
serialized_name: 'ExpressRouteCrossConnectionPeeringList',
type: {
name: 'Composite',
class_name: 'ExpressRouteCrossConnectionPeeringList',
model_properties: {
value: {
client_side_validation: true,
required: false,
serialized_name: 'value',
type: {
name: 'Sequence',
element: {
client_side_validation: true,
required: false,
serialized_name: 'ExpressRouteCrossConnectionPeeringElementType',
type: {
name: 'Composite',
class_name: 'ExpressRouteCrossConnectionPeering'
}
}
}
},
next_link: {
client_side_validation: true,
required: false,
read_only: true,
serialized_name: 'nextLink',
type: {
name: 'String'
}
}
}
}
}
end
end
end
end
| Azure/azure-sdk-for-ruby | management/azure_mgmt_network/lib/2018-02-01/generated/azure_mgmt_network/models/express_route_cross_connection_peering_list.rb | Ruby | mit | 3,078 |
// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2012 The Bitcoin developers
// Copyright (c) 2011-2012 Litecoin Developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "irc.h"
#include "net.h"
#include "strlcpy.h"
#include "base58.h"
using namespace std;
using namespace boost;
int nGotIRCAddresses = 0;
void ThreadIRCSeed2(void* parg);
#pragma pack(push, 1)
struct ircaddr
{
struct in_addr ip;
short port;
};
#pragma pack(pop)
string EncodeAddress(const CService& addr)
{
struct ircaddr tmp;
if (addr.GetInAddr(&tmp.ip))
{
tmp.port = htons(addr.GetPort());
vector<unsigned char> vch(UBEGIN(tmp), UEND(tmp));
return string("u") + EncodeBase58Check(vch);
}
return "";
}
bool DecodeAddress(string str, CService& addr)
{
vector<unsigned char> vch;
if (!DecodeBase58Check(str.substr(1), vch))
return false;
struct ircaddr tmp;
if (vch.size() != sizeof(tmp))
return false;
memcpy(&tmp, &vch[0], sizeof(tmp));
addr = CService(tmp.ip, ntohs(tmp.port));
return true;
}
static bool Send(SOCKET hSocket, const char* pszSend)
{
if (strstr(pszSend, "PONG") != pszSend)
printf("IRC SENDING: %s\n", pszSend);
const char* psz = pszSend;
const char* pszEnd = psz + strlen(psz);
while (psz < pszEnd)
{
int ret = send(hSocket, psz, pszEnd - psz, MSG_NOSIGNAL);
if (ret < 0)
return false;
psz += ret;
}
return true;
}
bool RecvLineIRC(SOCKET hSocket, string& strLine)
{
loop
{
bool fRet = RecvLine(hSocket, strLine);
if (fRet)
{
if (fShutdown)
return false;
vector<string> vWords;
ParseString(strLine, ' ', vWords);
if (vWords.size() >= 1 && vWords[0] == "PING")
{
strLine[1] = 'O';
strLine += '\r';
Send(hSocket, strLine.c_str());
continue;
}
}
return fRet;
}
}
int RecvUntil(SOCKET hSocket, const char* psz1, const char* psz2=NULL, const char* psz3=NULL, const char* psz4=NULL)
{
loop
{
string strLine;
strLine.reserve(10000);
if (!RecvLineIRC(hSocket, strLine))
return 0;
printf("IRC %s\n", strLine.c_str());
if (psz1 && strLine.find(psz1) != string::npos)
return 1;
if (psz2 && strLine.find(psz2) != string::npos)
return 2;
if (psz3 && strLine.find(psz3) != string::npos)
return 3;
if (psz4 && strLine.find(psz4) != string::npos)
return 4;
}
}
bool Wait(int nSeconds)
{
if (fShutdown)
return false;
printf("IRC waiting %d seconds to reconnect\n", nSeconds);
for (int i = 0; i < nSeconds; i++)
{
if (fShutdown)
return false;
Sleep(1000);
}
return true;
}
bool RecvCodeLine(SOCKET hSocket, const char* psz1, string& strRet)
{
strRet.clear();
loop
{
string strLine;
if (!RecvLineIRC(hSocket, strLine))
return false;
vector<string> vWords;
ParseString(strLine, ' ', vWords);
if (vWords.size() < 2)
continue;
if (vWords[1] == psz1)
{
printf("IRC %s\n", strLine.c_str());
strRet = strLine;
return true;
}
}
}
bool GetIPFromIRC(SOCKET hSocket, string strMyName, CNetAddr& ipRet)
{
Send(hSocket, strprintf("USERHOST %s\r", strMyName.c_str()).c_str());
string strLine;
if (!RecvCodeLine(hSocket, "302", strLine))
return false;
vector<string> vWords;
ParseString(strLine, ' ', vWords);
if (vWords.size() < 4)
return false;
string str = vWords[3];
if (str.rfind("@") == string::npos)
return false;
string strHost = str.substr(str.rfind("@")+1);
// Hybrid IRC used by lfnet always returns IP when you userhost yourself,
// but in case another IRC is ever used this should work.
printf("GetIPFromIRC() got userhost %s\n", strHost.c_str());
CNetAddr addr(strHost, true);
if (!addr.IsValid())
return false;
ipRet = addr;
return true;
}
void ThreadIRCSeed(void* parg)
{
IMPLEMENT_RANDOMIZE_STACK(ThreadIRCSeed(parg));
// Make this thread recognisable as the IRC seeding thread
RenameThread("bitcoin-ircseed");
try
{
ThreadIRCSeed2(parg);
}
catch (std::exception& e) {
PrintExceptionContinue(&e, "ThreadIRCSeed()");
} catch (...) {
PrintExceptionContinue(NULL, "ThreadIRCSeed()");
}
printf("ThreadIRCSeed exited\n");
}
void ThreadIRCSeed2(void* parg)
{
/* Dont advertise on IRC if we don't allow incoming connections */
if (mapArgs.count("-connect") || fNoListen)
return;
if (!GetBoolArg("-irc", false))
return;
printf("ThreadIRCSeed started\n");
int nErrorWait = 10;
int nRetryWait = 10;
while (!fShutdown)
{
CService addrConnect("92.243.23.21", 6667); // irc.lfnet.org
CService addrIRC("irc.lfnet.org", 6667, true);
if (addrIRC.IsValid())
addrConnect = addrIRC;
SOCKET hSocket;
if (!ConnectSocket(addrConnect, hSocket))
{
printf("IRC connect failed\n");
nErrorWait = nErrorWait * 11 / 10;
if (Wait(nErrorWait += 60))
continue;
else
return;
}
if (!RecvUntil(hSocket, "Found your hostname", "using your IP address instead", "Couldn't look up your hostname", "ignoring hostname"))
{
closesocket(hSocket);
hSocket = INVALID_SOCKET;
nErrorWait = nErrorWait * 11 / 10;
if (Wait(nErrorWait += 60))
continue;
else
return;
}
CNetAddr addrIPv4("1.2.3.4"); // arbitrary IPv4 address to make GetLocal prefer IPv4 addresses
CService addrLocal;
string strMyName;
if (GetLocal(addrLocal, &addrIPv4))
strMyName = EncodeAddress(GetLocalAddress(&addrConnect));
if (strMyName == "")
strMyName = strprintf("x%u", GetRand(1000000000));
Send(hSocket, strprintf("NICK %s\r", strMyName.c_str()).c_str());
Send(hSocket, strprintf("USER %s 8 * : %s\r", strMyName.c_str(), strMyName.c_str()).c_str());
int nRet = RecvUntil(hSocket, " 004 ", " 433 ");
if (nRet != 1)
{
closesocket(hSocket);
hSocket = INVALID_SOCKET;
if (nRet == 2)
{
printf("IRC name already in use\n");
Wait(10);
continue;
}
nErrorWait = nErrorWait * 11 / 10;
if (Wait(nErrorWait += 60))
continue;
else
return;
}
Sleep(500);
// Get our external IP from the IRC server and re-nick before joining the channel
CNetAddr addrFromIRC;
if (GetIPFromIRC(hSocket, strMyName, addrFromIRC))
{
printf("GetIPFromIRC() returned %s\n", addrFromIRC.ToString().c_str());
if (addrFromIRC.IsRoutable())
{
// IRC lets you to re-nick
AddLocal(addrFromIRC, LOCAL_IRC);
strMyName = EncodeAddress(GetLocalAddress(&addrConnect));
Send(hSocket, strprintf("NICK %s\r", strMyName.c_str()).c_str());
}
}
if (fTestNet) {
Send(hSocket, "JOIN #AFCoinTEST3\r");
Send(hSocket, "WHO #AFCoinTEST3\r");
} else {
// randomly join #AFCoin00-#AFCoin99
int channel_number = GetRandInt(100);
channel_number = 0; // Litecoin: for now, just use one channel
Send(hSocket, strprintf("JOIN #AFCoin%02d\r", channel_number).c_str());
Send(hSocket, strprintf("WHO #AFCoin%02d\r", channel_number).c_str());
}
int64 nStart = GetTime();
string strLine;
strLine.reserve(10000);
while (!fShutdown && RecvLineIRC(hSocket, strLine))
{
if (strLine.empty() || strLine.size() > 900 || strLine[0] != ':')
continue;
vector<string> vWords;
ParseString(strLine, ' ', vWords);
if (vWords.size() < 2)
continue;
char pszName[10000];
pszName[0] = '\0';
if (vWords[1] == "352" && vWords.size() >= 8)
{
// index 7 is limited to 16 characters
// could get full length name at index 10, but would be different from join messages
strlcpy(pszName, vWords[7].c_str(), sizeof(pszName));
printf("IRC got who\n");
}
if (vWords[1] == "JOIN" && vWords[0].size() > 1)
{
// :username!username@50000007.F000000B.90000002.IP JOIN :#channelname
strlcpy(pszName, vWords[0].c_str() + 1, sizeof(pszName));
if (strchr(pszName, '!'))
*strchr(pszName, '!') = '\0';
printf("IRC got join\n");
}
if (pszName[0] == 'u')
{
CAddress addr;
if (DecodeAddress(pszName, addr))
{
addr.nTime = GetAdjustedTime();
if (addrman.Add(addr, addrConnect, 51 * 60))
printf("IRC got new address: %s\n", addr.ToString().c_str());
nGotIRCAddresses++;
}
else
{
printf("IRC decode failed\n");
}
}
}
closesocket(hSocket);
hSocket = INVALID_SOCKET;
if (GetTime() - nStart > 20 * 60)
{
nErrorWait /= 3;
nRetryWait /= 3;
}
nRetryWait = nRetryWait * 11 / 10;
if (!Wait(nRetryWait += 60))
return;
}
}
#ifdef TEST
int main(int argc, char *argv[])
{
WSADATA wsadata;
if (WSAStartup(MAKEWORD(2,2), &wsadata) != NO_ERROR)
{
printf("Error at WSAStartup()\n");
return false;
}
ThreadIRCSeed(NULL);
WSACleanup();
return 0;
}
#endif
| afcoin/afcoin | src/irc.cpp | C++ | mit | 10,514 |
package se.slackers.nobloat.jsonrpc;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import se.slackers.nobloat.jsonrpc.annotation.JsonRpc;
import se.slackers.nobloat.jsonrpc.annotation.JsonRpcNamespace;
import se.slackers.nobloat.jsonrpc.model.MethodRegistration;
import se.slackers.nobloat.jsonrpc.protocol.JsonRpcRequest;
import javax.inject.Inject;
import java.lang.reflect.Method;
import java.util.Set;
import java.util.TreeSet;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
public class MethodRegistryImpl implements MethodRegistry {
private final Logger logger = LoggerFactory.getLogger(MethodRegistryImpl.class);
private final ConcurrentMap<String, Set<MethodRegistration>> methodMap;
@Inject
public MethodRegistryImpl() {
this.methodMap = new ConcurrentHashMap<>();
}
@Override
public <T> void register(T api) {
Class<?> apiClass = api.getClass();
String basePath = apiClass.getSimpleName();
String declaredBasePath = findApiBasePath(apiClass);
if (declaredBasePath != null) {
basePath = declaredBasePath;
}
registerMethods(apiClass, basePath, api);
}
private <T> void registerMethods(Class<?> apiClass, String basePath, T instance) {
for (Method method : apiClass.getDeclaredMethods()) {
if (method.getAnnotation(JsonRpc.class) == null) {
continue;
}
registerMethod(basePath, method, instance);
}
for (Class<?> classInterface : apiClass.getInterfaces()) {
registerMethods(classInterface, basePath, instance);
}
}
private String findApiBasePath(Class<?> apiClass) {
JsonRpcNamespace rpcPath = apiClass.getAnnotation(JsonRpcNamespace.class);
if (rpcPath != null) {
return rpcPath.value();
}
for (Class<?> classInterface : apiClass.getInterfaces()) {
String basePath = findApiBasePath(classInterface);
if (basePath != null) {
return basePath;
}
}
return null;
}
public MethodRegistration getMatchingMethod(JsonRpcRequest request) throws NoSuchMethodException {
Set<MethodRegistration> registrations = methodMap.get(request.getMethod());
if (registrations == null || registrations.isEmpty()) {
throw new NoSuchMethodException("Can't find method '" + request.getMethod() + "'");
}
for (MethodRegistration registration : registrations) {
if (methodMatch(registration, request)) {
return registration;
}
}
throw new NoSuchMethodException("Can't find any version of '" + request.getMethod() + "' with matching signature");
}
private boolean methodMatch(MethodRegistration registration, JsonRpcRequest request) {
Class<?>[] parameterTypes = registration.getParameterTypes();
Object[] parameters = request.getParams();
if (parameters.length != parameterTypes.length) {
return false;
}
for (int i = 0; i < parameters.length; i++) {
if (!parameterTypes[i].isAssignableFrom(parameters[i].getClass())) {
return false;
}
}
return true;
}
private synchronized <T> void registerMethod(String basePath, Method method, T api) {
final String methodName = basePath + '.' + method.getName();
Set<MethodRegistration> registrations = methodMap.get(methodName);
if (registrations == null) {
registrations = new TreeSet<>();
methodMap.put(methodName, registrations);
}
logger.info("Registering JsonRPC method {}", methodName);
registrations.add(new MethodRegistration(api, method));
}
}
| bysse/nobloat | jsonrpc-dispatch/src/main/java/se/slackers/nobloat/jsonrpc/MethodRegistryImpl.java | Java | mit | 3,875 |
package com.github.btrekkie.reductions.mario;
import java.util.Arrays;
import java.util.List;
import com.github.btrekkie.reductions.planar.Point;
/** A horizontal wire gadget for MarioProblem, as in IPlanarWireFactory.horizontalWire. */
public class MarioHorizontalWireGadget extends MarioGadget {
/** The height of horizontal wires. */
public static final int HEIGHT = 9;
private final int width;
public MarioHorizontalWireGadget(int width) {
this.width = width;
}
@Override
public int width() {
return width;
}
@Override
public int height() {
return HEIGHT;
}
@Override
public MarioTile[][] tiles(int minX, int minY, int width, int height) {
// The wire consists of height - 3 rows of blocks, then two rows of air, then one row of blocks
assertIsInBounds(minX, minY, width, height);
MarioTile[][] tiles = new MarioTile[height][];
for (int y = minY; y < minY + height; y++) {
MarioTile[] row = new MarioTile[width];
MarioTile tile;
if (y >= HEIGHT - 3 && y < HEIGHT - 1) {
tile = MarioTile.AIR;
} else {
tile = MarioTile.BLOCK;
}
for (int x = minX; x < minX + width; x++) {
row[x - minX] = tile;
}
tiles[y - minY] = row;
}
return tiles;
}
@Override
public MarioTile[][] tiles() {
return tiles(0, 0, width, HEIGHT);
}
@Override
public List<Point> ports() {
return Arrays.asList(new Point(0, HEIGHT - 1), new Point(width, HEIGHT - 1));
}
}
| btrekkie/reductions | src/com/github/btrekkie/reductions/mario/MarioHorizontalWireGadget.java | Java | mit | 1,661 |
<?php
/* TwigBundle:Exception:error.css.twig */
class __TwigTemplate_da96a27dc9be5c9fa346531d80544769230940a893c62a301473c8c8fba3e15e extends Twig_Template
{
public function __construct(Twig_Environment $env)
{
parent::__construct($env);
$this->parent = false;
$this->blocks = array(
);
}
protected function doDisplay(array $context, array $blocks = array())
{
// line 1
echo "/*
";
// line 2
echo twig_escape_filter($this->env, (isset($context["status_code"]) ? $context["status_code"] : $this->getContext($context, "status_code")), "html", null, true);
echo " ";
echo twig_escape_filter($this->env, (isset($context["status_text"]) ? $context["status_text"] : $this->getContext($context, "status_text")), "html", null, true);
echo "
*/
";
}
public function getTemplateName()
{
return "TwigBundle:Exception:error.css.twig";
}
public function isTraitable()
{
return false;
}
public function getDebugInfo()
{
return array ( 19 => 1, 79 => 21, 72 => 13, 69 => 12, 47 => 18, 40 => 11, 37 => 10, 22 => 2, 246 => 32, 157 => 56, 145 => 46, 139 => 45, 131 => 42, 123 => 41, 120 => 40, 115 => 39, 111 => 38, 108 => 37, 101 => 33, 98 => 32, 96 => 31, 83 => 25, 74 => 14, 66 => 11, 55 => 16, 52 => 21, 50 => 14, 43 => 9, 41 => 8, 35 => 9, 32 => 4, 29 => 6, 209 => 82, 203 => 78, 199 => 76, 193 => 73, 189 => 71, 187 => 70, 182 => 68, 176 => 64, 173 => 63, 168 => 62, 164 => 58, 162 => 57, 154 => 54, 149 => 51, 147 => 50, 144 => 49, 141 => 48, 133 => 42, 130 => 41, 125 => 38, 122 => 37, 116 => 36, 112 => 35, 109 => 34, 106 => 36, 103 => 32, 99 => 30, 95 => 28, 92 => 29, 86 => 24, 82 => 22, 80 => 24, 73 => 19, 64 => 19, 60 => 6, 57 => 12, 54 => 22, 51 => 10, 48 => 9, 45 => 17, 42 => 16, 39 => 6, 36 => 5, 33 => 4, 30 => 3,);
}
}
| symfony2forclient/CustomLoginAndResistration | app/cache/dev/twig/da/96/a27dc9be5c9fa346531d80544769230940a893c62a301473c8c8fba3e15e.php | PHP | mit | 1,979 |
""" Command to set maintenance status. """
from django.core.management.base import BaseCommand
import sys
import json
import os
BASE_DIR = os.path.dirname(__file__)
JSON_FILE = os.path.join(BASE_DIR, '../../maintenance_settings.json')
class Command(BaseCommand):
""" Set maintenance status """
@classmethod
def set_maintenance(cls, option):
""" Set maintenance status """
json_data = json.dumps({"DJANGO_MAINTENANCE": option},
indent=4, separators=(',', ': '))
json_file = open(JSON_FILE, 'w')
json_file.write(json_data)
json_file.close()
def handle(self, *args, **kwargs):
""" Handle maintenance command """
# sys.argv mut be equal to 3
if len(sys.argv) != 3:
print 'Invalid number of arguments: {0}'.format(len(sys.argv) - 2)
# sys.argv[2] must have on or off
elif sys.argv[2] != 'on' and sys.argv[2] != 'off':
print 'Invalid maintenance option: {0}'.format(sys.argv[2])
print 'Valid options: on/off'
else:
self.set_maintenance(sys.argv[2])
| mccricardo/django_maintenance | django_maintenance/management/commands/maintenance.py | Python | mit | 1,052 |
#ifndef JOHNPAUL_HPP_INCLUDED
#define JOHNPAUL_HPP_INCLUDED
void johnpaul (); // Prints "John, Paul, "
#endif /* ifndef JOHNPAUL_HPP_INCLUDED */
| CajetanP/code-learning | Build Systems/CommandLine/HelloBeatles/src/johnpaul/johnpaul.hpp | C++ | mit | 148 |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="Token.cs" company="KlusterKite">
// All rights reserved
// </copyright>
// <summary>
// The token response description
// </summary>
// --------------------------------------------------------------------------------------------------------------------
namespace KlusterKite.NodeManager.Launcher
{
using System;
using JetBrains.Annotations;
using Newtonsoft.Json;
/// <summary>
/// The token description
/// </summary>
[UsedImplicitly]
public class Token
{
/// <summary>
/// The token creation date
/// </summary>
private readonly DateTimeOffset created = DateTimeOffset.Now;
/// <summary>
/// Gets or sets the access token value
/// </summary>
[JsonProperty("access_token")]
public string AccessToken { get; set; }
/// <summary>
/// Gets or sets the token expiration in seconds
/// </summary>
[JsonProperty("expires_in")]
[UsedImplicitly]
public int? Expires { get; set; }
/// <summary>
/// Gets a value indicating whether current token was expired
/// </summary>
public bool IsExpired
=> !this.Expires.HasValue || (DateTimeOffset.Now - this.created).TotalSeconds > this.Expires.Value;
}
} | KlusterKite/KlusterKite | KlusterKite.NodeManager/KlusterKite.NodeManager.Launcher/Token.cs | C# | mit | 1,449 |
// generated by Neptune Namespaces v4.x.x
// file: Art/Engine/Elements/ShapeChildren/index.js
(module.exports = require('./namespace'))
.addModules({
FillElement: require('./FillElement'),
OutlineElement: require('./OutlineElement')
}); | art-suite/art-engine | source/Art/Engine/Elements/ShapeChildren/index.js | JavaScript | mit | 245 |
'use strict';
// Setting up route
angular.module('users').config(['$stateProvider',
function ($stateProvider) {
// Users state routing
$stateProvider
.state('settings', {
abstract: true,
url: '/settings',
templateUrl: 'modules/users/client/views/settings/settings.client.view.html',
data: {
roles: ['user', 'admin']
}
})
.state('settings.profile', {
url: '/profile',
templateUrl: 'modules/users/client/views/settings/edit-profile.client.view.html'
})
.state('settings.password', {
url: '/password',
templateUrl: 'modules/users/client/views/settings/change-password.client.view.html'
})
.state('settings.accounts', {
url: '/accounts',
templateUrl: 'modules/users/client/views/settings/manage-social-accounts.client.view.html'
})
.state('settings.picture', {
url: '/picture',
templateUrl: 'modules/users/client/views/settings/change-profile-picture.client.view.html'
})
.state('authentication', {
abstract: true,
url: '/authentication',
templateUrl: 'modules/users/client/views/authentication/authentication.client.view.html'
//templateUrl: 'modules/core/client/views/home.client.view.html'
})
.state('authentication.signup', {
url: '/',
templateUrl: 'modules/users/client/views/authentication/signup.client.view.html'
//templateUrl: 'modules/core/client/views/home.client.view.html'
})
.state('authentication.signin', {
url: '/signin?err',
templateUrl: 'modules/core/client/views/home.client.view.html'
//templateUrl: 'modules/users/client/views/authentication/signin.client.view.html'
})
.state('password', {
abstract: true,
url: '/password',
template: '<ui-view/>'
})
.state('password.forgot', {
url: '/forgot',
templateUrl: 'modules/users/client/views/password/forgot-password.client.view.html'
})
.state('password.reset', {
abstract: true,
url: '/reset',
template: '<ui-view/>'
})
.state('password.reset.invalid', {
url: '/invalid',
templateUrl: 'modules/users/client/views/password/reset-password-invalid.client.view.html'
})
.state('password.reset.success', {
url: '/success',
templateUrl: 'modules/users/client/views/password/reset-password-success.client.view.html'
})
.state('password.reset.form', {
url: '/:token',
templateUrl: 'modules/users/client/views/password/reset-password.client.view.html'
});
}
]);
| dpxxdp/segue4 | modules/users/client/config/users.client.routes.js | JavaScript | mit | 2,704 |
using System;
using Xunit;
namespace HelloWorld
{
public class HelloWorldTests
{
[Theory]
[InlineData(12)]
[InlineData(13)]
[InlineData(14)]
[InlineData(15)]
[InlineData(16)]
[InlineData(17)]
[InlineData(18)]
[InlineData(19)]
[InlineData(20)]
[InlineData(21)]
[InlineData(22)]
[InlineData(23)]
public void GivenAfternoon_ThenAfternoonMessage(int hour)
{
// Arrange
var afternoonTime = new TestTimeManager();
afternoonTime.SetDateTime(new DateTime(2017, 7, 13, hour, 0, 0));
var messageUtility = new MessageUtility(afternoonTime);
// Act
var message = messageUtility.GetMessage();
// Assert
Assert.Equal("Good afternoon", message);
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(2)]
[InlineData(3)]
[InlineData(4)]
[InlineData(5)]
[InlineData(6)]
[InlineData(7)]
[InlineData(8)]
[InlineData(9)]
[InlineData(10)]
[InlineData(11)]
public void GivenMorning_ThenMorningMessage(int hour)
{
// Arrange
var morningTime = new TestTimeManager();
morningTime.SetDateTime(new DateTime(2017, 7, 13, hour, 0, 0));
var messageUtility = new MessageUtility(morningTime);
// Act
var message = messageUtility.GetMessage();
// Assert
Assert.Equal("Good morning", message);
}
}
}
| PracticalTestDrivenDevelopment/Book-API | HelloWorld/HelloWorld/HelloWorldTests.cs | C# | mit | 1,633 |
require 'spec_helper'
describe Cms::User do
subject(:model) { Cms::User }
subject(:factory) { :ss_user }
it_behaves_like "mongoid#save"
it_behaves_like "mongoid#find"
end
| shakkun/ss-temp | spec/models/cms/user_spec.rb | Ruby | mit | 181 |
using Guitar32;
using Guitar32.Database;
using Guitar32.Utilities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using TechByte.Configs;
using TechByte.Values;
namespace TechByte.Architecture.Usecases
{
public class UCNewSystemUser : TechByte.Architecture.Beans.Accounts.SystemUser
{
private DatabaseConnection dbConn = TechByte.Configs.DatabaseInstance.databaseConnection;
public UCNewSystemUser() { }
public void Register() {
QueryBuilder query = new QueryBuilder();
int powerId,
addressId,
contactId,
profileId
;
// Check if already exists
query.Select()
.From("tblusers")
.Where("upper(username) = " + Strings.Surround(this.getUsername().ToUpper()));
QueryResultRow rowMatched = dbConn.QuerySingle(query);
if (rowMatched != null && rowMatched.Count > 0) {
this.setResponse(CODES.USERNAME_ALREADY_TAKEN);
return;
}
// Get PowerID
query.Select("id")
.From("tblpowers")
.Where("lower(name)", Strings.NoSpaces(Strings.Surround(this.getPower().ToLower())), true)
;
// Check for database error
try {
QueryResultRow row = dbConn.QuerySingle(query);
powerId = int.Parse(row["id"].ToString());
}
catch (Exception ex) {
this.setResponse(TechByte.Values.CODES.DATABASE_ERROR);
return;
}
// {{ BLOCK for Contact details creation
TechByte.Architecture.Beans.Profiles.ContactDetails
contactDetails = this.getProfileDetails().getContactDetails();
query.InsertInto("tblcontactdetails", new string[] { "email", "mobile", "landline", "fax" })
.Values(new object[] {
Strings.Surround(contactDetails.getEmail()),
Strings.Surround(contactDetails.getMobile()),
Strings.Surround(contactDetails.getLandline()),
Strings.Surround(contactDetails.getFax())
});
// Check for database error
if (!dbConn.Execute(query)) {
this.setResponse(TechByte.Values.CODES.DATABASE_ERROR);
return;
}
// Save Contact ID
query.Select("last_insert_id() AS id");
contactId = int.Parse(dbConn.QuerySingle(query)["id"]+"");
// }}
// {{ BLOCK for Address details creation
TechByte.Architecture.Beans.Profiles.AddressDetails
addressDetails = this.getProfileDetails().getAddressDetails();
query.InsertInto("tbladdressdetails", new string[] { "street", "city", "region", "country" })
.Values(new object[] {
Strings.Surround(addressDetails.getStreet()),
Strings.Surround(addressDetails.getCity()),
Strings.Surround(addressDetails.getRegion()),
Strings.Surround(addressDetails.getCountry())
});
// Check for database error
if (!dbConn.Execute(query)) {
this.setResponse(TechByte.Values.CODES.DATABASE_ERROR);
return;
}
// Save Address ID
query.Select("last_insert_id() AS id");
addressId = int.Parse(dbConn.QuerySingle(query)["id"] + "");
// }}
// {{ BLOCK for Profile details
TechByte.Architecture.Beans.Accounts.ProfileDetails
profileDetails = this.getProfileDetails();
query.InsertInto("tblprofiles", new string[] { "address_id", "contact_id", "fname", "mname", "lname", "gender", "birthdate", "birthplace", "nationality", "tin", "sss", "pagibig" })
.Values(new object[] {
addressId,
contactId,
Strings.Surround(profileDetails.getFullname().getFirstName()),
Strings.Surround(profileDetails.getFullname().getMiddleName()),
Strings.Surround(profileDetails.getFullname().getLastName()),
Strings.Surround(profileDetails.getGender()),
Strings.Surround(profileDetails.getBirthDate()),
Strings.Surround(profileDetails.getBirthPlace()),
Strings.Surround(profileDetails.getNationality()),
Strings.Surround(profileDetails.getTIN()),
Strings.Surround(profileDetails.getSSS()),
Strings.Surround(profileDetails.getPAGIBIG())
});
if (!dbConn.Execute(query)) {
this.setResponse(TechByte.Values.CODES.DATABASE_ERROR);
return;
}
// Save User ID
query.Select("last_insert_id() AS id");
profileId = int.Parse(dbConn.QuerySingle(query)["id"] + "");
// }}
// {{ BLOCK for User account creation
query.InsertInto("tblusers", new string[] { "power_id", "profile_id", "username", "password", "status" })
.Values(new object[] {
powerId,
profileId,
Strings.Surround(this.getUsername()),
Strings.Surround(this.getPassword()),
Strings.Surround(this.getStatus())
});
// Check for database error
if (!dbConn.Execute(query)) {
this.setResponse(TechByte.Values.CODES.DATABASE_ERROR);
return;
}
// }}
// Success!
this.setResponse(new SystemResponse("00", "Account has been succcessfully created!"));
}
}
}
| allenlinatoc/techbyte | TechByte/Architecture/Usecases/UCNewSystemUser.cs | C# | mit | 5,973 |
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Events;
using UnityEngine.EventSystems;
using NaughtyAttributes;
public class ButtonPro : MonoBehaviour, IPointerClickHandler, IPointerEnterHandler,IPointerExitHandler,IPointerDownHandler,IPointerUpHandler
{
public Graphic[] targetGraphics;
public Graphic[] secondaryGraphics;
public Color primaryColor;
public Color secondaryColor;
public bool useTertiaryColor;
[ShowIf("useTertiaryColor")]
public Color tertiaryColor;
public float transitionSpeed = 1;
public bool isHovered;
public bool isHeld;
public UnityEvent onClick;
public UnityEvent onDragOff;
public bool dragOffUI;
public void OnPointerEnter(PointerEventData pointerEventData)
{
isHovered = true;
}
//Detect when Cursor leaves the GameObject
public void OnPointerExit(PointerEventData pointerEventData)
{
isHovered = false;
if(isHeld)
{
if(!dragOffUI)
{
onDragOff.Invoke();
isHeld = false;
}
}
}
public void OnPointerClick(PointerEventData pointerEventData)
{
onClick.Invoke();
isHeld = false;
}
void Update()
{
if(isHovered)
{
for(int i = 0; i < targetGraphics.Length; i++)
{
targetGraphics[i].color = Color.Lerp(targetGraphics[i].color, secondaryColor, Time.deltaTime * transitionSpeed);
}
for(int i = 0; i < secondaryGraphics.Length; i++)
{
if(useTertiaryColor)
{
secondaryGraphics[i].color = Color.Lerp(secondaryGraphics[i].color, tertiaryColor, Time.deltaTime * transitionSpeed);
}
else
{
secondaryGraphics[i].color = Color.Lerp(secondaryGraphics[i].color, primaryColor, Time.deltaTime * transitionSpeed);
}
}
}
else
{
for (int i = 0; i < targetGraphics.Length; i++)
{
targetGraphics[i].color = Color.Lerp(targetGraphics[i].color, primaryColor, Time.deltaTime * transitionSpeed);
}
for (int i = 0; i < secondaryGraphics.Length; i++)
{
secondaryGraphics[i].color = Color.Lerp(secondaryGraphics[i].color, secondaryColor, Time.deltaTime * transitionSpeed);
}
}
if(isHeld && dragOffUI)
{
if(Input.GetMouseButtonUp(0))
{
isHeld = false;
}
if (!EventSystem.current.IsPointerOverGameObject(-1))
{
onDragOff.Invoke();
isHeld = false;
}
}
}
public void OnPointerDown(PointerEventData eventData)
{
isHeld = true;
}
public void OnPointerUp(PointerEventData eventData)
{
if(!Input.GetMouseButton(0))
{
isHeld = false;
}
}
}
| uniquecorn/dungeon-crossing | Assets/Scripts/ButtonPro.cs | C# | mit | 3,060 |
#region Copyright and License
/* @Copyright JONVON(NetCreditHub.COM) 2017. All rights reserved. - 8502090@qq.com */
#endregion
namespace NetCreditHub.Data
{
using Dependency;
using Environment;
public interface IZeroDatabaseFactory : ITransientDependency
{
IDatabase CreateDatabase();
IDatabase CreateLogDatabase();
IDatabase CreateDatabase(DatabaseInfo dbase);
}
} | netcredit/NetCreditHub | src/NetCreditHub.Zero/Data/IZeroDatabaseFactory.cs | C# | mit | 416 |
"""Functionality to interact with Google Cloud Platform.
"""
| chapmanb/bcbio-nextgen-vm | bcbiovm/gcp/__init__.py | Python | mit | 61 |
require_relative '../client'
module Spaceship
module ConnectAPI
class Client < Spaceship::Client
##
# Spaceship HTTP client for the App Store Connect API.
#
# This client is solely responsible for the making HTTP requests and
# parsing their responses. Parameters should be either named parameters, or
# for large request data bodies, pass in anything that can resond to
# `to_json`.
#
# Each request method should validate the required parameters. A required parameter is one that would result in 400-range response if it is not supplied.
# Each request method should make only one request. For more high-level logic, put code in the data models.
def self.hostname
'https://appstoreconnect.apple.com/iris/v1/'
end
def build_params(filter: nil, includes: nil, limit: nil, sort: nil)
params = {}
params[:filter] = filter if filter && !filter.empty?
params[:include] = includes if includes
params[:limit] = limit if limit
params[:sort] = sort if sort
return params
end
def get_beta_app_review_detail(filter: {}, includes: nil, limit: nil, sort: nil)
# GET
# https://appstoreconnect.apple.com/iris/v1/betaAppReviewDetails?filter[app]=<app_id>
params = build_params(filter: filter, includes: includes, limit: limit, sort: sort)
response = request(:get, "betaAppReviewDetails") do |req|
req.options.params_encoder = Faraday::NestedParamsEncoder
req.params = params
end
handle_response(response)
end
def patch_beta_app_review_detail(app_id: nil, attributes: {})
# PATCH
# https://appstoreconnect.apple.com/iris/v1/apps/<app_id>/betaAppReviewDetails
path = "betaAppReviewDetails/#{app_id}"
body = {
data: {
attributes: attributes,
id: app_id,
type: "betaAppReviewDetails"
}
}
response = request(:patch) do |req|
req.url(path)
req.body = body.to_json
req.headers['Content-Type'] = 'application/json'
end
handle_response(response)
end
def get_beta_app_localizations(filter: {}, includes: nil, limit: nil, sort: nil)
# GET
# https://appstoreconnect.apple.com/iris/v1/betaAppLocalizations?filter[app]=<app_id>
params = build_params(filter: filter, includes: includes, limit: limit, sort: sort)
response = request(:get, "betaAppLocalizations") do |req|
req.options.params_encoder = Faraday::NestedParamsEncoder
req.params = params
end
handle_response(response)
end
def get_beta_build_localizations(filter: {}, includes: nil, limit: nil, sort: nil)
# GET
# https://appstoreconnect.apple.com/iris/v1/betaBuildLocalizations?filter[build]=<build_id>
path = "betaBuildLocalizations"
params = build_params(filter: filter, includes: includes, limit: limit, sort: sort)
response = request(:get, path) do |req|
req.options.params_encoder = Faraday::NestedParamsEncoder
req.params = params
end
handle_response(response)
end
def post_beta_app_localizations(app_id: nil, attributes: {})
# POST
# https://appstoreconnect.apple.com/iris/v1/betaAppLocalizations
path = "betaAppLocalizations"
body = {
data: {
attributes: attributes,
type: "betaAppLocalizations",
relationships: {
app: {
data: {
type: "apps",
id: app_id
}
}
}
}
}
response = request(:post) do |req|
req.url(path)
req.body = body.to_json
req.headers['Content-Type'] = 'application/json'
end
handle_response(response)
end
def patch_beta_app_localizations(localization_id: nil, attributes: {})
# PATCH
# https://appstoreconnect.apple.com/iris/v1/apps/<app_id>/betaAppLocalizations/<localization_id>
path = "betaAppLocalizations/#{localization_id}"
body = {
data: {
attributes: attributes,
id: localization_id,
type: "betaAppLocalizations"
}
}
response = request(:patch) do |req|
req.url(path)
req.body = body.to_json
req.headers['Content-Type'] = 'application/json'
end
handle_response(response)
end
def post_beta_build_localizations(build_id: nil, attributes: {})
# POST
# https://appstoreconnect.apple.com/iris/v1/betaBuildLocalizations
path = "betaBuildLocalizations"
body = {
data: {
attributes: attributes,
type: "betaBuildLocalizations",
relationships: {
build: {
data: {
type: "builds",
id: build_id
}
}
}
}
}
response = request(:post) do |req|
req.url(path)
req.body = body.to_json
req.headers['Content-Type'] = 'application/json'
end
handle_response(response)
end
def patch_beta_build_localizations(localization_id: nil, feedbackEmail: nil, attributes: {})
# PATCH
# https://appstoreconnect.apple.com/iris/v1/apps/<app_id>/betaBuildLocalizations
path = "betaBuildLocalizations/#{localization_id}"
body = {
data: {
attributes: attributes,
id: localization_id,
type: "betaBuildLocalizations"
}
}
response = request(:patch) do |req|
req.url(path)
req.body = body.to_json
req.headers['Content-Type'] = 'application/json'
end
handle_response(response)
end
def get_build_beta_details(filter: {}, includes: nil, limit: nil, sort: nil)
# GET
# https://appstoreconnect.apple.com/iris/v1/buildBetaDetails
params = build_params(filter: filter, includes: includes, limit: limit, sort: sort)
response = request(:get, "buildBetaDetails") do |req|
req.options.params_encoder = Faraday::NestedParamsEncoder
req.params = params
end
handle_response(response)
end
def patch_build_beta_details(build_beta_details_id: nil, attributes: {})
# PATCH
# https://appstoreconnect.apple.com/iris/v1/buildBetaDetails/<build_beta_details_id>
path = "buildBetaDetails/#{build_beta_details_id}"
body = {
data: {
attributes: attributes,
id: build_beta_details_id,
type: "buildBetaDetails"
}
}
response = request(:patch) do |req|
req.url(path)
req.body = body.to_json
req.headers['Content-Type'] = 'application/json'
end
handle_response(response)
end
def get_builds(filter: {}, includes: "buildBetaDetail,betaBuildMetrics", limit: 10, sort: "uploadedDate")
# GET
# https://appstoreconnect.apple.com/iris/v1/builds
params = build_params(filter: filter, includes: includes, limit: limit, sort: sort)
response = request(:get, "builds") do |req|
req.options.params_encoder = Faraday::NestedParamsEncoder
req.params = params
end
handle_response(response)
end
def patch_builds(build_id: nil, attributes: {})
# PATCH
# https://appstoreconnect.apple.com/iris/v1/builds/<build_id>
path = "builds/#{build_id}"
body = {
data: {
attributes: attributes,
id: build_id,
type: "builds"
}
}
response = request(:patch) do |req|
req.url(path)
req.body = body.to_json
req.headers['Content-Type'] = 'application/json'
end
handle_response(response)
end
def post_beta_app_review_submissions(build_id: nil)
# POST
# https://appstoreconnect.apple.com/iris/v1/betaAppReviewSubmissions
body = {
data: {
type: "betaAppReviewSubmissions",
relationships: {
build: {
data: {
type: "builds",
id: build_id
}
}
}
}
}
response = request(:post) do |req|
req.url("betaAppReviewSubmissions")
req.body = body.to_json
req.headers['Content-Type'] = 'application/json'
end
handle_response(response)
end
protected
def handle_response(response)
if (200...300).cover?(response.status) && (response.body.nil? || response.body.empty?)
return
end
raise InternalServerError, "Server error got #{response.status}" if (500...600).cover?(response.status)
unless response.body.kind_of?(Hash)
raise UnexpectedResponse, response.body
end
raise UnexpectedResponse, response.body['error'] if response.body['error']
raise UnexpectedResponse, handle_errors(response) if response.body['errors']
raise UnexpectedResponse, "Temporary App Store Connect error: #{response.body}" if response.body['statusCode'] == 'ERROR'
return response.body['data'] if response.body['data']
return response.body
end
def handle_errors(response)
# Example error format
# {
# "errors" : [ {
# "id" : "ce8c391e-f858-411b-a14b-5aa26e0915f2",
# "status" : "400",
# "code" : "PARAMETER_ERROR.INVALID",
# "title" : "A parameter has an invalid value",
# "detail" : "'uploadedDate3' is not a valid field name",
# "source" : {
# "parameter" : "sort"
# }
# } ]
# }
return response.body['errors'].map do |error|
"#{error['title']} - #{error['detail']}"
end.join(" ")
end
private
# used to assert all of the named parameters are supplied values
#
# @raises NameError if the values are nil
def assert_required_params(method_name, binding)
parameter_names = method(method_name).parameters.map { |_, v| v }
parameter_names.each do |name|
if local_variable_get(binding, name).nil?
raise NameError, "`#{name}' is a required parameter"
end
end
end
def local_variable_get(binding, name)
if binding.respond_to?(:local_variable_get)
binding.local_variable_get(name)
else
binding.eval(name.to_s)
end
end
def provider_id
return team_id if self.provider.nil?
self.provider.provider_id
end
end
end
end
| mgrebenets/fastlane | spaceship/lib/spaceship/connect_api/client.rb | Ruby | mit | 11,093 |
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
// **NOTE** This file was generated by a tool and any changes will be overwritten.
namespace Microsoft.Graph
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Threading;
/// <summary>
/// The interface IWorkbookFunctionsPiRequest.
/// </summary>
public partial interface IWorkbookFunctionsPiRequest : IBaseRequest
{
/// <summary>
/// Issues the POST request.
/// </summary>
System.Threading.Tasks.Task<WorkbookFunctionResult> PostAsync();
/// <summary>
/// Issues the POST request.
/// </summary>
/// <param name=""cancellationToken"">The <see cref=""CancellationToken""/> for the request.</param>
/// <returns>The task to await for async call.</returns>
System.Threading.Tasks.Task<WorkbookFunctionResult> PostAsync(
CancellationToken cancellationToken);
/// <summary>
/// Adds the specified expand value to the request.
/// </summary>
/// <param name="value">The expand value.</param>
/// <returns>The request object to send.</returns>
IWorkbookFunctionsPiRequest Expand(string value);
/// <summary>
/// Adds the specified select value to the request.
/// </summary>
/// <param name="value">The select value.</param>
/// <returns>The request object to send.</returns>
IWorkbookFunctionsPiRequest Select(string value);
}
}
| garethj-msft/msgraph-sdk-dotnet | src/Microsoft.Graph/Requests/Generated/IWorkbookFunctionsPiRequest.cs | C# | mit | 1,849 |
MiniPos::Application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# In the development environment your application's code is reloaded on
# every request. This slows down response time but is perfect for development
# since you don't have to restart the web server when you make code changes.
config.cache_classes = false
# Do not eager load code on boot.
config.eager_load = false
# Show full error reports and disable caching.
config.consider_all_requests_local = true
config.action_controller.perform_caching = false
# Don't care if the mailer can't send.
config.action_mailer.raise_delivery_errors = false
# Print deprecation notices to the Rails logger.
config.active_support.deprecation = :log
# Raise an error on page load if there are pending migrations
config.active_record.migration_error = :page_load
# Debug mode disables concatenation and preprocessing of assets.
# This option may cause significant delays in view rendering with a large
# number of complex assets.
config.assets.debug = true
config.action_mailer.default_url_options = { host: 'localhost', port: '3000' }
config.action_mailer.delivery_method = :smtp
config.action_mailer.smtp_settings = {
address: "smtp.gmail.com",
port: 587,
domain: "mail.google.com",
authentication: "login",
enable_starttls_auto: true,
user_name: ENV["GMAIL_USERNAME"],
password: ENV["GMAIL_PASSWORD"]
}
end
| tolerantx/MiniPOS | config/environments/development.rb | Ruby | mit | 1,574 |
var raf = require('raf');
var createCaption = require('vendors/caption');
var glslify = require('glslify');
var windowSize = new THREE.Vector2(window.innerWidth, window.innerHeight);
var SwapRenderer = require('vendors/swapRenderer'), swapRenderer;
var velocityRenderer, pressureRenderer;
var Solver = require('./fluid/solver');
var solver;
var scene, camera, renderer;
var object, id;
var stats, wrapper;
var mouse = new THREE.Vector2(-9999, -9999);
var isAnimation = true;
var orthShaderMaterial;
var orthScene, orthCamera, orthPlane;
var renderPlane, renderMaterial;
var renderScene, renderCamera;
var clock;
var grid = {
size : new THREE.Vector2(window.innerWidth/4, window.innerHeight/4),
scale : 1
};
var time = {
step : 1
};
var outputRenderer;
function init(){
scene = new THREE.Scene();
camera = new THREE.PerspectiveCamera(50, window.innerWidth / window.innerHeight, 1, 10000);
camera.position.z = 200;
renderer = new THREE.WebGLRenderer({alpha: true});
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
solver = Solver.make(grid, time, windowSize, renderer)
outputRenderer = new SwapRenderer({
width : grid.size.width, height : grid.size.height,
renderer : renderer
});
setComponent();
raf(animate);
}
function setComponent(){
var title = 'Swap Rendering with the texture of random color';
var caption = 'Swap rendering with the texture of random color.';
var url = 'https://github.com/kenjiSpecial/webgl-sketch-dojo/tree/master/sketches/theme/swap-renderer/app00';
wrapper = createCaption(title, caption, url);
wrapper.style.position = "absolute";
wrapper.style.top = '50px';
wrapper.style.left = '30px';
stats = new Stats();
stats.setMode( 0 ); // 0: fps, 1: ms, 2: mb
// align top-left
stats.domElement.style.position = 'absolute';
stats.domElement.style.bottom = '30px';
stats.domElement.style.left = '30px';
stats.domElement.style.zIndex= 9999;
document.body.appendChild( stats.domElement );
}
function animate() {
/** --------------------- **/
renderScene = new THREE.Scene();
renderCamera = new THREE.OrthographicCamera( -window.innerWidth/2, window.innerWidth/2, -window.innerHeight/2, window.innerHeight/2, -10000, 10000 );
console.log(solver.density.output);
renderMaterial = new THREE.ShaderMaterial({
depthTest : false,
side : THREE.DoubleSide,
uniforms : {
"tDiffuse" : {type: "t", value: solver.velocity.output }
},
vertexShader : glslify('./display/shader.vert'),
fragmentShader : glslify('./display/shader.frag')
});
renderPlane = new THREE.Mesh(
new THREE.PlaneBufferGeometry(window.innerWidth, window.innerHeight),
renderMaterial
);
renderScene.add(renderPlane);
clock = new THREE.Clock();
clock.start();
id = raf(loop);
//
}
function loop(){
stats.begin();
var dt = clock.getDelta();
solver.step(mouse);
renderer.render(renderScene, renderCamera);
stats.end();
id=raf(loop);
}
window.addEventListener('click', function(ev){
// renderer.render(scene, camera, swapRenderer.target);
});
window.addEventListener('keydown', function(ev){
if(ev.keyCode == 27){
if(isAnimation) raf.cancel(id);
else id = raf(animate);
isAnimation = !isAnimation;
}
});
window.addEventListener('mousemove', function(ev){
mouse.x = ev.clientX;
mouse.y = ev.clientY;
// swapRenderer.uniforms.uMouse.value = mouse;
});
init(); | kenjiSpecial/webgl-sketch-dojo | sketches/theme/fluid/app00temp01/app.js | JavaScript | mit | 3,670 |
using System;
using System.Reflection;
namespace Eminent.CodeGenerator
{
/// <summary>
/// Factory class to create objects exposing IRemoteInterface
/// </summary>
public class RemoteLoaderFactory : MarshalByRefObject
{
private const BindingFlags bfi = BindingFlags.Instance | BindingFlags.Public | BindingFlags.CreateInstance;
public RemoteLoaderFactory() {}
/// <summary> Factory method to create an instance of the type whose name is specified,
/// using the named assembly file and the constructor that best matches the specified parameters. </summary>
/// <param name="assemblyFile"> The name of a file that contains an assembly where the type named typeName is sought. </param>
/// <param name="typeName"> The name of the preferred type. </param>
/// <param name="constructArgs"> An array of arguments that match in number, order, and type the parameters of the constructor to invoke, or null for default constructor. </param>
/// <returns> The return value is the created object represented as ILiveInterface. </returns>
public IRemoteInterface Create( string assemblyFile, string typeName, object[] constructArgs )
{
return (IRemoteInterface) Activator.CreateInstanceFrom( assemblyFile, typeName, false, bfi, null, constructArgs, null, null).Unwrap();
}
}
}
| EminentTechnology/CodeTorch | src/core/Eminent.CodeGenerator/RemoteLoaderFactory.cs | C# | mit | 1,301 |
module.exports = function() {
return {
connectionString : "mongodb://127.0.0.1:27017/mongolayer"
}
} | simpleviewinc/mongolayer | testing/config.js | JavaScript | mit | 108 |
#include "stdafx.h"
#include "Events.h"
#include "PoseEffect2PStartMan.h"
#include "ItemBoxItems.h"
#include "EmeraldSync.h"
#include "CharacterSync.h"
#include "AddHP.h"
#include "AddRings.h"
#include "Damage.h"
#include "OnStageChange.h"
#include "OnResult.h"
#include "Random.h"
#include "OnInput.h"
void nethax::events::Initialize()
{
InitCharacterSync();
InitEmeraldSync();
InitItemBoxItems();
InitPoseEffect2PStartMan();
InitAddHP();
InitAddRings();
InitDamage();
InitOnStageChange();
InitOnResult();
InitOnInput();
random::init();
}
void nethax::events::Deinitialize()
{
DeinitCharacterSync();
DeinitEmeraldSync();
DeinitItemBoxItems();
DeinitPoseEffect2PStartMan();
DeinitAddHP();
DeinitAddRings();
DeinitDamage();
DeinitOnStageChange();
DeinitOnResult();
DeinitOnInput();
random::deinit();
}
| SonicFreak94/sa2-battle-network | sa2-battle-network/Events.cpp | C++ | mit | 827 |
module MiniRacer
VERSION = "0.1.12"
end
| kamillamagna/NMF_Tool | vendor/bundle/gems/mini_racer-0.1.12/lib/mini_racer/version.rb | Ruby | mit | 42 |
#region PDFsharp - A .NET library for processing PDF
//
// Authors:
// Stefan Lange
//
// Copyright (c) 2005-2016 empira Software GmbH, Cologne Area (Germany)
//
// http://www.pdfsharp.com
// http://sourceforge.net/projects/pdfsharp
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
#endregion
namespace PdfSharp.Pdf
{
/// <summary>
/// Specifies what color model is used in a PDF document.
/// </summary>
public enum PdfColorMode
{
/// <summary>
/// All color values are written as specified in the XColor objects they come from.
/// </summary>
Undefined,
/// <summary>
/// All colors are converted to RGB.
/// </summary>
Rgb,
/// <summary>
/// All colors are converted to CMYK.
/// </summary>
Cmyk,
}
} | jumpchain/jumpmaker | JumpMaker/PDFSharp/PdfSharp/Pdf/enums/PdfColorMode.cs | C# | mit | 1,855 |
package lateralview.net.m2xapiv2exampleapp.activities;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import org.json.JSONException;
import org.json.JSONObject;
import lateralview.net.attm2xapiv2.listeners.ResponseListener;
import lateralview.net.attm2xapiv2.model.Distribution;
import lateralview.net.attm2xapiv2.network.ApiV2Response;
import lateralview.net.m2xapiv2exampleapp.R;
public class DistributionActivity extends Activity implements ResponseListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_distribution);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_distribution, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void listDistributions(View view) {
Distribution.list(DistributionActivity.this, new ResponseListener() {
@Override
public void onRequestCompleted(ApiV2Response result, int requestCode) {
}
@Override
public void onRequestError(ApiV2Response error, int requestCode) {
}
});
}
public void createDistribution(View view){
try {
JSONObject o = new JSONObject("{ \"name\": \"Sample Distribution\",\n" +
" \"description\": \"Longer description for Sample Distribution\",\n" +
" \"visibility\": \"public\" }");
Distribution.create(DistributionActivity.this, o, this);
} catch (JSONException e) {
e.printStackTrace();
}
}
public void viewDistributionDetails(View view){
Distribution.viewDetails(DistributionActivity.this,"cc86b9c881755506d356659363680d29",this);
}
public void updateDistributionDetails(View view){
try {
JSONObject o = new JSONObject("{ \"name\": \"Sample Distribution\",\n" +
" \"description\": \"Longer description for Sample Distribution\",\n" +
" \"visibility\": \"public\" }");
Distribution.updateDetails(DistributionActivity.this, o, "cc86b9c881755506d356659363680d29", this);
} catch (JSONException e) {
e.printStackTrace();
}
}
public void listDevicesExistingDistribution(View view){
Distribution.listDevices(DistributionActivity.this,"cc86b9c881755506d356659363680d29",this);
}
public void addDeviceToDistribution(View view){
try {
JSONObject o = new JSONObject("{ \"serial\": \"ABC1234\"}");
Distribution.addDevice(DistributionActivity.this, o, "cc86b9c881755506d356659363680d29", this);
} catch (JSONException e) {
e.printStackTrace();
}
}
public void deleteDistribution(View view){
Distribution.delete(DistributionActivity.this,"cc86b9c881755506d356659363680d29",this);
}
public void listDataStreams(View view){
Distribution.listDataStreams(DistributionActivity.this,"cc86b9c881755506d356659363680d29",this);
}
public void createUpdateDataStream(View view){
try{
JSONObject o = new JSONObject("{ \"unit\": { \"label\": \"celsius\", symbol: \"C\" }, \"type\": \"numeric\" }");
Distribution.createUpdateDataStream(DistributionActivity.this,o,"cc86b9c881755506d356659363680d29","LVStream",this);
}catch(JSONException e){
e.printStackTrace();
}
}
public void viewDataStream(View view){
Distribution.viewDataStream(DistributionActivity.this,"cc86b9c881755506d356659363680d29","LVStream",this);
}
public void deleteDataStream(View view){
Distribution.deleteDataStream(DistributionActivity.this,"cc86b9c881755506d356659363680d29","LVStreams",this);
}
//API listeners
@Override
public void onRequestCompleted(ApiV2Response result, int requestCode) {
Log.d("APIV2Request", "Completed");
Log.d("APIV2 - RESULT",result.get_raw());
}
@Override
public void onRequestError(ApiV2Response error, int requestCode) {
Log.d("APIV2Request","Error");
Log.d("APIV2 - ERROR",error.get_raw());
}
}
| attm2x/m2x-android-test-app | app/src/main/java/lateralview/net/m2xapiv2exampleapp/activities/DistributionActivity.java | Java | mit | 4,951 |
'use strict';
const clone = require('../helpers/clone');
class SaveOptions {
constructor(obj) {
if (obj == null) {
return;
}
Object.assign(this, clone(obj));
}
}
module.exports = SaveOptions; | aguerny/LacquerTracker | node_modules/mongoose/lib/options/saveOptions.js | JavaScript | mit | 216 |
/*
* Xero Payroll AU
* This is the Xero Payroll API for orgs in Australia region.
*
* The version of the OpenAPI document: 2.2.4
* Contact: api@xero.com
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package com.xero.models.payrollau;
import java.util.Objects;
import com.fasterxml.jackson.annotation.JsonProperty;
import io.swagger.annotations.ApiModelProperty;
import com.xero.api.StringUtil;
/** HomeAddress */
public class HomeAddress {
StringUtil util = new StringUtil();
@JsonProperty("AddressLine1")
private String addressLine1;
@JsonProperty("AddressLine2")
private String addressLine2;
@JsonProperty("City")
private String city;
@JsonProperty("Region")
private State region;
@JsonProperty("PostalCode")
private String postalCode;
@JsonProperty("Country")
private String country;
public HomeAddress addressLine1(String addressLine1) {
this.addressLine1 = addressLine1;
return this;
}
/**
* Address line 1 for employee home address
*
* @return addressLine1
*/
@ApiModelProperty(
example = "123 Main St",
required = true,
value = "Address line 1 for employee home address")
public String getAddressLine1() {
return addressLine1;
}
public void setAddressLine1(String addressLine1) {
this.addressLine1 = addressLine1;
}
public HomeAddress addressLine2(String addressLine2) {
this.addressLine2 = addressLine2;
return this;
}
/**
* Address line 2 for employee home address
*
* @return addressLine2
*/
@ApiModelProperty(example = "Apt 4", value = "Address line 2 for employee home address")
public String getAddressLine2() {
return addressLine2;
}
public void setAddressLine2(String addressLine2) {
this.addressLine2 = addressLine2;
}
public HomeAddress city(String city) {
this.city = city;
return this;
}
/**
* Suburb for employee home address
*
* @return city
*/
@ApiModelProperty(example = "St. Kilda", value = "Suburb for employee home address")
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public HomeAddress region(State region) {
this.region = region;
return this;
}
/**
* Get region
*
* @return region
*/
@ApiModelProperty(value = "")
public State getRegion() {
return region;
}
public void setRegion(State region) {
this.region = region;
}
public HomeAddress postalCode(String postalCode) {
this.postalCode = postalCode;
return this;
}
/**
* PostCode for employee home address
*
* @return postalCode
*/
@ApiModelProperty(example = "3182", value = "PostCode for employee home address")
public String getPostalCode() {
return postalCode;
}
public void setPostalCode(String postalCode) {
this.postalCode = postalCode;
}
public HomeAddress country(String country) {
this.country = country;
return this;
}
/**
* Country of HomeAddress
*
* @return country
*/
@ApiModelProperty(example = "AUSTRALIA", value = "Country of HomeAddress")
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
@Override
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
HomeAddress homeAddress = (HomeAddress) o;
return Objects.equals(this.addressLine1, homeAddress.addressLine1)
&& Objects.equals(this.addressLine2, homeAddress.addressLine2)
&& Objects.equals(this.city, homeAddress.city)
&& Objects.equals(this.region, homeAddress.region)
&& Objects.equals(this.postalCode, homeAddress.postalCode)
&& Objects.equals(this.country, homeAddress.country);
}
@Override
public int hashCode() {
return Objects.hash(addressLine1, addressLine2, city, region, postalCode, country);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class HomeAddress {\n");
sb.append(" addressLine1: ").append(toIndentedString(addressLine1)).append("\n");
sb.append(" addressLine2: ").append(toIndentedString(addressLine2)).append("\n");
sb.append(" city: ").append(toIndentedString(city)).append("\n");
sb.append(" region: ").append(toIndentedString(region)).append("\n");
sb.append(" postalCode: ").append(toIndentedString(postalCode)).append("\n");
sb.append(" country: ").append(toIndentedString(country)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces (except the first line).
*/
private String toIndentedString(java.lang.Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
| SidneyAllen/Xero-Java | src/main/java/com/xero/models/payrollau/HomeAddress.java | Java | mit | 5,057 |
import React from 'react';
import ShiftKey from './ShiftKey';
import 'scss/vigenere.scss';
export default class VigenereKeys extends React.Component {
constructor(props) {
super(props);
this.state = {
keyword: ''
};
this.keywordHandler = this.keywordHandler.bind(this);
}
keywordHandler(event) {
this.setState({
keyword: event.target.value
})
}
render() {
const {
characters
} = this.props;
const charactersArray = characters.split('');
let {
keyword
} = this.state;
keyword = keyword.toUpperCase();
return (
<div>
<input type='text'
value={keyword}
onChange={this.keywordHandler}
placeholder='Keyword' />
<div className='shift-keys'>
{
keyword.split('').map((char, index) => (
<div key={index} className='vigenere-char'>
<p>{index}</p>
<ShiftKey
characters={charactersArray}
noControls
initialShift={charactersArray.indexOf(char)} />
</div>
))
}
</div>
</div>
);
}
}
export const EnglishVigenereKeys = props => (
<VigenereKeys characters='ABCDEFGHIJKLMNOPQRSTUVWXYZ' />
);
| pshrmn/cryptonite | src/components/tools/VigenereKeys.js | JavaScript | mit | 1,314 |
import * as React from 'react';
import ActiveButtons from '../active-buttons/ActiveButtons';
import { TextField, FlatButton } from 'material-ui';
import "./References.css";
import Styling from "../jobTheme";
class References extends React.Component<any, any>{
constructor(props: any) {
super(props);
//state of component
this.state = {
reference: 1,
family: 1,
selectedJson: this.props.jsonData,
form: {
references: [{
name: "",
relation: "",
telephone: ""
}],
friendRef: [{
name: "",
relation: ""
}]
},
error: {
references: [{
name: { nameError: false, msg: "" },
relation: { relationError: false, msg: "" },
telephone: { telephoneError: false, msg: "" }
}],
friendRef: [{
name: { nameError: false, msg: "" },
relation: { relationError: false, msg: "" },
}]
}
};
}
//Getting reference form data from local storage
componentWillMount() {
if (localStorage.getItem('reference-form') !== null) {
let data: any = localStorage.getItem('reference-form');
data = JSON.parse(data);
let dataArray = this.state.error;
let errorHistory: any = [];
let friendHistory: any = [];
data.references.map((arr: any) => {
errorHistory.push({
name: { nameError: false, msg: "" },
relation: { relationError: false, msg: "" },
telephone: { telephoneError: false, msg: "" }
})
});
data.friendRef.map((arr: any) => {
friendHistory.push({
name: { nameError: false, msg: "" },
relation: { relationError: false, msg: "" },
})
})
dataArray.references = errorHistory;
dataArray.friendRef = friendHistory;
this.setState({
form: data,
family: data.friendRef.length,
reference: data.references.length,
dataArray
})
}
}
setError = (event: any, name: any, index: any) => {
let current = this.state.error[event][index][name];
current[name + "Error"] = true;
current["msg"] = name + " field is required";
console.log(current);
this.setState(current)
}
referenceValidationCheck = (event: any, name: any, index: any) => {
console.log()
}
//Handling next state
handleNext = () => {
var relationDone = false;
var friendDone = false;
this.state.form.references.map((arr: any, index: any) => {
if (arr.name && arr.relation && arr.telephone) {
relationDone = true;
}
else {
if (!arr.name) {
this.setError('references', 'name', index);
}
if (!arr.relation) {
this.setError('references', 'relation', index);
}
if (!arr.telephone) {
this.setError('references', 'telephone', index);
}
}
})
this.state.form.friendRef.map((arr: any, index: any) => {
if (arr.name && arr.relation) {
friendDone = true;
}
else {
if (!arr.name) {
this.setError('friendRef', 'name', index);
}
if (!arr.relation) {
this.setError('friendRef', 'relation', index);
}
}
})
if (relationDone && friendDone) {
this.props.handleNext("reference-form", this.state.form);
}
// if (this.state.form.street_address) {
// }
// else {
// if (!this.state.form.street_address) {
// this.setError('address')
// }
// }
}
//Handling previous state
handlePrev = () => {
this.props.handlePrev();
}
//Handling input form state of the component
handleTargetEvents = (arrayRef: string, ind: number, event?: any) => {
let formRef = this.state.form;
formRef[arrayRef][ind][event.target.name] = event.target.value;
this.setState(formRef);
}
//Selecting json according to selected lanugage
componentWillReceiveProps(nextProp: any) {
this.setState({
selectedJson: nextProp.jsonData
})
}
//Making and managing multiple references lists
handleReference = (action: string) => {
let formRef = this.state.form["references"];
let formRefError = this.state.error['references'];
if (action === "add") {
formRef.push({
name: "",
relation: "",
telephone: ""
});
formRefError.push({
name: { nameError: false, msg: "" },
relation: { relationError: false, msg: "" },
telephone: { telephoneError: false, msg: "" }
})
this.setState({ reference: this.state.reference + 1, formRef, formRefError })
}
else {
formRef.pop();
formRefError.pop();
this.setState({ reference: this.state.reference - 1, formRef, formRefError })
}
}
//Making and managing multiple friend references list
handleFriend = (action: string) => {
let formRef = this.state.form["friendRef"];
let formRefError = this.state.error['friendRef'];
if (action === "add") {
formRef.push({
name: "",
relation: ""
});
formRefError.push({
name: { nameError: false, msg: "" },
relation: { relationError: false, msg: "" },
})
this.setState({ family: this.state.family + 1, formRef, formRefError })
}
else {
formRef.pop();
formRefError.pop();
this.setState({ family: this.state.family - 1, formRef, formRefError })
}
}
//Handling input state of component
handleText = (arrRef: string, ind: number, event?: any) => {
let formRef = this.state.form;
formRef[arrRef][ind][event.target.name] = event.target.value;
this.setState(formRef)
}
render() {
const { name, relation, telephone, friends } = this.state.selectedJson;
var reference = [];
var family = [];
for (let i = 0; i < this.state.reference; i++) {
reference.push(<div key={i}>
<TextField
floatingLabelText={name}
fullWidth
className="text-area"
value={this.state.form.references[i].name}
errorStyle={Styling.errorMsg}
errorText={this.state.error.references[i].name.nameError ? this.state.error.references[i].name.msg : null}
name="name"
style={{ marginRight: "50px" }}
onChange={this.handleText.bind(this, "references", i)}
onBlur={this.handleTargetEvents.bind(this, "references", i)}
/>
<TextField
fullWidth
className="text-area"
floatingLabelText={relation}
name="relation"
errorStyle={Styling.errorMsg}
errorText={this.state.error.references[i].relation.relationError ? this.state.error.references[i].relation.msg : null}
value={this.state.form.references[i].relation}
style={{ marginRight: "50px" }}
onChange={this.handleText.bind(this, "references", i)}
onBlur={this.handleTargetEvents.bind(this, "references", i)}
/>
<TextField
fullWidth
className="text-area"
floatingLabelText={telephone}
errorStyle={Styling.errorMsg}
errorText={this.state.error.references[i].telephone.telephoneError ? this.state.error.references[i].telephone.msg : null}
name="telephone"
value={this.state.form.references[i].telephone}
onChange={this.handleText.bind(this, "references", i)}
onBlur={this.handleTargetEvents.bind(this, "references", i)}
/>
</div>);
}
for (let i = 0; i < this.state.family; i++) {
family.push(<div key={i}>
<TextField
floatingLabelText={name}
name="name"
fullWidth
className="text-area"
errorStyle={Styling.errorMsg}
errorText={this.state.error.friendRef[i].name.nameError ? this.state.error.friendRef[i].name.msg : null}
style={{ marginRight: "50px" }}
value={this.state.form.friendRef[i].name}
onChange={this.handleText.bind(this, "friendRef", i)}
onBlur={this.handleTargetEvents.bind(this, "friendRef", i)}
/>
<TextField
floatingLabelText={relation}
name="relation"
fullWidth
className="text-area"
errorStyle={Styling.errorMsg}
errorText={this.state.error.friendRef[i].relation.relationError ? this.state.error.friendRef[i].relation.msg : null}
onChange={this.handleText.bind(this, "friendRef", i)}
value={this.state.form.friendRef[i].relation}
onBlur={this.handleTargetEvents.bind(this, "friendRef", i)}
/>
</div>);
}
return (
<div className="transportation-container">
<p className="title"> References </p>
{reference}<br />
<div className="button-group">
<FlatButton className="hovered-class" style={Styling.addButton} labelStyle={Styling.addButtonLabel} label="Add" onClick={() => this.handleReference("add")} />
<FlatButton className="hovered-class" style={Styling.deleteButton} labelStyle={Styling.addButtonLabel} label="Remove" onTouchTap={() => this.state.reference === 1 ? null : this.handleReference("delete")} />
</div>
<br /><br /><br />
<p className="title">{friends}</p>
{family}<br />
<div className="button-group">
<FlatButton className="hovered-class" labelStyle={Styling.addButtonLabel} style={Styling.addButton} label="Add" onClick={() => this.handleFriend("add")} />
<FlatButton className="hovered-class" labelStyle={Styling.addButtonLabel} style={Styling.deleteButton} label="Remove" onTouchTap={() => this.state.family === 1 ? null : this.handleFriend("delete")} />
</div>
<br /><br /><br /><br />
<ActiveButtons handleNext={() => this.handleNext()} handlePrev={() => this.handlePrev()} />
</div>
);
}
}
export default References; | TYLANDER/interspan | client/src/components/job-form/references/References.tsx | TypeScript | mit | 11,774 |
using System.Collections.Generic;
using System.Threading.Tasks;
using AzureStorage;
using Common;
using Core.Finance;
using Microsoft.WindowsAzure.Storage.Table;
namespace AzureRepositories.Finance
{
public class TraderBalanceEntity : TableEntity, ITraderBalance
{
public static string GeneratePartitionKey(string traderId)
{
return traderId;
}
public static string GenerateRowKey(string currency)
{
return currency.ToUpper();
}
public string TraderId => PartitionKey;
public string Currency => RowKey;
public double Amount { get; set; }
public static TraderBalanceEntity Create(string traderId, string currency)
{
return new TraderBalanceEntity
{
PartitionKey = GeneratePartitionKey(traderId),
RowKey = GenerateRowKey(currency)
};
}
}
public class BalanceRepository : IBalanceRepository
{
private readonly INoSQLTableStorage<TraderBalanceEntity> _tableStorage;
public BalanceRepository(INoSQLTableStorage<TraderBalanceEntity> tableStorage)
{
_tableStorage = tableStorage;
}
public async Task<IEnumerable<ITraderBalance>> GetAsync(string traderId)
{
var partitionKey = TraderBalanceEntity.GeneratePartitionKey(traderId);
return await _tableStorage.GetDataAsync(partitionKey);
}
public async Task ChangeBalanceAsync(string traderId, string currency, double delta)
{
var partitionKey = TraderBalanceEntity.GeneratePartitionKey(traderId);
var rowKey = TraderBalanceEntity.GenerateRowKey(currency);
var entity = await _tableStorage.ReplaceAsync(partitionKey, rowKey, itm =>
{
itm.Amount += delta;
return itm;
});
if (entity != null)
return;
entity = TraderBalanceEntity.Create(traderId, currency);
entity.Amount = delta;
await _tableStorage.InsertAsync(entity);
}
}
}
| LykkeCity/MarketPlace | AzureRepositories/Finance/BalanceRepository.cs | C# | mit | 2,167 |
'use strict';
import UserNotificationConstants from '../constants/UserNotificationConstants';
import UserNotificationService from '../services/UserNotificationService';
const _initiateRequest = (type, data) => {
return {
'type': type,
'data': data
};
};
const _returnResponse = (type, data) => {
return {
'type': type,
'data': data,
'receivedAt': Date.now()
};
};
export default {
getByUserId: (id) => {
return (dispatch) => {
dispatch(_initiateRequest(UserNotificationConstants.INITIATE_USER_NOTIFICATION_REQUEST));
return UserNotificationService.getByUserId(criteria).then((response) => {
dispatch(_returnResponse(UserNotificationConstants.GET_USER_NOTIFICATIONS, response.results));
return response.pagination;
});
};
},
search: (criteria) => {
return (dispatch) => {
dispatch(_initiateRequest(UserNotificationConstants.INITIATE_USER_NOTIFICATION_REQUEST));
return UserNotificationService.search(criteria).then((response) => {
dispatch(_returnResponse(UserNotificationConstants.GET_USER_NOTIFICATIONS, response.results));
return response.pagination;
});
};
},
create: (data) => {
return (dispatch) => {
dispatch(_initiateRequest(UserNotificationConstants.INITIATE_USER_NOTIFICATION_REQUEST));
return UserNotificationService.create(data).then((userNotification) => {
dispatch(_returnResponse(UserNotificationConstants.CREATE_USER_NOTIFICATION, userNotification));
return userNotification;
});
};
},
update: (id, data) => {
return (dispatch) => {
dispatch(_initiateRequest(UserNotificationConstants.INITIATE_USER_NOTIFICATION_REQUEST));
return UserNotificationService.update(id, data).then((userNotification) => {
dispatch(_returnResponse(UserNotificationConstants.UPDATE_USER_NOTIFICATION, userNotification));
return userNotification;
});
};
},
remove: (id) => {
return (dispatch) => {
dispatch(_initiateRequest(UserNotificationConstants.INITIATE_USER_NOTIFICATION_REQUEST, id));
return UserNotificationService.remove(id).then((response) => {
dispatch(_returnResponse(UserNotificationConstants.REMOVE_USER_NOTIFICATION, id));
return response;
});
};
}
};
| zdizzle6717/battle-comm | src/actions/UserNotificationActions.js | JavaScript | mit | 2,189 |
<?php
declare(strict_types=1);
namespace App\Command;
use App\Model\Page\PageRepository;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
class AddPageCommand extends Command
{
/**
* @var PageRepository
*/
private $pageRepository;
public function __construct(PageRepository $pageRepository)
{
$this->pageRepository = $pageRepository;
parent::__construct();
}
protected function configure()
{
$this
->setName('app:add-page')
->setDescription('Add new page to the list')
->addArgument('pageId', InputArgument::REQUIRED, 'ID of the Facebook Page');
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$pageId = $input->getArgument('pageId');
if ($this->pageRepository->findById($pageId) !== null) {
$this->pageRepository->addPage($pageId);
$output->writeln(sprintf('Page "%s" added.', $pageId));
} else {
$output->writeln(sprintf('Page "%s" already exists.', $pageId));
}
}
}
| sustmi/fb-post-downloader | src/Command/AddPageCommand.php | PHP | mit | 1,246 |
<?php
/**
* This file is part of the Spryker Demoshop.
* For full license information, please view the LICENSE file that was distributed with this source code.
*/
namespace Pyz\Zed\Collector\Business;
use Generated\Shared\Transfer\LocaleTransfer;
use Orm\Zed\Touch\Persistence\SpyTouchQuery;
use Spryker\Zed\Collector\Business\Exporter\Reader\ReaderInterface;
use Spryker\Zed\Collector\Business\Exporter\Writer\TouchUpdaterInterface;
use Spryker\Zed\Collector\Business\Exporter\Writer\WriterInterface;
use Spryker\Zed\Collector\Business\Model\BatchResultInterface;
use Symfony\Component\Console\Output\OutputInterface;
interface CollectorFacadeInterface
{
/**
* @param \Orm\Zed\Touch\Persistence\SpyTouchQuery $baseQuery
* @param \Generated\Shared\Transfer\LocaleTransfer $localeTransfer
* @param \Spryker\Zed\Collector\Business\Model\BatchResultInterface $result
* @param \Spryker\Zed\Collector\Business\Exporter\Reader\ReaderInterface $dataReader
* @param \Spryker\Zed\Collector\Business\Exporter\Writer\WriterInterface $dataWriter
* @param \Spryker\Zed\Collector\Business\Exporter\Writer\TouchUpdaterInterface $touchUpdater
* @param \Symfony\Component\Console\Output\OutputInterface $output
*
* @return void
*/
public function runSearchProductCollector(
SpyTouchQuery $baseQuery,
LocaleTransfer $localeTransfer,
BatchResultInterface $result,
ReaderInterface $dataReader,
WriterInterface $dataWriter,
TouchUpdaterInterface $touchUpdater,
OutputInterface $output
);
/**
* @param \Orm\Zed\Touch\Persistence\SpyTouchQuery $baseQuery
* @param \Generated\Shared\Transfer\LocaleTransfer $localeTransfer
* @param \Spryker\Zed\Collector\Business\Model\BatchResultInterface $result
* @param \Spryker\Zed\Collector\Business\Exporter\Reader\ReaderInterface $dataReader
* @param \Spryker\Zed\Collector\Business\Exporter\Writer\WriterInterface $dataWriter
* @param \Spryker\Zed\Collector\Business\Exporter\Writer\TouchUpdaterInterface $touchUpdater
* @param \Symfony\Component\Console\Output\OutputInterface $output
*
* @return void
*/
public function runStorageCategoryNodeCollector(
SpyTouchQuery $baseQuery,
LocaleTransfer $localeTransfer,
BatchResultInterface $result,
ReaderInterface $dataReader,
WriterInterface $dataWriter,
TouchUpdaterInterface $touchUpdater,
OutputInterface $output
);
/**
* @param \Orm\Zed\Touch\Persistence\SpyTouchQuery $baseQuery
* @param \Generated\Shared\Transfer\LocaleTransfer $localeTransfer
* @param \Spryker\Zed\Collector\Business\Model\BatchResultInterface $result
* @param \Spryker\Zed\Collector\Business\Exporter\Reader\ReaderInterface $dataReader
* @param \Spryker\Zed\Collector\Business\Exporter\Writer\WriterInterface $dataWriter
* @param \Spryker\Zed\Collector\Business\Exporter\Writer\TouchUpdaterInterface $touchUpdater
* @param \Symfony\Component\Console\Output\OutputInterface $output
*
* @return void
*/
public function runStorageNavigationCollector(
SpyTouchQuery $baseQuery,
LocaleTransfer $localeTransfer,
BatchResultInterface $result,
ReaderInterface $dataReader,
WriterInterface $dataWriter,
TouchUpdaterInterface $touchUpdater,
OutputInterface $output
);
/**
* @param \Orm\Zed\Touch\Persistence\SpyTouchQuery $baseQuery
* @param \Generated\Shared\Transfer\LocaleTransfer $localeTransfer
* @param \Spryker\Zed\Collector\Business\Model\BatchResultInterface $result
* @param \Spryker\Zed\Collector\Business\Exporter\Reader\ReaderInterface $dataReader
* @param \Spryker\Zed\Collector\Business\Exporter\Writer\WriterInterface $dataWriter
* @param \Spryker\Zed\Collector\Business\Exporter\Writer\TouchUpdaterInterface $touchUpdater
* @param \Symfony\Component\Console\Output\OutputInterface $output
*
* @return void
*/
public function runStorageProductAbstractCollector(
SpyTouchQuery $baseQuery,
LocaleTransfer $localeTransfer,
BatchResultInterface $result,
ReaderInterface $dataReader,
WriterInterface $dataWriter,
TouchUpdaterInterface $touchUpdater,
OutputInterface $output
);
/**
* @param \Orm\Zed\Touch\Persistence\SpyTouchQuery $baseQuery
* @param \Generated\Shared\Transfer\LocaleTransfer $localeTransfer
* @param \Spryker\Zed\Collector\Business\Model\BatchResultInterface $result
* @param \Spryker\Zed\Collector\Business\Exporter\Reader\ReaderInterface $dataReader
* @param \Spryker\Zed\Collector\Business\Exporter\Writer\WriterInterface $dataWriter
* @param \Spryker\Zed\Collector\Business\Exporter\Writer\TouchUpdaterInterface $touchUpdater
* @param \Symfony\Component\Console\Output\OutputInterface $output
*
* @return void
*/
public function runStorageRedirectCollector(
SpyTouchQuery $baseQuery,
LocaleTransfer $localeTransfer,
BatchResultInterface $result,
ReaderInterface $dataReader,
WriterInterface $dataWriter,
TouchUpdaterInterface $touchUpdater,
OutputInterface $output
);
/**
* @param \Orm\Zed\Touch\Persistence\SpyTouchQuery $baseQuery
* @param \Generated\Shared\Transfer\LocaleTransfer $localeTransfer
* @param \Spryker\Zed\Collector\Business\Model\BatchResultInterface $result
* @param \Spryker\Zed\Collector\Business\Exporter\Reader\ReaderInterface $dataReader
* @param \Spryker\Zed\Collector\Business\Exporter\Writer\WriterInterface $dataWriter
* @param \Spryker\Zed\Collector\Business\Exporter\Writer\TouchUpdaterInterface $touchUpdater
* @param \Symfony\Component\Console\Output\OutputInterface $output
*
* @return void
*/
public function runStorageTranslationCollector(
SpyTouchQuery $baseQuery,
LocaleTransfer $localeTransfer,
BatchResultInterface $result,
ReaderInterface $dataReader,
WriterInterface $dataWriter,
TouchUpdaterInterface $touchUpdater,
OutputInterface $output
);
/**
* @param \Orm\Zed\Touch\Persistence\SpyTouchQuery $baseQuery
* @param \Generated\Shared\Transfer\LocaleTransfer $localeTransfer
* @param \Spryker\Zed\Collector\Business\Model\BatchResultInterface $result
* @param \Spryker\Zed\Collector\Business\Exporter\Reader\ReaderInterface $dataReader
* @param \Spryker\Zed\Collector\Business\Exporter\Writer\WriterInterface $dataWriter
* @param \Spryker\Zed\Collector\Business\Exporter\Writer\TouchUpdaterInterface $touchUpdater
* @param \Symfony\Component\Console\Output\OutputInterface $output
*
* @return void
*/
public function runStorageAttributeMapCollector(
SpyTouchQuery $baseQuery,
LocaleTransfer $localeTransfer,
BatchResultInterface $result,
ReaderInterface $dataReader,
WriterInterface $dataWriter,
TouchUpdaterInterface $touchUpdater,
OutputInterface $output
);
}
| spryker/demoshop | src/Pyz/Zed/Collector/Business/CollectorFacadeInterface.php | PHP | mit | 7,206 |
<?xml version="1.0" ?><!DOCTYPE TS><TS language="ar" version="2.1">
<context>
<name>AboutDialog</name>
<message>
<location filename="../forms/aboutdialog.ui" line="+14"/>
<source>About CM_CapitalName</source>
<translation>عن البلاك كوين</translation>
</message>
<message>
<location line="+39"/>
<source><b>CM_CapitalName</b> version</source>
<translation>جزء البلاك كوين</translation>
</message>
<message>
<location line="+41"/>
<source>Copyright © 2009-2014 The Bitcoin developers
Copyright © 2012-2014 The NovaCoin developers
Copyright © 2014 The BlackCoin developers
Copyright © 2015 The CM_CapitalName developers</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+15"/>
<source>
This is experimental software.
Distributed under the MIT/X11 software license, see the accompanying file COPYING or <a href="http://www.opensource.org/licenses/mit-license.php">http://www.opensource.org/licenses/mit-license.php</a>.
This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit (<a href="https://www.openssl.org/">https://www.openssl.org/</a>) and cryptographic software written by Eric Young (<a href="mailto:eay@cryptsoft.com">eay@cryptsoft.com</a>) and UPnP software written by Thomas Bernard.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>AddressBookPage</name>
<message>
<location filename="../forms/addressbookpage.ui" line="+14"/>
<source>Address Book</source>
<translation>كتاب العنوان</translation>
</message>
<message>
<location line="+22"/>
<source>Double-click to edit address or label</source>
<translation>أنقر على الماوس مرتين لتعديل العنوان</translation>
</message>
<message>
<location line="+24"/>
<source>Create a new address</source>
<translation>انشأ عنوان جديد</translation>
</message>
<message>
<location line="+10"/>
<source>Copy the currently selected address to the system clipboard</source>
<translation>قم بنسخ العنوان المختار لحافظة النظام</translation>
</message>
<message>
<location line="-7"/>
<source>&New Address</source>
<translation>&عنوان جديد</translation>
</message>
<message>
<location line="-43"/>
<source>These are your CM_CapitalName addresses for receiving payments. You may want to give a different one to each sender so you can keep track of who is paying you.</source>
<translation>هذه هي عناوين البلاك كوين لاستقبال الدفعات. يمكن أن تعطي عنوان مختلف لكل مرسل من اجل أن تتابع من يرسل لك.</translation>
</message>
<message>
<location line="+53"/>
<source>&Copy Address</source>
<translation>انسخ العنوان</translation>
</message>
<message>
<location line="+7"/>
<source>Show &QR Code</source>
<translation>اظهار &رمز الاستجابة السريعة</translation>
</message>
<message>
<location line="+7"/>
<source>Sign a message to prove you own a CM_CapitalName address</source>
<translation>التوقيع علي رسالة لاثبات بانك تملك عنوان البلاك كوين</translation>
</message>
<message>
<location line="+3"/>
<source>Sign &Message</source>
<translation>وقع &الرسالة</translation>
</message>
<message>
<location line="+17"/>
<source>Delete the currently selected address from the list</source>
<translation>خذف العنوان الحالي التي تم اختياره من القائمة</translation>
</message>
<message>
<location line="-10"/>
<source>Verify a message to ensure it was signed with a specified CM_CapitalName address</source>
<translation>تحقق من الرسالة لتثبت بانه تم توقيعه بعنوان بلاك كوين محدد</translation>
</message>
<message>
<location line="+3"/>
<source>&Verify Message</source>
<translation>&تحقق الرسالة</translation>
</message>
<message>
<location line="+10"/>
<source>&Delete</source>
<translation>&أمسح</translation>
</message>
<message>
<location filename="../addressbookpage.cpp" line="+65"/>
<source>Copy &Label</source>
<translation>نسخ &التسمية</translation>
</message>
<message>
<location line="+2"/>
<source>&Edit</source>
<translation>تعديل</translation>
</message>
<message>
<location line="+250"/>
<source>Export Address Book Data</source>
<translation>تصدير بيانات كتاب العناوين</translation>
</message>
<message>
<location line="+1"/>
<source>Comma separated file (*.csv)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>Error exporting</source>
<translation>خطا في التصدير</translation>
</message>
<message>
<location line="+0"/>
<source>Could not write to file %1.</source>
<translation>لا يمكن الكتابة الي الملف %1.</translation>
</message>
</context>
<context>
<name>AddressTableModel</name>
<message>
<location filename="../addresstablemodel.cpp" line="+145"/>
<source>Label</source>
<translation>وصف</translation>
</message>
<message>
<location line="+0"/>
<source>Address</source>
<translation>عنوان</translation>
</message>
<message>
<location line="+36"/>
<source>(no label)</source>
<translation>(لا وصف)</translation>
</message>
</context>
<context>
<name>AskPassphraseDialog</name>
<message>
<location filename="../forms/askpassphrasedialog.ui" line="+26"/>
<source>Passphrase Dialog</source>
<translation>حوار كلمة المرور</translation>
</message>
<message>
<location line="+21"/>
<source>Enter passphrase</source>
<translation>ادخل كلمة المرور</translation>
</message>
<message>
<location line="+14"/>
<source>New passphrase</source>
<translation>عبارة مرور جديدة</translation>
</message>
<message>
<location line="+14"/>
<source>Repeat new passphrase</source>
<translation>ادخل الجملة السرية مرة أخرى</translation>
</message>
<message>
<location line="+33"/>
<source>Serves to disable the trivial sendmoney when OS account compromised. Provides no real security.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>For staking only</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="+38"/>
<source>Encrypt wallet</source>
<translation>تشفير المحفظة</translation>
</message>
<message>
<location line="+7"/>
<source>This operation needs your wallet passphrase to unlock the wallet.</source>
<translation>هذه العملية تحتاج عبارة المرور محفظتك لفتحها</translation>
</message>
<message>
<location line="+5"/>
<source>Unlock wallet</source>
<translation>إفتح المحفظة</translation>
</message>
<message>
<location line="+3"/>
<source>This operation needs your wallet passphrase to decrypt the wallet.</source>
<translation>هذه العملية تحتاج عبارة المرور محفظتك فك تشفيرها</translation>
</message>
<message>
<location line="+5"/>
<source>Decrypt wallet</source>
<translation>فك تشفير المحفظة</translation>
</message>
<message>
<location line="+3"/>
<source>Change passphrase</source>
<translation>تغيير عبارة المرور</translation>
</message>
<message>
<location line="+1"/>
<source>Enter the old and new passphrase to the wallet.</source>
<translation>أدخل عبارة المرور القديمة والجديدة إلى المحفظة.</translation>
</message>
<message>
<location line="+45"/>
<source>Confirm wallet encryption</source>
<translation>تأكيد التشفير المحفظة</translation>
</message>
<message>
<location line="+1"/>
<source>Warning: If you encrypt your wallet and lose your passphrase, you will <b>LOSE ALL OF YOUR COINS</b>!</source>
<translation>تخذير : اذا تم تشفير المحفظة وضيعت كلمة المرور, لن تستطيع الحصول علي البلاك كوين</translation>
</message>
<message>
<location line="+0"/>
<source>Are you sure you wish to encrypt your wallet?</source>
<translation>هل انت متأكد من رغبتك في تشفير المحفظة؟</translation>
</message>
<message>
<location line="+15"/>
<source>IMPORTANT: Any previous backups you have made of your wallet file should be replaced with the newly generated, encrypted wallet file. For security reasons, previous backups of the unencrypted wallet file will become useless as soon as you start using the new, encrypted wallet.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+103"/>
<location line="+24"/>
<source>Warning: The Caps Lock key is on!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-133"/>
<location line="+60"/>
<source>Wallet encrypted</source>
<translation>محفظة مشفرة</translation>
</message>
<message>
<location line="-140"/>
<source>Enter the new passphrase to the wallet.<br/>Please use a passphrase of <b>ten or more random characters</b>, or <b>eight or more words</b>.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+82"/>
<source>CM_CapitalName will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your coins from being stolen by malware infecting your computer.</source>
<translation>بلاك كوين</translation>
</message>
<message>
<location line="+13"/>
<location line="+7"/>
<location line="+44"/>
<location line="+6"/>
<source>Wallet encryption failed</source>
<translation>فشل تشفير المحفظة</translation>
</message>
<message>
<location line="-56"/>
<source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source>
<translation>شل تشفير المحفظة بسبب خطأ داخلي. لم يتم تشفير محفظتك.</translation>
</message>
<message>
<location line="+7"/>
<location line="+50"/>
<source>The supplied passphrases do not match.</source>
<translation>عبارتي المرور ليستا متطابقتان
</translation>
</message>
<message>
<location line="-38"/>
<source>Wallet unlock failed</source>
<translation>فشل فتح المحفظة</translation>
</message>
<message>
<location line="+1"/>
<location line="+12"/>
<location line="+19"/>
<source>The passphrase entered for the wallet decryption was incorrect.</source>
<translation>عبارة المرور التي تم إدخالها لفك شفرة المحفظة غير صحيحة.
</translation>
</message>
<message>
<location line="-20"/>
<source>Wallet decryption failed</source>
<translation>فشل فك التشفير المحفظة</translation>
</message>
<message>
<location line="+14"/>
<source>Wallet passphrase was successfully changed.</source>
<translation>كلمة مرور المحفظة تم تغييره بشكل ناجح</translation>
</message>
</context>
<context>
<name>BitcoinGUI</name>
<message>
<location filename="../bitcoingui.cpp" line="+297"/>
<source>Sign &message...</source>
<translation>التوقيع و الرسائل</translation>
</message>
<message>
<location line="-64"/>
<source>Show general overview of wallet</source>
<translation>إظهار نظرة عامة على المحفظة</translation>
</message>
<message>
<location line="+17"/>
<source>&Transactions</source>
<translation>المعاملات</translation>
</message>
<message>
<location line="+1"/>
<source>Browse transaction history</source>
<translation>تصفح التاريخ المعاملات</translation>
</message>
<message>
<location line="+5"/>
<source>&Address Book</source>
<translation>&كتاب العنوان</translation>
</message>
<message>
<location line="+1"/>
<source>Edit the list of stored addresses and labels</source>
<translation>تعديل قائمة العنوان المحفوظة</translation>
</message>
<message>
<location line="-18"/>
<source>Show the list of addresses for receiving payments</source>
<translation>اظهار قائمة العناوين التي تستقبل التعاملات</translation>
</message>
<message>
<location line="+34"/>
<source>E&xit</source>
<translation>خروج</translation>
</message>
<message>
<location line="+1"/>
<source>Quit application</source>
<translation>الخروج من التطبيق</translation>
</message>
<message>
<location line="+4"/>
<source>Show information about CM_CapitalName</source>
<translation>اظهار المعلومات عن البلاك كوين</translation>
</message>
<message>
<location line="+2"/>
<source>About &Qt</source>
<translation>عن</translation>
</message>
<message>
<location line="+1"/>
<source>Show information about Qt</source>
<translation>اظهر المعلومات</translation>
</message>
<message>
<location line="+2"/>
<source>&Options...</source>
<translation>خيارات ...</translation>
</message>
<message>
<location line="+4"/>
<source>&Encrypt Wallet...</source>
<translation>تشفير المحفظة</translation>
</message>
<message>
<location line="+2"/>
<source>&Backup Wallet...</source>
<translation>حفظ ودعم المحفظة</translation>
</message>
<message>
<location line="+2"/>
<source>&Change Passphrase...</source>
<translation>تغيير كلمة المرور</translation>
</message>
<message>
<location line="+9"/>
<source>&Export...</source>
<translation>&تصدير...</translation>
</message>
<message>
<location line="-55"/>
<source>Send coins to a CM_CapitalName address</source>
<translation>ارسال البلاك كوين الي عنوان اخر</translation>
</message>
<message>
<location line="+39"/>
<source>Modify configuration options for CM_CapitalName</source>
<translation>تعديل خيارات التكوين للبلاك كوين</translation>
</message>
<message>
<location line="+17"/>
<source>Export the data in the current tab to a file</source>
<translation>ارسال البيانات الحالية الي ملف</translation>
</message>
<message>
<location line="-13"/>
<source>Encrypt or decrypt wallet</source>
<translation>تشفير او فك التشفير للمحفظة</translation>
</message>
<message>
<location line="+2"/>
<source>Backup wallet to another location</source>
<translation>احفظ نسخة احتياطية للمحفظة في مكان آخر</translation>
</message>
<message>
<location line="+2"/>
<source>Change the passphrase used for wallet encryption</source>
<translation>تغيير عبارة المرور المستخدمة لتشفير المحفظة</translation>
</message>
<message>
<location line="+10"/>
<source>&Debug window</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Open debugging and diagnostic console</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-5"/>
<source>&Verify message...</source>
<translation>تأكيد الرسالة</translation>
</message>
<message>
<location line="-214"/>
<location line="+551"/>
<source>CM_CapitalName</source>
<translation>البلاك كوين</translation>
</message>
<message>
<location line="-551"/>
<source>Wallet</source>
<translation>محفظة</translation>
</message>
<message>
<location line="+193"/>
<source>&About CM_CapitalName</source>
<translation>عن البلاك كوين</translation>
</message>
<message>
<location line="+9"/>
<source>&Show / Hide</source>
<translation>اظهار/ اخفاء</translation>
</message>
<message>
<location line="+8"/>
<source>Unlock wallet</source>
<translation>فتح المحفظة</translation>
</message>
<message>
<location line="+1"/>
<source>&Lock Wallet</source>
<translation>قفل المحفظة</translation>
</message>
<message>
<location line="+1"/>
<source>Lock wallet</source>
<translation>قفل المحفظة</translation>
</message>
<message>
<location line="+28"/>
<source>&File</source>
<translation>ملف</translation>
</message>
<message>
<location line="+8"/>
<source>&Settings</source>
<translation>الاعدادات</translation>
</message>
<message>
<location line="+8"/>
<source>&Help</source>
<translation>مساعدة</translation>
</message>
<message>
<location line="+17"/>
<source>Tabs toolbar</source>
<translation>شريط أدوات علامات التبويب</translation>
</message>
<message>
<location line="+46"/>
<location line="+9"/>
<source>[testnet]</source>
<translation>[testnet]</translation>
</message>
<message>
<location line="+0"/>
<location line="+58"/>
<source>CM_CapitalName client</source>
<translation>برنامج البلاك كوين</translation>
</message>
<message numerus="yes">
<location line="+70"/>
<source>%n active connection(s) to CM_CapitalName network</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+488"/>
<source>Staking.<br>Your weight is %1<br>Network weight is %2<br>Expected time to earn reward is %3</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Not staking because wallet is locked</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Not staking because wallet is offline</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Not staking because wallet is syncing</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Not staking because you don't have mature coins</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-808"/>
<source>&Dashboard</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>&Receive</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>&Send</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+49"/>
<source>&Unlock Wallet...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+273"/>
<source>Up to date</source>
<translation>محين</translation>
</message>
<message>
<location line="+43"/>
<source>Catching up...</source>
<translation>اللحاق بالركب ...</translation>
</message>
<message>
<location line="+113"/>
<source>Confirm transaction fee</source>
<translation>تأكيد رسوم المعاملة</translation>
</message>
<message>
<location line="+27"/>
<source>Sent transaction</source>
<translation>المعاملات المرسلة</translation>
</message>
<message>
<location line="+1"/>
<source>Incoming transaction</source>
<translation>المعاملات واردة</translation>
</message>
<message>
<location line="+1"/>
<source>Date: %1
Amount: %2
Type: %3
Address: %4
</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+100"/>
<location line="+15"/>
<source>URI handling</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-15"/>
<location line="+15"/>
<source>URI can not be parsed! This can be caused by an invalid CM_CapitalName address or malformed URI parameters.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+9"/>
<source>Wallet is <b>not encrypted</b></source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Wallet is <b>encrypted</b> and currently <b>unlocked</b></source>
<translation>المحفظة مشفرة و مفتوحة حاليا</translation>
</message>
<message>
<location line="+8"/>
<source>Wallet is <b>encrypted</b> and currently <b>locked</b></source>
<translation>المحفظة مشفرة و مقفلة حاليا</translation>
</message>
<message>
<location line="+24"/>
<source>Backup Wallet</source>
<translation>النسخ الاحتياطي للمحفظة</translation>
</message>
<message>
<location line="+0"/>
<source>Wallet Data (*.dat)</source>
<translation>بيانات المحفظة (*.dat)</translation>
</message>
<message>
<location line="+3"/>
<source>Backup Failed</source>
<translation>فشل الدعم</translation>
</message>
<message>
<location line="+0"/>
<source>There was an error trying to save the wallet data to the new location.</source>
<translation>خطا في محاولة حفظ بيانات الحفظة في مكان جديد</translation>
</message>
<message numerus="yes">
<location line="+91"/>
<source>%n second(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n minute(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message numerus="yes">
<location line="-429"/>
<location line="+433"/>
<source>%n hour(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="-456"/>
<source>Processed %1 blocks of transaction history.</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="+27"/>
<location line="+433"/>
<source>%n day(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message numerus="yes">
<location line="-429"/>
<location line="+6"/>
<source>%n week(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+0"/>
<source>%1 and %2</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="+0"/>
<source>%n year(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+5"/>
<source>%1 behind</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+15"/>
<source>Last received block was generated %1 ago.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Transactions after this will not yet be visible.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Error</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Warning</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Information</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+69"/>
<source>This transaction is over the size limit. You can still send it for a fee of %1, which goes to the nodes that process your transaction and helps to support the network. Do you want to pay the fee?</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+324"/>
<source>Not staking</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitcoin.cpp" line="+104"/>
<source>A fatal error occurred. CM_CapitalName can no longer continue safely and will quit.</source>
<translation>خطا فادح! بلاك كوين لا يمكن أن يستمر جاري الاغلاق</translation>
</message>
</context>
<context>
<name>ClientModel</name>
<message>
<location filename="../clientmodel.cpp" line="+110"/>
<source>Network Alert</source>
<translation>تحذير الشبكة</translation>
</message>
</context>
<context>
<name>CoinControlDialog</name>
<message>
<location filename="../forms/coincontroldialog.ui" line="+14"/>
<source>Coin Control</source>
<translation>سيطرة الكوين</translation>
</message>
<message>
<location line="+31"/>
<source>Quantity:</source>
<translation>الكمية:</translation>
</message>
<message>
<location line="+32"/>
<source>Bytes:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+48"/>
<source>Amount:</source>
<translation>المبلغ:</translation>
</message>
<message>
<location line="+32"/>
<source>Priority:</source>
<translation>اهمية:</translation>
</message>
<message>
<location line="+48"/>
<source>Fee:</source>
<translation>رسوم:</translation>
</message>
<message>
<location line="+35"/>
<source>Low Output:</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../coincontroldialog.cpp" line="+552"/>
<source>no</source>
<translation>لا</translation>
</message>
<message>
<location filename="../forms/coincontroldialog.ui" line="+51"/>
<source>After Fee:</source>
<translation>بعد الرسوم:</translation>
</message>
<message>
<location line="+35"/>
<source>Change:</source>
<translation>تغيير:</translation>
</message>
<message>
<location line="+69"/>
<source>(un)select all</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>Tree mode</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+16"/>
<source>List mode</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+45"/>
<source>Amount</source>
<translation>المبلغ</translation>
</message>
<message>
<location line="+5"/>
<source>Label</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Address</source>
<translation>عنوان</translation>
</message>
<message>
<location line="+5"/>
<source>Date</source>
<translation>التاريخ</translation>
</message>
<message>
<location line="+5"/>
<source>Confirmations</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Confirmed</source>
<translation>تأكيد</translation>
</message>
<message>
<location line="+5"/>
<source>Priority</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../coincontroldialog.cpp" line="-515"/>
<source>Copy address</source>
<translation> انسخ عنوان</translation>
</message>
<message>
<location line="+1"/>
<source>Copy label</source>
<translation> انسخ التسمية</translation>
</message>
<message>
<location line="+1"/>
<location line="+26"/>
<source>Copy amount</source>
<translation>نسخ الكمية</translation>
</message>
<message>
<location line="-25"/>
<source>Copy transaction ID</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+24"/>
<source>Copy quantity</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Copy fee</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy after fee</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy bytes</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy priority</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy low output</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy change</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+317"/>
<source>highest</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>high</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>medium-high</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>medium</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>low-medium</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>low</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>lowest</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+155"/>
<source>DUST</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>yes</source>
<translation>نعم</translation>
</message>
<message>
<location line="+10"/>
<source>This label turns red, if the transaction size is bigger than 10000 bytes.
This means a fee of at least %1 per kb is required.
Can vary +/- 1 Byte per input.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Transactions with higher priority get more likely into a block.
This label turns red, if the priority is smaller than "medium".
This means a fee of at least %1 per kb is required.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>This label turns red, if any recipient receives an amount smaller than %1.
This means a fee of at least %2 is required.
Amounts below 0.546 times the minimum relay fee are shown as DUST.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>This label turns red, if the change is smaller than %1.
This means a fee of at least %2 is required.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+36"/>
<location line="+66"/>
<source>(no label)</source>
<translation>(لا وصف)</translation>
</message>
<message>
<location line="-9"/>
<source>change from %1 (%2)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>(change)</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>EditAddressDialog</name>
<message>
<location filename="../forms/editaddressdialog.ui" line="+14"/>
<source>Edit Address</source>
<translation>عدل العنوان</translation>
</message>
<message>
<location line="+11"/>
<source>&Label</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>The label associated with this address book entry</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>&Address</source>
<translation>العنوان</translation>
</message>
<message>
<location line="+10"/>
<source>The address associated with this address book entry. This can only be modified for sending addresses.</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../editaddressdialog.cpp" line="+21"/>
<source>New receiving address</source>
<translation>عنوان تلقي جديد</translation>
</message>
<message>
<location line="+4"/>
<source>New sending address</source>
<translation>عنوان إرسال جديد</translation>
</message>
<message>
<location line="+3"/>
<source>Edit receiving address</source>
<translation>تعديل عنوان التلقي
</translation>
</message>
<message>
<location line="+4"/>
<source>Edit sending address</source>
<translation>تعديل عنوان الارسال</translation>
</message>
<message>
<location line="+76"/>
<source>The entered address "%1" is already in the address book.</source>
<translation>هدا العنوان "%1" موجود مسبقا في دفتر العناوين</translation>
</message>
<message>
<location line="-5"/>
<source>The entered address "%1" is not a valid CM_CapitalName address.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>Could not unlock wallet.</source>
<translation> يمكن فتح المحفظة.</translation>
</message>
<message>
<location line="+5"/>
<source>New key generation failed.</source>
<translation>فشل توليد مفتاح جديد.</translation>
</message>
</context>
<context>
<name>GUIUtil::HelpMessageBox</name>
<message>
<location filename="../guiutil.cpp" line="+426"/>
<location line="+12"/>
<source>CM_CapitalName-Qt</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-12"/>
<source>version</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Usage:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>command-line options</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>UI options</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Set language, for example "de_DE" (default: system locale)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Start minimized</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Show splash screen on startup (default: 1)</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>OptionsDialog</name>
<message>
<location filename="../forms/optionsdialog.ui" line="+14"/>
<source>Options</source>
<translation>خيارات ...</translation>
</message>
<message>
<location line="+16"/>
<source>&Main</source>
<translation>الرئيسي</translation>
</message>
<message>
<location line="+6"/>
<source>Optional transaction fee per kB that helps make sure your transactions are processed quickly. Most transactions are 1 kB. Fee 0.01 recommended.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+15"/>
<source>Pay transaction &fee</source>
<translation>ادفع &رسوم المعاملة</translation>
</message>
<message>
<location line="+31"/>
<source>Reserved amount does not participate in staking and is therefore spendable at any time.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+15"/>
<source>Reserve</source>
<translation>حجز</translation>
</message>
<message>
<location line="+31"/>
<source>Automatically start CM_CapitalName after logging in to the system.</source>
<translation>بد البلاك كوين تلقائي عند الدخول الي الجهاز</translation>
</message>
<message>
<location line="+3"/>
<source>&Start CM_CapitalName on system login</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+21"/>
<source>&Network</source>
<translation>&الشبكة</translation>
</message>
<message>
<location line="+6"/>
<source>Automatically open the CM_CapitalName client port on the router. This only works when your router supports UPnP and it is enabled.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Map port using &UPnP</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Connect to the CM_CapitalName network through a SOCKS proxy (e.g. when connecting through Tor).</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Connect through SOCKS proxy:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+9"/>
<source>Proxy &IP:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+19"/>
<source>IP address of the proxy (e.g. 127.0.0.1)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>&Port:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+19"/>
<source>Port of the proxy (e.g. 9050)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>SOCKS &Version:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>SOCKS version of the proxy (e.g. 5)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+36"/>
<source>&Window</source>
<translation>نافذه</translation>
</message>
<message>
<location line="+6"/>
<source>Show only a tray icon after minimizing the window.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Minimize to the tray instead of the taskbar</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Minimize instead of exit the application when the window is closed. When this option is enabled, the application will be closed only after selecting Quit in the menu.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>M&inimize on close</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+21"/>
<source>&Display</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>User Interface &language:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>The user interface language can be set here. This setting will take effect after restarting CM_CapitalName.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+11"/>
<source>&Unit to show amounts in:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>Choose the default subdivision unit to show in the interface and when sending coins.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+9"/>
<source>Whether to show coin control features or not.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Display coin &control features (experts only!)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Whether to select the coin outputs randomly or with minimal coin age.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Minimize weight consumption (experimental)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Use black visual theme (requires restart)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+71"/>
<source>&OK</source>
<translation>تم</translation>
</message>
<message>
<location line="+7"/>
<source>&Cancel</source>
<translation>الغاء</translation>
</message>
<message>
<location line="+10"/>
<source>&Apply</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../optionsdialog.cpp" line="+53"/>
<source>default</source>
<translation>الافتراضي</translation>
</message>
<message>
<location line="+149"/>
<location line="+9"/>
<source>Warning</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-9"/>
<location line="+9"/>
<source>This setting will take effect after restarting CM_CapitalName.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+29"/>
<source>The supplied proxy address is invalid.</source>
<translation>عنوان الوكيل توفيره غير صالح.</translation>
</message>
</context>
<context>
<name>OverviewPage</name>
<message>
<location filename="../forms/overviewpage.ui" line="+14"/>
<source>Form</source>
<translation>نمودج</translation>
</message>
<message>
<location line="+46"/>
<location line="+247"/>
<source>The displayed information may be out of date. Your wallet automatically synchronizes with the CM_CapitalName network after a connection is established, but this process has not completed yet.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-173"/>
<source>Stake:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+32"/>
<source>Unconfirmed:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-113"/>
<source>Wallet</source>
<translation>محفظة</translation>
</message>
<message>
<location line="+49"/>
<source>Spendable:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+16"/>
<source>Your current spendable balance</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+80"/>
<source>Immature:</source>
<translation>غير ناضجة</translation>
</message>
<message>
<location line="+13"/>
<source>Mined balance that has not yet matured</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Total:</source>
<translation>الكامل:</translation>
</message>
<message>
<location line="+16"/>
<source>Your current total balance</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+50"/>
<source><b>Recent transactions</b></source>
<translation>اخر المعملات </translation>
</message>
<message>
<location line="-118"/>
<source>Total of transactions that have yet to be confirmed, and do not yet count toward the current balance</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-32"/>
<source>Total of coins that was staked, and do not yet count toward the current balance</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../overviewpage.cpp" line="+116"/>
<location line="+1"/>
<source>out of sync</source>
<translation>خارج المزامنه</translation>
</message>
</context>
<context>
<name>PaymentServer</name>
<message>
<location filename="../paymentserver.cpp" line="+107"/>
<source>Cannot start blackcoin: click-to-pay handler</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>QRCodeDialog</name>
<message>
<location filename="../forms/qrcodedialog.ui" line="+14"/>
<source>QR Code Dialog</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+59"/>
<source>Request Payment</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+56"/>
<source>Amount:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-44"/>
<source>Label:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+19"/>
<source>Message:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+71"/>
<source>&Save As...</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../qrcodedialog.cpp" line="+62"/>
<source>Error encoding URI into QR Code.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+40"/>
<source>The entered amount is invalid, please check.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Resulting URI too long, try to reduce the text for label / message.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+25"/>
<source>Save QR Code</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>PNG Images (*.png)</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>RPCConsole</name>
<message>
<location filename="../forms/rpcconsole.ui" line="+46"/>
<source>Client name</source>
<translation>اسم العميل</translation>
</message>
<message>
<location line="+10"/>
<location line="+23"/>
<location line="+26"/>
<location line="+23"/>
<location line="+23"/>
<location line="+36"/>
<location line="+53"/>
<location line="+23"/>
<source>N/A</source>
<translation>غير معروف</translation>
</message>
<message>
<location line="-194"/>
<source>Client version</source>
<translation>نسخه العميل</translation>
</message>
<message>
<location line="-45"/>
<source>&Information</source>
<translation>المعلومات</translation>
</message>
<message>
<location line="+68"/>
<source>Using OpenSSL version</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+49"/>
<source>Startup time</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+29"/>
<source>Network</source>
<translation>الشبكه</translation>
</message>
<message>
<location line="+7"/>
<source>Number of connections</source>
<translation>عدد الاتصالات</translation>
</message>
<message>
<location line="+23"/>
<source>On testnet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Block chain</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Current number of blocks</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+197"/>
<source>&Network Traffic</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+52"/>
<source>&Clear</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>Totals</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+64"/>
<source>In:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+80"/>
<source>Out:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-383"/>
<source>Last block time</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+52"/>
<source>&Open</source>
<translation>الفتح</translation>
</message>
<message>
<location line="+16"/>
<source>Command-line options</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Show the CM_CapitalName-Qt help message to get a list with possible CM_CapitalName command-line options.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Show</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+24"/>
<source>&Console</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-237"/>
<source>Build date</source>
<translation>وقت البناء</translation>
</message>
<message>
<location line="-104"/>
<source>CM_CapitalName - Debug window</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+25"/>
<source>CM_CapitalName Core</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+256"/>
<source>Debug log file</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Open the CM_CapitalName debug log file from the current data directory. This can take a few seconds for large log files.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+102"/>
<source>Clear console</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../rpcconsole.cpp" line="+325"/>
<source>Welcome to the CM_CapitalName RPC console.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Use up and down arrows to navigate history, and <b>Ctrl-L</b> to clear screen.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Type <b>help</b> for an overview of available commands.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+127"/>
<source>%1 B</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>%1 KB</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>%1 MB</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>%1 GB</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>%1 m</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>%1 h</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>%1 h %2 m</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>SendCoinsDialog</name>
<message>
<location filename="../forms/sendcoinsdialog.ui" line="+14"/>
<location filename="../sendcoinsdialog.cpp" line="+181"/>
<location line="+5"/>
<location line="+5"/>
<location line="+5"/>
<location line="+6"/>
<location line="+5"/>
<location line="+5"/>
<source>Send Coins</source>
<translation>إرسال Coins</translation>
</message>
<message>
<location line="+76"/>
<source>Coin Control Features</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+20"/>
<source>Inputs...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>automatically selected</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+19"/>
<source>Insufficient funds!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+77"/>
<source>Quantity:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+22"/>
<location line="+35"/>
<source>0</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-19"/>
<source>Bytes:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+51"/>
<source>Amount:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+22"/>
<location line="+86"/>
<location line="+86"/>
<location line="+32"/>
<source>0.00 CC</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-191"/>
<source>Priority:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+19"/>
<source>medium</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+32"/>
<source>Fee:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+35"/>
<source>Low Output:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+19"/>
<source>no</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+32"/>
<source>After Fee:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+35"/>
<source>Change</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+50"/>
<source>custom change address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+106"/>
<source>Send to multiple recipients at once</source>
<translation>إرسال إلى عدة مستلمين في وقت واحد</translation>
</message>
<message>
<location line="+3"/>
<source>Add &Recipient</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+16"/>
<source>Remove all transaction fields</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Clear &All</source>
<translation>مسح الكل</translation>
</message>
<message>
<location line="+24"/>
<source>Balance:</source>
<translation>الرصيد:</translation>
</message>
<message>
<location line="+16"/>
<source>123.456 CC</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+31"/>
<source>Confirm the send action</source>
<translation>تأكيد الإرسال</translation>
</message>
<message>
<location line="+3"/>
<source>S&end</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="-173"/>
<source>Enter a CM_CapitalName address (e.g. B8gZqgY4r2RoEdqYk3QsAqFckyf9pRHN6i)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+15"/>
<source>Copy quantity</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy amount</source>
<translation>نسخ الكمية</translation>
</message>
<message>
<location line="+1"/>
<source>Copy fee</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy after fee</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy bytes</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy priority</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy low output</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy change</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+86"/>
<source><b>%1</b> to %2 (%3)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Confirm send coins</source>
<translation>تأكيد الإرسال Coins</translation>
</message>
<message>
<location line="+1"/>
<source>Are you sure you want to send %1?</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source> and </source>
<translation type="unfinished"/>
</message>
<message>
<location line="+29"/>
<source>The recipient address is not valid, please recheck.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>The amount to pay must be larger than 0.</source>
<translation>المبلغ المدفوع يجب ان يكون اكبر من 0</translation>
</message>
<message>
<location line="+5"/>
<source>The amount exceeds your balance.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>The total exceeds your balance when the %1 transaction fee is included.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Duplicate address found, can only send to each address once per send operation.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Error: Transaction creation failed!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+247"/>
<source>WARNING: Invalid CM_CapitalName address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>(no label)</source>
<translation>(لا وصف)</translation>
</message>
<message>
<location line="+4"/>
<source>WARNING: unknown change address</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>SendCoinsEntry</name>
<message>
<location filename="../forms/sendcoinsentry.ui" line="+14"/>
<source>Form</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+15"/>
<source>A&mount:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>Pay &To:</source>
<translation>ادفع الى </translation>
</message>
<message>
<location line="+34"/>
<source>The address to send the payment to (e.g. B8gZqgY4r2RoEdqYk3QsAqFckyf9pRHN6i)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+60"/>
<location filename="../sendcoinsentry.cpp" line="+26"/>
<source>Enter a label for this address to add it to your address book</source>
<translation>إدخال تسمية لهذا العنوان لإضافته إلى دفتر العناوين الخاص بك</translation>
</message>
<message>
<location line="-78"/>
<source>&Label:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+28"/>
<source>Choose address from address book</source>
<translation>اختيار عنوان من كتاب العناوين</translation>
</message>
<message>
<location line="+10"/>
<source>Alt+A</source>
<translation>Alt+A</translation>
</message>
<message>
<location line="+7"/>
<source>Paste address from clipboard</source>
<translation>انسخ العنوان من لوحة المفاتيح</translation>
</message>
<message>
<location line="+10"/>
<source>Alt+P</source>
<translation>Alt+P</translation>
</message>
<message>
<location line="+7"/>
<source>Remove this recipient</source>
<translation>خذف هذا المستخدم</translation>
</message>
<message>
<location filename="../sendcoinsentry.cpp" line="+1"/>
<source>Enter a CM_CapitalName address (e.g. B8gZqgY4r2RoEdqYk3QsAqFckyf9pRHN6i)</source>
<translation>ادخال عنوان البلاك كوين (مثلا B8gZqgY4r2RoEdqYk3QsAqFckyf9pRHN6i)</translation>
</message>
</context>
<context>
<name>SignVerifyMessageDialog</name>
<message>
<location filename="../forms/signverifymessagedialog.ui" line="+14"/>
<source>Signatures - Sign / Verify a Message</source>
<translation>التواقيع - التوقيع /تأكيد الرسالة</translation>
</message>
<message>
<location line="+13"/>
<location line="+124"/>
<source>&Sign Message</source>
<translation>&وقع الرسالة</translation>
</message>
<message>
<location line="-118"/>
<source>You can sign messages with your addresses to prove you own them. Be careful not to sign anything vague, as phishing attacks may try to trick you into signing your identity over to them. Only sign fully-detailed statements you agree to.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+18"/>
<source>The address to sign the message with (e.g. B8gZqgY4r2RoEdqYk3QsAqFckyf9pRHN6i)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<location line="+203"/>
<source>Choose an address from the address book</source>
<translation>اختيار عنوان من كتاب العناوين</translation>
</message>
<message>
<location line="-193"/>
<location line="+203"/>
<source>Alt+A</source>
<translation>Alt+A</translation>
</message>
<message>
<location line="-193"/>
<source>Paste address from clipboard</source>
<translation>انسخ العنوان من لوحة المفاتيح</translation>
</message>
<message>
<location line="+10"/>
<source>Alt+P</source>
<translation>Alt+P</translation>
</message>
<message>
<location line="+12"/>
<source>Enter the message you want to sign here</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+24"/>
<source>Copy the current signature to the system clipboard</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+21"/>
<source>Sign the message to prove you own this CM_CapitalName address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+17"/>
<source>Reset all sign message fields</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<location line="+146"/>
<source>Clear &All</source>
<translation>مسح الكل</translation>
</message>
<message>
<location line="-87"/>
<location line="+70"/>
<source>&Verify Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-64"/>
<source>Enter the signing address, message (ensure you copy line breaks, spaces, tabs, etc. exactly) and signature below to verify the message. Be careful not to read more into the signature than what is in the signed message itself, to avoid being tricked by a man-in-the-middle attack.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+21"/>
<source>The address the message was signed with (e.g. B8gZqgY4r2RoEdqYk3QsAqFckyf9pRHN6i)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+40"/>
<source>Verify the message to ensure it was signed with the specified CM_CapitalName address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+17"/>
<source>Reset all verify message fields</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../signverifymessagedialog.cpp" line="+27"/>
<location line="+3"/>
<source>Enter a CM_CapitalName address (e.g. B8gZqgY4r2RoEdqYk3QsAqFckyf9pRHN6i)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-2"/>
<source>Click "Sign Message" to generate signature</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Enter CM_CapitalName signature</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+82"/>
<location line="+81"/>
<source>The entered address is invalid.</source>
<translation>العنوان المدخل غير صالح</translation>
</message>
<message>
<location line="-81"/>
<location line="+8"/>
<location line="+73"/>
<location line="+8"/>
<source>Please check the address and try again.</source>
<translation>الرجاء التأكد من العنوان والمحاولة مرة اخرى</translation>
</message>
<message>
<location line="-81"/>
<location line="+81"/>
<source>The entered address does not refer to a key.</source>
<translation>العنوان المدخل لا يشير الى مفتاح</translation>
</message>
<message>
<location line="-73"/>
<source>Wallet unlock was cancelled.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Private key for the entered address is not available.</source>
<translation>المفتاح الخاص للعنوان المدخل غير موجود.</translation>
</message>
<message>
<location line="+12"/>
<source>Message signing failed.</source>
<translation>فشل توقيع الرسالة.</translation>
</message>
<message>
<location line="+5"/>
<source>Message signed.</source>
<translation>الرسالة موقعة.</translation>
</message>
<message>
<location line="+59"/>
<source>The signature could not be decoded.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<location line="+13"/>
<source>Please check the signature and try again.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>The signature did not match the message digest.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Message verification failed.</source>
<translation>فشلت عملية التأكد من الرسالة.</translation>
</message>
<message>
<location line="+5"/>
<source>Message verified.</source>
<translation>تم تأكيد الرسالة.</translation>
</message>
</context>
<context>
<name>TrafficGraphWidget</name>
<message>
<location filename="../trafficgraphwidget.cpp" line="+75"/>
<source>KB/s</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>TransactionDesc</name>
<message>
<location filename="../transactiondesc.cpp" line="+25"/>
<source>Open until %1</source>
<translation>مفتوح حتى 1٪</translation>
</message>
<message>
<location line="+6"/>
<source>conflicted</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>%1/offline</source>
<translation>1% غير متواجد</translation>
</message>
<message>
<location line="+2"/>
<source>%1/unconfirmed</source>
<translation>غير مؤكدة/1%</translation>
</message>
<message>
<location line="+2"/>
<source>%1 confirmations</source>
<translation>تأكيد %1</translation>
</message>
<message>
<location line="+17"/>
<source>Status</source>
<translation>الحالة.</translation>
</message>
<message numerus="yes">
<location line="+7"/>
<source>, broadcast through %n node(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+4"/>
<source>Date</source>
<translation>التاريخ</translation>
</message>
<message>
<location line="+7"/>
<source>Source</source>
<translation>المصدر</translation>
</message>
<message>
<location line="+0"/>
<source>Generated</source>
<translation>تم اصداره.</translation>
</message>
<message>
<location line="+5"/>
<location line="+17"/>
<source>From</source>
<translation>من</translation>
</message>
<message>
<location line="+1"/>
<location line="+22"/>
<location line="+58"/>
<source>To</source>
<translation>الى</translation>
</message>
<message>
<location line="-77"/>
<location line="+2"/>
<source>own address</source>
<translation>عنوانه</translation>
</message>
<message>
<location line="-2"/>
<source>label</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+37"/>
<location line="+12"/>
<location line="+45"/>
<location line="+17"/>
<location line="+30"/>
<source>Credit</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="-102"/>
<source>matures in %n more block(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+2"/>
<source>not accepted</source>
<translation>غير مقبولة</translation>
</message>
<message>
<location line="+44"/>
<location line="+8"/>
<location line="+15"/>
<location line="+30"/>
<source>Debit</source>
<translation>دين</translation>
</message>
<message>
<location line="-39"/>
<source>Transaction fee</source>
<translation>رسوم التحويل</translation>
</message>
<message>
<location line="+16"/>
<source>Net amount</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Comment</source>
<translation>تعليق</translation>
</message>
<message>
<location line="+2"/>
<source>Transaction ID</source>
<translation>رقم المعاملة</translation>
</message>
<message>
<location line="+3"/>
<source>Generated coins must mature 101 blocks before they can be spent. When you generated this block, it was broadcast to the network to be added to the block chain. If it fails to get into the chain, its state will change to "not accepted" and it won't be spendable. This may occasionally happen if another node generates a block within a few seconds of yours.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Debug information</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Transaction</source>
<translation>معاملة</translation>
</message>
<message>
<location line="+5"/>
<source>Inputs</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+21"/>
<source>Amount</source>
<translation>المبلغ</translation>
</message>
<message>
<location line="+1"/>
<source>true</source>
<translation>صحيح</translation>
</message>
<message>
<location line="+0"/>
<source>false</source>
<translation>خاطئ</translation>
</message>
<message>
<location line="-209"/>
<source>, has not been successfully broadcast yet</source>
<translation>لم يتم حتى الآن البث بنجاح</translation>
</message>
<message numerus="yes">
<location line="-36"/>
<source>Open for %n more block(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+71"/>
<source>unknown</source>
<translation>غير معروف</translation>
</message>
</context>
<context>
<name>TransactionDescDialog</name>
<message>
<location filename="../forms/transactiondescdialog.ui" line="+14"/>
<source>Transaction details</source>
<translation>تفاصيل المعاملة</translation>
</message>
<message>
<location line="+6"/>
<source>This pane shows a detailed description of the transaction</source>
<translation>يبين هذا الجزء وصفا مفصلا لهده المعاملة</translation>
</message>
</context>
<context>
<name>TransactionTableModel</name>
<message>
<location filename="../transactiontablemodel.cpp" line="+231"/>
<source>Date</source>
<translation>التاريخ</translation>
</message>
<message>
<location line="+0"/>
<source>Type</source>
<translation>النوع</translation>
</message>
<message>
<location line="+0"/>
<source>Address</source>
<translation>عنوان</translation>
</message>
<message>
<location line="+0"/>
<source>Amount</source>
<translation>المبلغ</translation>
</message>
<message>
<location line="+52"/>
<source>Open until %1</source>
<translation>مفتوح حتى 1٪</translation>
</message>
<message>
<location line="+12"/>
<source>Confirmed (%1 confirmations)</source>
<translation>تأكيد الإرسال Coins</translation>
</message>
<message numerus="yes">
<location line="-15"/>
<source>Open for %n more block(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+6"/>
<source>Offline</source>
<translation>غير متصل</translation>
</message>
<message>
<location line="+3"/>
<source>Unconfirmed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Confirming (%1 of %2 recommended confirmations)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Conflicted</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Immature (%1 confirmations, will be available after %2)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>This block was not received by any other nodes and will probably not be accepted!</source>
<translation>لم يتم تلقى هذه الكتلة (Block) من قبل أي العقد الأخرى وربما لن تكون مقبولة!</translation>
</message>
<message>
<location line="+3"/>
<source>Generated but not accepted</source>
<translation>ولدت ولكن لم تقبل</translation>
</message>
<message>
<location line="+42"/>
<source>Received with</source>
<translation>استقبل مع</translation>
</message>
<message>
<location line="+2"/>
<source>Received from</source>
<translation>استقبل من</translation>
</message>
<message>
<location line="+3"/>
<source>Sent to</source>
<translation>أرسل إلى</translation>
</message>
<message>
<location line="+2"/>
<source>Payment to yourself</source>
<translation>دفع لنفسك</translation>
</message>
<message>
<location line="+2"/>
<source>Mined</source>
<translation>Mined</translation>
</message>
<message>
<location line="+38"/>
<source>(n/a)</source>
<translation>غير متوفر</translation>
</message>
<message>
<location line="+194"/>
<source>Transaction status. Hover over this field to show number of confirmations.</source>
<translation>حالة المعاملة. تحوم حول هذا الحقل لعرض عدد التأكيدات.</translation>
</message>
<message>
<location line="+2"/>
<source>Date and time that the transaction was received.</source>
<translation>التاريخ والوقت الذي تم فيه تلقي المعاملة.</translation>
</message>
<message>
<location line="+2"/>
<source>Type of transaction.</source>
<translation>نوع المعاملات</translation>
</message>
<message>
<location line="+2"/>
<source>Destination address of transaction.</source>
<translation>عنوان وجهة المعاملة</translation>
</message>
<message>
<location line="+2"/>
<source>Amount removed from or added to balance.</source>
<translation>المبلغ الذي أزيل أو أضيف الى الرصيد</translation>
</message>
</context>
<context>
<name>TransactionView</name>
<message>
<location filename="../transactionview.cpp" line="+54"/>
<location line="+17"/>
<source>All</source>
<translation>الكل</translation>
</message>
<message>
<location line="-16"/>
<source>Today</source>
<translation>اليوم</translation>
</message>
<message>
<location line="+1"/>
<source>This week</source>
<translation>هدا الاسبوع</translation>
</message>
<message>
<location line="+1"/>
<source>This month</source>
<translation>هدا الشهر</translation>
</message>
<message>
<location line="+1"/>
<source>Last month</source>
<translation>الشهر الماضي</translation>
</message>
<message>
<location line="+1"/>
<source>This year</source>
<translation>هدا العام</translation>
</message>
<message>
<location line="+1"/>
<source>Range...</source>
<translation>نطاق</translation>
</message>
<message>
<location line="+12"/>
<source>Received with</source>
<translation>استقبل مع</translation>
</message>
<message>
<location line="+2"/>
<source>Sent to</source>
<translation>أرسل إلى</translation>
</message>
<message>
<location line="+2"/>
<source>To yourself</source>
<translation>إليك</translation>
</message>
<message>
<location line="+1"/>
<source>Mined</source>
<translation>Mined</translation>
</message>
<message>
<location line="+1"/>
<source>Other</source>
<translation>اخرى</translation>
</message>
<message>
<location line="+7"/>
<source>Enter address or label to search</source>
<translation>ادخل عنوان أووصف للبحث</translation>
</message>
<message>
<location line="+7"/>
<source>Min amount</source>
<translation>الكمية الادني</translation>
</message>
<message>
<location line="+34"/>
<source>Copy address</source>
<translation> انسخ عنوان</translation>
</message>
<message>
<location line="+1"/>
<source>Copy label</source>
<translation> انسخ التسمية</translation>
</message>
<message>
<location line="+1"/>
<source>Copy amount</source>
<translation>نسخ الكمية</translation>
</message>
<message>
<location line="+1"/>
<source>Copy transaction ID</source>
<translation>نسخ رقم المعاملة</translation>
</message>
<message>
<location line="+1"/>
<source>Edit label</source>
<translation>عدل الوصف</translation>
</message>
<message>
<location line="+1"/>
<source>Show transaction details</source>
<translation>اظهار تفاصيل المعاملة</translation>
</message>
<message>
<location line="+138"/>
<source>Export Transaction Data</source>
<translation>تصدير بيانات المعاملة</translation>
</message>
<message>
<location line="+1"/>
<source>Comma separated file (*.csv)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Confirmed</source>
<translation>تأكيد</translation>
</message>
<message>
<location line="+1"/>
<source>Date</source>
<translation>التاريخ</translation>
</message>
<message>
<location line="+1"/>
<source>Type</source>
<translation>النوع</translation>
</message>
<message>
<location line="+1"/>
<source>Label</source>
<translation>وصف</translation>
</message>
<message>
<location line="+1"/>
<source>Address</source>
<translation>عنوان</translation>
</message>
<message>
<location line="+1"/>
<source>Amount</source>
<translation>المبلغ</translation>
</message>
<message>
<location line="+1"/>
<source>ID</source>
<translation>العنوان</translation>
</message>
<message>
<location line="+4"/>
<source>Error exporting</source>
<translation>خطا في التصدير</translation>
</message>
<message>
<location line="+0"/>
<source>Could not write to file %1.</source>
<translation>لا يمكن الكتابة الي الملف %1.</translation>
</message>
<message>
<location line="+100"/>
<source>Range:</source>
<translation>نطاق:</translation>
</message>
<message>
<location line="+8"/>
<source>to</source>
<translation>الى</translation>
</message>
</context>
<context>
<name>WalletModel</name>
<message>
<location filename="../walletmodel.cpp" line="+208"/>
<source>Sending...</source>
<translation>ارسال....</translation>
</message>
</context>
<context>
<name>bitcoin-core</name>
<message>
<location filename="../bitcoinstrings.cpp" line="+173"/>
<source>CM_CapitalName version</source>
<translation>جزع البلاك كوين</translation>
</message>
<message>
<location line="+1"/>
<source>Usage:</source>
<translation>المستخدم</translation>
</message>
<message>
<location line="+1"/>
<source>Send command to -server or blackcoind</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>List commands</source>
<translation>اعرض الأوامر</translation>
</message>
<message>
<location line="+1"/>
<source>Get help for a command</source>
<translation>مساعدة في كتابة الاوامر</translation>
</message>
<message>
<location line="-147"/>
<source>Options:</source>
<translation>خيارات: </translation>
</message>
<message>
<location line="+2"/>
<source>Specify configuration file (default: blackcoin.conf)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Specify pid file (default: blackcoind.pid)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Specify wallet file (within data directory)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-1"/>
<source>Specify data directory</source>
<translation>حدد موقع مجلد المعلومات او data directory</translation>
</message>
<message>
<location line="-25"/>
<source>%s, you must set a rpcpassword in the configuration file:
%s
It is recommended you use the following random password:
rpcuser=blackcoinrpc
rpcpassword=%s
(you do not need to remember this password)
The username and password MUST NOT be the same.
If the file does not exist, create it with owner-readable-only file permissions.
It is also recommended to set alertnotify so you are notified of problems;
for example: alertnotify=echo %%s | mail -s "CM_CapitalName Alert" admin@foo.com
</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+27"/>
<source>Set database cache size in megabytes (default: 25)</source>
<translation>ضع حجم كاش قاعدة البيانات بالميجابايت (الافتراضي: 25)</translation>
</message>
<message>
<location line="+1"/>
<source>Set database disk log size in megabytes (default: 100)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Listen for connections on <port> (default: CM_Port or testnet: CM_Port_Testnet)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Maintain at most <n> connections to peers (default: 125)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Connect to a node to retrieve peer addresses, and disconnect</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Specify your own public address</source>
<translation>حدد عنوانك العام هنا</translation>
</message>
<message>
<location line="+4"/>
<source>Bind to given address. Use [host]:port notation for IPv6</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Query for peer addresses via DNS lookup, if low on addresses (default: 1 unless -connect)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Always query for peer addresses via DNS lookup (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Threshold for disconnecting misbehaving peers (default: 100)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-37"/>
<source>An error occurred while setting up the RPC port %u for listening on IPv4: %s</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+65"/>
<source>Listen for JSON-RPC connections on <port> (default: CM_RPC or testnet: 25715)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-17"/>
<source>Accept command line and JSON-RPC commands</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Run in the background as a daemon and accept commands</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Use the test network</source>
<translation>استخدم التحقق من الشبكه</translation>
</message>
<message>
<location line="-24"/>
<source>Accept connections from outside (default: 1 if no -proxy or -connect)</source>
<translation>قبول الاتصالات من خارج</translation>
</message>
<message>
<location line="-29"/>
<source>An error occurred while setting up the RPC port %u for listening on IPv6, falling back to IPv4: %s</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+96"/>
<source>Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+12"/>
<source>Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-103"/>
<source>Warning: Please check that your computer's date and time are correct! If your clock is wrong CM_CapitalName will not work properly.</source>
<translation>تحذير : تأكد من ساعة وتاريخ الكمبيوتر! اذا ساعة غير صحيحة بلاك كوين لن يعمل بشكل صحيح</translation>
</message>
<message>
<location line="+132"/>
<source>Warning: error reading wallet.dat! All keys read correctly, but transaction data or address book entries might be missing or incorrect.</source>
<translation>تحذير : خطا في قراءة wallet.dat! كل المفاتيح تم قرائتة بشكل صحيح لكن بيانات الصفقة او إدخالات كتاب العنوان غير صحيحة او غير موجودة</translation>
</message>
<message>
<location line="-18"/>
<source>Warning: wallet.dat corrupt, data salvaged! Original wallet.dat saved as wallet.{timestamp}.bak in %s; if your balance or transactions are incorrect you should restore from a backup.</source>
<translation>تخذير :wallet.dat غير صالح تم حفظ البيانات. المحفظة الاصلية تم حفظه ك wallet.{timestamp}.bak %s في ; اذا حسابك او صفقاتك غير صحيح يجب عليك استعادة النسخ الاحتياطي</translation>
</message>
<message>
<location line="-31"/>
<source>Attempt to recover private keys from a corrupt wallet.dat</source>
<translation>محاولة استرجاع المفاتيح الخاصة من wallet.dat الغير صالح</translation>
</message>
<message>
<location line="+5"/>
<source>Block creation options:</source>
<translation>خيارات صناعة الكتل</translation>
</message>
<message>
<location line="-69"/>
<source>Connect only to the specified node(s)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Discover own IP address (default: 1 when listening and no -externalip)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+101"/>
<source>Failed to listen on any port. Use -listen=0 if you want this.</source>
<translation>فشل في الاستماع على أي منفذ. استخدام الاستماع = 0 إذا كنت تريد هذا.</translation>
</message>
<message>
<location line="-91"/>
<source>Sync checkpoints policy (default: strict)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+89"/>
<source>Invalid -tor address: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Invalid amount for -reservebalance=<amount></source>
<translation type="unfinished"/>
</message>
<message>
<location line="-88"/>
<source>Maximum per-connection receive buffer, <n>*1000 bytes (default: 5000)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Maximum per-connection send buffer, <n>*1000 bytes (default: 1000)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-17"/>
<source>Only connect to nodes in network <net> (IPv4, IPv6 or Tor)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+31"/>
<source>Prepend debug output with timestamp</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+41"/>
<source>SSL options: (see the Bitcoin Wiki for SSL setup instructions)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-81"/>
<source>Select the version of socks proxy to use (4-5, default: 5)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+42"/>
<source>Send trace/debug info to console instead of debug.log file</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Send trace/debug info to debugger</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+30"/>
<source>Set maximum block size in bytes (default: 250000)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-1"/>
<source>Set minimum block size in bytes (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-35"/>
<source>Shrink debug.log file on client startup (default: 1 when no -debug)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-43"/>
<source>Specify connection timeout in milliseconds (default: 5000)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+116"/>
<source>Unable to sign checkpoint, wrong checkpointkey?
</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-86"/>
<source>Use UPnP to map the listening port (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-1"/>
<source>Use UPnP to map the listening port (default: 1 when listening)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-26"/>
<source>Use proxy to reach tor hidden services (default: same as -proxy)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+47"/>
<source>Username for JSON-RPC connections</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+51"/>
<source>Verifying database integrity...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+44"/>
<source>Error: Wallet locked, unable to create transaction!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Error: Transaction creation failed!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Error: The transaction was rejected! This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Warning</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Information</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>WARNING: syncronized checkpoint violation detected, but skipped!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-1"/>
<source>Warning: This version is obsolete, upgrade required!</source>
<translation>تحذير هذا الجزء قديم, التجديد مطلوب</translation>
</message>
<message>
<location line="-54"/>
<source>wallet.dat corrupt, salvage failed</source>
<translation>wallet.dat غير صالح لا يمكن الاسترجاع</translation>
</message>
<message>
<location line="-56"/>
<source>Password for JSON-RPC connections</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-32"/>
<source>Sync time with other nodes. Disable if time on your system is precise e.g. syncing with NTP (default: 1)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>When creating transactions, ignore inputs with value less than this (default: 0.01)</source>
<translation>عند</translation>
</message>
<message>
<location line="+6"/>
<source>Output debugging information (default: 0, supplying <category> is optional)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>If <category> is not supplied, output all debugging information.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source><category> can be:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Enter regression test mode, which uses a special chain in which blocks can be solved instantly. This is intended for regression testing tools and app development.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+9"/>
<source>Allow JSON-RPC connections from specified IP address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Send commands to node running on <ip> (default: 127.0.0.1)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Wait for RPC server to start</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Set the number of threads to service RPC calls (default: 4)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Require a confirmations for change (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Execute command when a relevant alert is received (%s in cmd is replaced by message)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Upgrade wallet to latest format</source>
<translation>ارقاء المحفظة الي اخر نسخة</translation>
</message>
<message>
<location line="+1"/>
<source>Set key pool size to <n> (default: 100)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Rescan the block chain for missing wallet transactions</source>
<translation>اعادة بحث سلسلة الكتلة لايجاد معالمات المحفظة</translation>
</message>
<message>
<location line="+3"/>
<source>How thorough the block verification is (0-6, default: 1)</source>
<translation>كمية تأكيد الكتل (0-6 التلقائي 1)</translation>
</message>
<message>
<location line="+1"/>
<source>Imports blocks from external blk000?.dat file</source>
<translation>نقل كتل من ملف blk000.dat خارجي</translation>
</message>
<message>
<location line="+9"/>
<source>Use OpenSSL (https) for JSON-RPC connections</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Server certificate file (default: server.cert)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Server private key (default: server.pem)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>Initialization sanity check failed. CM_CapitalName is shutting down.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+50"/>
<source>Error: Wallet unlocked for staking only, unable to create transaction.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+17"/>
<source>Error: Disk space is low!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>This is a pre-release test build - use at your own risk - do not use for mining or merchant applications</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>WARNING: Invalid checkpoint found! Displayed transactions may not be correct! You may need to upgrade, or notify developers.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-174"/>
<source>This help message</source>
<translation>رسالة المساعدة هذه</translation>
</message>
<message>
<location line="+104"/>
<source>Wallet %s resides outside data directory %s.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+37"/>
<source>Unable to bind to %s on this computer (bind returned error %d, %s)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-133"/>
<source>Connect through socks proxy</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Allow DNS lookups for -addnode, -seednode and -connect</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+126"/>
<source>Loading addresses...</source>
<translation>تحميل العنوان</translation>
</message>
<message>
<location line="-12"/>
<source>Error loading blkindex.dat</source>
<translation>خظا في تحميل blkindex.dat</translation>
</message>
<message>
<location line="+2"/>
<source>Error loading wallet.dat: Wallet corrupted</source>
<translation>خطأ عند تنزيل wallet.dat: المحفظة تالفة</translation>
</message>
<message>
<location line="+4"/>
<source>Error loading wallet.dat: Wallet requires newer version of CM_CapitalName</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Wallet needed to be rewritten: restart CM_CapitalName to complete</source>
<translation>المحفظة يجب أن يعاد كتابته : أعد البلاك كوين لتكتمل</translation>
</message>
<message>
<location line="+1"/>
<source>Error loading wallet.dat</source>
<translation>خطأ عند تنزيل wallet.dat</translation>
</message>
<message>
<location line="-16"/>
<source>Invalid -proxy address: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-1"/>
<source>Unknown network specified in -onlynet: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-1"/>
<source>Unknown -socks proxy version requested: %i</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Cannot resolve -bind address: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Cannot resolve -externalip address: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-23"/>
<source>Invalid amount for -paytxfee=<amount>: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+60"/>
<source>Sending...</source>
<translation>ارسال....</translation>
</message>
<message>
<location line="+5"/>
<source>Invalid amount</source>
<translation>مبلغ خاطئ</translation>
</message>
<message>
<location line="+1"/>
<source>Insufficient funds</source>
<translation>حسابك لا يكفي</translation>
</message>
<message>
<location line="-40"/>
<source>Loading block index...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-110"/>
<source>Add a node to connect to and attempt to keep the connection open</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+125"/>
<source>Unable to bind to %s on this computer. CM_CapitalName is probably already running.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-101"/>
<source>Fee per KB to add to transactions you send</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+34"/>
<source>Minimize weight consumption (experimental) (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>How many blocks to check at startup (default: 500, 0 = all)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Keep at most <n> unconnectable blocks in memory (default: %u)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+11"/>
<source>Acceptable ciphers (default: TLSv1.2+HIGH:TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!3DES:@STRENGTH)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Warning: Deprecated argument -debugnet ignored, use -debug=net</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Invalid amount for -mininput=<amount>: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Cannot obtain a lock on data directory %s. CM_CapitalName is probably already running.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Error initializing wallet database environment %s!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+17"/>
<source>Loading wallet...</source>
<translation>تحميل المحفظه</translation>
</message>
<message>
<location line="+8"/>
<source>Cannot downgrade wallet</source>
<translation> لا يمكن خفض المحفظة</translation>
</message>
<message>
<location line="+1"/>
<source>Cannot write default address</source>
<translation> لا يمكن كتابة العنوان الافتراضي</translation>
</message>
<message>
<location line="+1"/>
<source>Rescanning...</source>
<translation>إعادة مسح</translation>
</message>
<message>
<location line="+2"/>
<source>Done loading</source>
<translation>انتهاء التحميل</translation>
</message>
<message>
<location line="-161"/>
<source>To use the %s option</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+188"/>
<source>Error</source>
<translation>خطأ</translation>
</message>
<message>
<location line="-18"/>
<source>You must set rpcpassword=<password> in the configuration file:
%s
If the file does not exist, create it with owner-readable-only file permissions.</source>
<translation type="unfinished"/>
</message>
</context>
</TS> | realspencerdupre/PoS_Sourcecoin | src/qt/locale/bitcoin_ar.ts | TypeScript | mit | 119,926 |
class RandBnb < Sinatra::Base
get '/signin' do
redirect '/sessions/new'
end
get '/sessions/new' do
erb :signin
end
post '/sessions' do
user = User.authenticate(params[:email], params[:password])
if user
session[:user_id] = user.id
session[:new_user] = false
redirect("/dashboard")
else
flash[:error] = "Wrong password"
redirect('/sessions/new')
end
end
delete '/sessions' do
session.clear
flash[:notice] = "Thank you for using RAND-bnb, see you again soon!"
redirect ('/sessions/new')
end
end
| sultanhq/RAND-MakersBNB | app/controllers/session_controller.rb | Ruby | mit | 580 |
namespace ArchitectNow.ApiStarter.Api.Models.ViewModels
{
public class LoginResultVm
{
public string AuthToken { get; set; }
public UserVm CurrentUser { get; set; }
}
} | ArchitectNow/ArchitectNow.ApiStarter | src/ArchitectNow.ApiStarter.Api/Models/ViewModels/LoginResultVm.cs | C# | mit | 199 |
class ExpressionRelationshipType < ActiveRecord::Base
attr_accessible :name, :position, :definition, :url
acts_as_list
end
| nabeta/enju_root | app/models/expression_relationship_type.rb | Ruby | mit | 127 |
<?php
#############################################################################
# IMDBPHP (c) Giorgos Giagas & Itzchak Rehberg #
# written by Giorgos Giagas #
# extended & maintained by Itzchak Rehberg <izzysoft AT qumran DOT org> #
# http://www.izzysoft.de/ #
# ------------------------------------------------------------------------- #
# Budget data (c) Isyankar #
# ------------------------------------------------------------------------- #
# This program is free software; you can redistribute and/or modify it #
# under the terms of the GNU General Public License (see doc/LICENSE) #
#############################################################################
/* $Id: imdb_budget.class.php 482 2011-10-27 15:24:38Z izzy $ */
require_once (dirname(__FILE__)."/movie_base.class.php");
#=============================================================================
#=================================================[ The IMDB class itself ]===
#=============================================================================
/** Accessing IMDB Budget Data
* @package IMDB
* @class imdb_budget
* @extends movie_base
* @author Isyankar
* @author Izzy (izzysoft AT qumran DOT org)
* @version $Revision: 482 $ $Date: 2011-10-27 17:24:38 +0200 (Do, 27. Okt 2011) $
*/
class imdb_budget extends movie_base {
#======================================================[ Common functions ]===
#-----------------------------------------------------------[ Constructor ]---
/** Initialize the class
* @constructor imdb_budget
* @param string id IMDBID to use for data retrieval
*/
function __construct($id) {
parent::__construct($id);
$this->revision = preg_replace('|^.*?(\d+).*$|','$1','$Revision: 482 $');
$this->setid($id);
$this->reset_vars();
}
#--------------------------------------------------[ Start (over) / Reset ]---
/** Reset page vars
* @method protected reset_vars
*/
protected function reset_vars() {
$this->budget = '';
$this->openingWeekend = array();
$this->gross = array();
$this->weekendGross = array();
$this->admissions = array();
$this->filmingDates = array();
}
#-------------------------------------------------------------[ Open Page ]---
/** Define page urls
* @method protected set_pagename
* @param string wt internal name of the page
* @return string urlname page URL
*/
protected function set_pagename($wt) {
switch ($wt){
case "BoxOffice" : $urlname="/business"; break;
default :
$this->page[$wt] = "unknown page identifier";
$this->debug_scalar("Unknown page identifier: $wt");
return false;
}
return $urlname;
}
#-----------------------------------------------[ URL to movies main page ]---
/** Set up the URL to the movie title page
* @method main_url
* @return string url full URL to the current movies main page
*/
public function main_url(){
return "http://".$this->imdbsite."/title/tt".$this->imdbid()."/";
}
#====================================================[ /business page ]===
/* Get budget
* @method get_budget
* @param ref string budg
* @return string
* @brief Assuming budget is estimated, and in american dollar
* @see IMDB page / (TitlePage)
*/
private function get_budget(&$budg){
// Tries to get a single entry
if (@preg_match("!(.*?)\s*\(estimated\)!ims",$budg,$opWe)){
$result = $opWe[1];
return intval(substr(str_replace(",","",$result), 1));
}
else return "";
} // End of get_budget
/* Get budget
* @method get_budget
* @return string
* @brief Assuming budget is estimated, and in american dollar
* @see IMDB page / (TitlePage)
*/
public function budget() {
if (empty($this->budget)) {
if ($this->page["BoxOffice"] == "") $this->openpage ("BoxOffice");
if ($this->page["BoxOffice"] == "cannot open page" ) return $this->budget; // no such page
if (@preg_match("!<h5>Budget</h5>\s*\n*(.*?)(<br/>\n*)*<h5!ims",$this->page["BoxOffice"],$bud)) // Opening Weekend
$budget = $bud[1];
$this->budget = $this->get_budget($budget);
}
return $this->budget;
}
#-------------------------------------------------[ Openingbudget ]---
/** Get opening weekend budget
* @method get_openingWeekend
* @param ref string listOpening
* @return array[0..n] of array[value,country,date,nbScreens]
* @see IMDB page
*/
private function get_openingWeekend(&$listOpening){
$result = array();
$temp = $listOpening;
$i = 0;
while($temp != NULL){
// Tries to get a single entry
if (@preg_match("!(.*?)<br/>!ims",$temp,$opWe))
$entry = $opWe[1];
// Tries to extract the value
if (@preg_match("!(.*?)\(!ims",$opWe[1],$value))
$opWe[1] = str_replace($value,"",$opWe[1]);
// Tries to extract the country
if (@preg_match("!(.*?)\)\s*!ims",$opWe[1],$country))
$opWe[1] = str_replace($country,"",$opWe[1]);
// Tries to extract the date
if (@preg_match("!\((.*?)\)\s*!ims",$opWe[1],$date))
if (@preg_match("!<a href=\"/date/(.*?)/\">!ims",$date[1],$dayMonth))
if (@preg_match("!<a href=\"/year/(.*?)/\">!ims",$date[1],$year))
$dateValue = $year[1].'-'.$dayMonth[1];
$opWe[1] = str_replace($date,"",$opWe[1]);
// Tries to extract the number of screens
if (@preg_match("!\((.*?)\)\s*!ims",$opWe[1],$nbScreen))
$opWe[1] = str_replace($nbScreen,"",$opWe[1]);
// Parse the results in an array
$result[$i] = array(
'value' => $value[1],
'country' => $country[1],
'date' => $dateValue,
'nbScreens' => intval(str_replace(",","",$nbScreen[1]))
);
// Remove the entry from the list of entries
if (@preg_match("!<br/>(.*?)$!ims",$temp,$temp))
$temp = $temp[1];
$i++;
}
return $result;
} // End of get_openingWeekend
/** Opening weekend budget
* @method openingWeekend
* @return array[0..n] of array[value,country,date,nbScreens]
* @see IMDB page
*/
public function openingWeekend() {
if (empty($this->openingWeekend)) {
if ($this->page["BoxOffice"] == "") $this->openpage ("BoxOffice");
if ($this->page["BoxOffice"] == "cannot open page" ) return $this->openingWeekend; // no such page
if (@preg_match("!<h5>Opening Weekend</h5>\n*(.*?)<br/>\n*<h5!ims",$this->page["BoxOffice"],$opWe)) // Opening Weekend
$openingWeekend = $opWe[1];
$this->openingWeekend = $this->get_openingWeekend($openingWeekend);
}
return $this->openingWeekend;
}
#-------------------------------------------------[ Gross ]---
/** Get gross budget
* @method get_gross
* @param ref string listGross
* @return array[0..n] of array[value,country,date]
* @see IMDB page / (TitlePage)
*/
private function get_gross(&$listGross) {
$result = array();
$temp = $listGross;
$i = 0;
while($temp != NULL){
// Tries to get a single entry
if (@preg_match("!(.*?)<br/>!ims",$temp,$gr))
$entry = $gr[1];
//echo 'ici'.$entry.'ici';
// Tries to extract the value
if (@preg_match("!(.*?)\(!ims",$gr[1],$value))
$gr[1] = str_replace($value,"",$gr[1]);
// Tries to extract the country
if (@preg_match("!(.*?)\)\s*!ims",$gr[1],$country))
$gr[1] = str_replace($country,"",$gr[1]);
// Tries to extract the date
if (@preg_match("!\((.*?)\)\s*!ims",$gr[1],$date))
if (@preg_match("!<a href=\"/date/(.*?)/\">!ims",$date[1],$dayMonth))
if (@preg_match("!<a href=\"/year/(.*?)/\">!ims",$date[1],$year))
$dateValue = $year[1].'-'.$dayMonth[1];
$gr[1] = str_replace($date,"",$gr[1]);
// Parse the results in an array
$result[$i] = array(
'value' => $value[1],
'country' => $country[1],
'date' => $dateValue,
);
// Remove the entry from the list of entries
if (@preg_match("!<br/>(.*?)$!ims",$temp,$temp))
$temp = $temp[1];
$i++;
}
return $result;
} // End of get_gross
/** Get gross budget
* @method gross
* @return array[0..n] of array[value,country,date]
* @see IMDB page / (TitlePage)
*/
public function gross() {
if (empty($this->gross)) {
if ($this->page["BoxOffice"] == "") $this->openpage ("BoxOffice");
if ($this->page["BoxOffice"] == "cannot open page" ) return $this->gross; // no such page
if (@preg_match("!<h5>Gross</h5>\n*(.*?)<br/>\n*<h5!ims",$this->page["BoxOffice"],$gr)) // Gross
$gross = $gr[1];
$this->gross = $this->get_gross($gross);
}
return $this->gross;
}
#-------------------------------------------------[ Weekend Gross ]---
/** Get weekend gross budget
* @method get_weekendGross
* @param ref string listweekendGross
* @return array[0..n] of array[value,country,date,nbScreens]
* @see IMDB page / (TitlePage)
*/
private function get_weekendGross(&$listweekendGross){
$result = array();
$temp = $listweekendGross;
$i = 0;
while($temp != NULL){
// Tries to get a single entry
if (@preg_match("!(.*?)<br/>!ims",$temp,$weGr))
$entry = $weGr[1];
// Tries to extract the value
if (@preg_match("!(.*?)\(!ims",$weGr[1],$value))
$weGr[1] = str_replace($value,"",$weGr[1]);
// Tries to extract the country
if (@preg_match("!(.*?)\)\s*!ims",$weGr[1],$country))
$weGr[1] = str_replace($country,"",$weGr[1]);
// Tries to extract the date
if (@preg_match("!\((.*?)\)\s*!ims",$weGr[1],$date))
if (@preg_match("!<a href=\"/date/(.*?)/\">!ims",$date[1],$dayMonth))
if (@preg_match("!<a href=\"/year/(.*?)/\">!ims",$date[1],$year))
$dateValue = $year[1].'-'.$dayMonth[1];
$weGr[1] = str_replace($date,"",$weGr[1]);
// Tries to extract the number of screens
if (@preg_match("!\((.*?)\)\s*!ims",$weGr[1],$nbScreen))
$weGr[1] = str_replace($nbScreen,"",$weGr[1]);
// Parse the results in an array
$result[$i] = array(
'value' => $value[1],
'country' => $country[1],
'date' => $dateValue,
'nbScreens' => intval(str_replace(",","",$nbScreen[1]))
);
// Remove the entry from the list of entries
if (@preg_match("!<br/>(.*?)$!ims",$temp,$temp))
$temp = $temp[1];
$i++;
}
return $result;
} // End of get_weekendGross
/** Get weekend gross budget
* @method weekendGross
* @return array[0..n] of array[value,country,date,nbScreen]
* @see IMDB page / (TitlePage)
*/
public function weekendGross() {
if (empty($this->weekendGross)) {
if ($this->page["BoxOffice"] == "") $this->openpage ("BoxOffice");
if ($this->page["BoxOffice"] == "cannot open page" ) return $this->weekendGross; // no such page
if (@preg_match("!<h5>Weekend Gross</h5>\n*(.*?)<br/>\n*<h5!ims",$this->page["BoxOffice"],$weGr)) // Weekend Gross
$weekendGross = $weGr[1];
$this->weekendGross = $this->get_weekendGross($weekendGross);
}
return $this->weekendGross;
} // End of weekendGross
#-------------------------------------------------[ Admissions ]---
/** Get admissions budget
* @method get_admissions
* @param ref string listAdmissions
* @return array[0..n] of array[value,country,date]
* @see IMDB page / (TitlePage)
*/
private function get_admissions(&$listAdmissions) {
$result = array();
$temp = $listAdmissions;
$i = 0;
while($temp != NULL){
// Tries to get a single entry
if (@preg_match("!(.*?)<br/>!ims",$temp,$adm))
$entry = $adm[1];
// Tries to extract the value
if (@preg_match("!(.*?)\(!ims",$adm[1],$value))
$adm[1] = str_replace($value,"",$adm[1]);
// Tries to extract the country
if (@preg_match("!(.*?)\)\s*!ims",$adm[1],$country))
$adm[1] = str_replace($country,"",$adm[1]);
// Tries to extract the date
if (@preg_match("!\((.*?)\)\s*!ims",$adm[1],$date))
if (@preg_match("!<a href=\"/date/(.*?)/\">!ims",$date[1],$dayMonth))
if (@preg_match("!<a href=\"/year/(.*?)/\">!ims",$date[1],$year))
$dateValue = $year[1].'-'.$dayMonth[1];
$adm[1] = str_replace($date,"",$adm[1]);
// Parse the results in an array
$result[$i] = array(
'value' => intval(str_replace(",","",$value[1])),
'country' => $country[1],
'date' => $dateValue,
);
// Remove the entry from the list of entries
if (@preg_match("!<br/>(.*?)$!ims",$temp,$temp))
$temp = $temp[1];
$i++;
}
return $result;
} // End of get_admissions
/** Get admissions budget
* @method admissions
* @return array[0..n] of array[value,country,date]
* @see IMDB page / (TitlePage)
*/
public function admissions() {
if (empty($this->admissions)) {
if ($this->page["BoxOffice"] == "") $this->openpage ("BoxOffice");
if ($this->page["BoxOffice"] == "cannot open page" ) return $this->admissions; // no such page
if (@preg_match("!<h5>Admissions</h5>\n*(.*?)<br/>\n*<h5!ims",$this->page["BoxOffice"],$weGr)) // Admissions
$admissions = $weGr[1];
$this->admissions = $this->get_admissions($admissions);
}
return $this->admissions;
} // End of admissions
#-------------------------------------------------[ Filming Dates ]---
/** Get filming dates
* @method get_filmingDates
* @param ref string listFilmingDates
* @return array[0..n] of array[beginning,end]
* Time format : YYYY-MM-DD
* @see IMDB page / (TitlePage)
*/
function get_filmingDates($listFilmingDates){
$result = array();
$temp = $listFilmingDates;
// Tries to get the beginning
if (@preg_match("!(.*?) -!ims",$temp,$beginning))
if (@preg_match("#[A-Z0-9]#",$beginning[1])) { // Check if there is a date
if (@preg_match("!<a(.*?) -!ims",$temp)) { // Check if there is a linked date
if (@preg_match("!<a href=\"/date/(.*?)/\">!ims",$beginning[1],$dayMonthB))
if (@preg_match("!<a href=\"/year/(.*?)/\">!ims",$beginning[1],$yearB))
$beginningDate = $yearB[1].'-'.$dayMonthB[1];
} else if (@preg_match("!(.*?) -!ims",$temp,$beginning)) {
$beginningDate = date('Y-m-d', strtotime($beginning[1]));
}
}
// Tries to get the end
if (@preg_match("!- (.*?)$!ims",$temp,$end))
if (@preg_match("#[A-Z0-9]#",$end[1])) { // Check if there is a date
if (@preg_match("!- <a(.*?)!ims",$temp)) { // Check if there is a linked date
if (@preg_match("!<a href=\"/date/(.*?)/\">!ims",$end[1],$dayMonthE))
if (@preg_match("!<a href=\"/year/(.*?)/\">!ims",$end[1],$yearE))
$endDate = $yearE[1].'-'.$dayMonthE[1];
} else if (@preg_match("!- (.*?)$!ims",$temp,$end)) {
$endDate = date('Y-m-d', strtotime($end[1]));
}
}
// Parse the results in an array
$result = array(
'beginning' => $beginningDate,
'end' => $endDate
);
return $result;
} // End of get_filmingDates
/** Get filming dates
* @method filmingDates
* @return array[0..n] of array[beginning,end]
* Time format : YYYY-MM-DD
* @see IMDB page / (TitlePage)
*/
public function filmingDates() {
if (empty($this->filmingDates)) {
if ($this->page["BoxOffice"] == "") $this->openpage ("BoxOffice");
if ($this->page["BoxOffice"] == "cannot open page" ) return $this->filmingDates; // no such page
if (@preg_match("!<h5>Filming Dates</h5>\s*\n*(.*?)(<br/>\n*)*<h5!ims",$this->page["BoxOffice"],$filDates)) // Filming Dates
$filmingDates = $filDates[1];
$this->filmingDates = $this->get_filmingDates($filmingDates);
}
return $this->filmingDates;
} // End of filmingDates
} // end class imdb_budget
?> | rnavarro/Movie-Magic | imdbphp2/imdb_budget.class.php | PHP | mit | 15,927 |
/*jshint node: true, eqnull: true*/
exports.purge = require('./lib/purge').AkamaiPurge; | patrickkettner/grunt-akamai-clear | node_modules/akamai/akamai.js | JavaScript | mit | 88 |
() => {
const [startDate, setStartDate] = useState(new Date());
let handleColor = (time) => {
return time.getHours() > 12 ? "text-success" : "text-error";
};
return (
<DatePicker
showTimeSelect
selected={startDate}
onChange={(date) => setStartDate(date)}
timeClassName={handleColor}
/>
);
};
| Hacker0x01/react-datepicker | docs-site/src/examples/customTimeClassName.js | JavaScript | mit | 340 |
'use strict';
var arg = require('../util').arg;
var oneDHeightmapFactory = require('../1d-heightmap');
var rng = require('../rng');
var random = rng.float;
var randomRange = rng.range;
var randomRangeInt = rng.rangeInt;
var randomSpacedIndexes = rng.spacedIndexes;
var interpolators = require('../interpolators');
var math = require('../math');
var getDistance = math.getDistance;
var getNormalizedVector = math.getNormalizedVector;
module.exports = {
keyIndexes: createKeyIndexes,
fromKeyIndexes: fromKeyIndexes,
interpolateKeyIndexes: interpolateKeyIndexes,
addKeyIndexes: addKeyIndexes,
addDisplacementKeyIndexes: addDisplacementKeyIndexes,
}
function createKeyIndexes(settings) {
var defaults = {
length: null,
startHeight: undefined,
endHeight: undefined,
minSpacing: undefined,
maxSpacing: undefined,
interpolator: null,
min: 0,
max: 100,
minSlope: undefined,
maxSlope: undefined,
};
var s = Object.assign({}, defaults, settings);
var length = s.length;
var startHeight = s.startHeight;
var endHeight = s.endHeight;
var minSpacing = arg(s.minSpacing, length * 0.1);
var maxSpacing = arg(s.maxSpacing, length * 0.1);
var minHeight = s.min;
var maxHeight = s.max;
var minSlope = s.minSlope;
var maxSlope = s.maxSlope;
var keyIndexes = randomSpacedIndexes(length, minSpacing, maxSpacing);
var prev;
var out = keyIndexes.map(function(index, i, data) {
var value;
if (i === 0 && startHeight !== undefined) {
value = startHeight;
} else {
value = getValue(prev, index, minHeight, maxHeight, minSlope, maxSlope);
}
var result = {
index: index,
value: value,
};
prev = result;
return result;
});
if (endHeight !== undefined) {
out[out.length - 1].value = endHeight;
}
return out;
}
function getValue(prev, index, minHeight, maxHeight, minSlope, maxSlope) {
var min = minHeight;
var max = maxHeight;
if (prev !== undefined) {
var prevVal = prev.value;
var distance = index - prev.index;
if (minSlope !== undefined) {
min = Math.max(min, prevVal + (distance * minSlope));
}
if (maxSlope !== undefined) {
max = Math.min(max, prevVal + (distance * maxSlope));
}
}
return randomRangeInt(min, max);
}
function interpolateKeyIndexes(keyIndexes, interpolator) {
var results = [];
interpolator = arg(interpolator, interpolators.linear);
keyIndexes.forEach(function(item, i) {
results.push(item.value);
var next = keyIndexes[i + 1];
if (!next) {
return;
}
var curerntKeyIndex = item.index;
var nextKeyIndex = next.index;
var wavelength = Math.abs(nextKeyIndex - curerntKeyIndex - 1);
var a = item.value;
var b = next.value;
for (var j = 0; j < wavelength; j++) {
var x = j / wavelength;
var interpolatedVal = interpolator(a, b, x);
results.push(interpolatedVal);
}
});
return results;
}
function fromKeyIndexes(keyIndexes, interpolator) {
return oneDHeightmapFactory({
data: this.interpolateKeyIndexes(keyIndexes, interpolator)
});
}
function addKeyIndexes(settings) {
var defaults = {
keyIndexes: null,
// position on line determined by percent of distance between points
posRatioMin: 0.33,
posRatioMax: 0.66,
// distance from pos on line determined by percent of distance between points
distRatioMin: 0.1,
distRatioMax: 0.2,
// absolute min / max distance
distMin: undefined,
distMax: undefined,
direction: undefined,
upDirection: undefined,
downDirection: undefined,
upPosRatioMin: undefined,
upPosRatioMax: undefined,
downPosRatioMin: undefined,
downPosRatioMax: undefined,
upDistRatioMin: undefined,
upDistRatioMax: undefined,
downDistRatioMin: undefined,
downDistRatioMax: undefined,
};
var s = Object.assign({}, defaults, settings);
var keyIndexes = s.keyIndexes;
var result = [];
keyIndexes.forEach(function(item, i, data) {
var next = data[i + 1];
if (!next) {
result.push(item);
return;
}
var splitSettings = Object.assign({
left: item,
right: next,
}, settings);
var add = splitKeyIndexes(splitSettings);
result.push(item);
result.push(add);
});
return result;
}
function splitKeyIndexes(settings) {
var defaults = {
left: null,
right: null,
// position on line determined by percent of distance between points
posRatioMin: 0.33,
posRatioMax: 0.66,
// distance from pos on line determined by percent of distance between points
distRatioMin: 0.1,
distRatioMax: 0.2,
// absolute min / max distance
distMin: undefined,
distMax: undefined,
direction: undefined,
upDirection: undefined,
downDirection: undefined,
upPosRatioMin: undefined,
upPosRatioMax: undefined,
downPosRatioMin: undefined,
downPosRatioMax: undefined,
upDistRatioMin: undefined,
upDistRatioMax: undefined,
downDistRatioMin: undefined,
downDistRatioMax: undefined,
};
var s = Object.assign({}, defaults, settings);
var left = s.left;
var right = s.right;
var slopeUp = left.value < right.value;
var posRatioMin = s.posRatioMin;
var posRatioMax = s.posRatioMax;
var distRatioMin = s.distRatioMin;
var distRatioMax = s.distRatioMax;
var direction = s.direction;
var distMin = s.distMin;
var distMax = s.distMax;
if (slopeUp) {
posRatioMin = arg(s.upPosRatioMin, posRatioMin);
posRatioMax = arg(s.upPosRatioMax, posRatioMax);
distRatioMin = arg(s.upDistRatioMin, distRatioMin);
distRatioMax = arg(s.upDistRatioMax, distRatioMax);
direction = arg(s.upDirection, direction);
} else {
posRatioMin = arg(s.downPosRatioMin, posRatioMin);
posRatioMax = arg(s.downPosRatioMax, posRatioMax);
distRatioMin = arg(s.downDistRatioMin, distRatioMin);
distRatioMax = arg(s.downDistRatioMax, distRatioMax);
direction = arg(s.downDirection, direction);
}
direction = arg(direction, random() < 0.5 ? 'up' : 'down');
var posRatio = randomRange(posRatioMin, posRatioMax);
var distRatio = randomRange(distRatioMin, distRatioMax);
var a = {
x: left.index,
y: left.value,
};
var b = {
x: right.index,
y: right.value,
};
var p = generateMidPoint(a, b, posRatio, distRatio, direction, distMin, distMax);
return {
value: p.y,
index: p.x
};
}
function generateMidPoint(a, b, cPosRatio, distRatio, direction, distMin, distMax) {
var vDist = getDistance(a, b);
var v = getNormalizedVector(a, b, vDist);
var dx = b.x - a.x;
var dy = b.y - a.y;
// c is a point on line ab at given ratio
var c = {
x: (dx * cPosRatio),
y: (dy * cPosRatio)
};
// distance proportional to ab length
var dist = vDist * distRatio;
if (distMin !== undefined) {
dist = Math.max(distMin);
}
if (distMax !== undefined) {
dist = Math.min(distMax);
}
var vDir = vectorRotate90(v, direction);
var d = {
x: vDir.x * dist,
y: vDir.y * dist,
};
// width of line ab
var ab = dx;
// postion of d offset from c
var dC = c.x + d.x;
// scale to fit horizontal bounds of ab
var scale = false;
// d left of a
if (dC < 0) {
scale = -(c.x / d.x);
}
// d right of b
else if (dC > ab) {
scale = (dx - c.x) / (d.x);
}
if (scale !== false) {
d.x *= scale;
d.y *= scale;
}
// add offsets to d
d.x += c.x + a.x;
d.y += c.y + a.y;
d.x = Math.round(d.x);
if (d.x === a.x) {
d.x += 1;
}
if (d.x === b.x) {
d.x -= 1;
}
// set c offset for debug
// c.x += a.x;
// c.y += a.y;
return d;
}
function vectorRotate90(v, direction){
if (direction === 'left' || direction === 'up') {
return {
x: -v.y,
y: v.x,
}
}
else if (direction === 'right' || direction === 'down') {
return {
x: v.y,
y: -v.x,
}
}
}
function addDisplacementKeyIndexes(settings) {
var defaults = {
keyIndexes: null,
startingDisplacement: 50,
roughness: 0.77,
maxIterations: 1,
calcDisplacement: defaultCalcDisplacement,
};
var s = Object.assign({}, defaults, settings);
var keyIndexes = s.keyIndexes;
var roughness = s.roughness;
var maxIterations = s.maxIterations;
var calcDisplacement = s.calcDisplacement;
var startingDisplacement = s.startingDisplacement;
keyIndexes = keyIndexes.map(function(item) {
return Object.assign({}, item);
});
var results = [];
keyIndexes.forEach(function(item, i, data) {
var next = data[i + 1];
if (!next) {
results.push(item);
return;
}
var arr = split(item, next, startingDisplacement);
results = results.concat(item, arr);
});
return results;
function defaultCalcDisplacement(current, left, right, iteration) {
if (iteration == 1) {
return current;
}
return current * roughness;
}
function split(left, right, displacement, iteration) {
iteration = iteration || 0;
iteration++;
if (left.index + 1 == right.index) {
return false;
}
displacement = calcDisplacement(displacement, left, right, iteration);
var mid = splitNodes(left, right, displacement);
if (iteration >= maxIterations) {
return mid;
}
var result = [];
var canSplitLeft = left.index + 1 !== mid.index;
var canSplitRight = right.index - 1 !== mid.index;
if (canSplitLeft) {
var leftSplit = split(left, mid, displacement, iteration);
if (leftSplit) {
result = result.concat(leftSplit);
}
}
result.push(mid);
if (canSplitRight) {
var rightSplit = split(mid, right, displacement, iteration);
if (rightSplit) {
result = result.concat(rightSplit);
}
}
return result;
}
}
function splitNodes(left, right, displacement) {
var midIndex = Math.floor((left.index + right.index) * 0.5);
var midValue = (left.value + right.value) * 0.5;
var adjustment = (randomRange(-1, 1) * displacement);
return {
index: midIndex,
value: midValue + adjustment,
};
} | unstoppablecarl/1d-heightmap | src/key-indexes/index.js | JavaScript | mit | 11,619 |
namespace PaintShop.Models
{
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
public class ApplicationUser : IdentityUser
{
public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
{
// Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
// Add custom user claims here
return userIdentity;
}
}
}
| georgipyaramov/PaintShop | PaintShop/PaintShop.Models/ApplicationUser.cs | C# | mit | 693 |
package ruanmianbao.binetwork;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.Socket;
import java.net.UnknownHostException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Main{
boolean running = false;
Socket socket;
ByteOrder order;
String script = "";
public Main(String[] args) throws Exception {
String server = "localhost";
int port = 8788;
ByteOrder order = ByteOrder.LITTLE_ENDIAN;
for(String a: args) {
String[] a2 = a.split("=",2);
if (a2.length==2) {
switch(a2[0]) {
case "-s":
case "--server":
server = a2[1];
break;
case "-p":
case "--port":
port = Integer.parseInt(a2[1]);
break;
case "-e":
case "--endian":
order = a2[1].equalsIgnoreCase("be")?ByteOrder.BIG_ENDIAN:ByteOrder.LITTLE_ENDIAN;
break;
case "-r":
case "--run":
script = a2[1];
break;
}
}
}
Main.log("connect to:"+server+":"+port);
socket = new Socket(server, port);
socket.setSoTimeout(15000);
Main.log("connected.");
this.order = order;
if (this.script.isEmpty()) {
// read from input
this.running = true;
ExecutorService taskExecutor = Executors.newFixedThreadPool(2);
try {
taskExecutor.execute(new RecvWorker());
taskExecutor.execute(new SendWorker());
} finally {
taskExecutor.shutdown();
}
} else {
this.running = false;
this.RunWorker();
}
}
/**
* 进行一次测试
* @throws Exception
*/
private void RunWorker() throws Exception {
if(script.startsWith("'") && script.endsWith("'"))
script = script.substring(1, script.length()-1);
Main.log("run script:" + script);
sendData(script);
recvData();
}
private String recvData() throws IOException {
int buffer_size = 4096;
byte[] buffer = new byte[buffer_size];
BufferedInputStream in = new BufferedInputStream(socket.getInputStream());
int readed = 0, pos = 0;
readed = in.read(buffer, pos, buffer.length-pos);
if (readed>0) pos+=readed;
String msg = toHex(buffer,0,pos);
Main.log("recv["+pos+"]:"+msg);
return msg;
}
private void sendData(String line) throws IOException {
ByteBuffer outbuffer = ByteBuffer.allocate(4*1024);
outbuffer.order(order);
String[] items = line.split("\\|");
for(int i=0; i<items.length; i++) {
String[] sp = items[i].split(":");
if(sp.length!=3) {
Main.log("item ["+i+"] format error:"+items[i]);
continue;
}
switch(sp[0]) {
case "b": //二进制
putBin(outbuffer, Integer.parseInt(sp[1]), sp[2]);
break;
case "o": //八进制
putOct(outbuffer, Integer.parseInt(sp[1]), sp[2]);
break;
case "d": //十进制
putDec(outbuffer, Integer.parseInt(sp[1]), sp[2]);
break;
case "x": //十六进制
putHex(outbuffer, Integer.parseInt(sp[1]), sp[2]);
break;
case "s": //字符串
putStr(outbuffer, sp[1], sp[2]);
break;
}
}
outbuffer.flip();
socket.getOutputStream().write(outbuffer.array(), 0, outbuffer.limit());
socket.getOutputStream().flush();
Main.log("send["+outbuffer.limit()+"]"+toHex(outbuffer.array(), 0, outbuffer.limit()));
}
// 二进制
private void putBin(ByteBuffer outbuffer, int parseInt, String string) {
putByte(outbuffer, parseInt, string, 2);
}
// 八进制
private void putOct(ByteBuffer outbuffer, int parseInt, String string) {
putByte(outbuffer, parseInt, string, 8);
}
// 十进制
private void putDec(ByteBuffer outbuffer, int parseInt, String string) {
putByte(outbuffer, parseInt, string, 10);
}
// 十六进制
private void putHex(ByteBuffer outbuffer, int parseInt, String string) {
putByte(outbuffer, parseInt, string, 16);
}
// 字符串
private void putStr(ByteBuffer outbuffer, String encode, String string) throws UnsupportedEncodingException {
byte[] data = string.getBytes(encode);
outbuffer.put(data);
}
/**
* 把一个字符串按指定进制转换成字节,存入指定的缓冲区内。如果指定的长度与字符串拆分后的长度不符,则自动补0。
* @param outbuffer 填充的buffer
* @param parseInt 单位:1-byte 2-short 4-int 8-long
* @param string 待处理字符串
* @param radix 进制(2,8,10,16)
*/
private void putByte(ByteBuffer outbuffer, int parseInt, String string, int radix) {
String[] strs = string.split(" ");
for(int i=0; i<strs.length; i++) {
if (i<strs.length) {
switch(parseInt) {
case 1:
short b = Short.parseShort(strs[i], radix);
outbuffer.put((byte)(b&0x00ff));
break;
case 2:
int s = Integer.parseInt(strs[i], radix);
outbuffer.putShort((short)(s&0x00ffff));
break;
case 4:
long ii = Long.parseLong(strs[i], radix);
outbuffer.putInt((int)(ii&0x00ffffffff));
break;
case 8:
long l = Long.parseLong(strs[i], radix);
outbuffer.putLong(l);
break;
default:
Main.log("unsupport type:"+parseInt);
}
}
}
}
/**
* 发送信息的线程
*/
private class SendWorker implements Runnable {
@Override
public void run() {
try {
Scanner scan = new Scanner(System.in);
while (running) {
String line = scan.nextLine();
Main.log("input:"+line);
sendData(line);
}
scan.close();
} catch (Exception e) {
running = false;
e.printStackTrace();
}
}
}
/**
* 接收信息的线程
*/
private class RecvWorker implements Runnable{
@Override
public void run() {
try {
byte[] buffer = new byte[4*1024];
BufferedInputStream in = new BufferedInputStream(socket.getInputStream());
while (running) {
int readed = in.read(buffer, 0, buffer.length);
Main.log("recv["+readed+"]:"+toHex(buffer, 0, readed));
}
} catch (Exception e) {
running = false;
e.printStackTrace();
}
}
}
/**
* 统一输出
* @param string 要输出的信息
*/
static void log(String msg) {
Date dNow = new Date( );
SimpleDateFormat ft = new SimpleDateFormat ("yyyy.MM.dd HH:mm:ss");
System.out.println("["+ft.format(dNow)+"] "+msg);
}
/**
* 入口
* @param args host ip [le|be]
*/
public static void main(String[] args) {
if (args.length==0
|| args[0].equalsIgnoreCase("help")
|| args[0].equalsIgnoreCase("-h")
|| args[0].equalsIgnoreCase("?")
|| args[0].equalsIgnoreCase("--help")
) {
printHelp("binetwork");
System.exit(0);
}
try {
new Main(args);
} catch (Exception e) {
e.printStackTrace();
System.exit(-1);
}
}
private static void printHelp(String cmd) {
System.out.println("usage: check 'readme.md' for more info.\n\n" +
cmd + "[-s|--server]=<host> [-p|--port]=<port> [-e|-endian]=<le|be>\n" +
" -host or ip: the host name or ip (default: localhost)\n"+
" -port: the port of server (default: 8080) \n" +
" -le: little endian (default)\n"+
" -be: big endian \n\n" +
"example:\n"+
" "+ cmd + "-s=127.0.0.1 -p=8080 -e=le -r=\"x:1:fa fb fc fd\"\n");
}
/**
* 把一个数组用16进制格式输出
* @param buf 需要转换的数据
* @param start 起始位置
* @param length 长度
* @return 16进制字符串
*/
private String toHex(byte[] buf, int start, int length) {
if (buf == null)
return "";
StringBuffer result = new StringBuffer(2 * length);
for (int i = start; (( i < start+length) && (i<buf.length)); i++) {
appendHex(result, buf[i]);
}
return result.toString();
}
private final static String HEX = "0123456789ABCDEF";
private static void appendHex(StringBuffer sb, byte b) {
sb.append(HEX.charAt((b >> 4) & 0x0f)).append(HEX.charAt(b & 0x0f));
}
}
| flairyu/binetwork | src/ruanmianbao/binetwork/Main.java | Java | mit | 7,911 |
using Keeper.Warm;
using System;
using System.Collections.Generic;
namespace Keeper.Warm
{
public class QueryResult
{
private Machine machine;
private Variable[] variables;
public QueryResult(bool success, Variable[] variables, Machine machine)
{
this.Success = success;
this.variables = variables;
this.machine = machine;
}
public bool Success
{
get;
private set;
}
public bool CanContinue
{
get
{
return this.machine.IsBacktrackAvailable;
}
}
public bool Continue()
{
bool result = this.machine.Continue();
this.Success = result;
return result;
}
public IEnumerable<Variable> Variables
{
get
{
return this.variables;
}
}
public ITerm GetVariable(Variable variable)
{
int index = Array.IndexOf(variables, variable);
if (index < 0)
{
return null;
}
else
{
return BuildTermFromHeap(this.machine, variables.Length - (index + 1));
}
}
public static ITerm BuildTermFromHeap(Machine machine, int index)
{
return BuildTermFromAddress(machine, new Address(AddressType.Heap, index));
}
public static ITerm BuildTermFromAddress(Machine machine, Address termAddress)
{
Cell value = new Cell(machine.DereferenceAndLoad(termAddress));
switch (value.Tag)
{
case Tag.Ref:
string name = value.Address.Pointer.ToString();
if(value.Address.Type == AddressType.Retained)
{
name = "R" + name;
}
return new Variable(name);
case Tag.Str:
Cell functorCell = new Cell(machine.DereferenceAndLoad(value.Address));
FunctorDescriptor functor = machine.GetFunctor(functorCell.Address.Pointer);
ITerm[] terms = null;
if (functor.Arity > 0)
{
terms = new ITerm[functor.Arity];
for (int termIndex = 0; termIndex < functor.Arity; termIndex++)
{
terms[termIndex] = BuildTermFromAddress(machine, value.Address + termIndex + 1);
}
}
return new CompoundTerm(functor.Name, terms);
case Tag.Con:
FunctorDescriptor constantFunctor = machine.GetFunctor(value.Address.Pointer);
if (constantFunctor.Name == "[]")
{
return EmptyList.Instance;
}
else
{
return new Atom(constantFunctor.Name);
}
case Tag.Lis:
var headTerm = BuildTermFromAddress(machine, value.Address);
var TailTerm = BuildTermFromAddress(machine, (value.Address + 1));
return new ListPair(headTerm, (IListTail)TailTerm);
default:
throw new Exception("Unexpected tag in term:" + value);
}
}
}
} | FacticiusVir/Warm | Keeper.Warm/QueryResult.cs | C# | mit | 3,572 |
using System;
using System.IO;
using System.Linq;
using SharpCompress.IO;
namespace SharpCompress.Common.SevenZip
{
internal class SevenZipFilePart : FilePart
{
private CompressionType? _type;
private readonly Stream _stream;
private readonly ArchiveDatabase _database;
internal SevenZipFilePart(Stream stream, ArchiveDatabase database, int index, CFileItem fileEntry, ArchiveEncoding archiveEncoding)
: base(archiveEncoding)
{
_stream = stream;
_database = database;
Index = index;
Header = fileEntry;
if (Header.HasStream)
{
Folder = database._folders[database._fileIndexToFolderIndexMap[index]];
}
}
internal CFileItem Header { get; }
internal CFolder? Folder { get; }
internal int Index { get; }
internal override string FilePartName => Header.Name;
internal override Stream? GetRawStream()
{
return null;
}
internal override Stream GetCompressedStream()
{
if (!Header.HasStream)
{
return null!;
}
var folderStream = _database.GetFolderStream(_stream, Folder!, _database.PasswordProvider);
int firstFileIndex = _database._folderStartFileIndex[_database._folders.IndexOf(Folder!)];
int skipCount = Index - firstFileIndex;
long skipSize = 0;
for (int i = 0; i < skipCount; i++)
{
skipSize += _database._files[firstFileIndex + i].Size;
}
if (skipSize > 0)
{
folderStream.Skip(skipSize);
}
return new ReadOnlySubStream(folderStream, Header.Size);
}
public CompressionType CompressionType
{
get
{
if (_type is null)
{
_type = GetCompression();
}
return _type.Value;
}
}
//copied from DecoderRegistry
private const uint K_COPY = 0x0;
private const uint K_DELTA = 3;
private const uint K_LZMA2 = 0x21;
private const uint K_LZMA = 0x030101;
private const uint K_PPMD = 0x030401;
private const uint K_BCJ = 0x03030103;
private const uint K_BCJ2 = 0x0303011B;
private const uint K_DEFLATE = 0x040108;
private const uint K_B_ZIP2 = 0x040202;
internal CompressionType GetCompression()
{
var coder = Folder!._coders.First();
switch (coder._methodId._id)
{
case K_LZMA:
case K_LZMA2:
{
return CompressionType.LZMA;
}
case K_PPMD:
{
return CompressionType.PPMd;
}
case K_B_ZIP2:
{
return CompressionType.BZip2;
}
default:
throw new NotImplementedException();
}
}
internal bool IsEncrypted => Folder!._coders.FindIndex(c => c._methodId._id == CMethodId.K_AES_ID) != -1;
}
} | adamhathcock/sharpcompress | src/SharpCompress/Common/SevenZip/SevenZipFilePart.cs | C# | mit | 3,350 |
using System;
using System.Collections.Generic;
using Mailer.NET.Mailer.Rendering;
using Mailer.NET.Mailer.Transport;
using Mailer.NET.Mailer.Internal;
using Mailer.NET.Mailer.Response;
using System.Threading.Tasks;
namespace Mailer.NET.Mailer
{
public class Email
{
public AbstractTransport Transport { get; set; }
public String Message { get; set; }
public String Template { get; set; }
public List<TemplateVar> TemplateVars { get; set; }
public List<Contact> To { get; set; }
public List<Contact> Cco { get; set; }
public List<Contact> Bco { get; set; }
public Contact From { get; set; }
public String Subject { get; set; }
public EmailContentType Type { get; set; }
public List<Attachment> Attachments { get; set; }
public Boolean HasReadNotification { get; set; }
public String ReplyTo { get; set; }
public Email(AbstractTransport transport, EmailContentType type = EmailContentType.Text)
{
Transport = transport;
Type = type;
}
public Email(EmailContentType type = EmailContentType.Text)
{
Transport = AppConfig.DefaultInstance.TryGetDefaultTransport();
Type = type;
}
public void AddTo(string email, string name = null)
{
if (To == null)
{
To = new List<Contact>();
}
To.Add(new Contact(){Email = email, Name=name});
}
public void AddCco(string email, string name = null)
{
if (Cco == null)
{
Cco = new List<Contact>();
}
Cco.Add(new Contact() { Email = email, Name = name });
}
public void AddBco(string email, string name = null)
{
if (Bco == null)
{
Bco = new List<Contact>();
}
Bco.Add(new Contact() { Email = email, Name = name });
}
public void AddTemplateVar(string name, object data)
{
if (TemplateVars == null)
{
TemplateVars = new List<TemplateVar>();
}
TemplateVars.Add(new TemplateVar(){Name = name, Data = data});
}
public void AddAttachment(Attachment file)
{
if (Attachments == null)
{
Attachments = new List<Attachment>();
}
Attachments.Add(file);
}
public EmailResponse Send()
{
ValidateEmail();
return Transport.SendEmail(this);
}
public async Task<EmailResponse> SendEmailAsync()
{
ValidateEmail();
return await Transport.SendEmailAsync(this);
}
private void ValidateEmail()
{
if (From == null)
{
throw new InvalidOperationException("The From is not defined!");
}
if (To == null && Bco == null && Cco == null)
{
throw new InvalidOperationException("You need specify one destination on to, cc or bcc.");
}
if (Transport == null)
{
throw new InvalidOperationException("Transport is not defined!");
}
if (!String.IsNullOrEmpty(Template))
{
Message = EmailRender.RenderEmail(this);
}
}
}
}
| Inside-Sistemas/mailer.net | src/Mailer.NET/Mailer/Email.cs | C# | mit | 3,511 |
// <copyright file="ParsingTests.cs" company="MIT License">
// Licensed under the MIT License. See LICENSE file in the project root for license information.
// </copyright>
namespace SmallBasic.Tests.Compiler
{
using SmallBasic.Compiler;
using SmallBasic.Compiler.Diagnostics;
using Xunit;
public sealed class ParsingTests : IClassFixture<CultureFixture>
{
[Fact]
public void ItReportsUnterminatedSubModules()
{
new SmallBasicCompilation(@"
Sub a").VerifyDiagnostics(
// Sub a
// ^
// I was expecting to see 'EndSub' after this.
new Diagnostic(DiagnosticCode.UnexpectedEndOfStream, ((1, 4), (1, 4)), "EndSub"));
}
[Fact]
public void ItReportsNestedSubModules()
{
new SmallBasicCompilation(@"
If x < 1 Then
Sub b
EndSub
EndIf").VerifyDiagnostics(
// Sub b
// ^^^
// I didn't expect to see 'Sub' here. I was expecting the start of a new statement.
new Diagnostic(DiagnosticCode.UnexpectedTokenInsteadOfStatement, ((2, 0), (2, 2)), "Sub"),
// EndSub
// ^^^^^^
// I didn't expect to see 'EndSub' here. I was expecting the start of a new statement.
new Diagnostic(DiagnosticCode.UnexpectedTokenInsteadOfStatement, ((3, 0), (3, 5)), "EndSub"));
}
[Fact]
public void ItReportsIncompleteNestedSubModules()
{
new SmallBasicCompilation(@"
Sub a
Sub b
EndSub").VerifyDiagnostics(
// Sub b
// ^^^
// I didn't expect to see 'Sub' here. I was expecting 'EndSub' instead.
new Diagnostic(DiagnosticCode.UnexpectedTokenFound, ((2, 0), (2, 2)), "Sub", "EndSub"));
}
[Fact]
public void ItReportsEndSubWithoutSub()
{
new SmallBasicCompilation(@"
x = 1
EndSub").VerifyDiagnostics(
// EndSub
// ^^^^^^
// I didn't expect to see 'EndSub' here. I was expecting the start of a new statement.
new Diagnostic(DiagnosticCode.UnexpectedTokenInsteadOfStatement, ((2, 0), (2, 5)), "EndSub"));
}
[Fact]
public void ItReportsElseIfWithoutIf()
{
new SmallBasicCompilation(@"
x = 1
ElseIf x < 1 Then
EndIf").VerifyDiagnostics(
// ElseIf x < 1 Then
// ^^^^^^
// I didn't expect to see 'ElseIf' here. I was expecting the start of a new statement.
new Diagnostic(DiagnosticCode.UnexpectedTokenInsteadOfStatement, ((2, 0), (2, 5)), "ElseIf"),
// EndIf
// ^^^^^
// I didn't expect to see 'EndIf' here. I was expecting the start of a new statement.
new Diagnostic(DiagnosticCode.UnexpectedTokenInsteadOfStatement, ((3, 0), (3, 4)), "EndIf"));
}
[Fact]
public void ItReportsElseWithoutIf()
{
new SmallBasicCompilation(@"
x = 1
Else
EndIf").VerifyDiagnostics(
// Else
// ^^^^
// I didn't expect to see 'Else' here. I was expecting the start of a new statement.
new Diagnostic(DiagnosticCode.UnexpectedTokenInsteadOfStatement, ((2, 0), (2, 3)), "Else"),
// EndIf
// ^^^^^
// I didn't expect to see 'EndIf' here. I was expecting the start of a new statement.
new Diagnostic(DiagnosticCode.UnexpectedTokenInsteadOfStatement, ((3, 0), (3, 4)), "EndIf"));
}
[Fact]
public void ItReportsEndIfWithoutIf()
{
new SmallBasicCompilation(@"
x = 1
EndIf").VerifyDiagnostics(
// EndIf
// ^^^^^
// I didn't expect to see 'EndIf' here. I was expecting the start of a new statement.
new Diagnostic(DiagnosticCode.UnexpectedTokenInsteadOfStatement, ((2, 0), (2, 4)), "EndIf"));
}
[Fact]
public void ItReportsElseIfAfterElse()
{
new SmallBasicCompilation(@"
x = 1
If x > 1 Then
Else
ElseIf x < 1
EndIf").VerifyDiagnostics(
// ElseIf x < 1
// ^^^^^^
// I didn't expect to see 'ElseIf' here. I was expecting 'EndIf' instead.
new Diagnostic(DiagnosticCode.UnexpectedTokenFound, ((4, 0), (4, 5)), "ElseIf", "EndIf"),
// ElseIf x < 1
// ^^^^^^
// I didn't expect to see 'ElseIf' here. I was expecting the start of a new statement.
new Diagnostic(DiagnosticCode.UnexpectedTokenInsteadOfStatement, ((4, 0), (4, 5)), "ElseIf"),
// EndIf
// ^^^^^
// I didn't expect to see 'EndIf' here. I was expecting the start of a new statement.
new Diagnostic(DiagnosticCode.UnexpectedTokenInsteadOfStatement, ((5, 0), (5, 4)), "EndIf"));
}
[Fact]
public void ItReportsEndWhileWithoutWhile()
{
new SmallBasicCompilation(@"
x = 1
EndWhile").VerifyDiagnostics(
// EndWhile
// ^^^^^^^^
// I didn't expect to see 'EndWhile' here. I was expecting the start of a new statement.
new Diagnostic(DiagnosticCode.UnexpectedTokenInsteadOfStatement, ((2, 0), (2, 7)), "EndWhile"));
}
[Fact]
public void ItReportsInvalidStartOfStatements()
{
new SmallBasicCompilation(@"
x = 1
Then").VerifyDiagnostics(
// Then
// ^^^^
// I didn't expect to see 'Then' here. I was expecting the start of a new statement.
new Diagnostic(DiagnosticCode.UnexpectedTokenInsteadOfStatement, ((2, 0), (2, 3)), "Then"));
}
[Fact]
public void ItReportsTokensAfterACompleteStatement()
{
new SmallBasicCompilation(@"
If x = 1 Then y
EndIf").VerifyDiagnostics(
// If x = 1 Then y
// ^
// This statement should go on a new line.
new Diagnostic(DiagnosticCode.UnexpectedStatementInsteadOfNewLine, ((1, 14), (1, 14))));
}
[Fact]
public void ItReportsAssignmentWithNonExpressions()
{
new SmallBasicCompilation(@"
x = .").VerifyDiagnostics(
// x = .
// ^
// I didn't expect to see '.' here. I was expecting 'identifier' instead.
new Diagnostic(DiagnosticCode.UnexpectedTokenFound, ((1, 4), (1, 4)), ".", "identifier"));
}
[Fact]
public void ItReportsAssignmentWithNothing()
{
new SmallBasicCompilation(@"
x =").VerifyDiagnostics(
// x =
// ^
// I was expecting to see 'identifier' after this.
new Diagnostic(DiagnosticCode.UnexpectedEndOfStream, ((1, 2), (1, 2)), "identifier"));
}
[Fact]
public void ItReportsNonExpressionsInWhileLoop()
{
new SmallBasicCompilation(@"
While .
EndWhile").VerifyDiagnostics(
// While .
// ^
// I didn't expect to see '.' here. I was expecting 'identifier' instead.
new Diagnostic(DiagnosticCode.UnexpectedTokenFound, ((1, 6), (1, 6)), ".", "identifier"));
}
[Fact]
public void ItReportsMissingThenAfterIf()
{
new SmallBasicCompilation(@"
If x < 1
EndIf").VerifyDiagnostics(
// EndIf
// ^^^^^
// I didn't expect to see 'EndIf' here. I was expecting 'Then' instead.
new Diagnostic(DiagnosticCode.UnexpectedTokenFound, ((2, 0), (2, 4)), "EndIf", "Then"));
}
[Fact]
public void ItReportsMissingThenAfterElseIf()
{
new SmallBasicCompilation(@"
If x < 1 Then
ElseIf x > 1
EndIf").VerifyDiagnostics(
// EndIf
// ^^^^^
// I didn't expect to see 'EndIf' here. I was expecting 'Then' instead.
new Diagnostic(DiagnosticCode.UnexpectedTokenFound, ((3, 0), (3, 4)), "EndIf", "Then"));
}
[Fact]
public void ItReportsStepAfterIf()
{
new SmallBasicCompilation(@"
If x < 1 Step
EndIf").VerifyDiagnostics(
// If x < 1 Step
// ^^^^
// I didn't expect to see 'Step' here. I was expecting 'Then' instead.
new Diagnostic(DiagnosticCode.UnexpectedTokenFound, ((1, 9), (1, 12)), "Step", "Then"),
// If x < 1 Step
// ^^^^
// This statement should go on a new line.
new Diagnostic(DiagnosticCode.UnexpectedStatementInsteadOfNewLine, ((1, 9), (1, 12))));
}
[Fact]
public void ItReportsStepAfterElseIf()
{
new SmallBasicCompilation(@"
If x > 1 Then
ElseIf x < 1 Step
EndIf").VerifyDiagnostics(
// ElseIf x < 1 Step
// ^^^^
// I didn't expect to see 'Step' here. I was expecting 'Then' instead.
new Diagnostic(DiagnosticCode.UnexpectedTokenFound, ((2, 13), (2, 16)), "Step", "Then"),
// ElseIf x < 1 Step
// ^^^^
// This statement should go on a new line.
new Diagnostic(DiagnosticCode.UnexpectedStatementInsteadOfNewLine, ((2, 13), (2, 16))));
}
[Fact]
public void ItReportsExtraTokensAfterIfStatement()
{
new SmallBasicCompilation(@"
For x = 1 To 2 Step 1 :
EndFor").VerifyDiagnostics(
// For x = 1 To 2 Step 1 :
// ^
// This statement should go on a new line.
new Diagnostic(DiagnosticCode.UnexpectedStatementInsteadOfNewLine, ((1, 23), (1, 23))));
}
[Fact]
public void ItReportsUnevenParenthesis()
{
new SmallBasicCompilation(@"
TextWindow.WriteLine(5").VerifyDiagnostics(
// TextWindow.WriteLine(5
// ^
// I was expecting to see ')' after this.
new Diagnostic(DiagnosticCode.UnexpectedEndOfStream, ((1, 21), (1, 21)), ")"));
}
[Fact]
public void ItReportsUnevenBrackets()
{
new SmallBasicCompilation(@"
x = a[1").VerifyDiagnostics(
// x = a[1
// ^
// I was expecting to see ']' after this.
new Diagnostic(DiagnosticCode.UnexpectedEndOfStream, ((1, 6), (1, 6)), "]"));
}
[Fact]
public void ItReportsArgumentsWithoutCommasInInvocation()
{
new SmallBasicCompilation(@"
x = Math.Power(1 4)").VerifyDiagnostics(
// x = Math.Power(1 4)
// ^
// I didn't expect to see 'number' here. I was expecting ',' instead.
new Diagnostic(DiagnosticCode.UnexpectedTokenFound, ((1, 17), (1, 17)), "number", ","));
}
[Fact]
public void ItReportsCommasWithoutArgumentsInInvocation()
{
new SmallBasicCompilation(@"
x = Math.Sin(, )").VerifyDiagnostics(
// x = Math.Sin(, )
// ^
// I didn't expect to see ',' here. I was expecting 'identifier' instead.
new Diagnostic(DiagnosticCode.UnexpectedTokenFound, ((1, 13), (1, 13)), ",", "identifier"));
}
}
}
| OmarTawfik/SuperBasic | Source/SmallBasic.Tests/Compiler/ParsingTests.cs | C# | mit | 11,842 |