repo_name stringlengths 4 116 | path stringlengths 4 379 | size stringlengths 1 7 | content stringlengths 3 1.05M | license stringclasses 15
values |
|---|---|---|---|---|
tulp/omniauth-vk | lib/omniauth/strategies/vk.rb | 1606 | require 'omniauth/strategies/oauth2'
module OmniAuth
module Strategies
# Authenticate to VK utilizing OAuth 2.0 and retrieve
# basic user information.
# documentation available here:
# http://vk.com/dev/authentication
#
# @example Basic Usage
# use OmniAuth::Strategies::VK, 'API Key', 'Secret Key'
class VK < OmniAuth::Strategies::OAuth2
option :client_options, {
site: 'https://oauth.vk.com',
token_url: '/access_token',
authorize_url: '/authorize'
}
# VK API Version
option :v, '5.0'
option :scope, nil
option :authorize_options, %i(scope v)
# Defaults for API call for fetching user information
option :fields, %w(photo_50)
def api_response
@api_response ||=\
(VKClient.new(
logger: OmniAuth.config.logger,
**{
access_token: access_token.token,
v: options['v'],
fields: options['fields'].join(','),
user_id: uid
})
).get
end
uid { access_token['user_id'].to_s }
# https://github.com/intridea/omniauth/wiki/Auth-Hash-Schema
info {{
first_name: api_response['first_name'],
last_name: api_response['last_name'],
# if VK should be nice, we would be happy
email: access_token['email'],
photo: api_response['photo_50']
}}
extra { skip_info? ? {} : { raw_info: api_response } }
end
end
end
| mit |
spatie-custom/blender.js | modules/form.autosave.js | 1192 | // Autosave form input
var $ = require('jquery')
require('sisyphus.js')
var translate = require("./interface.translations.js")
$("form[data-autosave]").each(function () {
var $form = $(this)
var $save = $(' <a class="button -small" href="#">'+translate('sisyphus.save')+'</a>')
.on('click', function (e) {
e.preventDefault()
$form.submit();
})
var $erase = $(' <a class="button -warning -small" href="?revert=1">'+translate('sisyphus.revert')+'</a>')
.on('click', function (e) {
e.preventDefault()
$form.sisyphus().manuallyReleaseData()
window.location = $(this).attr('href')
})
var $warn = $('<div class="alert -warning" data-autosave-warn>'+translate('sisyphus.warn')+' </div>').append($save).append($erase);
// Add the function to the DOM node so it can be called externally
$form[0].addDraftWarning = function() {
// Prevent duplicate warnings
if ($('[data-autosave-warn]').length) {
return
}
$form.before($warn)
}
// Init sisyphus
$form.sisyphus({
onRestore: $form[0].addDraftWarning
})
})
| mit |
langri-sha/langri-sha.github.io | packages/components/src/analytics.js | 954 | // @flow
import * as React from 'react'
declare function ga(...any[]): void
window.ga =
window.ga ||
function(...args) {
ga.q = ga.q || []
ga.q.push(args)
}
type Props = {|
id: string
|}
export default class Analytics extends React.PureComponent<Props> {
insertScript() {
const script = document.createElement('script')
script.src = 'https://www.google-analytics.com/analytics.js'
script.async = true
if (process.env.NODE_ENV === 'development') {
script.src = script.src.replace(/\/analytics/, '$&_debug')
}
if (document.body !== null) {
document.body.appendChild(script)
}
}
componentDidMount() {
const scriptExists = document.querySelector('script[src$="analytics.js"]')
if (scriptExists) {
return
}
this.insertScript()
}
render() {
ga.l = Number(new Date())
ga('create', this.props.id, 'auto')
ga('send', 'pageview')
return null
}
}
| mit |
elydon/fragments | fragments-core/src/main/java/de/elydon/fragments/core/ClassScanner.java | 3091 | package de.elydon.fragments.core;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.HashMap;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
public class ClassScanner {
private ClassScanner() {
}
public static Map<Class<?>, URL> scan(final ClassLoader classLoader, final ClassFilter filter, final Path root) {
final Map<Class<?>, URL> classes = new HashMap<>();
System.out.println("scanning " + root);
try {
Files.walkFileTree(root, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(final Path file, final BasicFileAttributes attrs) throws IOException {
if (file.toString().endsWith(".class")) {
System.out.println(" scanning file " + file);
String classname = file.toString().replace(root.toString() + File.separator, "")
.replace(File.separator, ".");
classname = classname.substring(0, classname.length() - ".class".length());
try {
final Class<?> clazz = classLoader.loadClass(classname);
if (filter.accepts(clazz)) {
System.out.println(" added " + classname);
classes.put(clazz, null);
}
} catch (final NoClassDefFoundError | ClassNotFoundException e) {
System.err.println(
classname + " could not be loaded from [" + file + "], reason: " + e.getMessage());
}
} else if (file.toString().endsWith(".jar")) {
System.out.println(" scanning JAR file " + file);
// construct class loader for the JAR file
final URL url = file.toUri().toURL();
try (final URLClassLoader jarClassLoader = new URLClassLoader(
new URL[] { url }, classLoader)) {
// loop through the JAR file's entries
try (final ZipInputStream zip = new ZipInputStream(new FileInputStream(file.toFile()))) {
for (ZipEntry entry = zip.getNextEntry(); entry != null; entry = zip.getNextEntry()) {
if (!entry.isDirectory() && entry.getName().endsWith(".class")) {
// extract class name
String classname = entry.getName().replace('/', '.');
classname = classname.substring(0, classname.length() - ".class".length());
try {
final Class<?> clazz = jarClassLoader.loadClass(classname);
if (filter.accepts(clazz)) {
System.out.println(" added " + classname);
classes.put(clazz, url);
}
} catch (final NoClassDefFoundError | ClassNotFoundException e) {
System.err.println(classname + " could not be loaded from [" + file
+ "], reason: " + e.getMessage());
}
}
}
}
}
}
return FileVisitResult.CONTINUE;
}
});
} catch (final IOException e) {
e.printStackTrace();
}
return classes;
}
}
| mit |
OutpostOmni/OmniAPI | OmniAPI/Services/Story/IStoryService.cs | 2293 | /**
* This file is part of OmniAPI, licensed under the MIT License (MIT).
*
* Copyright (c) 2017 Helion3 http://helion3.com/
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
using OmniAPI.Services.Messaging;
using OmniAPI.Services.Save;
namespace OmniAPI.Services.Story {
/// <summary>
/// Represents the story manager.
/// </summary>
public interface IStoryService : IService, IPersistanceTarget {
/// <summary>
/// Activate a story point. Will fail if a story point is already active.
/// </summary>
/// <param name="message">Story message.</param>
void Activate(Message message);
/// <summary>
/// Activate the specified message after a delay.
/// </summary>
/// <returns>The activate.</returns>
/// <param name="message">Message.</param>
/// <param name="delay">Delay.</param>
void Activate(Message message, float delay);
/// <summary>
/// Complete the specified point.
/// </summary>
/// <param name="message">Story Message.</param>
void Complete(Message message);
/// <summary>
/// Register a story type for the given ID.
/// </summary>
/// <param name="message">Story Message.</param>
void Register(Message message);
}
}
| mit |
florin-chelaru/epiviz-5 | export/controllers/master.js | 770 | /**
* Created by Florin Chelaru ( florin [dot] chelaru [at] gmail [dot] com )
* Date: 11/9/2015
* Time: 4:06 PM
*/
goog.require('epiviz.controllers.Master');
goog.exportSymbol('epiviz.controllers.Master', epiviz.controllers.Master);
goog.exportProperty(epiviz.controllers.Master.prototype, 'loadMoreEpigenomes', epiviz.controllers.Master.prototype.loadMoreEpigenomes);
goog.exportProperty(epiviz.controllers.Master.prototype, 'selectAllEpigenomes', epiviz.controllers.Master.prototype.selectAllEpigenomes);
goog.exportProperty(epiviz.controllers.Master.prototype, 'loadMoreGroups', epiviz.controllers.Master.prototype.loadMoreGroups);
goog.exportProperty(epiviz.controllers.Master.prototype, 'selectAllGroups', epiviz.controllers.Master.prototype.selectAllGroups);
| mit |
WaveEngine/Materials | Shared/DualMaterial.cs | 25032 | // Copyright © 2018 Wave Engine S.L. All rights reserved. Use is subject to license terms.
#region Using Statements
using System;
using System.Linq;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using WaveEngine.Common.Attributes;
using WaveEngine.Common.Graphics;
using WaveEngine.Common.Graphics.VertexFormats;
using WaveEngine.Common.Math;
using WaveEngine.Framework.Graphics;
using WaveEngine.Materials.VertexFormats;
#endregion
namespace WaveEngine.Materials
{
/// <summary>
/// Drawing mode for dual texture effect.
/// </summary>
public enum DualTextureMode
{
/// <summary>
/// Lightmap blending (Difusse1 * (2 * Difusse2)).
/// </summary>
Lightmap,
/// <summary>
/// Multiplicative blending (Difusse1 * Difusse2)..
/// </summary>
Multiplicative,
/// <summary>
/// Additive blending. (Difusse1 + Difusse2).
/// </summary>
Additive,
/// <summary>
/// Second texture behaves as a decal.
/// </summary>
Mask,
}
/// <summary>
/// Light PrePass Material
/// </summary>
[DataContract(Namespace = "WaveEngine.Materials")]
public class DualMaterial : DeferredMaterial
{
/// <summary>
/// The diffuse color
/// </summary>
[DataMember]
private Vector4 diffuseColor;
/// <summary>
/// The ambient color
/// </summary>
[DataMember]
private Vector3 ambientColor;
/// <summary>
/// The texture1
/// </summary>
private Texture texture1;
/// <summary>
/// The texture1
/// </summary>
private Texture texture2;
/// <summary>
/// The diffuse1 path
/// </summary>
[DataMember]
private string texture1Path;
/// <summary>
/// The diffuse1 path
/// </summary>
[DataMember]
private string texture2Path;
/// <summary>
/// The normal texture
/// </summary>
private Texture normal;
/// <summary>
/// The normal path
/// </summary>
[DataMember]
private string normalPath;
/// <summary>
/// The techniques
/// </summary>
private static ShaderTechnique[] techniques =
{
// Forward pass
new ShaderTechnique("None", "vsDualMaterial", "psDualMaterial", VertexPositionDualTexture.VertexFormat, null, null),
new ShaderTechnique("F", "vsDualMaterial", "psDualMaterial", VertexPositionDualTexture.VertexFormat, null, new string[] { "FIRST" }),
new ShaderTechnique("S", "vsDualMaterial", "psDualMaterial", VertexPositionDualTexture.VertexFormat, null, new string[] { "SECON" }),
new ShaderTechnique("FSM", "vsDualMaterial", "psDualMaterial", VertexPositionDualTexture.VertexFormat, null, new string[] { "FIRST", "SECON", "MUL" }),
new ShaderTechnique("FSA", "vsDualMaterial", "psDualMaterial", VertexPositionDualTexture.VertexFormat, null, new string[] { "FIRST", "SECON", "ADD" }),
new ShaderTechnique("FSK", "vsDualMaterial", "psDualMaterial", VertexPositionDualTexture.VertexFormat, null, new string[] { "FIRST", "SECON", "MSK" }),
new ShaderTechnique("FSI", "vsDualMaterial", "psDualMaterial", VertexPositionDualTexture.VertexFormat, null, new string[] { "FIRST", "SECON", "LMAP" }),
new ShaderTechnique("L", "vsDualMaterial", "psDualMaterial", VertexPositionDualTexture.VertexFormat, null, new string[] { "LIT" }),
new ShaderTechnique("LF", "vsDualMaterial", "psDualMaterial", VertexPositionDualTexture.VertexFormat, null, new string[] { "LIT", "FIRST" }),
new ShaderTechnique("LS", "vsDualMaterial", "psDualMaterial", VertexPositionDualTexture.VertexFormat, null, new string[] { "LIT", "SECON" }),
new ShaderTechnique("LFSM", "vsDualMaterial", "psDualMaterial", VertexPositionDualTexture.VertexFormat, null, new string[] { "LIT", "FIRST", "SECON", "MUL" }),
new ShaderTechnique("LFSA", "vsDualMaterial", "psDualMaterial", VertexPositionDualTexture.VertexFormat, null, new string[] { "LIT", "FIRST", "SECON", "ADD" }),
new ShaderTechnique("LFSK", "vsDualMaterial", "psDualMaterial", VertexPositionDualTexture.VertexFormat, null, new string[] { "LIT", "FIRST", "SECON", "MSK" }),
new ShaderTechnique("LFSI", "vsDualMaterial", "psDualMaterial", VertexPositionDualTexture.VertexFormat, null, new string[] { "LIT", "FIRST", "SECON", "LMAP" }),
// GBuffer pass
new ShaderTechnique("G", "LPPGBuffer", "vsGBuffer", "LPPGBuffer", "psGBuffer", VertexPositionNormal.VertexFormat, null, null),
new ShaderTechnique("GN", "LPPGBuffer", "vsGBuffer", "LPPGBuffer", "psGBuffer", VertexPositionNormalTangentTexture.VertexFormat, new string[] { "NORMAL" }, new string[] { "NORMAL" }),
new ShaderTechnique("GD", "LPPGBuffer", "vsGBuffer", "LPPGBuffer", "psGBuffer", VertexPositionNormal.VertexFormat, null, new string[] { "DEPTH" }),
new ShaderTechnique("GDN", "LPPGBuffer", "vsGBuffer", "LPPGBuffer", "psGBuffer", VertexPositionNormalTangentTexture.VertexFormat, new string[] { "NORMAL" }, new string[] { "NORMAL", "DEPTH" }),
new ShaderTechnique("GR", "LPPGBuffer", "vsGBuffer", "LPPGBuffer", "psGBuffer", VertexPositionNormal.VertexFormat, null, new string[] { "MRT" }),
new ShaderTechnique("GRN", "LPPGBuffer", "vsGBuffer", "LPPGBuffer", "psGBuffer", VertexPositionNormalTangentTexture.VertexFormat, new string[] { "NORMAL" }, new string[] { "NORMAL", "MRT" }),
};
#region Struct
/// <summary>
/// GBuffer Shader parameters.
/// </summary>
[StructLayout(LayoutKind.Explicit, Size = 16)]
private struct GBufferMaterialParameters
{
/// <summary>
/// The Specular power
/// </summary>
[FieldOffset(0)]
public float SpecularPower;
/// <summary>
/// Texture offset.
/// </summary>
[FieldOffset(4)]
public Vector2 TextureOffset;
}
/// <summary>
/// Shader parameters.
/// </summary>
[StructLayout(LayoutKind.Explicit, Size = 48)]
private struct MaterialParameters
{
/// <summary>
/// The diffuse color
/// </summary>
[FieldOffset(0)]
public Vector4 DiffuseColor;
/// <summary>
/// The ambient color
/// </summary>
[FieldOffset(16)]
public Vector3 AmbientColor;
/// <summary>
/// Fix texture coordinates in OpenGL
/// </summary>
[FieldOffset(28)]
public float TexCoordFix;
/// <summary>
/// The offset's texture1
/// </summary>
[FieldOffset(32)]
public Vector2 TextureOffset1;
/// <summary>
/// The offset's texture2
/// </summary>
[FieldOffset(40)]
public Vector2 TextureOffset2;
}
#endregion
/// <summary>
/// Handle the GBuffer shader parameters struct.
/// </summary>
private GBufferMaterialParameters gbufferShaderParameters;
/// <summary>
/// Handle the shader parameters struct.
/// </summary>
private MaterialParameters shaderParameters;
#region Properties
/// <summary>
/// Gets or sets the shader mode.
/// </summary>
[DataMember]
public DualTextureMode EffectMode { get; set; }
/// <summary>
/// Gets or sets the specular power value.
/// </summary>
[DataMember]
[RenderPropertyAsSlider(0, 255, 1)]
public float SpecularPower { get; set; }
/// <summary>
/// Gets or sets the color of the diffuse.
/// </summary>
/// <value>
/// The color of the diffuse.
/// </value>
public Color DiffuseColor
{
get
{
return Color.FromVector4(ref this.diffuseColor);
}
set
{
value.ToVector4(ref this.diffuseColor);
}
}
/// <summary>
/// Gets or sets the color of the ambient.
/// </summary>
/// <value>
/// The color of the ambient.
/// </value>
public Color AmbientColor
{
get
{
return Color.FromVector3(ref this.ambientColor);
}
set
{
value.ToVector3(ref this.ambientColor);
}
}
/// <summary>
/// Gets or sets the diffuse texture path
/// </summary>
[RenderPropertyAsAsset(AssetType.Texture)]
public string Diffuse1Path
{
get
{
return this.texture1Path;
}
set
{
this.texture1Path = value;
this.RefreshTexture(this.texture1Path, ref this.texture1);
}
}
/// <summary>
/// Gets or sets the diffuse texture path
/// </summary>
[RenderPropertyAsAsset(AssetType.Texture)]
public string Diffuse2Path
{
get
{
return this.texture2Path;
}
set
{
this.texture2Path = value;
this.RefreshTexture(this.texture2Path, ref this.texture2);
}
}
/// <summary>
/// Gets or sets the primary texcoord offset.
/// </summary>
[DataMember]
public Vector2 TexcoordOffset1 { get; set; }
/// <summary>
/// Gets or sets the secondary texcoord offset.
/// </summary>
[DataMember]
public Vector2 TexcoordOffset2 { get; set; }
/// <summary>
/// Gets or sets the normal texture path
/// </summary>
[RenderPropertyAsAsset(AssetType.Texture)]
public string NormalPath
{
get
{
return this.normalPath;
}
set
{
this.normalPath = value;
this.RefreshTexture(this.normalPath, ref this.normal);
}
}
/// <summary>
/// Gets or sets the diffuse texture1.
/// </summary>
/// <exception cref="System.NullReferenceException">Diffuse texture cannot be null.</exception>
[DontRenderProperty]
public Texture Texture1
{
get
{
return this.texture1;
}
set
{
if (value == null)
{
throw new NullReferenceException("Diffuse texture cannot be null.");
}
this.texture1 = value;
}
}
/// <summary>
/// Gets or sets the diffuse texture2.
/// </summary>
/// <exception cref="System.NullReferenceException">Diffuse texture cannot be null.</exception>
[DontRenderProperty]
public Texture Texture2
{
get
{
return this.texture2;
}
set
{
if (value == null)
{
throw new NullReferenceException("Diffuse texture cannot be null.");
}
this.texture2 = value;
}
}
/// <summary>
/// Gets the lighting texture
/// </summary>
[DontRenderProperty]
public Texture LightingTexture
{
get;
private set;
}
/// <summary>
/// Gets or sets a value indicating whether [lighting enable].
/// </summary>
/// <value>
/// <c>true</c> if [lighting enable]; otherwise, <c>false</c>.
/// </value>
[DataMember]
public bool LightingEnabled { get; set; }
/// <summary>
/// Gets or sets the normal.
/// </summary>
/// <value>
/// The normal.
/// </value>
/// <exception cref="System.NullReferenceException">Normal texture cannot be null.</exception>
[DontRenderProperty]
public Texture Normal
{
get
{
return this.normal;
}
set
{
if (value == null)
{
throw new NullReferenceException("Normal texture cannot be null.");
}
this.normal = value;
}
}
#region techniques array
/// <summary>
/// The techniques array
/// </summary>
private static string[] s = new string[]
{
"None",
"F",
"S",
"FSM",
"FSA",
"FSK",
"FSI",
"L",
"LF",
"LS",
"LFSM",
"LFSA",
"LFSK",
"LFSI",
"G",
"GN",
"GD",
"GDN",
"GR",
"GRN",
"G",
"GN",
"GD",
"GDN",
"GR",
"GRN",
};
#endregion
/// <summary>
/// Gets gets or sets the current technique.
/// </summary>
/// <value>
/// The current technique.
/// </value>
[DontRenderProperty]
public override string CurrentTechnique
{
get
{
string technique = string.Empty;
int index = 0;
if (this.DeferredLightingPass == DeferredLightingPass.GBufferPass)
{
technique += "G";
if (this.graphicsDevice != null)
{
if (this.graphicsDevice.RenderTargets.IsDepthAsTextureSupported)
{
technique += "D";
}
else if (this.graphicsDevice.RenderTargets.IsMRTsupported)
{
technique += "R";
}
}
if (this.normal != null)
{
technique += "N";
}
}
else
{
if (this.LightingEnabled)
{
technique += "L";
}
if (this.Texture1 != null)
{
technique += "F";
}
if (this.Texture2 != null)
{
technique += "S";
}
if (this.texture1 != null && this.texture2 != null)
{
switch (this.EffectMode)
{
case DualTextureMode.Multiplicative:
technique += "M";
break;
case DualTextureMode.Additive:
technique += "A";
break;
case DualTextureMode.Mask:
technique += "K";
break;
case DualTextureMode.Lightmap:
technique += "I";
break;
}
}
if (string.IsNullOrEmpty(technique))
{
technique = "None";
}
}
for (int i = 0; i < s.Length; i++)
{
if (s[i] == technique)
{
index = i;
break;
}
}
ShaderTechnique seletedTechnique = techniques[index];
// Lazy initialization
if (!seletedTechnique.IsInitialized)
{
if (this.DeferredLightingPass == DeferredLightingPass.GBufferPass)
{
this.Parameters = this.gbufferShaderParameters;
}
else
{
this.Parameters = this.shaderParameters;
}
seletedTechnique.Initialize(this);
}
return seletedTechnique.Name;
}
}
#endregion
#region Initialize
/// <summary>
/// Initializes a new instance of the <see cref="DualMaterial"/> class.
/// </summary>
public DualMaterial()
: base(DefaultLayers.Opaque)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="DualMaterial"/> class.
/// </summary>
/// <param name="layerId">The associated layer</param>
public DualMaterial(int layerId)
: base(layerId)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="DualMaterial"/> class.
/// </summary>
/// <param name="diffuseColor">The diffuse color.</param>
/// <param name="layerId">The associated layer</param>
public DualMaterial(Color diffuseColor, int layerId)
: this(layerId)
{
this.DiffuseColor = diffuseColor;
}
/// <summary>
/// Initializes a new instance of the <see cref="DualMaterial"/> class.
/// </summary>
/// <param name="layerId">The associated layer</param>
/// <param name="texture1Path">The texture1 path.</param>
/// <param name="texture2Path">The texture2 path.</param>
/// <param name="normalPath">The normal path.</param>
public DualMaterial(int layerId, string texture1Path = null, string texture2Path = null, string normalPath = null)
: this(layerId)
{
this.texture1Path = texture1Path;
this.texture2Path = texture2Path;
this.normalPath = normalPath;
}
/// <summary>
/// Initializes a new instance of the <see cref="DualMaterial"/> class.
/// </summary>
/// <param name="layerId">The associated layer</param>
/// <param name="texture1">The texture1.</param>
/// <param name="texture2">The texture2.</param>
/// <param name="normal">The normal.</param>
public DualMaterial(int layerId, Texture texture1 = null, Texture texture2 = null, Texture normal = null)
: this(layerId)
{
this.texture1 = texture1;
this.texture2 = texture2;
this.normal = normal;
}
/// <summary>
/// Defaults the values.
/// </summary>
protected override void DefaultValues()
{
base.DefaultValues();
this.EffectMode = DualTextureMode.Multiplicative;
this.DiffuseColor = Color.White;
this.AmbientColor = Color.Black;
this.SpecularPower = 64;
this.LightingEnabled = true;
this.shaderParameters = new MaterialParameters();
this.gbufferShaderParameters = new GBufferMaterialParameters();
// ToDo: You need to initialize at least one technique
this.Parameters = this.shaderParameters;
techniques[0].Initialize(this);
}
/// <summary>
/// Initializes the specified assets.
/// </summary>
/// <param name="assets">The assets.</param>
public override void Initialize(WaveEngine.Framework.Services.AssetsContainer assets)
{
base.Initialize(assets);
this.LoadTexture(this.texture1Path, ref this.texture1);
this.LoadTexture(this.texture2Path, ref this.texture2);
this.LoadTexture(this.normalPath, ref this.normal);
}
#endregion
#region Public Methods
/// <summary>
/// Check if this material require the specified pass
/// </summary>
/// <param name="pass">The deferred pass</param>
/// <returns>True if this material require this pass</returns>
public override bool RequireDeferredPass(DeferredLightingPass pass)
{
if (pass == DeferredLightingPass.GBufferPass)
{
return this.LightingEnabled;
}
return true;
}
/// <summary>
/// Sets the parameters.
/// </summary>
/// <param name="cached">if set to <c>true</c> [cached].</param>
public override void SetParameters(bool cached)
{
base.SetParameters(cached);
if (!cached)
{
Camera camera = this.renderManager.CurrentDrawingCamera;
if (this.DeferredLightingPass == DeferredLightingPass.ForwardPass)
{
this.shaderParameters.DiffuseColor = this.diffuseColor;
this.shaderParameters.AmbientColor = this.ambientColor;
this.shaderParameters.TexCoordFix = this.renderManager.GraphicsDevice.RenderTargets.RenderTargetActive ? 1 : -1;
this.shaderParameters.TextureOffset1 = this.TexcoordOffset1;
this.shaderParameters.TextureOffset2 = this.TexcoordOffset2;
this.Parameters = this.shaderParameters;
this.LightingTexture = camera.LightingRT;
if (this.LightingTexture != null)
{
this.graphicsDevice.SetTexture(this.LightingTexture, 2);
}
if (this.texture1 != null)
{
this.graphicsDevice.SetTexture(this.texture1, 0);
}
if (this.texture2 != null)
{
this.graphicsDevice.SetTexture(this.texture2, 1);
}
}
else
{
this.gbufferShaderParameters.SpecularPower = this.SpecularPower;
this.gbufferShaderParameters.TextureOffset = this.TexcoordOffset1;
this.Parameters = this.gbufferShaderParameters;
if (this.normal != null)
{
this.graphicsDevice.SetTexture(this.normal, 0);
}
}
}
}
#endregion
#region Private Methods
/// <summary>
/// Refreshes the texture.
/// </summary>
/// <param name="path">The path.</param>
/// <param name="texture">The texture.</param>
private void RefreshTexture(string path, ref Texture texture)
{
this.UnloadTexture(ref texture);
this.LoadTexture(path, ref texture);
}
/// <summary>
/// Unload the texture.
/// </summary>
/// <param name="texture">The texture.</param>
private void UnloadTexture(ref Texture texture)
{
if (this.assetsContainer != null && texture != null && !string.IsNullOrEmpty(texture.AssetPath))
{
this.assetsContainer.UnloadAsset(texture.AssetPath);
texture = null;
}
}
/// <summary>
/// Load the texture.
/// </summary>
/// <param name="path">The path.</param>
/// <param name="texture">The texture.</param>
private void LoadTexture(string path, ref Texture texture)
{
if (texture != null)
{
return;
}
if (this.assetsContainer != null && texture == null && !string.IsNullOrEmpty(path))
{
texture = this.assetsContainer.LoadAsset<Texture2D>(path);
}
}
#endregion
}
}
| mit |
WulfMarius/ModComponent | ModComponentAPI/src/TypeResolver.cs | 770 | using System;
using System.Reflection;
namespace ModComponentAPI
{
public class TypeResolver
{
public static Type Resolve(string name)
{
Type result = Type.GetType(name, false);
if (result != null)
{
return result;
}
Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
foreach (Assembly eachAssembly in assemblies)
{
result = eachAssembly.GetType(name, false);
if (result != null)
{
return result;
}
}
throw new ArgumentException("Could not resolve type '" + name + "'. Are you missing an assembly?");
}
}
} | mit |
janrain/jruby-rack | src/main/ruby/jruby/rack/servlet_log.rb | 575 | #--
# Copyright (c) 2010-2012 Engine Yard, Inc.
# Copyright (c) 2007-2009 Sun Microsystems, Inc.
# This source code is available under the MIT license.
# See the file LICENSE.txt for details.
#++
module JRuby
module Rack
class ServletLog
def initialize(context = JRuby::Rack.context)
raise ArgumentError, "no context" unless context
@context = context
end
def puts(msg)
write msg.to_s
end
def write(msg)
@context.log(msg)
end
def flush
end
def close
end
end
end
end
| mit |
marko-js/marko | packages/translator-default/src/tag/native-tag[vdom]/index.js | 5313 | import { types as t } from "@marko/compiler";
import write from "../../util/vdom-out-write";
import * as FLAGS from "../../util/runtime-flags";
import { getAttrs, evaluateAttr } from "../util";
import {
getTagDef,
normalizeTemplateString,
importDefault
} from "@marko/babel-utils";
import withPreviousLocation from "../../util/with-previous-location";
const SIMPLE_ATTRS = ["id", "class", "style"];
const MAYBE_SVG = {
a: true,
script: true,
style: true,
title: true
};
export function tagArguments(path, isStatic) {
const {
hub: { file },
node,
parent
} = path;
const {
name,
key,
body: { body },
handlers
} = node;
const tagProperties = (path.node.extra && path.node.extra.properties) || [];
let runtimeFlags = 0;
path.get("attributes").forEach(attr => {
const { confident, computed } = evaluateAttr(attr);
if (confident) {
if (computed == null || computed === false) {
attr.remove();
} else {
attr.set("value", t.stringLiteral(computed));
}
}
});
let attrsObj = getAttrs(path, true, true);
if (!t.isNullLiteral(attrsObj)) {
if (
!t.isObjectExpression(attrsObj) ||
attrsObj.properties.some(t.isSpreadElement)
) {
runtimeFlags |= FLAGS.SPREAD_ATTRS;
attrsObj = t.callExpression(
importDefault(
file,
"marko/src/runtime/vdom/helpers/attrs.js",
"marko_attrs"
),
[attrsObj]
);
}
}
const writeArgs = [
name,
attrsObj,
!key && isStatic ? t.nullLiteral() : key,
isStatic ? t.nullLiteral() : file._componentInstanceIdentifier,
isStatic
? t.numericLiteral(body.length)
: body.length
? t.nullLiteral()
: t.numericLiteral(0)
];
if (node.preserveAttrs) {
tagProperties.push(
t.objectProperty(
t.identifier("pa"),
t.arrayExpression(node.preserveAttrs.map(name => t.stringLiteral(name)))
)
);
}
if (handlers) {
Object.entries(handlers).forEach(
([eventName, { arguments: args, once }]) => {
const delegateArgs = [t.stringLiteral(eventName), args[0]];
// TODO: look into only sending this if once is true.
delegateArgs.push(t.booleanLiteral(once));
if (args.length > 1) {
delegateArgs.push(t.arrayExpression(args.slice(1)));
}
// TODO: why do we output eventName twice.
tagProperties.push(
t.objectProperty(
t.stringLiteral(`on${eventName}`),
t.callExpression(
t.memberExpression(
file._componentDefIdentifier,
t.identifier("d")
),
delegateArgs
)
)
);
}
);
}
if (
t.isObjectExpression(attrsObj) &&
attrsObj.properties.every(n => isPropertyName(n, SIMPLE_ATTRS)) &&
!node.preserveAttrs
) {
runtimeFlags |= FLAGS.HAS_SIMPLE_ATTRS;
}
const tagDef = getTagDef(path);
if (tagDef) {
const { htmlType, name } = tagDef;
if (htmlType === "custom-element") {
runtimeFlags |= FLAGS.IS_CUSTOM_ELEMENT;
} else if (
htmlType === "svg" ||
(MAYBE_SVG[name] &&
t.isMarkoTag(parent) &&
parent.tagDef &&
parent.tagDef.htmlType === "svg")
) {
runtimeFlags |= FLAGS.IS_SVG;
} else if (name === "textarea") {
runtimeFlags |= FLAGS.IS_TEXTAREA;
}
}
writeArgs.push(t.numericLiteral(runtimeFlags));
if (tagProperties.length) {
writeArgs.push(t.objectExpression(tagProperties));
}
return writeArgs;
}
/**
* Translates the html streaming version of a standard html element.
*/
export default function (path, isNullable) {
const { node } = path;
const {
name,
key,
body: { body }
} = node;
const isEmpty = !body.length;
const writeArgs = tagArguments(path, false);
let writeStartNode = withPreviousLocation(
write(isEmpty ? "e" : "be", ...writeArgs),
node.name
);
if (isNullable) {
writeStartNode = t.ifStatement(
name,
writeStartNode,
t.expressionStatement(
t.callExpression(
t.memberExpression(t.identifier("out"), t.identifier("bf")),
[
normalizeTemplateString`f_${key}`,
path.hub.file._componentInstanceIdentifier
]
)
)
);
}
if (isEmpty) {
path.replaceWith(writeStartNode);
return;
}
let writeEndNode = write("ee");
if (isNullable) {
writeEndNode = t.ifStatement(
name,
writeEndNode,
t.expressionStatement(
t.callExpression(
t.memberExpression(t.identifier("out"), t.identifier("ef")),
[]
)
)
);
}
let needsBlock;
for (const childNode of body) {
if (t.isVariableDeclaration(childNode)) {
if (childNode.kind === "const" || childNode.kind === "let") {
needsBlock = true;
break;
}
}
}
path.replaceWithMultiple(
[writeStartNode]
.concat(needsBlock ? t.blockStatement(body) : body)
.concat(writeEndNode)
);
}
function isPropertyName({ key }, names) {
if (t.isStringLiteral(key)) {
return names.includes(key.value);
} else if (t.isIdentifier(key)) {
return names.includes(key.name);
}
}
| mit |
mailjet/mailjet-apiv3-java | src/test/java/com/mailjet/client/MailjetClientExceptionTest.java | 4339 | package com.mailjet.client;
import com.mailjet.client.errors.*;
import com.mailjet.client.resource.Email;
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.MockWebServer;
import org.json.JSONArray;
import org.json.JSONObject;
import org.junit.*;
import java.io.IOException;
/**
* @author Nikola-Andreev
*/
public class MailjetClientExceptionTest {
private static final String FROM_EMAIL = "pilot@mailjet.com";
private static final String FROM_NAME = "Mailjet Pilot";
private static final String SUBJECT = "Your email flight plan!";
private static final String TEXT_PART = "Dear passenger, welcome to Mailjet! May the delivery force be with you!";
private static final String HTML_PART = "<h3>Dear passenger, welcome to Mailjet</h3><br/>May the delivery force be with you!";
private static final String RECIPIENT = "passenger@mailjet.com";
private static MailjetClient client;
private static MailjetRequest request;
private static MockWebServer mockWebServer;
@BeforeClass
public static void initialize() throws IOException {
request = new MailjetRequest(Email.resource)
.property(Email.FROMEMAIL, FROM_EMAIL)
.property(Email.FROMNAME, FROM_NAME)
.property(Email.SUBJECT, SUBJECT)
.property(Email.TEXTPART, TEXT_PART)
.property(Email.HTMLPART, HTML_PART)
.property(Email.RECIPIENTS, new JSONArray()
.put(new JSONObject()
.put(Email.EMAIL, RECIPIENT)));
mockWebServer = new MockWebServer();
mockWebServer.start();
ClientOptions clientOptions = ClientOptions
.builder()
.baseUrl(mockWebServer.url("/").toString())
.apiSecretKey("secret-key")
.apiKey("api-key")
.build();
client = new MailjetClient(clientOptions);
}
@Test
public void testTooManyRequestsResponse() {
// arrange
mockWebServer.enqueue(new MockResponse().setResponseCode(429));
// act
MailjetRateLimitException exception = Assert.assertThrows(MailjetRateLimitException.class, () ->{
client.post(request);
});
// assert
Assert.assertEquals("Too Many Requests", exception.getMessage());
}
@Test
public void testInternalServerErrorResponse() {
// arrange
mockWebServer.enqueue(new MockResponse().setResponseCode(500).setBody("Error Description"));
// act
MailjetServerException exception = Assert.assertThrows(MailjetServerException.class, () ->{
client.post(request);
});
// assert
Assert.assertEquals("Error Description", exception.getMessage());
}
@Test
public void testBadRequestResponse() {
// arrange
mockWebServer.enqueue(new MockResponse().setResponseCode(400).setBody("Error Description"));
// act
MailjetClientRequestException exception = Assert.assertThrows(MailjetClientRequestException.class, () ->{
client.post(request);
});
// assert
Assert.assertEquals("Error Description", exception.getMessage());
}
@Test
public void testUnauthorizedResponse() {
// arrange
mockWebServer.enqueue(new MockResponse().setResponseCode(401));
// act
MailjetUnauthorizedException exception = Assert.assertThrows(MailjetUnauthorizedException.class, () ->{
client.post(request);
});
// assert
Assert.assertEquals("Unauthorized. Please,verify your access key and access secret key or token for the given account", exception.getMessage());
}
@Test
public void testForbiddenResponse() {
// arrange
mockWebServer.enqueue(new MockResponse().setResponseCode(403).setBody("Error Description"));
// act
MailjetClientRequestException exception = Assert.assertThrows(MailjetClientRequestException.class, () ->{
client.post(request);
});
// assert
Assert.assertEquals("Error Description", exception.getMessage());
}
@AfterClass
public static void tearDown() throws IOException {
mockWebServer.shutdown();
}
}
| mit |
OpenFibers/TOT2 | app/controllers/application_controller.rb | 382 | class ApplicationController < ActionController::Base
# redirect of devise login
def after_sign_in_path_for(resource)
"/admin"
end
# redirect of devise logout
def after_sign_out_path_for(resource_or_scope)
#request.referrer #Keeping user on the same page after signing out
"/admin"
end
def not_found
raise ActionController::RoutingError.new('Not Found')
end
end
| mit |
jdbence/capstone-project | src/components/layout/RoomLayout/index.js | 67 | import RoomLayout from './RoomLayout';
export default RoomLayout;
| mit |
levfurtado/scoops | vendor/willdurand/js-translation-bundle/Bazinga/Bundle/JsTranslationBundle/Tests/Dumper/TranslationDumperTest.php | 3145 | <?php
namespace Bazinga\JsTranslationBundle\Tests\Finder;
use Bazinga\Bundle\JsTranslationBundle\Tests\WebTestCase;
/**
* @author Adrien Russo <adrien.russo.qc@gmail.com>
*/
class TranslationDumperTest extends WebTestCase
{
private $target;
private $filesystem;
private $dumper;
public function setUp()
{
$client = static::createClient();
$container = $client->getContainer();
$this->target = sys_get_temp_dir() . '/bazinga/js-translation-bundle';
$this->filesystem = $container->get('filesystem');
$this->dumper = $container->get('bazinga.jstranslation.translation_dumper');
$this->filesystem->mkdir($this->target, 0755);
}
public function tearDown()
{
if (is_dir($this->target)) {
$this->filesystem->remove($this->target);
}
}
public function testDump()
{
$this->dumper->dump($this->target);
foreach (array(
'messages/en.js',
'messages/en.json',
'messages/fr.js',
'messages/fr.json',
'foo/en.js',
'foo/en.json',
'numerics/en.js',
'numerics/en.json',
) as $file) {
$this->assertFileExists($this->target . '/translations/' . $file);
}
foreach (array(
'front/en.js',
'front/en.json',
'front/fr.js',
'front/fr.json',
'messages/es.js',
'messages/es.json',
) as $file) {
$this->assertFileNotExists($this->target . '/translations/' . $file);
}
$this->assertEquals(<<<JS
(function (Translator) {
// fr
Translator.add("hello", "bonjour", "messages", "fr");
})(Translator);
JS
, file_get_contents($this->target . '/translations/messages/fr.js'));
$this->assertEquals(<<<JS
(function (Translator) {
// en
Translator.add("hello", "hello", "messages", "en");
})(Translator);
JS
, file_get_contents($this->target . '/translations/messages/en.js'));
$this->assertEquals(<<<JS
(function (Translator) {
Translator.fallback = 'en';
Translator.defaultDomain = 'messages';
})(Translator);
JS
, file_get_contents($this->target . '/translations/config.js'));
$this->assertEquals(<<<JSON
{
"translations": {"fr":{"messages":{"hello":"bonjour"}}}
}
JSON
, file_get_contents($this->target . '/translations/messages/fr.json'));
$this->assertEquals(<<<JSON
{
"translations": {"en":{"messages":{"hello":"hello"}}}
}
JSON
, file_get_contents($this->target . '/translations/messages/en.json'));
$this->assertEquals(<<<JSON
{
"fallback": "en",
"defaultDomain": "messages"
}
JSON
, file_get_contents($this->target . '/translations/config.json'));
$this->assertEquals(<<<JSON
{
"translations": {"en":{"numerics":{"7":"Nos occasions","8":"Nous contacter","12":"pr\u00e9nom","13":"nom","14":"adresse","15":"code postal"}}}
}
JSON
, file_get_contents($this->target . '/translations/numerics/en.json'));
}
}
| mit |
nusskylab/nusskylab | app/assets/javascripts/public_projects.js | 1367 | 'use strict';
function createModalBox(team_id) {
var modal = document.getElementById("modal_".concat(team_id));
var button = document.getElementById("button_".concat(team_id));
var span = modal.getElementsByClassName("close")[0];
modal.style.display = "block";
// Close using the window close.
span.addEventListener('click', function() {
closeModal(modal);
});
// Close modal outside of the modal
window.addEventListener('click', function(event) {
if (event.target == modal) {
closeModal(modal);
}
});
}
function closeModal(modal) {
modal.style.display = "none";
}
function replaceImg(image, team_level) {
if (team_level == 'vostok') {
return $(image).attr('src', "/assets/Vostok_Icon.jpg");
} else if (team_level == 'project_gemini') {
return $(image).attr('src', "/assets/Project_Gemini_Icon.png");
} else if (team_level == 'apollo_11') {
return $(image).attr('src', "/assets/Apollo_11_Icon.png");
} else {
return $(image).attr('src',"/assets/Artemis_Icon.png");
}
}
document.addEventListener('DOMContentLoaded', function () {
Array.from(document.getElementsByClassName("button_team")).forEach(function(element) {
element.addEventListener('click', function() {
createModalBox(element.id.slice(element.id.indexOf("_") + 1));
});
});
});
| mit |
EntityFX/GdcGame | Sources/EntityFX.Gdcame.DataAccess.Repository/Queries/Counetrs/GetAllCountersQuery.cs | 810 | using System.Collections.Generic;
using System.Linq;
using EntityFX.Gdcame.DataAccess.Model.Ef;
using EntityFX.Gdcame.DataAccess.Repository.Contract.Criterions.Counters;
using EntityFX.Gdcame.Infrastructure.Repository.EF;
using EntityFX.Gdcame.Infrastructure.Repository.Query;
namespace EntityFX.Gdcame.DataAccess.Repository.Ef.Queries.Counetrs
{
public class GetAllCountersQuery : QueryBase,
IQuery<GetAllCountersCriterion, IEnumerable<CounterEntity>>
{
public GetAllCountersQuery(EconomicsArcadeDbContext dbContext)
: base(dbContext)
{
}
public IEnumerable<CounterEntity> Execute(GetAllCountersCriterion criterion)
{
return DbContext.Set<CounterEntity>()
.ToArray();
}
}
} | mit |
Hubert51/ROOMr | server_part/app/forms.py | 270 | from flask_wtf import FlaskForm
from wtforms import StringField, BooleanField
from wtforms.validators import DataRequired
class LoginForm(FlaskForm):
openid = StringField('openid', validators=[DataRequired()])
remember_me = BooleanField('remember_me', default=False)
| mit |
MingXingTeam/webpack-react-starter | src/scripts/modules/change.js | 100 | module.exports.change = function change() {
document.getElementById('test').innerHTML = 'bb';
};
| mit |
ignaciocases/hermeneumatics | node_modules/scala-node/main/target/streams/compile/externalDependencyClasspath/$global/package-js/extracted-jars/scalajs-library_2.10-0.4.0.jar--29fb2f8b/scala/collection/convert/Wrappers$JPropertiesWrapper$$anon$3.js | 3995 | /** @constructor */
ScalaJS.c.scala_collection_convert_Wrappers$JPropertiesWrapper$$anon$3 = (function() {
ScalaJS.c.scala_collection_AbstractIterator.call(this);
this.ui$2 = null
});
ScalaJS.c.scala_collection_convert_Wrappers$JPropertiesWrapper$$anon$3.prototype = new ScalaJS.inheritable.scala_collection_AbstractIterator();
ScalaJS.c.scala_collection_convert_Wrappers$JPropertiesWrapper$$anon$3.prototype.constructor = ScalaJS.c.scala_collection_convert_Wrappers$JPropertiesWrapper$$anon$3;
ScalaJS.c.scala_collection_convert_Wrappers$JPropertiesWrapper$$anon$3.prototype.ui__p2__Ljava_util_Iterator = (function() {
return this.ui$2
});
ScalaJS.c.scala_collection_convert_Wrappers$JPropertiesWrapper$$anon$3.prototype.hasNext__Z = (function() {
return this.ui__p2__Ljava_util_Iterator().hasNext__Z()
});
ScalaJS.c.scala_collection_convert_Wrappers$JPropertiesWrapper$$anon$3.prototype.next__Lscala_Tuple2 = (function() {
var e = ScalaJS.as.java_util_Map$Entry(this.ui__p2__Ljava_util_Iterator().next__O());
return new ScalaJS.c.scala_Tuple2().init___O__O(ScalaJS.as.java_lang_String(e.getKey__O()), ScalaJS.as.java_lang_String(e.getValue__O()))
});
ScalaJS.c.scala_collection_convert_Wrappers$JPropertiesWrapper$$anon$3.prototype.next__O = (function() {
return this.next__Lscala_Tuple2()
});
ScalaJS.c.scala_collection_convert_Wrappers$JPropertiesWrapper$$anon$3.prototype.init___Lscala_collection_convert_Wrappers$JPropertiesWrapper = (function($$outer) {
ScalaJS.c.scala_collection_AbstractIterator.prototype.init___.call(this);
this.ui$2 = $$outer.underlying__Ljava_util_Properties().entrySet__Ljava_util_Set().iterator__Ljava_util_Iterator();
return this
});
/** @constructor */
ScalaJS.inheritable.scala_collection_convert_Wrappers$JPropertiesWrapper$$anon$3 = (function() {
/*<skip>*/
});
ScalaJS.inheritable.scala_collection_convert_Wrappers$JPropertiesWrapper$$anon$3.prototype = ScalaJS.c.scala_collection_convert_Wrappers$JPropertiesWrapper$$anon$3.prototype;
ScalaJS.is.scala_collection_convert_Wrappers$JPropertiesWrapper$$anon$3 = (function(obj) {
return (!(!((obj && obj.$classData) && obj.$classData.ancestors.scala_collection_convert_Wrappers$JPropertiesWrapper$$anon$3)))
});
ScalaJS.as.scala_collection_convert_Wrappers$JPropertiesWrapper$$anon$3 = (function(obj) {
if ((ScalaJS.is.scala_collection_convert_Wrappers$JPropertiesWrapper$$anon$3(obj) || (obj === null))) {
return obj
} else {
ScalaJS.throwClassCastException(obj, "scala.collection.convert.Wrappers$JPropertiesWrapper$$anon$3")
}
});
ScalaJS.isArrayOf.scala_collection_convert_Wrappers$JPropertiesWrapper$$anon$3 = (function(obj, depth) {
return (!(!(((obj && obj.$classData) && (obj.$classData.arrayDepth === depth)) && obj.$classData.arrayBase.ancestors.scala_collection_convert_Wrappers$JPropertiesWrapper$$anon$3)))
});
ScalaJS.asArrayOf.scala_collection_convert_Wrappers$JPropertiesWrapper$$anon$3 = (function(obj, depth) {
if ((ScalaJS.isArrayOf.scala_collection_convert_Wrappers$JPropertiesWrapper$$anon$3(obj, depth) || (obj === null))) {
return obj
} else {
ScalaJS.throwArrayCastException(obj, "Lscala.collection.convert.Wrappers$JPropertiesWrapper$$anon$3;", depth)
}
});
ScalaJS.data.scala_collection_convert_Wrappers$JPropertiesWrapper$$anon$3 = new ScalaJS.ClassTypeData({
scala_collection_convert_Wrappers$JPropertiesWrapper$$anon$3: 0
}, false, "scala.collection.convert.Wrappers$JPropertiesWrapper$$anon$3", ScalaJS.data.scala_collection_AbstractIterator, {
scala_collection_convert_Wrappers$JPropertiesWrapper$$anon$3: 1,
scala_collection_AbstractIterator: 1,
scala_collection_Iterator: 1,
scala_collection_TraversableOnce: 1,
scala_collection_GenTraversableOnce: 1,
java_lang_Object: 1
});
ScalaJS.c.scala_collection_convert_Wrappers$JPropertiesWrapper$$anon$3.prototype.$classData = ScalaJS.data.scala_collection_convert_Wrappers$JPropertiesWrapper$$anon$3;
//@ sourceMappingURL=Wrappers$JPropertiesWrapper$$anon$3.js.map
| mit |
CARFAX/wharf | example/test/paths/queryString.test.js | 633 | describe('paths', function() {
describe('queryString', function() {
it('should work with one value', function () {
var params = {
foo: 'bar'
};
var string = foo.paths.queryString(params);
expect(string).toBe('?foo=bar');
});
it('work with multiple values', function () {
var params = {
foo: 'bar',
fizz: 'buzz',
num: 2
};
var string = foo.paths.queryString(params);
expect(string).toBe('?foo=bar&fizz=buzz&num=2');
});
});
}); | mit |
daleksic/poster | www/js/services/database/image.js | 2056 | angular.module('starter.service.image', ['starter.database'])
.factory('ImageService', ['$q', 'DatabaseService', function ($q, DatabaseService) {
return {
addImage: function(title, location, uri, width, height, contentType, albumId){
DatabaseService.insertImage(title, location, uri, width, height, contentType, albumId);
},
deleteImage: function(imageId){
DatabaseService.deleteImage(imageId);
},
deleteImagesByAlbumId: function(albumId){
DatabaseService.deleteImagesByAlbumId(albumId);
},
imageExists: function(title){
var q = $q.defer();
var response = '';
DatabaseService.imageExists(title).then(function(result){
response = result;
q.resolve(response);
});
return q.promise;
},
findImageById: function (imageId) {
var q = $q.defer();
var image = {};
DatabaseService.findImageById(imageId).then(function(result){
for(var i=0; i < result.rows.length; i++){
image['id'] = result.rows.item(0).image_id;
image['title'] = result.rows.item(0).image_title;
image['location'] = result.rows.item(0).image_location;
image['uri'] = result.rows.item(0).image_uri;
image['date_created'] = result.rows.item(0).image_date_created;
}
q.resolve(image);
});
return q.promise;
},
findImagesByAlbumId: function (albumId) {
var q = $q.defer();
var images = [];
DatabaseService.findImagesByAlbumId(albumId).then(function(result){
for(var i=0; i < result.rows.length; i++){
var image = {};
image['id'] = result.rows.item(i).image_id;
image['title'] = result.rows.item(i).image_title;
image['location'] = result.rows.item(i).image_location;
image['uri'] = result.rows.item(i).image_uri;
image['date_created'] = result.rows.item(i).image_date_created;
images.push(image);
}
q.resolve(images);
});
return q.promise;
}
};
}]);
| mit |
joeferraro/MavensMate-VisualStudioCode | typings/main.d.ts | 179 | /// <reference path="main/definitions/bluebird/index.d.ts" />
/// <reference path="main/definitions/nock/index.d.ts" />
/// <reference path="main/definitions/sinon/index.d.ts" />
| mit |
ankhuve/bonus | library/enqueue-scripts.php | 2683 | <?php
/**
* Enqueue all styles and scripts
*
* Learn more about enqueue_script: {@link https://codex.wordpress.org/Function_Reference/wp_enqueue_script}
* Learn more about enqueue_style: {@link https://codex.wordpress.org/Function_Reference/wp_enqueue_style }
*
* @package WordPress
* @subpackage FoundationPress
* @since FoundationPress 1.0.0
*/
if ( ! function_exists( 'foundationpress_scripts' ) ) :
function foundationpress_scripts() {
// Enqueue the main Stylesheet.
wp_enqueue_style( 'main-stylesheet', get_stylesheet_directory_uri() . '/assets/stylesheets/foundation.css' );
// Deregister the jquery version bundled with WordPress.
wp_deregister_script( 'jquery' );
// Modernizr is used for polyfills and feature detection. Must be placed in header. (Not required).
wp_enqueue_script( 'modernizr', get_template_directory_uri() . '/assets/javascript/vendor/modernizr.js', array(), '2.8.3', false );
// Fastclick removes the 300ms delay on click events in mobile environments. Must be placed in header. (Not required).
wp_enqueue_script( 'fastclick', get_template_directory_uri() . '/assets/javascript/vendor/fastclick.js', array(), '1.0.0', false );
// CDN hosted jQuery placed in the header, as some plugins require that jQuery is loaded in the header.
wp_enqueue_script( 'jquery', '//ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js', array(), '2.1.0', false );
// If you'd like to cherry-pick the foundation components you need in your project, head over to Gruntfile.js and see lines 67-88.
// It's a good idea to do this, performance-wise. No need to load everything if you're just going to use the grid anyway, you know :)
wp_enqueue_script( 'foundation', get_template_directory_uri() . '/assets/javascript/foundation.js', array('jquery'), '5.5.2', true );
// Add the comment-reply library on pages where it is necessary
if ( is_singular() && comments_open() && get_option( 'thread_comments' ) ) {
wp_enqueue_script( 'comment-reply' );
}
}
add_action( 'wp_enqueue_scripts', 'foundationpress_scripts' );
endif;
if ( ! function_exists( 'custom_scripts' ) ) :
function custom_scripts() {
// Flickity for the hero slider
wp_enqueue_script( 'flickity', get_template_directory_uri() . '/assets/javascript/vendor/flickity.pkgd.min.js', array(), '1.0.0', false );
// wp_enqueue_style( 'flickity-css', get_stylesheet_directory_uri() . '/assets/stylesheets/flickity.css', array(), '1.0.0', 'screen' );
// Bonus list sorting
wp_enqueue_script( 'list', get_template_directory_uri() . '/assets/javascript/vendor/list.min.js', array(), '1.0.0', false );
}
add_action( 'wp_enqueue_scripts', 'custom_scripts' );
endif;
?>
| mit |
easytp/easytp | App/Common/Plugin/Imagine/Filter/Basic/Resize.class.php | 1066 | <?php
/*
* This file is part of the Imagine package.
*
* (c) Bulat Shakirzyanov <mallluhuct@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Common\Plugin\Imagine\Filter\Basic;
use Common\Plugin\Imagine\Filter\FilterInterface;
use Common\Plugin\Imagine\Image\ImageInterface;
use Common\Plugin\Imagine\Image\BoxInterface;
/**
* A resize filter
*/
class Resize implements FilterInterface
{
/**
* @var BoxInterface
*/
private $size;
private $filter;
/**
* Constructs Resize filter with given width and height
*
* @param BoxInterface $size
* @param string $filter
*/
public function __construct(BoxInterface $size, $filter = ImageInterface::FILTER_UNDEFINED)
{
$this->size = $size;
$this->filter = $filter;
}
/**
* {@inheritdoc}
*/
public function apply(ImageInterface $image)
{
return $image->resize($this->size, $this->filter);
}
}
| mit |
barsgroup/barsup-core | src/pynch/service.py | 11075 | # coding: utf-8
"""Конструкции для реализация уровня сервисов."""
import operator
from datetime import date
from sqlalchemy.exc import IntegrityError
from sqlalchemy.orm.exc import NoResultFound
from sqlalchemy.sql import expression, operators
from pynch.adapter import DefaultAdapter
import pynch.exceptions as exc
def _mapping_property(f):
"""Декоратор, возвращающий объект sqlalchemy по составному имени поля. """
def wrapper(self, property, *args, **kwargs):
return f(self, self._model.get_field(property), *args, **kwargs)
return wrapper
def _filter(column, operator_text, value):
values = {
'like': {
'type': operators.ilike_op,
'format': '%{0}%'
},
'eq': operator.eq,
'lt': operator.lt,
'le': operator.le,
'gt': operator.gt,
'ge': operator.ge,
'in': operators.in_op
}
if operator_text not in values.keys():
raise exc.ValidationError(
'Operator "{0}" not supported. Available operators: [{1}]'.format(
operator_text,
', '.join(values.keys())
))
oper = values[operator_text]
if isinstance(oper, dict):
func = oper['type']
value = oper['format'].format(value)
else:
func = oper
return func(column, value)
def _sorter(direction):
values = {
'ASC': expression.asc,
'DESC': expression.desc
}
if direction not in values.keys():
raise exc.ValidationError(
('Direction "{0}" not supported. '
'Available directions: [{1}]').format(
direction,
', '.join(values.keys())
))
return values[direction]
def _delegate_proxy(name):
def wrap(self, *args, **kwargs):
return self.create_proxy(
self._callback,
self._model,
self.queue + [(name, args, kwargs)])
return wrap
def _delegate_service(name):
def wrap(self, *args, **kwargs):
return self._callback(name)(
self.query_builder(
self._model
).build(
self.queue
), *args, **kwargs)
return wrap
class _QuerySetBuilder:
apply_filter = staticmethod(_filter)
apply_sorter = staticmethod(lambda x, y: _sorter(y)(x))
def __init__(self, model):
self._model = model
self._qs = self._create_qs()
def _create_qs(self):
return self._model.create_query()
def build(self, queue):
for item, args, kwargs in queue:
getattr(self, item)(*args, **kwargs)
return self._qs
# FILTERS:
@_mapping_property
def _filter(self, property, operator, *args, **kwargs):
if args or kwargs:
if kwargs:
value = kwargs['value']
if args:
value = args[0]
self._qs = self._qs.filter(
self.apply_filter(
property,
operator,
Serializer.to_record(property, value)))
def _filters(self, filters):
for filter_ in filters:
self._filter(**filter_)
def _filter_by_id(self, id_):
self._filter('id', 'eq', id_)
# SORTERS:
@_mapping_property
def _sort(self, property, direction):
sort = self.apply_sorter(property, direction)
self._qs = self._qs.order_by(sort)
def _sorts(self, sorts):
for sort in sorts:
self._sort(**sort)
def _limit(self, offset, limit):
if offset is not None:
self._qs = self._qs.offset(offset)
if limit is not None:
self._qs = self._qs.limit(limit)
class _Proxy:
query_builder = _QuerySetBuilder
def __init__(self, callback, model, queue=None):
self._callback = callback
self._model = model
self.queue = queue or []
@classmethod
def create_proxy(cls, *args, **kwargs):
return cls(*args, **kwargs)
filter = _delegate_proxy('_filter')
filters = _delegate_proxy('_filters')
filter_by_id = _delegate_proxy('_filter_by_id')
sort = _delegate_proxy('_sort')
sorts = _delegate_proxy('_sorts')
limiter = _delegate_proxy('_limit')
get = _delegate_service('_get')
read = _delegate_service('_read')
exists = _delegate_service('_exists')
update = _delegate_service('_update')
delete = _delegate_service('_delete')
class Serializer:
@staticmethod
def to_record(field, value):
type_ = field.type
if issubclass(type_.python_type, date):
if len(str(value)) == 13: # timestamp c милисекундами
value /= 1000.0
value = date.fromtimestamp(float(value))
return value
@staticmethod
def from_record(value):
if isinstance(value, date):
return date.strftime(value, '%m/%d/%Y')
return value
class View:
serialization = staticmethod(Serializer.to_record)
deserialization = staticmethod(Serializer.from_record)
def __init__(self, adapters, current_model):
self.adapters = adapters
self._current_model = current_model
def from_record(self, params):
"""
Controller <- Model.
Правило работы:
Deserialization <- Include/Exclude <- Adapters
:param params:
:return:
"""
result = {}
for adapter in self.adapters:
result, params = adapter.from_record(result, params)
return {name: self.deserialization(value) for name, value in
result.items()}
def to_record(self, params):
"""
Controller -> Model.
Правило работы:
Include/Exclude -> Adapters -> Serialization -> Validation
:param params:
:return:
"""
# Преобразования на уровне адаптеров
result = {}
for adapter in self.adapters:
result, params = adapter.to_record(result, params)
new_params = {}
for name, value in result.items():
field = getattr(self._current_model, name)
# Серриализация перед валидацией
value = self.serialization(field, value)
# Умолчательная валидация на уровне типов значений
self.validation(field, value)
new_params[name] = value
return new_params
@staticmethod
def validation(field, value):
if value is None:
if field.expression.nullable:
return
else:
raise exc.NullValidationError(field)
if not isinstance(value, field.type.python_type):
raise exc.TypeValidationError(field, value)
if hasattr(field.type, 'length') and len(value) > field.type.length:
raise exc.LengthValidationError(field, value)
class Service:
"""Реализация CRUD сервиса."""
to_dict = staticmethod(lambda o: o._asdict())
def __init__(self, model, adapters, include=None, exclude=None):
""".
:param model: Ссылка на модель
:param adapters: Список адаптеров
:param include: Список полей для обязательного включения
:param exclude: Список полей для исключения
:return:
"""
self._model = model
adapters += (DefaultAdapter(model.current, include, exclude),)
self._adapter = View(adapters, model.current)
def __call__(self, model=None):
"""
Возвращает прокси-объект.
Для делегирования операций изменения и поиска
:param model: Ссылка на модель
:return:
"""
return _Proxy(
callback=lambda name: self.__getattribute__(name),
model=model or self._model)
def __getattr__(self, item):
"""
Возвращает прокси-объект.
Для делегирования операций изменения и поиска
:param item:
:return:
"""
proxy = _Proxy(
callback=lambda name: self.__getattribute__(name),
model=self._model)
return getattr(proxy, item)
def _get(self, qs):
# Операция получение объекта по кверисету
try:
record = qs.one()
except NoResultFound:
raise exc.NotFound()
return self._adapter.from_record(
self.to_dict(record)
)
def _read(self, qs):
# Операция получения списка объектов по кверисету
return map(
self._adapter.from_record,
map(self.to_dict, qs.all())
)
def _exists(self, qs):
# Операция проверки наличия объекта по кверисету
return self._model.exists(qs).scalar()
def _update(self, qs, **kwargs):
# Операция изменения объекта
if kwargs:
params = {}
for item, value in kwargs.items():
value = self._deserialize(item, value)
params[item] = value
qs.with_entities(self._model.current).update(
self._adapter.to_record(params)
)
return self._adapter.from_record(
self.to_dict(qs.one())
)
def _delete(self, qs):
# Операция удаления объекта
try:
qs.with_entities(self._model.current).delete()
except IntegrityError as e:
info = getattr(e, 'orig', None)
# Код ошибки 23503 в postgresql
# соответствует имеющимся ссылкам на запись
# http://www.postgresql.org/docs/8.2/static/errcodes-appendix.html
if info and getattr(info, 'pgcode', None) == '23503':
raise exc.BadRequest(
"Record can't be delete, because it has FK")
raise
# For create & update
def _deserialize(self, item, value):
# Преобразования dict -> model object
return Serializer.to_record(self._model.get_field(item), value)
def create(self, **kwargs):
"""
Операция создания объекта.
:param kwargs:
:return:
"""
obj = self._model.create_object(
**self._adapter.to_record(kwargs)
)
as_dict = {x.name: getattr(obj, x.name) for x in obj.__table__.columns}
return self._adapter.from_record(as_dict)
__all__ = ('Service',)
| mit |
zurcoin/zurcoin | src/qt/addresstablemodel.cpp | 14358 | // Copyright (c) 2011-2015 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "addresstablemodel.h"
#include "guiutil.h"
#include "walletmodel.h"
#include "base58.h"
#include "wallet/wallet.h"
#include <boost/foreach.hpp>
#include <QFont>
#include <QDebug>
const QString AddressTableModel::Send = "S";
const QString AddressTableModel::Receive = "R";
struct AddressTableEntry
{
enum Type {
Sending,
Receiving,
Hidden /* QSortFilterProxyModel will filter these out */
};
Type type;
QString label;
QString address;
AddressTableEntry() {}
AddressTableEntry(Type type, const QString &label, const QString &address):
type(type), label(label), address(address) {}
};
struct AddressTableEntryLessThan
{
bool operator()(const AddressTableEntry &a, const AddressTableEntry &b) const
{
return a.address < b.address;
}
bool operator()(const AddressTableEntry &a, const QString &b) const
{
return a.address < b;
}
bool operator()(const QString &a, const AddressTableEntry &b) const
{
return a < b.address;
}
};
/* Determine address type from address purpose */
static AddressTableEntry::Type translateTransactionType(const QString &strPurpose, bool isMine)
{
AddressTableEntry::Type addressType = AddressTableEntry::Hidden;
// "refund" addresses aren't shown, and change addresses aren't in mapAddressBook at all.
if (strPurpose == "send")
addressType = AddressTableEntry::Sending;
else if (strPurpose == "receive")
addressType = AddressTableEntry::Receiving;
else if (strPurpose == "unknown" || strPurpose == "") // if purpose not set, guess
addressType = (isMine ? AddressTableEntry::Receiving : AddressTableEntry::Sending);
return addressType;
}
// Private implementation
class AddressTablePriv
{
public:
CWallet *wallet;
QList<AddressTableEntry> cachedAddressTable;
AddressTableModel *parent;
AddressTablePriv(CWallet *wallet, AddressTableModel *parent):
wallet(wallet), parent(parent) {}
void refreshAddressTable()
{
cachedAddressTable.clear();
{
LOCK(wallet->cs_wallet);
BOOST_FOREACH(const PAIRTYPE(CTxDestination, CAddressBookData)& item, wallet->mapAddressBook)
{
const CBitcoinAddress& address = item.first;
bool fMine = IsMine(*wallet, address.Get());
AddressTableEntry::Type addressType = translateTransactionType(
QString::fromStdString(item.second.purpose), fMine);
const std::string& strName = item.second.name;
cachedAddressTable.append(AddressTableEntry(addressType,
QString::fromStdString(strName),
QString::fromStdString(address.ToString())));
}
}
// qLowerBound() and qUpperBound() require our cachedAddressTable list to be sorted in asc order
// Even though the map is already sorted this re-sorting step is needed because the originating map
// is sorted by binary address, not by base58() address.
qSort(cachedAddressTable.begin(), cachedAddressTable.end(), AddressTableEntryLessThan());
}
void updateEntry(const QString &address, const QString &label, bool isMine, const QString &purpose, int status)
{
// Find address / label in model
QList<AddressTableEntry>::iterator lower = qLowerBound(
cachedAddressTable.begin(), cachedAddressTable.end(), address, AddressTableEntryLessThan());
QList<AddressTableEntry>::iterator upper = qUpperBound(
cachedAddressTable.begin(), cachedAddressTable.end(), address, AddressTableEntryLessThan());
int lowerIndex = (lower - cachedAddressTable.begin());
int upperIndex = (upper - cachedAddressTable.begin());
bool inModel = (lower != upper);
AddressTableEntry::Type newEntryType = translateTransactionType(purpose, isMine);
switch(status)
{
case CT_NEW:
if(inModel)
{
qWarning() << "AddressTablePriv::updateEntry: Warning: Got CT_NEW, but entry is already in model";
break;
}
parent->beginInsertRows(QModelIndex(), lowerIndex, lowerIndex);
cachedAddressTable.insert(lowerIndex, AddressTableEntry(newEntryType, label, address));
parent->endInsertRows();
break;
case CT_UPDATED:
if(!inModel)
{
qWarning() << "AddressTablePriv::updateEntry: Warning: Got CT_UPDATED, but entry is not in model";
break;
}
lower->type = newEntryType;
lower->label = label;
parent->emitDataChanged(lowerIndex);
break;
case CT_DELETED:
if(!inModel)
{
qWarning() << "AddressTablePriv::updateEntry: Warning: Got CT_DELETED, but entry is not in model";
break;
}
parent->beginRemoveRows(QModelIndex(), lowerIndex, upperIndex-1);
cachedAddressTable.erase(lower, upper);
parent->endRemoveRows();
break;
}
}
int size()
{
return cachedAddressTable.size();
}
AddressTableEntry *index(int idx)
{
if(idx >= 0 && idx < cachedAddressTable.size())
{
return &cachedAddressTable[idx];
}
else
{
return 0;
}
}
};
AddressTableModel::AddressTableModel(CWallet *wallet, WalletModel *parent) :
QAbstractTableModel(parent),walletModel(parent),wallet(wallet),priv(0)
{
columns << tr("Label") << tr("Address");
priv = new AddressTablePriv(wallet, this);
priv->refreshAddressTable();
}
AddressTableModel::~AddressTableModel()
{
delete priv;
}
int AddressTableModel::rowCount(const QModelIndex &parent) const
{
Q_UNUSED(parent);
return priv->size();
}
int AddressTableModel::columnCount(const QModelIndex &parent) const
{
Q_UNUSED(parent);
return columns.length();
}
QVariant AddressTableModel::data(const QModelIndex &index, int role) const
{
if(!index.isValid())
return QVariant();
AddressTableEntry *rec = static_cast<AddressTableEntry*>(index.internalPointer());
if(role == Qt::DisplayRole || role == Qt::EditRole)
{
switch(index.column())
{
case Label:
if(rec->label.isEmpty() && role == Qt::DisplayRole)
{
return tr("(no label)");
}
else
{
return rec->label;
}
case Address:
return rec->address;
}
}
else if (role == Qt::FontRole)
{
QFont font;
if(index.column() == Address)
{
font = GUIUtil::fixedPitchFont();
}
return font;
}
else if (role == TypeRole)
{
switch(rec->type)
{
case AddressTableEntry::Sending:
return Send;
case AddressTableEntry::Receiving:
return Receive;
default: break;
}
}
return QVariant();
}
bool AddressTableModel::setData(const QModelIndex &index, const QVariant &value, int role)
{
if(!index.isValid())
return false;
AddressTableEntry *rec = static_cast<AddressTableEntry*>(index.internalPointer());
std::string strPurpose = (rec->type == AddressTableEntry::Sending ? "send" : "receive");
editStatus = OK;
if(role == Qt::EditRole)
{
LOCK(wallet->cs_wallet); /* For SetAddressBook / DelAddressBook */
CTxDestination curAddress = CBitcoinAddress(rec->address.toStdString()).Get();
if(index.column() == Label)
{
// Do nothing, if old label == new label
if(rec->label == value.toString())
{
editStatus = NO_CHANGES;
return false;
}
wallet->SetAddressBook(curAddress, value.toString().toStdString(), strPurpose);
} else if(index.column() == Address) {
CTxDestination newAddress = CBitcoinAddress(value.toString().toStdString()).Get();
// Refuse to set invalid address, set error status and return false
if(boost::get<CNoDestination>(&newAddress))
{
editStatus = INVALID_ADDRESS;
return false;
}
// Do nothing, if old address == new address
else if(newAddress == curAddress)
{
editStatus = NO_CHANGES;
return false;
}
// Check for duplicate addresses to prevent accidental deletion of addresses, if you try
// to paste an existing address over another address (with a different label)
else if(wallet->mapAddressBook.count(newAddress))
{
editStatus = DUPLICATE_ADDRESS;
return false;
}
// Double-check that we're not overwriting a receiving address
else if(rec->type == AddressTableEntry::Sending)
{
// Remove old entry
wallet->DelAddressBook(curAddress);
// Add new entry with new address
wallet->SetAddressBook(newAddress, rec->label.toStdString(), strPurpose);
}
}
return true;
}
return false;
}
QVariant AddressTableModel::headerData(int section, Qt::Orientation orientation, int role) const
{
if(orientation == Qt::Horizontal)
{
if(role == Qt::DisplayRole && section < columns.size())
{
return columns[section];
}
}
return QVariant();
}
Qt::ItemFlags AddressTableModel::flags(const QModelIndex &index) const
{
if(!index.isValid())
return 0;
AddressTableEntry *rec = static_cast<AddressTableEntry*>(index.internalPointer());
Qt::ItemFlags retval = Qt::ItemIsSelectable | Qt::ItemIsEnabled;
// Can edit address and label for sending addresses,
// and only label for receiving addresses.
if(rec->type == AddressTableEntry::Sending ||
(rec->type == AddressTableEntry::Receiving && index.column()==Label))
{
retval |= Qt::ItemIsEditable;
}
return retval;
}
QModelIndex AddressTableModel::index(int row, int column, const QModelIndex &parent) const
{
Q_UNUSED(parent);
AddressTableEntry *data = priv->index(row);
if(data)
{
return createIndex(row, column, priv->index(row));
}
else
{
return QModelIndex();
}
}
void AddressTableModel::updateEntry(const QString &address,
const QString &label, bool isMine, const QString &purpose, int status)
{
// Update address book model from Zurcoin core
priv->updateEntry(address, label, isMine, purpose, status);
}
QString AddressTableModel::addRow(const QString &type, const QString &label, const QString &address)
{
std::string strLabel = label.toStdString();
std::string strAddress = address.toStdString();
editStatus = OK;
if(type == Send)
{
if(!walletModel->validateAddress(address))
{
editStatus = INVALID_ADDRESS;
return QString();
}
// Check for duplicate addresses
{
LOCK(wallet->cs_wallet);
if(wallet->mapAddressBook.count(CBitcoinAddress(strAddress).Get()))
{
editStatus = DUPLICATE_ADDRESS;
return QString();
}
}
}
else if(type == Receive)
{
// Generate a new address to associate with given label
CPubKey newKey;
if(!wallet->GetKeyFromPool(newKey))
{
WalletModel::UnlockContext ctx(walletModel->requestUnlock());
if(!ctx.isValid())
{
// Unlock wallet failed or was cancelled
editStatus = WALLET_UNLOCK_FAILURE;
return QString();
}
if(!wallet->GetKeyFromPool(newKey))
{
editStatus = KEY_GENERATION_FAILURE;
return QString();
}
}
strAddress = CBitcoinAddress(newKey.GetID()).ToString();
}
else
{
return QString();
}
// Add entry
{
LOCK(wallet->cs_wallet);
wallet->SetAddressBook(CBitcoinAddress(strAddress).Get(), strLabel,
(type == Send ? "send" : "receive"));
}
return QString::fromStdString(strAddress);
}
bool AddressTableModel::removeRows(int row, int count, const QModelIndex &parent)
{
Q_UNUSED(parent);
AddressTableEntry *rec = priv->index(row);
if(count != 1 || !rec || rec->type == AddressTableEntry::Receiving)
{
// Can only remove one row at a time, and cannot remove rows not in model.
// Also refuse to remove receiving addresses.
return false;
}
{
LOCK(wallet->cs_wallet);
wallet->DelAddressBook(CBitcoinAddress(rec->address.toStdString()).Get());
}
return true;
}
/* Look up label for address in address book, if not found return empty string.
*/
QString AddressTableModel::labelForAddress(const QString &address) const
{
{
LOCK(wallet->cs_wallet);
CBitcoinAddress address_parsed(address.toStdString());
std::map<CTxDestination, CAddressBookData>::iterator mi = wallet->mapAddressBook.find(address_parsed.Get());
if (mi != wallet->mapAddressBook.end())
{
return QString::fromStdString(mi->second.name);
}
}
return QString();
}
int AddressTableModel::lookupAddress(const QString &address) const
{
QModelIndexList lst = match(index(0, Address, QModelIndex()),
Qt::EditRole, address, 1, Qt::MatchExactly);
if(lst.isEmpty())
{
return -1;
}
else
{
return lst.at(0).row();
}
}
void AddressTableModel::emitDataChanged(int idx)
{
Q_EMIT dataChanged(index(idx, 0, QModelIndex()), index(idx, columns.length()-1, QModelIndex()));
}
| mit |
eloquent/phony | test/src/Test/TestInterfaceWithSelfReturnType.php | 330 | <?php
declare(strict_types=1);
namespace Eloquent\Phony\Test;
interface TestInterfaceWithSelfReturnType
{
public static function staticMethod(): self;
public static function __callStatic($name, array $arguments): self;
public function method(): self;
public function __call($name, array $arguments): self;
}
| mit |
pootzko/InfluxData.Net | InfluxData.Net.InfluxDb/RequestClients/InfluxDbRequestClient_v_0_9_6.cs | 334 | using InfluxData.Net.Common.Infrastructure;
namespace InfluxData.Net.InfluxDb.RequestClients
{
public class InfluxDbRequestClient_v_0_9_6 : InfluxDbRequestClient_v_1_0_0
{
public InfluxDbRequestClient_v_0_9_6(IInfluxDbClientConfiguration configuration)
: base(configuration)
{
}
}
} | mit |
webtown-php/KunstmaanExtensionBundle | src/HttpCache/Manager.php | 1347 | <?php
/**
* Created by IntelliJ IDEA.
* User: chris
* Date: 2016.04.20.
* Time: 9:35
*/
namespace Webtown\KunstmaanExtensionBundle\HttpCache;
use FOS\HttpCacheBundle\CacheManager;
use Symfony\Component\Filesystem\Filesystem;
class Manager
{
/**
* @var string
*/
protected $cacheDir;
/**
* @var Filesystem
*/
protected $filesystem;
/**
* For the future...
*
* @var CacheManager
*/
protected $fosHttpCacheManager;
/**
* Manager constructor.
* @param string $cacheDir
* @param Filesystem $filesystem
* @param CacheManager $fosHttpCacheManager
*/
public function __construct($cacheDir, Filesystem $filesystem, CacheManager $fosHttpCacheManager = null)
{
$this->cacheDir = $cacheDir;
$this->filesystem = $filesystem;
$this->fosHttpCacheManager = $fosHttpCacheManager;
}
public function forcePurgeAll()
{
$cacheDir = $this->cacheDir . DIRECTORY_SEPARATOR . 'http_cache';
if ($this->filesystem->exists($cacheDir) && is_dir($cacheDir)) {
$this->filesystem->remove(new \FilesystemIterator($cacheDir));
}
if (defined('apc_clear_cache')) {
apc_clear_cache();
apc_clear_cache('user');
apc_clear_cache('opcode');
}
}
}
| mit |
LeandroSJN/CrashBall | Source/src/Engine/GameObject.cpp | 107 | #include "GameObject.h"
GameObject::GameObject()
{
//ctor
}
GameObject::~GameObject()
{
//dtor
}
| mit |
knomedia/js-store | lib/create_collection_store.js | 2707 | var createStore = require('./create_store');
var findIndex = require('./utils/find_index');
var mergeObject = require('./utils/merge_object');
var findById = require('./utils/find_by_id');
module.exports = function(collectionKey, syncLocally) {
var buildInitialState = function() {
var initialState = {};
initialState[collectionKey] = [];
return initialState;
}
var getId = function getId(obj) {
if (obj && obj.id) {
id = obj.id;
} else {
id = obj;
}
return id
}
var getCollection = function getCollection() {
return collectionStore.getState()[collectionKey]
}
var setCollection = function setCollection(collection) {
let results = {}
results[collectionKey] = collection
return collectionStore.setState(results)
}
var collectionStore = createStore(buildInitialState());
collectionStore.findById = function(id, allowNonIntIds) {
var found;
if (!allowNonIntIds) {
id = parseInt(id, 10);
}
return findById(collectionStore.getState()[collectionKey], id)
}
collectionStore.findIndex = function(obj, allowNonIntIds) {
let id = getId(obj)
if (!allowNonIntIds) {
id = parseInt(id, 10);
}
return findIndex(collectionStore.getState()[collectionKey], id);
}
collectionStore.mergeObject = function(item) {
mergeObject(collectionStore, collectionKey, item);
}
// save resetState, and pass in new state for collection
var ogResetState = collectionStore.resetState;
collectionStore.resetState = function(newState){
var state = newState || buildInitialState();
ogResetState.call(collectionStore, state);
}
collectionStore.add = function(item) {
let collection = getCollection()
collection.push(item)
return setCollection(collection)
}
collectionStore.replace = function(item) {
let collection = getCollection()
let idx = findIndex(collection, getId(item))
if (idx >= 0) {
collection[idx] = item
setCollection(collection)
return item
} else {
return undefined
}
}
collectionStore.upsert = function(item) {
let collection = getCollection()
let idx = findIndex(collection, getId(item))
if (idx >= 0) {
collectionStore.replace(item)
} else {
collectionStore.add(item)
}
}
collectionStore.destroy = function(id) {
let collection = getCollection()
let idx = findIndex(collection, getId(id))
if (idx >= 0) {
collection.splice(idx, 1)
return id
} else {
return undefined
}
}
if (syncLocally) {
var localSync = require('./local_sync');
localSync(collectionKey, collectionStore);
}
return collectionStore;
};
| mit |
remp2020/remp | Beam/database/seeders/ArticleSeeder.php | 1407 | <?php
namespace Database\Seeders;
use Illuminate\Database\Seeder;
class ArticleSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run(\Faker\Generator $faker)
{
/** @var \App\Property $property */
$properties = \App\Property::all();
$sections = \App\Section::factory()->count(3)->create();
$tags = \App\Model\Tag::factory()->count(10)->create();
/** @var \Illuminate\Database\Eloquent\Collection $articles */
$articles = \App\Article::factory()->count(50)->create([
'property_uuid' => $properties->random()->uuid,
])->each(function (\App\Article $article) use ($sections, $tags) {
$article->sections()->save($sections[rand(0, count($sections)-1)]);
$article->tags()->save($tags[rand(0, count($tags)-1)]);
});
$authors = \App\Author::factory()->count(5)->create();
$articles->each(function (\App\Article $article) use ($authors) {
$article->authors()->attach($authors->random());
});
$articles->each(function (\App\Article $article) use ($faker) {
$article->conversions()->saveMany(
\App\Conversion::factory()->count($faker->numberBetween(5,20))->make([
'article_id' => $article->id,
])
);
});
}
}
| mit |
sebpiq/pychedelic | pychedelic/core/errors.py | 355 | class PcmDecodeError(Exception):
"""
Raised when attempt to decode pcm string has failed
"""
pass
class WavFormatError(Exception):
"""
Raised when attempting to read a wave file failed.
"""
pass
class WavSizeLimitError(Exception):
"""
Raised when the size limit for wav files has been reached.
"""
pass
| mit |
bashiransari/Restract | src/Restract/Core/Proxy/IProxyInterceptor.cs | 244 | namespace Restract.Core.Proxy
{
using System.Reflection;
public interface IProxyInterceptor
{
object OnMethodCall(MethodInfo mi, object[] args);
RestClientConfiguration RestClientConfiguration { get; set; }
}
} | mit |
e7d/neap | api/module/Application/test/ApplicationTest/Hydrator/Panel/PanelHydratorTest.php | 1008 | <?php
/**
* Neap (http://neap.io/)
*
* @link http://github.com/e7d/neap for the canonical source repository
* @copyright Copyright (c) 2016 Michaël "e7d" Ferrand (http://github.com/e7d)
* @license https://github.com/e7d/neap/blob/master/LICENSE.txt The MIT License
*/
namespace ApplicationTest\Hydrator\Panel;
use Zend\Test\PHPUnit\Controller\AbstractControllerTestCase;
class PanelHydratorTest extends AbstractControllerTestCase
{
private $serviceManager;
public function setUp()
{
$this->setApplicationConfig(
include './config/tests.config.php'
);
parent::setUp();
$this->serviceManager = $this->getApplicationServiceLocator();
$this->serviceManager->setAllowOverride(true);
}
public function testClassType()
{
$panelHydrator = $this->serviceManager->get('Application\Hydrator\Panel\PanelHydrator');
$this->assertInstanceOf('Application\Hydrator\Panel\PanelHydrator', $panelHydrator);
}
}
| mit |
blambeau/wlang | spec/unit/dialect/test_evaluate.rb | 1363 | require 'spec_helper'
module WLang
describe Dialect, 'evaluate' do
let(:struct){ Struct.new(:who) }
let(:dialect){ Dialect.new }
def with_scope(*args, &bl)
dialect.with_scope(*args, &bl)
end
def evaluate(*args, &bl)
dialect.evaluate(*args, &bl)
end
it 'works with a hash' do
with_scope({:who => "World"}) do
evaluate("who").should eq("World")
evaluate(:who).should eq("World")
end
end
it 'works with a struct' do
with_scope(struct.new("World")) do
evaluate("who").should eq("World")
evaluate(:who).should eq("World")
end
end
it 'uses the hash in priority' do
with_scope({:keys => [1,2,3]}) do
evaluate("keys").should eq([1,2,3])
end
end
it 'falls back to send' do
with_scope({:who => "World"}) do
evaluate("keys").should eq([:who])
end
end
it 'supports a default value' do
evaluate("who", 12).should eq(12)
evaluate("who", nil).should be_nil
end
it 'supports a default value through a Proc' do
evaluate("who"){ 12 }.should eq(12)
evaluate("who"){ nil }.should be_nil
end
it 'raises a NameError when not found' do
lambda{ evaluate("who") }.should raise_error(NameError)
end
end # describe Dialect, 'evaluate'
end # module WLang
| mit |
wjh/zif | vendor/github.com/wjh/zest/vendor/github.com/bitly/go-nsq/conn.go | 17778 | package nsq
import (
"bufio"
"bytes"
"compress/flate"
"crypto/tls"
"encoding/json"
"errors"
"fmt"
"io"
"net"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/golang/snappy"
)
// IdentifyResponse represents the metadata
// returned from an IDENTIFY command to nsqd
type IdentifyResponse struct {
MaxRdyCount int64 `json:"max_rdy_count"`
TLSv1 bool `json:"tls_v1"`
Deflate bool `json:"deflate"`
Snappy bool `json:"snappy"`
AuthRequired bool `json:"auth_required"`
}
// AuthResponse represents the metadata
// returned from an AUTH command to nsqd
type AuthResponse struct {
Identity string `json:"identity"`
IdentityUrl string `json:"identity_url"`
PermissionCount int64 `json:"permission_count"`
}
type msgResponse struct {
msg *Message
cmd *Command
success bool
backoff bool
}
// Conn represents a connection to nsqd
//
// Conn exposes a set of callbacks for the
// various events that occur on a connection
type Conn struct {
// 64bit atomic vars need to be first for proper alignment on 32bit platforms
messagesInFlight int64
maxRdyCount int64
rdyCount int64
lastRdyCount int64
lastMsgTimestamp int64
mtx sync.Mutex
config *Config
conn *net.TCPConn
tlsConn *tls.Conn
addr string
delegate ConnDelegate
logger logger
logLvl LogLevel
logFmt string
logGuard sync.RWMutex
r io.Reader
w io.Writer
cmdChan chan *Command
msgResponseChan chan *msgResponse
exitChan chan int
drainReady chan int
closeFlag int32
stopper sync.Once
wg sync.WaitGroup
readLoopRunning int32
}
// NewConn returns a new Conn instance
func NewConn(addr string, config *Config, delegate ConnDelegate) *Conn {
if !config.initialized {
panic("Config must be created with NewConfig()")
}
return &Conn{
addr: addr,
config: config,
delegate: delegate,
maxRdyCount: 2500,
lastMsgTimestamp: time.Now().UnixNano(),
cmdChan: make(chan *Command),
msgResponseChan: make(chan *msgResponse),
exitChan: make(chan int),
drainReady: make(chan int),
}
}
// SetLogger assigns the logger to use as well as a level.
//
// The format parameter is expected to be a printf compatible string with
// a single %s argument. This is useful if you want to provide additional
// context to the log messages that the connection will print, the default
// is '(%s)'.
//
// The logger parameter is an interface that requires the following
// method to be implemented (such as the the stdlib log.Logger):
//
// Output(calldepth int, s string)
//
func (c *Conn) SetLogger(l logger, lvl LogLevel, format string) {
c.logGuard.Lock()
defer c.logGuard.Unlock()
c.logger = l
c.logLvl = lvl
c.logFmt = format
if c.logFmt == "" {
c.logFmt = "(%s)"
}
}
func (c *Conn) getLogger() (logger, LogLevel, string) {
c.logGuard.RLock()
defer c.logGuard.RUnlock()
return c.logger, c.logLvl, c.logFmt
}
// Connect dials and bootstraps the nsqd connection
// (including IDENTIFY) and returns the IdentifyResponse
func (c *Conn) Connect() (*IdentifyResponse, error) {
dialer := &net.Dialer{
LocalAddr: c.config.LocalAddr,
Timeout: c.config.DialTimeout,
}
conn, err := dialer.Dial("tcp", c.addr)
if err != nil {
return nil, err
}
c.conn = conn.(*net.TCPConn)
c.r = conn
c.w = conn
_, err = c.Write(MagicV2)
if err != nil {
c.Close()
return nil, fmt.Errorf("[%s] failed to write magic - %s", c.addr, err)
}
resp, err := c.identify()
if err != nil {
return nil, err
}
if resp != nil && resp.AuthRequired {
if c.config.AuthSecret == "" {
c.log(LogLevelError, "Auth Required")
return nil, errors.New("Auth Required")
}
err := c.auth(c.config.AuthSecret)
if err != nil {
c.log(LogLevelError, "Auth Failed %s", err)
return nil, err
}
}
c.wg.Add(2)
atomic.StoreInt32(&c.readLoopRunning, 1)
go c.readLoop()
go c.writeLoop()
return resp, nil
}
// Close idempotently initiates connection close
func (c *Conn) Close() error {
atomic.StoreInt32(&c.closeFlag, 1)
if c.conn != nil && atomic.LoadInt64(&c.messagesInFlight) == 0 {
return c.conn.CloseRead()
}
return nil
}
// IsClosing indicates whether or not the
// connection is currently in the processing of
// gracefully closing
func (c *Conn) IsClosing() bool {
return atomic.LoadInt32(&c.closeFlag) == 1
}
// RDY returns the current RDY count
func (c *Conn) RDY() int64 {
return atomic.LoadInt64(&c.rdyCount)
}
// LastRDY returns the previously set RDY count
func (c *Conn) LastRDY() int64 {
return atomic.LoadInt64(&c.lastRdyCount)
}
// SetRDY stores the specified RDY count
func (c *Conn) SetRDY(rdy int64) {
atomic.StoreInt64(&c.rdyCount, rdy)
atomic.StoreInt64(&c.lastRdyCount, rdy)
}
// MaxRDY returns the nsqd negotiated maximum
// RDY count that it will accept for this connection
func (c *Conn) MaxRDY() int64 {
return c.maxRdyCount
}
// LastMessageTime returns a time.Time representing
// the time at which the last message was received
func (c *Conn) LastMessageTime() time.Time {
return time.Unix(0, atomic.LoadInt64(&c.lastMsgTimestamp))
}
// RemoteAddr returns the configured destination nsqd address
func (c *Conn) RemoteAddr() net.Addr {
return c.conn.RemoteAddr()
}
// String returns the fully-qualified address
func (c *Conn) String() string {
return c.addr
}
// Read performs a deadlined read on the underlying TCP connection
func (c *Conn) Read(p []byte) (int, error) {
c.conn.SetReadDeadline(time.Now().Add(c.config.ReadTimeout))
return c.r.Read(p)
}
// Write performs a deadlined write on the underlying TCP connection
func (c *Conn) Write(p []byte) (int, error) {
c.conn.SetWriteDeadline(time.Now().Add(c.config.WriteTimeout))
return c.w.Write(p)
}
// WriteCommand is a goroutine safe method to write a Command
// to this connection, and flush.
func (c *Conn) WriteCommand(cmd *Command) error {
c.mtx.Lock()
_, err := cmd.WriteTo(c)
if err != nil {
goto exit
}
err = c.Flush()
exit:
c.mtx.Unlock()
if err != nil {
c.log(LogLevelError, "IO error - %s", err)
c.delegate.OnIOError(c, err)
}
return err
}
type flusher interface {
Flush() error
}
// Flush writes all buffered data to the underlying TCP connection
func (c *Conn) Flush() error {
if f, ok := c.w.(flusher); ok {
return f.Flush()
}
return nil
}
func (c *Conn) identify() (*IdentifyResponse, error) {
ci := make(map[string]interface{})
ci["client_id"] = c.config.ClientID
ci["hostname"] = c.config.Hostname
ci["user_agent"] = c.config.UserAgent
ci["short_id"] = c.config.ClientID // deprecated
ci["long_id"] = c.config.Hostname // deprecated
ci["tls_v1"] = c.config.TlsV1
ci["deflate"] = c.config.Deflate
ci["deflate_level"] = c.config.DeflateLevel
ci["snappy"] = c.config.Snappy
ci["feature_negotiation"] = true
if c.config.HeartbeatInterval == -1 {
ci["heartbeat_interval"] = -1
} else {
ci["heartbeat_interval"] = int64(c.config.HeartbeatInterval / time.Millisecond)
}
ci["sample_rate"] = c.config.SampleRate
ci["output_buffer_size"] = c.config.OutputBufferSize
if c.config.OutputBufferTimeout == -1 {
ci["output_buffer_timeout"] = -1
} else {
ci["output_buffer_timeout"] = int64(c.config.OutputBufferTimeout / time.Millisecond)
}
ci["msg_timeout"] = int64(c.config.MsgTimeout / time.Millisecond)
cmd, err := Identify(ci)
if err != nil {
return nil, ErrIdentify{err.Error()}
}
err = c.WriteCommand(cmd)
if err != nil {
return nil, ErrIdentify{err.Error()}
}
frameType, data, err := ReadUnpackedResponse(c)
if err != nil {
return nil, ErrIdentify{err.Error()}
}
if frameType == FrameTypeError {
return nil, ErrIdentify{string(data)}
}
// check to see if the server was able to respond w/ capabilities
// i.e. it was a JSON response
if data[0] != '{' {
return nil, nil
}
resp := &IdentifyResponse{}
err = json.Unmarshal(data, resp)
if err != nil {
return nil, ErrIdentify{err.Error()}
}
c.log(LogLevelDebug, "IDENTIFY response: %+v", resp)
c.maxRdyCount = resp.MaxRdyCount
if resp.TLSv1 {
c.log(LogLevelInfo, "upgrading to TLS")
err := c.upgradeTLS(c.config.TlsConfig)
if err != nil {
return nil, ErrIdentify{err.Error()}
}
}
if resp.Deflate {
c.log(LogLevelInfo, "upgrading to Deflate")
err := c.upgradeDeflate(c.config.DeflateLevel)
if err != nil {
return nil, ErrIdentify{err.Error()}
}
}
if resp.Snappy {
c.log(LogLevelInfo, "upgrading to Snappy")
err := c.upgradeSnappy()
if err != nil {
return nil, ErrIdentify{err.Error()}
}
}
// now that connection is bootstrapped, enable read buffering
// (and write buffering if it's not already capable of Flush())
c.r = bufio.NewReader(c.r)
if _, ok := c.w.(flusher); !ok {
c.w = bufio.NewWriter(c.w)
}
return resp, nil
}
func (c *Conn) upgradeTLS(tlsConf *tls.Config) error {
// create a local copy of the config to set ServerName for this connection
var conf tls.Config
if tlsConf != nil {
conf = *tlsConf
}
host, _, err := net.SplitHostPort(c.addr)
if err != nil {
return err
}
conf.ServerName = host
c.tlsConn = tls.Client(c.conn, &conf)
err = c.tlsConn.Handshake()
if err != nil {
return err
}
c.r = c.tlsConn
c.w = c.tlsConn
frameType, data, err := ReadUnpackedResponse(c)
if err != nil {
return err
}
if frameType != FrameTypeResponse || !bytes.Equal(data, []byte("OK")) {
return errors.New("invalid response from TLS upgrade")
}
return nil
}
func (c *Conn) upgradeDeflate(level int) error {
conn := net.Conn(c.conn)
if c.tlsConn != nil {
conn = c.tlsConn
}
fw, _ := flate.NewWriter(conn, level)
c.r = flate.NewReader(conn)
c.w = fw
frameType, data, err := ReadUnpackedResponse(c)
if err != nil {
return err
}
if frameType != FrameTypeResponse || !bytes.Equal(data, []byte("OK")) {
return errors.New("invalid response from Deflate upgrade")
}
return nil
}
func (c *Conn) upgradeSnappy() error {
conn := net.Conn(c.conn)
if c.tlsConn != nil {
conn = c.tlsConn
}
c.r = snappy.NewReader(conn)
c.w = snappy.NewWriter(conn)
frameType, data, err := ReadUnpackedResponse(c)
if err != nil {
return err
}
if frameType != FrameTypeResponse || !bytes.Equal(data, []byte("OK")) {
return errors.New("invalid response from Snappy upgrade")
}
return nil
}
func (c *Conn) auth(secret string) error {
cmd, err := Auth(secret)
if err != nil {
return err
}
err = c.WriteCommand(cmd)
if err != nil {
return err
}
frameType, data, err := ReadUnpackedResponse(c)
if err != nil {
return err
}
if frameType == FrameTypeError {
return errors.New("Error authenticating " + string(data))
}
resp := &AuthResponse{}
err = json.Unmarshal(data, resp)
if err != nil {
return err
}
c.log(LogLevelInfo, "Auth accepted. Identity: %q %s Permissions: %d",
resp.Identity, resp.IdentityUrl, resp.PermissionCount)
return nil
}
func (c *Conn) readLoop() {
delegate := &connMessageDelegate{c}
for {
if atomic.LoadInt32(&c.closeFlag) == 1 {
goto exit
}
frameType, data, err := ReadUnpackedResponse(c)
if err != nil {
if err == io.EOF && atomic.LoadInt32(&c.closeFlag) == 1 {
goto exit
}
if !strings.Contains(err.Error(), "use of closed network connection") {
c.log(LogLevelError, "IO error - %s", err)
c.delegate.OnIOError(c, err)
}
goto exit
}
if frameType == FrameTypeResponse && bytes.Equal(data, []byte("_heartbeat_")) {
c.log(LogLevelDebug, "heartbeat received")
c.delegate.OnHeartbeat(c)
err := c.WriteCommand(Nop())
if err != nil {
c.log(LogLevelError, "IO error - %s", err)
c.delegate.OnIOError(c, err)
goto exit
}
continue
}
switch frameType {
case FrameTypeResponse:
c.delegate.OnResponse(c, data)
case FrameTypeMessage:
msg, err := DecodeMessage(data)
if err != nil {
c.log(LogLevelError, "IO error - %s", err)
c.delegate.OnIOError(c, err)
goto exit
}
msg.Delegate = delegate
msg.NSQDAddress = c.String()
atomic.AddInt64(&c.rdyCount, -1)
atomic.AddInt64(&c.messagesInFlight, 1)
atomic.StoreInt64(&c.lastMsgTimestamp, time.Now().UnixNano())
c.delegate.OnMessage(c, msg)
case FrameTypeError:
c.log(LogLevelError, "protocol error - %s", data)
c.delegate.OnError(c, data)
default:
c.log(LogLevelError, "IO error - %s", err)
c.delegate.OnIOError(c, fmt.Errorf("unknown frame type %d", frameType))
}
}
exit:
atomic.StoreInt32(&c.readLoopRunning, 0)
// start the connection close
messagesInFlight := atomic.LoadInt64(&c.messagesInFlight)
if messagesInFlight == 0 {
// if we exited readLoop with no messages in flight
// we need to explicitly trigger the close because
// writeLoop won't
c.close()
} else {
c.log(LogLevelWarning, "delaying close, %d outstanding messages", messagesInFlight)
}
c.wg.Done()
c.log(LogLevelInfo, "readLoop exiting")
}
func (c *Conn) writeLoop() {
for {
select {
case <-c.exitChan:
c.log(LogLevelInfo, "breaking out of writeLoop")
// Indicate drainReady because we will not pull any more off msgResponseChan
close(c.drainReady)
goto exit
case cmd := <-c.cmdChan:
err := c.WriteCommand(cmd)
if err != nil {
c.log(LogLevelError, "error sending command %s - %s", cmd, err)
c.close()
continue
}
case resp := <-c.msgResponseChan:
// Decrement this here so it is correct even if we can't respond to nsqd
msgsInFlight := atomic.AddInt64(&c.messagesInFlight, -1)
if resp.success {
c.log(LogLevelDebug, "FIN %s", resp.msg.ID)
c.delegate.OnMessageFinished(c, resp.msg)
c.delegate.OnResume(c)
} else {
c.log(LogLevelDebug, "REQ %s", resp.msg.ID)
c.delegate.OnMessageRequeued(c, resp.msg)
if resp.backoff {
c.delegate.OnBackoff(c)
} else {
c.delegate.OnContinue(c)
}
}
err := c.WriteCommand(resp.cmd)
if err != nil {
c.log(LogLevelError, "error sending command %s - %s", resp.cmd, err)
c.close()
continue
}
if msgsInFlight == 0 &&
atomic.LoadInt32(&c.closeFlag) == 1 {
c.close()
continue
}
}
}
exit:
c.wg.Done()
c.log(LogLevelInfo, "writeLoop exiting")
}
func (c *Conn) close() {
// a "clean" connection close is orchestrated as follows:
//
// 1. CLOSE cmd sent to nsqd
// 2. CLOSE_WAIT response received from nsqd
// 3. set c.closeFlag
// 4. readLoop() exits
// a. if messages-in-flight > 0 delay close()
// i. writeLoop() continues receiving on c.msgResponseChan chan
// x. when messages-in-flight == 0 call close()
// b. else call close() immediately
// 5. c.exitChan close
// a. writeLoop() exits
// i. c.drainReady close
// 6a. launch cleanup() goroutine (we're racing with intraprocess
// routed messages, see comments below)
// a. wait on c.drainReady
// b. loop and receive on c.msgResponseChan chan
// until messages-in-flight == 0
// i. ensure that readLoop has exited
// 6b. launch waitForCleanup() goroutine
// b. wait on waitgroup (covers readLoop() and writeLoop()
// and cleanup goroutine)
// c. underlying TCP connection close
// d. trigger Delegate OnClose()
//
c.stopper.Do(func() {
c.log(LogLevelInfo, "beginning close")
close(c.exitChan)
c.conn.CloseRead()
c.wg.Add(1)
go c.cleanup()
go c.waitForCleanup()
})
}
func (c *Conn) cleanup() {
<-c.drainReady
ticker := time.NewTicker(100 * time.Millisecond)
lastWarning := time.Now()
// writeLoop has exited, drain any remaining in flight messages
for {
// we're racing with readLoop which potentially has a message
// for handling so infinitely loop until messagesInFlight == 0
// and readLoop has exited
var msgsInFlight int64
select {
case <-c.msgResponseChan:
msgsInFlight = atomic.AddInt64(&c.messagesInFlight, -1)
case <-ticker.C:
msgsInFlight = atomic.LoadInt64(&c.messagesInFlight)
}
if msgsInFlight > 0 {
if time.Now().Sub(lastWarning) > time.Second {
c.log(LogLevelWarning, "draining... waiting for %d messages in flight", msgsInFlight)
lastWarning = time.Now()
}
continue
}
// until the readLoop has exited we cannot be sure that there
// still won't be a race
if atomic.LoadInt32(&c.readLoopRunning) == 1 {
if time.Now().Sub(lastWarning) > time.Second {
c.log(LogLevelWarning, "draining... readLoop still running")
lastWarning = time.Now()
}
continue
}
goto exit
}
exit:
ticker.Stop()
c.wg.Done()
c.log(LogLevelInfo, "finished draining, cleanup exiting")
}
func (c *Conn) waitForCleanup() {
// this blocks until readLoop and writeLoop
// (and cleanup goroutine above) have exited
c.wg.Wait()
c.conn.CloseWrite()
c.log(LogLevelInfo, "clean close complete")
c.delegate.OnClose(c)
}
func (c *Conn) onMessageFinish(m *Message) {
c.msgResponseChan <- &msgResponse{msg: m, cmd: Finish(m.ID), success: true}
}
func (c *Conn) onMessageRequeue(m *Message, delay time.Duration, backoff bool) {
if delay == -1 {
// linear delay
delay = c.config.DefaultRequeueDelay * time.Duration(m.Attempts)
// bound the requeueDelay to configured max
if delay > c.config.MaxRequeueDelay {
delay = c.config.MaxRequeueDelay
}
}
c.msgResponseChan <- &msgResponse{msg: m, cmd: Requeue(m.ID, delay), success: false, backoff: backoff}
}
func (c *Conn) onMessageTouch(m *Message) {
select {
case c.cmdChan <- Touch(m.ID):
case <-c.exitChan:
}
}
func (c *Conn) log(lvl LogLevel, line string, args ...interface{}) {
logger, logLvl, logFmt := c.getLogger()
if logger == nil {
return
}
if logLvl > lvl {
return
}
logger.Output(2, fmt.Sprintf("%-4s %s %s", lvl,
fmt.Sprintf(logFmt, c.String()),
fmt.Sprintf(line, args...)))
}
| mit |
arian/pngjs | test/canvas.js | 1177 | "use strict";
var PNGReader = require('../PNGReader');
var Canvas = require('canvas');
var fs = require("fs");
var out = fs.createWriteStream(__dirname + '/test.png');
var file = __dirname + "/../html/ubuntu-screenshot.png";
fs.readFile(file, function(err, bytes){
if (err) throw err;
var reader = new PNGReader(bytes);
reader.parse(function(err, png){
if (err) throw err;
console.log('pixels', png.pixels.length);
console.log('width', png.width, 'height', png.height, 'colors', png.colors);
console.log('colorType', png.colorType);
console.log('bitDepth', png.bitDepth);
console.log('colors', png.colors);
var canvas = new Canvas(png.width, png.height);
var ctx = canvas.getContext('2d');
var stream = canvas.createPNGStream();
for (var x = 0; x < png.width; x++){
for (var y = 0; y < png.height; y++){
var colors = png.getPixel(x, y);
var fillStyle = "rgba(" + colors.slice(0, 3).join(',') + ", " + colors[3] / 255 + ")";
ctx.fillStyle = fillStyle;
ctx.fillRect(x, y, 1, 1);
}
}
stream.on('data', function(chunk){
out.write(chunk);
});
stream.on('end', function(){
console.log('saved png');
});
});
});
| mit |
asyncee/home-bookkeeping-sample | src/expenses/queries/invalidators.py | 295 | from expenses.queries.cache import KeyedCache
class Invalidator:
def __init__(self, query):
self.query = query
def invalidate(self, **kwargs):
params = self.query.Params.from_dict(kwargs)
self.cache = KeyedCache.create(str(params))
self.cache.delete()
| mit |
pablo1n7/ProyectoBacheo | web/application/views/mapa.php | 2392 | <div id="informacionBache" class="modal fade informacionBache" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header tituloFormularioBache">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title">Información sobre Bache</h4>
</div>
<div class="contenedorCampos">
<form id="formularioBache">
<input name="titulo" type="text" class="form-control campoIzquierdo" placeholder="Titulo">
<select id="criticidad" class="form-control campoDerecho">
<!-- <option value="baja">Pequeño</option>
<option value="media">Mediano</option>
<option value="alta">Grande</option> -->
</select>
<!-- <div class="alerta">
<strong>Nota:</strong> Esta descripcion corresponde a un bache mediano
</div> -->
<button id="seleccionarCalle" type='button' class="seleccionarCalle" rel="tooltip" title="Marcar calle en el Mapa" ><i class="fa fa-crosshairs"></i></button>
<input name="calle" type="text" class="form-control campoIzquierdo campoCalle" placeholder="Calle">
<input name="altura" type="numeric" class="form-control campoDerecho" placeholder="Altura">
<textarea name="descripcion" placeholder="Descripcion" maxlength="100" class="form-control campoDescripcion"></textarea>
</form>
<!-- <form id="my-awesome-dropzone" action="/upload" class="dropzone cargarImagenes"> -->
<form id="imagenesForm" action="./index.php/inicio/subirImagen/21" class="dropzone cargarImagenes">
<div class="dropzone-previews"></div>
<div class="fallback"> <!-- this is the fallback if JS isn't working -->
<input name="file" type="file" multiple />
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cancelar</button>
<button id="modaInfoBacheAceptar" type="button" class="btn btn-primary" data-dismiss="modal">Guardar Bache</button>
</div>
</div>
</div>
</div>
<div id="canvasMapa" class="contenedorMapa"> Mapa </div> | mit |
zhunicole/rekindle_temp | node_modules/lunr/oliver.js | 1069 | var fs = require('fs')
var store = {}
var hash = function (str) {
return str.split("")
.reduce(function (memo, char) {
var memo = ((memo << 5) - memo) - char.charCodeAt(0);
return memo & memo
}, 0)
}
fs.readFile('/usr/share/dict/words', 'ascii', function (err, words) {
words
.split("\n")
.reduce(function (cache, word) {
var h = hash(word)
if (h in cache) console.log('collision on', word)
cache[h] = true
return cache
}, {})
})
var oliver = function (haystack, needle) {
var stacks = {}
var distances = []
for (var i = 0; i < needle.length; i++) {
stacks[needle[i]] = [-Infinity]
}
for (var i = 0; i < haystack.length; i++) {
var char = haystack[i]
if (char in stacks) {
stacks[char].unshift(i)
var heads = Object.keys(stacks).map(function (key) {
return stacks[key][0]
})
var max = Math.max.apply(null, heads),
min = Math.min.apply(null, heads)
distances.push(max - min)
}
}
return Math.min.apply(null, distances)
}
| mit |
stingerlabs/ember-graph | src/util/util.js | 4095 | import Ember from 'ember';
import EmberGraphSet from 'ember-graph/util/set';
import { computed } from 'ember-graph/util/computed';
/**
* Denotes that method must be implemented in a subclass.
* If it's not overridden, calling it will throw an error.
*
* ```js
* var Shape = Ember.Object.extend({
* getNumberOfSides: EG.abstractMethod('getNumberOfSides')
* });
* ```
*
* @method abstractMethod
* @param {String} methodName
* @return {Function}
* @namespace EmberGraph
*/
function abstractMethod(methodName) {
return function() {
throw new Ember.Error('You failed to implement the abstract `' + methodName + '` method.');
};
}
/**
* Denotes that a property must be overridden in a subclass.
* If it's not overridden, using it will throw an error.
*
* ```js
* var Shape = Ember.Object.extend({
* name: EG.abstractProperty('name')
* });
* ```
*
* @method abstractProperty
* @param {String} propertyName
* @return {ComputedProperty}
* @namespace EmberGraph
*/
function abstractProperty(propertyName) {
return computed({
get() {
throw new Ember.Error('You failed to override the abstract `' + propertyName + '` property.');
}
});
}
/**
* Generates a version 4 (random) UUID.
*
* @method generateUUID
* @return {String}
* @namespace EmberGraph
*/
function generateUUID() {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
var r = Math.random() * 16|0; // eslint-disable-line
var v = (c == 'x' ? r : (r&0x3|0x8)); // eslint-disable-line
return v.toString(16);
});
}
/**
* Compares the contents of two arrays for equality. Uses
* Ember.Set to make the comparison, so the objects must
* be equal with `===`.
*
* @method arrayContentsEqual
* @param {Array} a
* @param {Array} b
* @returns {Boolean}
* @namespace EmberGraph
*/
function arrayContentsEqual(a, b) {
var set = EmberGraphSet.create();
set.addObjects(a);
return (a.length === b.length && set.isEqual(b));
}
/**
* Takes a list of record objects (with `type` and `id`)
* and groups them into arrays based on their type.
*
* @method groupRecords
* @param {Object[]} records
* @return {Array[]}
* @namespace EmberGraph
*/
function groupRecords(records) {
var groups = records.reduce(function(groups, record) {
if (groups[record.type]) {
groups[record.type].push(record);
} else {
groups[record.type] = [record];
}
return groups;
}, {});
return Object.keys(groups).reduce(function(array, key) {
if (groups[key].length > 0) {
array.push(groups[key]);
}
return array;
}, []);
}
/**
* Calls `callback` once for each value of the given object.
* The callback receives `key` and `value` parameters.
*
* @method values
* @param {Object} obj
* @param {Function} callback
* @param {Any} [thisArg=undefined]
* @namespace EmberGraph
*/
function values(obj, callback, thisArg) {
var keys = Object.keys(obj);
for (var i = 0; i < keys.length; ++i) {
callback.call(thisArg, keys[i], obj[keys[i]]);
}
}
/**
* Works like `Ember.aliasMethod` only it displays a
* deprecation warning before the aliased method is called.
*
* @method deprecateMethod
* @param {String} message
* @param {String} method
* @return {Function}
* @namespace EmberGraph
*/
function deprecateMethod(message, method) {
return function() {
Ember.deprecate(message, false, { id: method, until: '2.0.0' });
this[method].apply(this, arguments);
};
}
/**
* Works like 'Ember.computed.alias' only it displays a
* deprecation warning before the aliased property is returned.
*
* @method deprecateProperty
* @param {String} message
* @param {String} property
* @return {ComputedProperty}
* @namespace EmberGraph
*/
function deprecateProperty(message, property) {
return computed(property, {
get() {
Ember.deprecate(message, false, { id: property, until: '2.0.0' });
return this.get(property);
},
set(key, value) {
this.set(property, value);
}
});
}
export {
abstractMethod,
abstractProperty,
generateUUID,
arrayContentsEqual,
groupRecords,
values,
deprecateMethod,
deprecateProperty
};
| mit |
lynxtdc/hwh | app/LTDC/Common/Site_Data.php | 237 | <?php
/**
* Created by LYNX Technology Development
* User: LYNXTDC
* Date: 1/14/2015
* Time: 8:41 PM
* http://lynxtdc.com
*/
namespace App\LTDC\Common;
class Site_Data {
//put functions for returning static site data here
} | mit |
reidiculous/actionwebservice-client | lib/action_web_service/wsdl/soap/data.rb | 1517 | # WSDL4R - WSDL SOAP binding data definitions.
# Copyright (C) 2002, 2003 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.
# This program is copyrighted free software by NAKAMURA, Hiroshi. You can
# redistribute it and/or modify it under the same terms of Ruby's license;
# either the dual license version in 2003, or any later version.
require 'action_web_service/xsd/qname'
require 'action_web_service/wsdl/soap/definitions'
require 'action_web_service/wsdl/soap/binding'
require 'action_web_service/wsdl/soap/operation'
require 'action_web_service/wsdl/soap/body'
require 'action_web_service/wsdl/soap/element'
require 'action_web_service/wsdl/soap/header'
require 'action_web_service/wsdl/soap/headerfault'
require 'action_web_service/wsdl/soap/fault'
require 'action_web_service/wsdl/soap/address'
require 'action_web_service/wsdl/soap/complexType'
module WSDL
module SOAP
HeaderFaultName = XSD::QName.new(SOAPBindingNamespace, 'headerfault')
LocationAttrName = XSD::QName.new(nil, 'location')
StyleAttrName = XSD::QName.new(nil, 'style')
TransportAttrName = XSD::QName.new(nil, 'transport')
UseAttrName = XSD::QName.new(nil, 'use')
PartsAttrName = XSD::QName.new(nil, 'parts')
PartAttrName = XSD::QName.new(nil, 'part')
NameAttrName = XSD::QName.new(nil, 'name')
MessageAttrName = XSD::QName.new(nil, 'message')
EncodingStyleAttrName = XSD::QName.new(nil, 'encodingStyle')
NamespaceAttrName = XSD::QName.new(nil, 'namespace')
SOAPActionAttrName = XSD::QName.new(nil, 'action_web_service/soapAction')
end
end
| mit |
zoomulus/weaver | rest/src/test/java/com/zoomulus/weaver/rest/RestServerRequestPayloadHandlerTest.java | 27963 | package com.zoomulus.weaver.rest;
import java.io.IOException;
import org.apache.http.client.ClientProtocolException;
import org.junit.Test;
import com.zoomulus.weaver.core.content.ContentType;
import com.zoomulus.weaver.rest.testutils.PostRequestResult;
import com.zoomulus.weaver.rest.testutils.PutRequestResult;
import com.zoomulus.weaver.rest.testutils.RequestResult;
public class RestServerRequestPayloadHandlerTest extends RestServerTestBase
{
@Test
public void testPostTextPlainToStringPayloadProvidesRawData() throws ClientProtocolException, IOException
{
final RequestResult result = new PostRequestResult("/post/string", "text", ContentType.TEXT_PLAIN_TYPE);
verifyOkResult(result, "text");
}
@Test
public void testPostApplicationJsonToStringPayloadProvidesJsonData() throws ClientProtocolException, IOException
{
final RequestResult result = new PostRequestResult("/post/string", "{\"s\":\"custom\"}", ContentType.APPLICATION_JSON_TYPE);
verifyOkResult(result, "{\"s\":\"custom\"}");
}
@Test
public void testPostApplicationXmlToStringPayloadProvidesXmlData() throws ClientProtocolException, IOException
{
final RequestResult result = new PostRequestResult("/post/string", "<String>text</String>", ContentType.APPLICATION_XML_TYPE);
verifyOkResult(result, "<String>text</String>");
}
@Test
public void testPostOtherContentTypeToStringPayloadProvidesRawData() throws ClientProtocolException, IOException
{
final RequestResult result = new PostRequestResult("/post/string", "<html>hi</html>", ContentType.TEXT_HTML_TYPE);
verifyOkResult(result, "<html>hi</html>");
}
@Test
public void testPostToStringPayloadWithConsumesTextPlainProvidesText() throws ClientProtocolException, IOException
{
final RequestResult result = new PostRequestResult("/post/string/text", "text", ContentType.TEXT_PLAIN_TYPE);
verifyOkResult(result, "text");
}
@Test
public void testPostToStringPayloadWithConsumesApplicationJsonProvidesJson() throws ClientProtocolException, IOException
{
final RequestResult result = new PostRequestResult("/post/string/json", "{\"s\":\"custom\"}", ContentType.APPLICATION_JSON_TYPE);
verifyOkResult(result, "custom");
}
@Test
public void testPostNonJsonStringPayloadWithConsumesApplicationJsonFails() throws ClientProtocolException, IOException
{
final RequestResult result = new PostRequestResult("/post/string/json", "not json", ContentType.TEXT_PLAIN_TYPE);
verifyUnsupportedMediaTypeResult(result);
}
@Test
public void testPostToStringPayloadWithConsumesApplicationXmlProvidesXml() throws ClientProtocolException, IOException
{
final RequestResult result = new PostRequestResult("/post/string/xml",
"<CustomWithStringCtor><s>custom</s></CustomWithStringCtor>", ContentType.APPLICATION_XML_TYPE);
verifyOkResult(result, "custom");
}
@Test
public void testPostNonXmlStringPayloadWithConsumesApplicationXmlFails() throws ClientProtocolException, IOException
{
final RequestResult result = new PostRequestResult("/post/string/xml", "not xml", ContentType.TEXT_PLAIN_TYPE);
verifyUnsupportedMediaTypeResult(result);
}
@Test
public void testPostTextHtmlStringWithConsumesTextPlainFails() throws ClientProtocolException, IOException
{
final RequestResult result = new PostRequestResult("/post/string/text", "<html>hi</html>", ContentType.TEXT_HTML_TYPE);
verifyUnsupportedMediaTypeResult(result);
}
@Test
public void testPostApplicationJsonToObjectPayloadProvidesObject() throws ClientProtocolException, IOException
{
final RequestResult result = new PostRequestResult("/post/string/json/noconsumes", "{\"s\":\"custom\"}", ContentType.APPLICATION_JSON_TYPE);
verifyOkResult(result, "custom");
}
@Test
public void testPostApplicationXmlToObjectPayloadProvidesObject() throws ClientProtocolException, IOException
{
final RequestResult result = new PostRequestResult("/post/string/xml/noconsumes",
"<CustomWithStringCtor><s>custom</s></CustomWithStringCtor>", ContentType.APPLICATION_XML_TYPE);
verifyOkResult(result, "custom");
}
@Test
public void testPostTextPlainToObjectCallsStringConstructor() throws ClientProtocolException, IOException
{
final RequestResult result = new PostRequestResult("/post/object/text/noconsumes/stringctor", "custom", ContentType.TEXT_PLAIN_TYPE);
verifyOkResult(result, "custom");
}
@Test
public void testPostTextPlainToObjectCallsValueOf() throws ClientProtocolException, IOException
{
final RequestResult result = new PostRequestResult("/post/object/text/noconsumes/valueof", "custom", ContentType.TEXT_PLAIN_TYPE);
verifyOkResult(result, "custom");
}
@Test
public void testPostOtherContentTypeToObjectFails() throws ClientProtocolException, IOException
{
final RequestResult result = new PostRequestResult("/post/object/text/noconsumes/valueof", "custom", ContentType.TEXT_HTML_TYPE);
verifyInternalServerErrorResult(result);
}
@Test
public void testPostJsonStringToObjectPayloadWithConsumesApplicationJsonProvidesObject() throws ClientProtocolException, IOException
{
final RequestResult result = new PostRequestResult("/post/string/object/consumes/json", "{\"s\":\"custom\"}", ContentType.TEXT_PLAIN_TYPE);
verifyOkResult(result, "custom");
}
@Test
public void testPostNonJsonStringToObjectPayloadWithConsumesApplicationJsonFails() throws ClientProtocolException, IOException
{
final RequestResult result = new PostRequestResult("/post/string/object/consumes/json", "not json", ContentType.TEXT_PLAIN_TYPE);
verifyUnsupportedMediaTypeResult(result);
}
@Test
public void testPostXmlStringToObjectPayloadWithConsumesApplicationXmlProvidesObject() throws ClientProtocolException, IOException
{
final RequestResult result = new PostRequestResult("/post/string/object/consumes/xml",
"<CustomWithStringCtor><s>custom</s></CustomWithStringCtor>", ContentType.TEXT_PLAIN_TYPE);
verifyOkResult(result, "custom");
}
@Test
public void testPostNonXmlStringToObjectPayloadWithConsumesApplicationXmlFails() throws ClientProtocolException, IOException
{
final RequestResult result = new PostRequestResult("/post/string/object/consumes/xml", "not xml", ContentType.TEXT_PLAIN_TYPE);
verifyUnsupportedMediaTypeResult(result);
}
@Test
public void testPostTextStringToObjectPayloadWithConsumesTextPlainCallsStringCtor() throws ClientProtocolException, IOException
{
final RequestResult result = new PostRequestResult("/post/string/object/consumes/text/stringctor", "custom", ContentType.TEXT_PLAIN_TYPE);
verifyOkResult(result, "custom");
}
@Test
public void testPostTextStringToObjectPayloadWithConsumesTextPlainCallsValueOf() throws ClientProtocolException, IOException
{
final RequestResult result = new PostRequestResult("/post/string/object/consumes/text/valueof", "custom", ContentType.TEXT_PLAIN_TYPE);
verifyOkResult(result, "custom");
}
@Test
public void testPostTextHtmlToObjectConsumesApplicationJsonFails() throws ClientProtocolException, IOException
{
final RequestResult result = new PostRequestResult("/post/string/object/consumes/json", "{\"s\":\"custom\"}", ContentType.TEXT_HTML_TYPE);
verifyUnsupportedMediaTypeResult(result);
}
@Test
public void testPostApplicationJsonToNativePayloadProvidesNative() throws ClientProtocolException, IOException
{
final RequestResult result = new PostRequestResult("/post/native", "111", ContentType.APPLICATION_JSON_TYPE);
verifyOkResult(result, "111");
}
@Test
public void testPostApplicationXmlToNativePayloadFails() throws ClientProtocolException, IOException
{
final RequestResult result = new PostRequestResult("/post/native", "<Integer>111</Integer>", ContentType.APPLICATION_XML_TYPE);
verifyUnsupportedMediaTypeResult(result);
// This appears at first glance to be broken, but actually it is more true that deserialization
// of scalar type representations to scalar types is generally unsupported by the spec implemented
// by Jackson, and only by luck does it work for JSON at all. This is primarily due to the fact that when
// a scalar is serialized into JSON, there is no "object" wrapper around the value, which there
// is in XML. It is this START_OBJECT token at the start of the XML stream that is throwing
// the Jackson parser off and making it so this deserialization does not work as you might expect.
//
// Issue https://github.com/FasterXML/jackson-dataformat-xml/issues/139 was submitted for this issue.
// I tried to write a patch but the way jackson-dataformat-xml is implemented makes it
// extremely difficult to support this functionality without a significant redesign.
// I came up with a hacky patch (https://github.com/FasterXML/jackson-dataformat-xml/issues/140)
// but they had concerns which, once explained to me, I share.
//
// So the result is that deserialization of XML to native types is not supported.
// JSON works though.
//
// -MR
}
@Test
public void testPostTextPlainToNativeProvidesNative() throws ClientProtocolException, IOException
{
final RequestResult result = new PostRequestResult("/post/native", "111", ContentType.TEXT_PLAIN_TYPE);
verifyOkResult(result, "111");
}
@Test
public void testPostOtherContentTypeToNativeFails() throws ClientProtocolException, IOException
{
final RequestResult result = new PostRequestResult("/post/native", "111", ContentType.TEXT_HTML_TYPE);
verifyInternalServerErrorResult(result);
}
@Test
public void testPostJsonStringToNativePayloadWithConsumesApplicationJsonProvidesNative() throws ClientProtocolException, IOException
{
final RequestResult result = new PostRequestResult("/post/native/consumes/json", "111", ContentType.APPLICATION_JSON_TYPE);
verifyOkResult(result, "111");
}
@Test
public void testPostNonJsonStringToNativePayloadWithConsumesApplicationJsonFails() throws ClientProtocolException, IOException
{
final RequestResult result = new PostRequestResult("/post/native/consumes/json", "not json", ContentType.APPLICATION_JSON_TYPE);
verifyUnsupportedMediaTypeResult(result);
}
@Test
public void testPostXmlStringToNativePayloadWithConsumesApplicationXmlFails() throws ClientProtocolException, IOException
{
final RequestResult result = new PostRequestResult("/post/native/consumes/xml", "<Integer>111</Integer>", ContentType.APPLICATION_XML_TYPE);
verifyUnsupportedMediaTypeResult(result);
}
@Test
public void testPostNonXmlStringToNativePayloadWithConsumesApplicationXmlFails() throws ClientProtocolException, IOException
{
final RequestResult result = new PostRequestResult("/post/native/consumes/xml", "not xml", ContentType.APPLICATION_XML_TYPE);
verifyUnsupportedMediaTypeResult(result);
}
@Test
public void testPostTextStringToNativePayloadWithConsumesTextPlainProvidesNative() throws ClientProtocolException, IOException
{
final RequestResult result = new PostRequestResult("/post/native/consumes/text", "111", ContentType.TEXT_PLAIN_TYPE);
verifyOkResult(result, "111");
}
@Test
public void testPostTextHtmlToNativeConsumesTextPlainFails() throws ClientProtocolException, IOException
{
final RequestResult result = new PostRequestResult("/post/native/consumes/text", "111", ContentType.TEXT_HTML_TYPE);
verifyUnsupportedMediaTypeResult(result);
}
@Test
public void testPostApplicationJsonToByteArrayPayloadProvidesByteArray() throws ClientProtocolException, IOException
{
final RequestResult result = new PostRequestResult("/post/bytearray", "bytes", ContentType.APPLICATION_JSON_TYPE);
verifyOkResult(result, "bytes");
}
@Test
public void testPostApplicationXmlToByteArrayPayloadProvidesByteArray() throws ClientProtocolException, IOException
{
final RequestResult result = new PostRequestResult("/post/bytearray", "bytes", ContentType.APPLICATION_XML_TYPE);
verifyOkResult(result, "bytes");
}
@Test
public void testPostTextPlainToByteArrayProvidesByteArray() throws ClientProtocolException, IOException
{
final RequestResult result = new PostRequestResult("/post/bytearray", "bytes", ContentType.TEXT_PLAIN_TYPE);
verifyOkResult(result, "bytes");
}
@Test
public void testPostAnyContentTypeToByteArrayProvidesRawData() throws ClientProtocolException, IOException
{
final RequestResult result = new PostRequestResult("/post/bytearray", "bytes", ContentType.TEXT_HTML_TYPE);
verifyOkResult(result, "bytes");
}
@Test
public void testPostJsonStringToByteArrayPayloadWithConsumesApplicationJsonProvidesByteArray() throws ClientProtocolException, IOException
{
final RequestResult result = new PostRequestResult("/post/bytearray/consumes/json", "bytes", ContentType.APPLICATION_JSON_TYPE);
verifyOkResult(result, "bytes");
}
@Test
public void testPostXmlStringToByteArrayPayloadWithConsumesApplicationXmlProvidesByteArray() throws ClientProtocolException, IOException
{
final RequestResult result = new PostRequestResult("/post/bytearray/consumes/xml", "bytes", ContentType.APPLICATION_XML_TYPE);
verifyOkResult(result, "bytes");
}
@Test
public void testPostTextStringToByteArrayPayloadWithConsumesTextPlainProvidesByteArray() throws ClientProtocolException, IOException
{
final RequestResult result = new PostRequestResult("/post/bytearray/consumes/text", "bytes", ContentType.TEXT_PLAIN_TYPE);
verifyOkResult(result, "bytes");
}
@Test
public void testPostTextHtmlToByteArrayConsumesApplicationJsonFails() throws ClientProtocolException, IOException
{
final RequestResult result = new PostRequestResult("/post/bytearray/consumes/json", "bytes", ContentType.TEXT_HTML_TYPE);
verifyUnsupportedMediaTypeResult(result);
}
@Test
public void testPutTextPlainToStringPayloadProvidesRawData() throws ClientProtocolException, IOException
{
final RequestResult result = new PutRequestResult("/put/string", "text", ContentType.TEXT_PLAIN_TYPE);
verifyOkResult(result, "text");
}
@Test
public void testPutApplicationJsonToStringPayloadProvidesJsonData() throws ClientProtocolException, IOException
{
final RequestResult result = new PutRequestResult("/put/string", "{\"s\":\"custom\"}", ContentType.APPLICATION_JSON_TYPE);
verifyOkResult(result, "{\"s\":\"custom\"}");
}
@Test
public void testPutApplicationXmlToStringPayloadProvidesXmlData() throws ClientProtocolException, IOException
{
final RequestResult result = new PutRequestResult("/put/string", "<String>text</String>", ContentType.APPLICATION_XML_TYPE);
verifyOkResult(result, "<String>text</String>");
}
@Test
public void testPutOtherContentTypeToStringPayloadProvidesRawData() throws ClientProtocolException, IOException
{
final RequestResult result = new PutRequestResult("/put/string", "<html>hi</html>", ContentType.TEXT_HTML_TYPE);
verifyOkResult(result, "<html>hi</html>");
}
@Test
public void testPutToStringPayloadWithConsumesTextPlainProvidesText() throws ClientProtocolException, IOException
{
final RequestResult result = new PutRequestResult("/put/string/text", "text", ContentType.TEXT_PLAIN_TYPE);
verifyOkResult(result, "text");
}
@Test
public void testPutToStringPayloadWithConsumesApplicationJsonProvidesJson() throws ClientProtocolException, IOException
{
final RequestResult result = new PutRequestResult("/put/string/json", "{\"s\":\"custom\"}", ContentType.APPLICATION_JSON_TYPE);
verifyOkResult(result, "custom");
}
@Test
public void testPutNonJsonStringPayloadWithConsumesApplicationJsonFails() throws ClientProtocolException, IOException
{
final RequestResult result = new PutRequestResult("/put/string/json", "not json", ContentType.TEXT_PLAIN_TYPE);
verifyUnsupportedMediaTypeResult(result);
}
@Test
public void testPutToStringPayloadWithConsumesApplicationXmlProvidesXml() throws ClientProtocolException, IOException
{
final RequestResult result = new PutRequestResult("/put/string/xml",
"<CustomWithStringCtor><s>custom</s></CustomWithStringCtor>", ContentType.APPLICATION_XML_TYPE);
verifyOkResult(result, "custom");
}
@Test
public void testPutNonXmlStringPayloadWithConsumesApplicationXmlFails() throws ClientProtocolException, IOException
{
final RequestResult result = new PutRequestResult("/put/string/xml", "not xml", ContentType.TEXT_PLAIN_TYPE);
verifyUnsupportedMediaTypeResult(result);
}
@Test
public void testPutTextHtmlToStringConsumesTextPlainFails() throws ClientProtocolException, IOException
{
final RequestResult result = new PutRequestResult("/put/string/text", "<html>hi</html>", ContentType.TEXT_HTML_TYPE);
verifyUnsupportedMediaTypeResult(result);
}
@Test
public void testPutApplicationJsonToObjectPayloadProvidesObject() throws ClientProtocolException, IOException
{
final RequestResult result = new PutRequestResult("/put/string/json/noconsumes", "{\"s\":\"custom\"}", ContentType.APPLICATION_JSON_TYPE);
verifyOkResult(result, "custom");
}
@Test
public void testPutApplicationXmlToObjectPayloadProvidesObject() throws ClientProtocolException, IOException
{
final RequestResult result = new PutRequestResult("/put/string/xml/noconsumes",
"<CustomWithStringCtor><s>custom</s></CustomWithStringCtor>", ContentType.APPLICATION_XML_TYPE);
verifyOkResult(result, "custom");
}
@Test
public void testPutTextPlainToObjectCallsStringConstructor() throws ClientProtocolException, IOException
{
final RequestResult result = new PutRequestResult("/put/object/text/noconsumes/stringctor", "custom", ContentType.TEXT_PLAIN_TYPE);
verifyOkResult(result, "custom");
}
@Test
public void testPutTextPlainToObjectCallsValueOf() throws ClientProtocolException, IOException
{
final RequestResult result = new PutRequestResult("/put/object/text/noconsumes/valueof", "custom", ContentType.TEXT_PLAIN_TYPE);
verifyOkResult(result, "custom");
}
@Test
public void testPutOtherContentTypeToObjectFails() throws ClientProtocolException, IOException
{
final RequestResult result = new PutRequestResult("/put/object/text/noconsumes/valueof", "custom", ContentType.TEXT_HTML_TYPE);
verifyInternalServerErrorResult(result);
}
@Test
public void testPutJsonStringToObjectPayloadWithConsumesApplicationJsonProvidesObject() throws ClientProtocolException, IOException
{
final RequestResult result = new PutRequestResult("/put/string/object/consumes/json", "{\"s\":\"custom\"}", ContentType.TEXT_PLAIN_TYPE);
verifyOkResult(result, "custom");
}
@Test
public void testPutNonJsonStringToObjectPayloadWithConsumesApplicationJsonFails() throws ClientProtocolException, IOException
{
final RequestResult result = new PutRequestResult("/put/string/object/consumes/json", "not json", ContentType.TEXT_PLAIN_TYPE);
verifyUnsupportedMediaTypeResult(result);
}
@Test
public void testPutXmlStringToObjectPayloadWithConsumesApplicationXmlProvidesObject() throws ClientProtocolException, IOException
{
final RequestResult result = new PutRequestResult("/put/string/object/consumes/xml",
"<CustomWithStringCtor><s>custom</s></CustomWithStringCtor>", ContentType.TEXT_PLAIN_TYPE);
verifyOkResult(result, "custom");
}
@Test
public void testPutNonXmlStringToObjectPayloadWithConsumesApplicationXmlFails() throws ClientProtocolException, IOException
{
final RequestResult result = new PutRequestResult("/put/string/object/consumes/xml", "not xml", ContentType.TEXT_PLAIN_TYPE);
verifyUnsupportedMediaTypeResult(result);
}
@Test
public void testPutTextStringToObjectPayloadWithConsumesTextPlainCallsStringCtor() throws ClientProtocolException, IOException
{
final RequestResult result = new PutRequestResult("/put/string/object/consumes/text/stringctor", "custom", ContentType.TEXT_PLAIN_TYPE);
verifyOkResult(result, "custom");
}
@Test
public void testPutTextStringToObjectPayloadWithConsumesTextPlainCallsValueOf() throws ClientProtocolException, IOException
{
final RequestResult result = new PutRequestResult("/put/string/object/consumes/text/valueof", "custom", ContentType.TEXT_PLAIN_TYPE);
verifyOkResult(result, "custom");
}
@Test
public void testPutTextHtmlToObjectConsumesApplicationJsonFails() throws ClientProtocolException, IOException
{
final RequestResult result = new PutRequestResult("/put/string/object/consumes/json", "{\"s\":\"custom\"}", ContentType.TEXT_HTML_TYPE);
verifyUnsupportedMediaTypeResult(result);
}
@Test
public void testPutApplicationJsonToNativePayloadProvidesNative() throws ClientProtocolException, IOException
{
final RequestResult result = new PutRequestResult("/put/native", "111", ContentType.APPLICATION_JSON_TYPE);
verifyOkResult(result, "111");
}
@Test
public void testPutApplicationXmlToNativePayloadFails() throws ClientProtocolException, IOException
{
final RequestResult result = new PutRequestResult("/put/native", "<Integer>111</Integer>", ContentType.APPLICATION_XML_TYPE);
verifyUnsupportedMediaTypeResult(result);
}
@Test
public void testPutTextPlainToNativeProvidesNative() throws ClientProtocolException, IOException
{
final RequestResult result = new PutRequestResult("/put/native", "111", ContentType.TEXT_PLAIN_TYPE);
verifyOkResult(result, "111");
}
@Test
public void testPutOtherContentTypeToNativeFails() throws ClientProtocolException, IOException
{
final RequestResult result = new PutRequestResult("/put/native", "111", ContentType.TEXT_HTML_TYPE);
verifyInternalServerErrorResult(result);
}
@Test
public void testPutJsonStringToNativePayloadWithConsumesApplicationJsonProvidesNative() throws ClientProtocolException, IOException
{
final RequestResult result = new PutRequestResult("/put/native/consumes/json", "111", ContentType.APPLICATION_JSON_TYPE);
verifyOkResult(result, "111");
}
@Test
public void testPutNonJsonStringToNativePayloadWithConsumesApplicationJsonFails() throws ClientProtocolException, IOException
{
final RequestResult result = new PutRequestResult("/put/native/consumes/json", "not json", ContentType.APPLICATION_JSON_TYPE);
verifyUnsupportedMediaTypeResult(result);
}
@Test
public void testPutXmlStringToNativePayloadWithConsumesApplicationXmlFails() throws ClientProtocolException, IOException
{
final RequestResult result = new PutRequestResult("/put/native/consumes/xml", "<Integer>111</Integer>", ContentType.APPLICATION_XML_TYPE);
verifyUnsupportedMediaTypeResult(result);
}
@Test
public void testPutNonXmlStringToNativePayloadWithConsumesApplicationXmlFails() throws ClientProtocolException, IOException
{
final RequestResult result = new PutRequestResult("/put/native/consumes/xml", "not xml", ContentType.APPLICATION_XML_TYPE);
verifyUnsupportedMediaTypeResult(result);
}
@Test
public void testPutTextStringToNativePayloadWithConsumesTextPlainProvidesNative() throws ClientProtocolException, IOException
{
final RequestResult result = new PutRequestResult("put/native/consumes/text", "111", ContentType.TEXT_PLAIN_TYPE);
verifyOkResult(result, "111");
}
@Test
public void testPutTextHtmlToNativeConsumesTextPlainFails() throws ClientProtocolException, IOException
{
final RequestResult result = new PutRequestResult("/put/native/consumes/text", "111", ContentType.TEXT_HTML_TYPE);
verifyUnsupportedMediaTypeResult(result);
}
@Test
public void testPutApplicationJsonToByteArrayPayloadProvidesByteArray() throws ClientProtocolException, IOException
{
final RequestResult result = new PutRequestResult("/put/bytearray", "bytes", ContentType.APPLICATION_JSON_TYPE);
verifyOkResult(result, "bytes");
}
@Test
public void testPutApplicationXmlToByteArrayPayloadProvidesByteArray() throws ClientProtocolException, IOException
{
final RequestResult result = new PutRequestResult("/put/bytearray", "bytes", ContentType.APPLICATION_XML_TYPE);
verifyOkResult(result, "bytes");
}
@Test
public void testPutTextPlainToByteArrayProvidesByteArray() throws ClientProtocolException, IOException
{
final RequestResult result = new PutRequestResult("/put/bytearray", "bytes", ContentType.TEXT_PLAIN_TYPE);
verifyOkResult(result, "bytes");
}
@Test
public void testPutAnyContentTypeToByteArrayProvidesRawData() throws ClientProtocolException, IOException
{
final RequestResult result = new PutRequestResult("/put/bytearray", "bytes", ContentType.TEXT_HTML_TYPE);
verifyOkResult(result, "bytes");
}
@Test
public void testPutJsonStringToByteArrayPayloadWithConsumesApplicationJsonProvidesByteArray() throws ClientProtocolException, IOException
{
final RequestResult result = new PutRequestResult("/put/bytearray/consumes/json", "bytes", ContentType.APPLICATION_JSON_TYPE);
verifyOkResult(result, "bytes");
}
@Test
public void testPutXmlStringToByteArrayPayloadWithConsumesApplicationXmlProvidesByteArray() throws ClientProtocolException, IOException
{
final RequestResult result = new PutRequestResult("/put/bytearray/consumes/xml", "bytes", ContentType.APPLICATION_XML_TYPE);
verifyOkResult(result, "bytes");
}
@Test
public void testPutTextStringToByteArrayPayloadWithConsumesTextPlainProvidesByteArray() throws ClientProtocolException, IOException
{
final RequestResult result = new PutRequestResult("/put/bytearray/consumes/text", "bytes", ContentType.TEXT_PLAIN_TYPE);
verifyOkResult(result, "bytes");
}
@Test
public void testPutTextHtmlToByteArrayConsumesApplicationXmlFails() throws ClientProtocolException, IOException
{
final RequestResult result = new PutRequestResult("/put/bytearray/consumes/json", "bytes", ContentType.TEXT_HTML_TYPE);
verifyUnsupportedMediaTypeResult(result);
}
}
| mit |
GerritErpenstein/ionic2-custom-icons-example | src/pages/platform/platform.page.module.ts | 420 | import {NgModule} from '@angular/core';
import {IonicPageModule} from 'ionic-angular';
import {PlatformPage} from './platform.page';
import {CustomIconsModule} from 'ionic2-custom-icons';
@NgModule({
declarations: [
PlatformPage
],
imports: [
IonicPageModule.forChild(PlatformPage),
CustomIconsModule
],
entryComponents: [
PlatformPage
]
})
export class PlatformPageModule {
}
| mit |
GIlyass/TouristScheduler | AndroidApp/TEScheduler/TEScheduler/app/src/test/java/com/ericsson/project/tescheduler/ExampleUnitTest.java | 325 | package com.ericsson.project.tescheduler;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* To work on unit tests, switch the Test Artifact in the Build Variants view.
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() throws Exception {
assertEquals(4, 2 + 2);
}
} | mit |
almamedia/moment-timezone | tests/zones/pacific/ponape.js | 310 | "use strict";
var helpers = require("../../helpers/helpers");
exports["Pacific/Ponape"] = {
"guess:by:offset" : helpers.makeTestGuess("Pacific/Ponape", { offset: true, expect: "Pacific/Norfolk" }),
"guess:by:abbr" : helpers.makeTestGuess("Pacific/Ponape", { abbr: true, expect: "Pacific/Norfolk" }),
}; | mit |
agconti/scala-school | 04-functions-as-values/slides/slide045.scala | 126 |
// what if we don't want our object to inherit Function1 ?
object Foo {
def isGood(x: Int): Boolean = { x % 2 == 0 }
}
| mit |
kgroener/Stayin-Alive | src/StayinAlive/World/Specimen/Attributes/MotorInternalAttribute.cs | 1616 | using StayinAlive.Interface.Specimen.Attributes;
using StayinAlive.World.Specimen.Attributes.Actuators;
using StayinAlive.World.Specimen.Attributes.Sensors;
using System;
using System.Collections.Generic;
using System.Linq;
namespace StayinAlive.World.Specimen.Attributes
{
internal class MotorInternalAttribute : SpecimenInternalAttributeBase<MotorAttribute>
{
private readonly ISpecimenInternalActuator[] _actuators;
private readonly AngularForceActuator _angularForceActuator;
private readonly ForceActuator _forceActuator;
public MotorInternalAttribute(ISpecimenInternal specimen, MotorAttribute attribute) : base(specimen, attribute)
{
_forceActuator = new ForceActuator(specimen);
_angularForceActuator = new AngularForceActuator(specimen);
_actuators = new ISpecimenInternalActuator[]
{
_forceActuator,
_angularForceActuator
};
}
public override IEnumerable<ISpecimenInternalActuator> Actuators => _actuators;
public override IEnumerable<ISpecimenInternalSensor> Sensors => Enumerable.Empty<ISpecimenInternalSensor>();
public override double Weight => 10;
protected override void GetAttributeActuatorValues(MotorAttribute attribute)
{
_forceActuator.SetActivationLevel(attribute.Throttle);
_angularForceActuator.SetActivationLevel(attribute.Steering);
}
protected override void SetAttributeSensorValues(MotorAttribute attribute)
{
}
}
}
| mit |
Houston-Inc/ppr.js | tests/helper/page.js | 351 | import PageBasePrototype from 'ppr.page.baseprototype';
import EventBusPrototype from 'ppr.library.eventbusprototype';
export const getPageInstance = pageNode => (
new PageBasePrototype(pageNode, { eventBus: new EventBusPrototype() })
);
export const buildPageInstance = (pageInstance) => {
pageInstance.build();
pageInstance.afterBuild();
};
| mit |
Statwolf/node-statwolf | packages/node-statwolf-mocks/mocks/events.js | 476 | var events = module.exports = function() {
this.events = {};
};
events.prototype.on = function(evt, callback) {
this.events[evt] = callback;
};
events.prototype.once = function(evt, callback) {
var self = this;
this.on(evt, function() {
delete this.events[evt];
callback.apply(self, arguments);
});
};
events.prototype.emit = function(evt) {
if(!this.events[evt]) return;
this.events[evt].apply(this, Array.prototype.slice.call(arguments, 1))
};
| mit |
lc8882972/HuiTong | webapp/Models/LoginModel.cs | 254 | using System;
namespace webapp.Models
{
public class LoginModel
{
public string Name { get; set; }
public string Password { get; set; }
public bool IsRemember { get; set; }
public string Code { get; set; }
}
} | mit |
kaola-fed/nek-ui | src/js/components/navigation/KLPager/index.js | 4225 | /**
* @file KLPager 分页
* @author sensen(rainforest92@126.com)
*/
const Component = require('../../../ui-base/component');
const template = require('./index.html');
const _ = require('../../../ui-base/_');
/**
* @class KLPager
* @extend Component
* @param {object} [options.data] = 绑定属性
* @param {number} [options.data.current=1] <=> 当前页
* @param {number} [options.data.total=0] => 总页数
* @param {number} [options.data.sumTotal=0] => 总个数
* @param {number} [options.data.pageSize=20] => 每页个数
* @param {number} [options.data.middle=5] => 当页数较多时,中间显示的页数
* @param {number} [options.data.side=2] => 当页数较多时,两端显示的页数
* @param {number} [options.data.step=5] => 每页条数选择步长
* @param {number} [options.data.maxPageSize=50] => 最大可设置的每页条数
* @param {boolean} [options.data.isEllipsis=false] => 是否展示位总条数+
* @param {number} [options.data.maxTotal] => 总条数超过maxTotal条数时,展示为maxTotal+条数
* @param {string} [options.data.class] => 补充class
*/
const KLPager = Component.extend({
name: 'kl-pager',
template,
config() {
_.extend(this.data, {
current: 1,
total: '',
sumTotal: '',
pageSize: '',
position: 'center',
middle: 5,
side: 2,
_start: 1,
_end: 5,
step: 5,
maxPageSize: 50,
pageSizeList: [],
isEllipsis: false,
});
this.supr();
this._setPageSizeList();
this.$watch(['current', 'total'], function (_current, _total) {
const current = +_current;
const total = +_total;
this.data.current = current;
this.data.total = total;
const show = Math.floor(this.data.middle / 2);
const side = this.data.side;
this.data._start = current - show;
this.data._end = current + show;
if (this.data._start < side + 1) this.data._start = side + 1;
if (this.data._end > total - side) this.data._end = total - side;
if (current - this.data._start < show) {
this.data._end += ((this.data._start - current) + show);
}
if (this.data._end - current < show) {
this.data._start += this.data._end - current - show;
}
});
this.$watch(['middle', 'side'], function (middle, side) {
this.data.middle = +middle;
this.data.side = +side;
});
this.$watch('pageSize', function (val, oldVal) {
if (!oldVal) return;
this.initTotal();
this.select(1);
});
this.$watch('sumTotal', () => {
this.initTotal();
});
},
initTotal() {
if (this.data.pageSize) {
this.data.total = Math.ceil(this.data.sumTotal / this.data.pageSize);
}
if (
(!!this.data.sumTotal || this.data.sumTotal === 0) &&
!this.data.pageSize
) {
console.error('Pager组件需要传pageSize');
}
},
_setPageSizeList() {
const { step, maxPageSize } = this.data;
for (let i = 1; i * step <= maxPageSize; i += 1) {
this.data.pageSizeList.push({
id: i * step,
name: (i * step) + this.$trans('ITEM_PAGE'),
});
}
},
select(page) {
if (this.data.readonly || this.data.disabled) return;
if (page < 1) return;
if (page > this.data.total) return;
this.data.current = page;
/**
* @event KLPager#select 选择某一页时触发
* @property {object} sender 事件发送对象
* @property {object} current 当前选择页
*/
this.$update();
this.$emit('select', {
sender: this,
current: this.data.current,
});
},
enter(ev) {
if (ev.which === 13) {
// ENTER key
ev.preventDefault();
this.goto();
}
},
goto() {
const data = this.data;
if (!data.pageNo && data.pageNo / 1 !== 0) return;
if (data.pageNo > data.total) {
data.pageNo = data.total;
} else if (data.pageNo < 1) {
data.pageNo = 1;
}
this.select(this.data.pageNo);
},
});
module.exports = KLPager;
| mit |
markfinger/fatcontroller | tests/js/unit-tests.js | 2753 | (function() {
QUnit.test('Triggers bindings', 3, function() {
var someFunction = function() {
ok(true, 'called bound function');
};
fc.on('test:trigger', someFunction);
fc.trigger('test:trigger');
fc.on('test:trigger', someFunction);
fc.trigger('test:trigger');
});
QUnit.test('Once only fires once', 1, function() {
var someFunction = function() {
ok(true, 'called bound function');
};
fc.once('test:once', someFunction);
fc.trigger('test:once');
fc.trigger('test:once');
});
QUnit.test('After triggers when bound after an event occurred', function() {
var someFunction = function() {
ok(true, 'called bound function');
};
fc.trigger('test:after1');
fc.after('test:after1', someFunction);
});
QUnit.test('After triggers when bound before and after an event occurs', 2, function() {
var someFunction = function() {
ok(true, 'called bound function');
};
fc.after('test:after2', someFunction);
fc.trigger('test:after2');
fc.after('test:after2', someFunction);
});
QUnit.test('AfterAll triggers after a succession of events', 2, function() {
var preTrigger = true;
var testFunc1 = function() {
ok(!preTrigger, 'this should be triggered after the events occur');
};
fc.afterAll(['test:afterAll1', 'test:afterAll2', 'test:afterAll3'], testFunc1);
fc.trigger('test:afterAll1');
fc.trigger('test:afterAll2');
preTrigger = false;
fc.trigger('test:afterAll3');
var testFunc2 = function() {
ok(!preTrigger, 'this should fire immediately');
};
fc.afterAll(['test:afterAll1', 'test:afterAll2'], testFunc2);
var testFunc3 = function() {
ok(true, 'this should not fire');
};
fc.afterAll(['test:afterAllThatDoesNotFire', 'test:afterAll1'], testFunc3);
// Spam the triggered events to ensure there are no issues regarding the
// event count
fc.trigger('test:afterAll1');
fc.trigger('test:afterAll1');
fc.trigger('test:afterAll1');
fc.trigger('test:afterAll1');
});
QUnit.test('Off removes event bindings', 0, function() {
var someFunction = function() {
ok(false, 'should not be called');
};
fc.on('test:off1', someFunction);
fc.off('test:off1');
fc.trigger('test:off1');
});
QUnit.test('Off removes a specific binding', 1, function() {
var someFunction = function() {
ok(false, 'should not be called');
};
var someOtherFunction = function() {
ok(true, 'called bound function');
};
fc.on('test:off2', someFunction);
fc.on('test:off2', someOtherFunction);
fc.off('test:off2', someFunction);
fc.trigger('test:off2');
});
})();
| mit |
fourlabsldn/QBJSParser | tests/Util/Doctrine/Mock/DoctrineParser/MockBadEntityDoctrineParser.php | 526 | <?php
namespace FL\QBJSParser\Tests\Util\Doctrine\Mock\DoctrineParser;
use FL\QBJSParser\Parser\Doctrine\DoctrineParser;
use FL\QBJSParser\Tests\Util\Doctrine\Mock\Entity\MockEntity;
class MockBadEntityDoctrineParser extends DoctrineParser
{
public function __construct()
{
parent::__construct(MockEntity::class, [
'id' => 'id',
'price' => 'price',
'name' => 'name',
'date' => 'date',
'someMadeUpField', 'someMadeUpField',
], []);
}
}
| mit |
Team-Cerberus/Invoice | public/models/Address.js | 334 | class Address {
constructor(streetAddress, city, zIP) {
this._streetAddress = streetAddress;
this._city = city;
this._zIP = zIP;
}
get streetAddress() {
return this._streetAddress;
}
get city() {
return this._city;
}
get zIP() {
return this._zIP;
}
} | mit |
devanhurst/trivtrainer | db/migrate/20160110194840_set_column_default_queue.rb | 332 | class SetColumnDefaultQueue < ActiveRecord::Migration
def change
change_column_default :queue1_clues, :queue, 1
change_column_default :queue2_clues, :queue, 2
change_column_default :queue3_clues, :queue, 3
change_column_default :queue4_clues, :queue, 4
change_column_default :queue5_clues, :queue, 5
end
end
| mit |
nhnent/tui.editor | plugins/table-merged-cell/webpack.config.js | 3330 | /* eslint-disable @typescript-eslint/no-var-requires */
const path = require('path');
const webpack = require('webpack');
const { name, version, author, license } = require('./package.json');
const CssMinimizerPlugin = require('css-minimizer-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const TerserPlugin = require('terser-webpack-plugin');
const ESLintPlugin = require('eslint-webpack-plugin');
const filename = `toastui-${name.replace(/@toast-ui\//, '')}`;
function getOutputConfig(isProduction, isCDN, minify) {
const defaultConfig = {
environment: {
arrowFunction: false,
const: false,
},
};
if (!isProduction || isCDN) {
const config = {
...defaultConfig,
library: {
name: ['toastui', 'Editor', 'plugin', 'tableMergedCell'],
export: 'default',
type: 'umd',
},
path: path.resolve(__dirname, 'dist/cdn'),
filename: `${filename}${minify ? '.min' : ''}.js`,
};
if (!isProduction) {
config.publicPath = '/dist/cdn';
}
return config;
}
return {
...defaultConfig,
library: {
export: 'default',
type: 'commonjs2',
},
path: path.resolve(__dirname, 'dist'),
filename: `${filename}.js`,
};
}
function getOptimizationConfig(isProduction, minify) {
const minimizer = [];
if (isProduction && minify) {
minimizer.push(
new TerserPlugin({
parallel: true,
extractComments: false,
}),
new CssMinimizerPlugin()
);
}
return { minimizer };
}
module.exports = (env) => {
const isProduction = env.WEBPACK_BUILD;
const { minify = false, cdn = false } = env;
const config = {
mode: isProduction ? 'production' : 'development',
entry: './src/index.ts',
output: getOutputConfig(isProduction, cdn, minify),
module: {
rules: [
{
test: /\.ts$|\.js$/,
use: [
{
loader: 'ts-loader',
options: {
transpileOnly: true,
},
},
],
exclude: /node_modules/,
},
{
test: /\.css$/,
use: [MiniCssExtractPlugin.loader, 'css-loader'],
},
],
},
resolve: {
extensions: ['.ts', '.js'],
alias: {
'@': path.resolve('src'),
'@t': path.resolve('types'),
},
},
plugins: [
new MiniCssExtractPlugin({
filename: () => `${filename}${minify ? '.min' : ''}.css`,
}),
new ESLintPlugin({
extensions: ['js', 'ts'],
exclude: ['node_modules', 'dist'],
failOnError: isProduction,
}),
],
optimization: getOptimizationConfig(isProduction, minify),
};
if (isProduction) {
config.plugins.push(
new webpack.BannerPlugin(
[
'TOAST UI Editor : Table Merged Cell Plugin',
`@version ${version} | ${new Date().toDateString()}`,
`@author ${author}`,
`@license ${license}`,
].join('\n')
)
);
} else {
config.devServer = {
// https://github.com/webpack/webpack-dev-server/issues/2484
injectClient: false,
inline: true,
host: '0.0.0.0',
port: 8081,
};
config.devtool = 'inline-source-map';
}
return config;
};
| mit |
plotly/python-api | packages/python/plotly/plotly/validators/contourcarpet/_legendgroup.py | 474 | import _plotly_utils.basevalidators
class LegendgroupValidator(_plotly_utils.basevalidators.StringValidator):
def __init__(
self, plotly_name="legendgroup", parent_name="contourcarpet", **kwargs
):
super(LegendgroupValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
edit_type=kwargs.pop("edit_type", "style"),
role=kwargs.pop("role", "info"),
**kwargs
)
| mit |
vurdalakov/rawcmp | src/rawcmp/Properties/AssemblyInfo.cs | 1519 | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Raw File Compare (rawcmp)")]
[assembly: AssemblyDescription("Compares raw content of two files, ignoring insignificant data and metadata")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Vurdalakov")]
[assembly: AssemblyProduct("Raw File Compare (rawcmp)")]
[assembly: AssemblyCopyright("Copyright © 2015 Vurdalakov")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("0d2d194d-7318-414f-8e84-c6fd6ec68b34")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| mit |
krytarowski/corert | src/ILCompiler.Compiler/src/Compiler/InteropStubManager.cs | 11272 | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using Internal.IL.Stubs;
using Internal.TypeSystem;
using Internal.TypeSystem.Interop;
using ILCompiler.DependencyAnalysis;
using Debug = System.Diagnostics.Debug;
using DependencyList = ILCompiler.DependencyAnalysisFramework.DependencyNodeCore<ILCompiler.DependencyAnalysis.NodeFactory>.DependencyList;
namespace ILCompiler
{
/// <summary>
/// This class is responsible for managing stub methods for interop
/// </summary>
public sealed class InteropStubManager
{
private readonly CompilationModuleGroup _compilationModuleGroup;
private readonly CompilerTypeSystemContext _typeSystemContext;
internal HashSet<TypeDesc> _delegateMarshalingTypes = new HashSet<TypeDesc>();
private HashSet<TypeDesc> _structMarshallingTypes = new HashSet<TypeDesc>();
private ModuleDesc _interopModule;
private const string _interopModuleName = "System.Private.Interop";
public InteropStateManager InteropStateManager
{
get;
}
public InteropStubManager(CompilationModuleGroup compilationModuleGroup, CompilerTypeSystemContext typeSystemContext, InteropStateManager interopStateManager)
{
_compilationModuleGroup = compilationModuleGroup;
_typeSystemContext = typeSystemContext;
InteropStateManager = interopStateManager;
// Note: interopModule might be null if we're building with a class library that doesn't support rich interop
_interopModule = typeSystemContext.GetModuleForSimpleName(_interopModuleName, false);
}
internal MethodDesc GetOpenStaticDelegateMarshallingStub(TypeDesc delegateType)
{
var stub = InteropStateManager.GetOpenStaticDelegateMarshallingThunk(delegateType);
Debug.Assert(stub != null);
_delegateMarshalingTypes.Add(delegateType);
return stub;
}
internal MethodDesc GetClosedDelegateMarshallingStub(TypeDesc delegateType)
{
var stub = InteropStateManager.GetClosedDelegateMarshallingThunk(delegateType);
Debug.Assert(stub != null);
_delegateMarshalingTypes.Add(delegateType);
return stub;
}
internal MethodDesc GetForwardDelegateCreationStub(TypeDesc delegateType)
{
var stub = InteropStateManager.GetForwardDelegateCreationThunk(delegateType);
Debug.Assert(stub != null);
_delegateMarshalingTypes.Add(delegateType);
return stub;
}
internal MethodDesc GetStructMarshallingManagedToNativeStub(TypeDesc structType)
{
MethodDesc stub = InteropStateManager.GetStructMarshallingManagedToNativeThunk(structType);
Debug.Assert(stub != null);
_structMarshallingTypes.Add(structType);
return stub;
}
internal MethodDesc GetStructMarshallingNativeToManagedStub(TypeDesc structType)
{
MethodDesc stub = InteropStateManager.GetStructMarshallingNativeToManagedThunk(structType);
Debug.Assert(stub != null);
_structMarshallingTypes.Add(structType);
return stub;
}
internal MethodDesc GetStructMarshallingCleanupStub(TypeDesc structType)
{
MethodDesc stub = InteropStateManager.GetStructMarshallingCleanupThunk(structType);
Debug.Assert(stub != null);
_structMarshallingTypes.Add(structType);
return stub;
}
internal TypeDesc GetInlineArrayType(InlineArrayCandidate candidate)
{
TypeDesc inlineArrayType = InteropStateManager.GetInlineArrayType(candidate);
Debug.Assert(inlineArrayType != null);
return inlineArrayType;
}
internal struct DelegateMarshallingThunks
{
public TypeDesc DelegateType;
public MethodDesc OpenStaticDelegateMarshallingThunk;
public MethodDesc ClosedDelegateMarshallingThunk;
public MethodDesc DelegateCreationThunk;
}
internal IEnumerable<DelegateMarshallingThunks> GetDelegateMarshallingThunks()
{
foreach (var delegateType in _delegateMarshalingTypes)
{
yield return
new DelegateMarshallingThunks()
{
DelegateType = delegateType,
OpenStaticDelegateMarshallingThunk = InteropStateManager.GetOpenStaticDelegateMarshallingThunk(delegateType),
ClosedDelegateMarshallingThunk = InteropStateManager.GetClosedDelegateMarshallingThunk(delegateType),
DelegateCreationThunk = InteropStateManager.GetForwardDelegateCreationThunk(delegateType)
};
}
}
internal struct StructMarshallingThunks
{
public TypeDesc StructType;
public NativeStructType NativeStructType;
public MethodDesc MarshallingThunk;
public MethodDesc UnmarshallingThunk;
public MethodDesc CleanupThunk;
}
internal IEnumerable<StructMarshallingThunks> GetStructMarshallingTypes()
{
foreach (var structType in _structMarshallingTypes)
{
yield return
new StructMarshallingThunks()
{
StructType = structType,
NativeStructType = InteropStateManager.GetStructMarshallingNativeType(structType),
MarshallingThunk = InteropStateManager.GetStructMarshallingManagedToNativeThunk(structType),
UnmarshallingThunk = InteropStateManager.GetStructMarshallingNativeToManagedThunk(structType),
CleanupThunk = InteropStateManager.GetStructMarshallingCleanupThunk(structType)
};
}
}
public void AddDependeciesDueToPInvoke(ref DependencyList dependencies, NodeFactory factory, MethodDesc method)
{
if (method.IsPInvoke)
{
dependencies = dependencies ?? new DependencyList();
MethodSignature methodSig = method.Signature;
AddDependenciesDueToPInvokeDelegate(ref dependencies, factory, methodSig.ReturnType);
for (int i = 0; i < methodSig.Length; i++)
{
AddDependenciesDueToPInvokeDelegate(ref dependencies, factory, methodSig[i]);
}
}
if (method.HasInstantiation)
{
dependencies = dependencies ?? new DependencyList();
AddMarshalAPIsGenericDependencies(ref dependencies, factory, method);
}
}
public void AddInterestingInteropConstructedTypeDependencies(ref DependencyList dependencies, NodeFactory factory, TypeDesc type)
{
if (type.IsDelegate)
{
var delegateType = (MetadataType)type;
if (delegateType.HasCustomAttribute("System.Runtime.InteropServices", "UnmanagedFunctionPointerAttribute"))
{
AddDependenciesDueToPInvokeDelegate(ref dependencies, factory, delegateType);
}
}
}
/// <summary>
/// For Marshal generic APIs(eg. Marshal.StructureToPtr<T>, GetFunctionPointerForDelegate) we add
/// the generic parameter as dependencies so that we can generate runtime data for them
/// </summary>
public void AddMarshalAPIsGenericDependencies(ref DependencyList dependencies, NodeFactory factory, MethodDesc method)
{
Debug.Assert(method.HasInstantiation);
TypeDesc owningType = method.OwningType;
MetadataType metadataType = owningType as MetadataType;
if (metadataType != null && metadataType.Module == _interopModule)
{
if (metadataType.Name == "Marshal" && metadataType.Namespace == "System.Runtime.InteropServices")
{
string methodName = method.Name;
if (methodName == "GetFunctionPointerForDelegate" ||
methodName == "GetDelegateForFunctionPointer" ||
methodName == "PtrToStructure" ||
methodName == "StructureToPtr" ||
methodName == "SizeOf" ||
methodName == "OffsetOf")
{
foreach (TypeDesc type in method.Instantiation)
{
AddDependenciesDueToPInvokeDelegate(ref dependencies, factory, type);
AddDependenciesDueToPInvokeStruct(ref dependencies, factory, type);
}
}
}
}
}
public void AddDependenciesDueToPInvokeDelegate(ref DependencyList dependencies, NodeFactory factory, TypeDesc type)
{
if (type.IsDelegate)
{
dependencies.Add(factory.NecessaryTypeSymbol(type), "Delegate Marshalling Stub");
dependencies.Add(factory.MethodEntrypoint(factory.InteropStubManager.GetOpenStaticDelegateMarshallingStub(type)), "Delegate Marshalling Stub");
dependencies.Add(factory.MethodEntrypoint(factory.InteropStubManager.GetClosedDelegateMarshallingStub(type)), "Delegate Marshalling Stub");
dependencies.Add(factory.MethodEntrypoint(factory.InteropStubManager.GetForwardDelegateCreationStub(type)), "Delegate Marshalling Stub");
}
}
public void AddDependenciesDueToPInvokeStruct(ref DependencyList dependencies, NodeFactory factory, TypeDesc type)
{
if (MarshalHelpers.IsStructMarshallingRequired(type))
{
dependencies.Add(factory.NecessaryTypeSymbol(type), "Struct Marshalling Stub");
var stub = (Internal.IL.Stubs.StructMarshallingThunk)factory.InteropStubManager.GetStructMarshallingManagedToNativeStub(type);
dependencies.Add(factory.MethodEntrypoint(stub), "Struct Marshalling stub");
dependencies.Add(factory.MethodEntrypoint(factory.InteropStubManager.GetStructMarshallingNativeToManagedStub(type)), "Struct Marshalling stub");
dependencies.Add(factory.MethodEntrypoint(factory.InteropStubManager.GetStructMarshallingCleanupStub(type)), "Struct Marshalling stub");
foreach (var inlineArrayCandidate in stub.GetInlineArrayCandidates())
{
foreach (var method in inlineArrayCandidate.ElementType.GetMethods())
{
dependencies.Add(factory.MethodEntrypoint(method), "inline array marshalling stub");
}
}
}
}
}
}
| mit |
rgnrok/Symfony | app/AppKernel.php | 1409 | <?php
use Symfony\Component\HttpKernel\Kernel;
use Symfony\Component\Config\Loader\LoaderInterface;
class AppKernel extends Kernel
{
public function registerBundles()
{
$bundles = array(
new Symfony\Bundle\FrameworkBundle\FrameworkBundle(),
new Symfony\Bundle\SecurityBundle\SecurityBundle(),
new Symfony\Bundle\TwigBundle\TwigBundle(),
new Symfony\Bundle\MonologBundle\MonologBundle(),
new Symfony\Bundle\SwiftmailerBundle\SwiftmailerBundle(),
new Symfony\Bundle\AsseticBundle\AsseticBundle(),
new Doctrine\Bundle\DoctrineBundle\DoctrineBundle(),
new Sensio\Bundle\FrameworkExtraBundle\SensioFrameworkExtraBundle(),
new Volcano\VideoStatusBundle\VolcanoVideoStatusBundle(),
new Knp\Bundle\MenuBundle\KnpMenuBundle(),
);
if (in_array($this->getEnvironment(), array('dev', 'test'))) {
$bundles[] = new Symfony\Bundle\WebProfilerBundle\WebProfilerBundle();
$bundles[] = new Sensio\Bundle\DistributionBundle\SensioDistributionBundle();
$bundles[] = new Sensio\Bundle\GeneratorBundle\SensioGeneratorBundle();
}
return $bundles;
}
public function registerContainerConfiguration(LoaderInterface $loader)
{
$loader->load(__DIR__.'/config/config_'.$this->getEnvironment().'.yml');
}
} | mit |
dmaldonadol/adm-ceppi | ws/ceppi-core/src/main/java/cl/ml/ceppi/core/model/persona/Persona.java | 3657 | /**
*
*/
package cl.ml.ceppi.core.model.persona;
import java.io.Serializable;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import cl.ml.ceppi.core.model.estado.Genero;
/**
* @author Maldonado León
*
*/
@Entity
@SequenceGenerator(name = "SEC_PERSONA", sequenceName = "SEC_PERSONA")
@Table(name = "PERSONA")
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public class Persona implements Serializable {
private static final long serialVersionUID = 8554029070080556470L;
@Id
@GeneratedValue(generator = "SEC_PERSONA")
@Column(name = "ID_PERSONA", nullable = false)
private int oid;
@Column(name = "RUT", unique = true, length = 10)
private String rut;
@Column(name = "DV", length = 1)
private String dv;
@Column(name = "NOMBRE", nullable = false, length = 100)
private String nombre;
@Column(name = "APE_PATERNO", nullable = false, length = 100)
private String apellidoPaterno;
@Column(name = "APE_MATERNO", length = 100)
private String apellidoMaterno;
@Column(name = "EMAIL", length = 50)
private String email;
@Column(name = "ESTATURA")
private String estatura;
@Column(name = "PESO")
private String peso;
@Column(name = "GENERO")
@Enumerated(EnumType.STRING)
private Genero genero;
@Column(name = "FECHA_NACIMIENTO")
@Temporal(TemporalType.DATE)
private Date fechaNacimiento;
/**
*
*/
public Persona() {
// TODO Auto-generated constructor stub
}
public Persona(String nombre, String apepaterno, String apematerno, String rut, String dv, String email,
Genero genero, String estatura, String peso, Date fechanac) {
this.nombre = nombre;
this.apellidoPaterno = apepaterno;
this.apellidoMaterno = apematerno;
this.rut = rut;
this.dv = dv;
this.email = email;
this.genero = genero;
this.estatura = estatura;
this.peso = peso;
this.fechaNacimiento = fechanac;
}
public int getOid() {
return oid;
}
public void setOid(int oid) {
this.oid = oid;
}
public String getRut() {
return rut;
}
public void setRut(String rut) {
this.rut = rut;
}
public String getDv() {
return dv;
}
public void setDv(String dv) {
this.dv = dv;
}
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public String getApellidoPaterno() {
return apellidoPaterno;
}
public void setApellidoPaterno(String apellidoPaterno) {
this.apellidoPaterno = apellidoPaterno;
}
public String getApellidoMaterno() {
return apellidoMaterno;
}
public void setApellidoMaterno(String apellidoMaterno) {
this.apellidoMaterno = apellidoMaterno;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getEstatura() {
return estatura;
}
public void setEstatura(String estatura) {
this.estatura = estatura;
}
public String getPeso() {
return peso;
}
public void setPeso(String peso) {
this.peso = peso;
}
public Genero getGenero() {
return genero;
}
public void setGenero(Genero genero) {
this.genero = genero;
}
public Date getFechaNacimiento() {
return fechaNacimiento;
}
public void setFechaNacimiento(Date fechaNacimiento) {
this.fechaNacimiento = fechaNacimiento;
}
}
| mit |
Grimace1975/gpustructs | src/Structs.Data.Pager/Core/KeyInfo.cs | 575 | namespace Contoso.Core
{
public class KeyInfo
{
public sqlite3b db; // The database connection
public byte enc; // Text encoding - one of the SQLITE_UTF* values
public ushort nField; // Number of entries in aColl[]
public byte[] aSortOrder; // Sort order for each column. May be NULL
public CollSeq[] aColl = new CollSeq[1]; // Collating sequence for each term of the key
public KeyInfo Copy()
{
return (KeyInfo)MemberwiseClone();
}
}
}
| mit |
Sylius/Resource | Storage/StorageInterface.php | 679 | <?php
/*
* This file is part of the Sylius package.
*
* (c) Paweł Jędrzejewski
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
declare(strict_types=1);
namespace Sylius\Component\Resource\Storage;
interface StorageInterface
{
public function has(string $name): bool;
/**
* @param mixed $default
*
* @return mixed
*/
public function get(string $name, $default = null);
/**
* @param mixed $value
*/
public function set(string $name, $value): void;
public function remove(string $name): void;
public function all(): array;
}
| mit |
arnosthavelka/spring-advanced-training | sat-core/src/test/java/com/github/aha/sat/core/wiring/beverage/BeverageSingleWiringTest.java | 1217 | package com.github.aha.sat.core.wiring.beverage;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.test.context.SpringBootTest;
import com.github.aha.sat.core.wiring.WiringConfig;
import com.github.aha.sat.core.wiring.trait.Alcoholic;
@SpringBootTest(classes = WiringConfig.class)
class BeverageSingleWiringTest {
@Autowired
private Beverage soda; // it's tea due to @Primary annotation
@Autowired
@Qualifier("soda")
private Beverage qualifiedBeverage;
@Autowired
private AbstractCarbonatedBeverage cola;
@Autowired
@Alcoholic
private Beverage coldBeer;
@Test
void shouldWirePrimaryBean() {
assertThat(soda.getName()).isEqualTo("Tea");
}
@Test
void shouldWireBeanByQualifier() {
assertThat(qualifiedBeverage.getName()).isEqualTo("Soda");
}
@Test
void shouldWireBeanByName() {
assertThat(cola.getName()).isEqualTo("Cola");
}
@Test
void shouldWireBeanByAnnotation() {
assertThat(coldBeer.getName()).isEqualTo("Beer");
}
}
| mit |
The127/JIoC | src/de/jioc3/IocContainer.java | 8768 | package de.jioc3;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Parameter;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.function.Supplier;
import de.jreflect4.ClassReflector;
import de.jreflect4.IInstanceReflector;
import de.jreflect4.ReflectionUtil;
import de.jreflect4.SimpleInstance;
import de.jreflect4.SuperToken;
import lombok.NonNull;
public class IocContainer implements IReadableContainer, IWritableContainer {
private class ObjectSupplier<T> implements Supplier<T> {
private final ClassReflector<? extends T> reflector;
public ObjectSupplier(Class<? extends T> implementationClass) {
if(implementationClass.isInterface() || ReflectionUtil.isAbstract(implementationClass.getModifiers()))
throw new RegisterException();
reflector = new ClassReflector<>(implementationClass);
}
@Override
public T get() {
try{
IocContainer.this.lock();
Constructor<? extends T>[] ctors = reflector.getAnnotatedConstructors(Inject.class);
if(ctors == null || ctors.length != 1)
throw new InjectorException("Could not identify @Inject constructor in '" + reflector.getReflectingClass().getName() + "'");
Constructor<? extends T> ctor = ctors[0];
ctor.setAccessible(true);
Parameter[] parameters = ctor.getParameters();
Class<?>[] ctorParameterTypes = ctor.getParameterTypes();
Object[] ctorParameters = new Object[ctorParameterTypes.length];
for(int i = 0; i < ctorParameters.length; i++)
if(ctorParameterTypes[i].equals(IReadableContainer.class))
ctorParameters[i] = IocContainer.this;
else if(parameters[i].isAnnotationPresent(InjectSingleton.class))
ctorParameters[i] = IocContainer.this.requestSingleton(ctorParameterTypes[i]);
else
ctorParameters[i] = IocContainer.this.request(ctorParameterTypes[i]);
try {
IInstanceReflector<? extends T> instance = new SimpleInstance<T>(ctor.newInstance(ctorParameters), reflector.getSecurityModel());
return instance.getObject();
} catch (InstantiationException | IllegalAccessException | IllegalArgumentException
| InvocationTargetException e) {
throw new RuntimeException(e);
}
}finally{
IocContainer.this.unlock();
}
}
}
private class SingletonSupplier<T> implements Supplier<T> {
private T singleton = null;
private Supplier<T> objectSupplier;
public SingletonSupplier(Supplier<T> objectSupplier) {
this.objectSupplier = objectSupplier;
}
public SingletonSupplier(T singleton) {
this.singleton = singleton;
}
@Override
public T get() {
if (singleton == null)
singleton = objectSupplier.get();
return singleton;
}
}
private final String name;
private final ReentrantReadWriteLock objectLock = new ReentrantReadWriteLock();
private final ReentrantReadWriteLock singletonLock = new ReentrantReadWriteLock();
private final Map<String, Supplier<?>> objectMappings = new HashMap<>();
private final Map<String, SingletonSupplier<?>> singletonMappings = new HashMap<>();
public IocContainer(String name) {
this.name = name;
}
public String getName() {
return name;
}
/**
* Locks the container while injecting.
*/
private void lock() {
objectLock.readLock().lock();
singletonLock.readLock().lock();
}
/**
* Unlocks the container after injecting.
*/
private void unlock() {
objectLock.readLock().unlock();
singletonLock.readLock().unlock();
}
private void register(String key, final Supplier<?> implementationSupplier) {
try {
objectLock.writeLock().lock();
if (objectMappings.containsKey(key))
throw new DuplicateIocEntryException(this, MappingType.Object, key);
else
objectMappings.put(key, implementationSupplier);
} finally {
objectLock.writeLock().unlock();
}
}
private void registerSingleton(String key, SingletonSupplier<?> singletonSupplier) {
try {
singletonLock.writeLock().lock();
if (singletonMappings.containsKey(key))
throw new DuplicateIocEntryException(this, MappingType.Singleton, key);
else
singletonMappings.put(key, singletonSupplier);
} finally {
singletonLock.writeLock().unlock();
}
}
@Override
public <Interface> void register(@NonNull final Class<Interface> interfaceClass,
@NonNull final Supplier<? extends Interface> implementationSupplier) {
register(interfaceClass.getName(), implementationSupplier);
}
@Override
public <Interface> void register(@NonNull final SuperToken<Interface> genericInterfaceToken,
@NonNull final Supplier<? extends Interface> implementationSupplier) {
register(genericInterfaceToken.getTypeName(), implementationSupplier);
}
@Override
public <Interface> void register(@NonNull final Class<Interface> interfaceClass,
@NonNull final Class<? extends Interface> implementationClass) {
register(interfaceClass.getName(), new ObjectSupplier<Interface>(implementationClass));
}
@Override
public <Interface> void register(@NonNull final SuperToken<Interface> genericInterfaceToken,
@NonNull final Class<? extends Interface> implementationClass) {
register(genericInterfaceToken.getTypeName(), new ObjectSupplier<Interface>(implementationClass));
}
@Override
public <Interface> void registerSingleton(@NonNull Class<Interface> interfaceClass,
@NonNull Interface implementation) {
registerSingleton(interfaceClass.getName(), new SingletonSupplier<>(implementation));
}
@Override
public <Interface> void registerSingleton(@NonNull SuperToken<Interface> genericInterfaceToken,
@NonNull Interface implementation) {
registerSingleton(genericInterfaceToken.getTypeName(), new SingletonSupplier<>(implementation));
}
@Override
public <Interface> void registerSingleton(@NonNull final Class<Interface> interfaceClass,
@NonNull Supplier<? extends Interface> implementationSupplier) {
registerSingleton(interfaceClass.getName(), new SingletonSupplier<>(implementationSupplier));
}
@Override
public <Interface> void registerSingleton(@NonNull final SuperToken<Interface> genericInterfaceToken,
@NonNull final Supplier<? extends Interface> implementationSupplier) {
registerSingleton(genericInterfaceToken.getTypeName(), new SingletonSupplier<>(implementationSupplier));
}
@Override
public <Interface> void registerSingleton(@NonNull final Class<Interface> interfaceClass,
@NonNull final Class<? extends Interface> implementationClass) {
registerSingleton(interfaceClass.getName(), new SingletonSupplier<>(new ObjectSupplier<>(implementationClass)));
}
@Override
public <Interface> void registerSingleton(@NonNull final SuperToken<Interface> genericInterfaceToken,
@NonNull final Class<? extends Interface> implementationClass) {
registerSingleton(genericInterfaceToken.getTypeName(), new SingletonSupplier<>(new ObjectSupplier<>(implementationClass)));
}
@SuppressWarnings("unchecked")
private <Interface> Interface request(String key) {
try {
objectLock.readLock().lock();
if (!objectMappings.containsKey(key))
throw new EntryNotFoundException(this, MappingType.Object, key);
else
return (Interface) objectMappings.get(key).get();
} finally {
objectLock.readLock().unlock();
}
}
@SuppressWarnings("unchecked")
private <Interface> Interface requestSingleton(String key) {
try {
singletonLock.readLock().lock();
if (!singletonMappings.containsKey(key))
throw new EntryNotFoundException(this, MappingType.Singleton, key);
else
return (Interface) singletonMappings.get(key).get();
} finally {
singletonLock.readLock().unlock();
}
}
@Override
public <Interface> Interface request(@NonNull final Class<Interface> interfaceClass) {
return request(interfaceClass.getName());
}
@Override
public <Interface> Interface request(@NonNull final SuperToken<Interface> genericInterfaceToken) {
return request(genericInterfaceToken.getTypeName());
}
@Override
public <Interface> Interface requestSingleton(@NonNull final Class<Interface> interfaceClass) {
return requestSingleton(interfaceClass.getName());
}
@Override
public <Interface> Interface requestSingleton(@NonNull final SuperToken<Interface> genericInterfaceToken) {
return requestSingleton(genericInterfaceToken.getTypeName());
}
boolean contains(Class<?> clazz){
try{
objectLock.readLock().lock();
return objectMappings.containsKey(clazz.getName());
}finally{
objectLock.readLock().unlock();
}
}
boolean contains(SuperToken<?> token){
try{
objectLock.readLock().lock();
return objectMappings.containsKey(token.getTypeName());
}finally{
objectLock.readLock().unlock();
}
}
}
| mit |
robinjfisher/Touchstone | lib/generators/touchstone/templates/touchstone.rb | 1019 | # encoding: utf-8
Touchstone.config do |c|
# By default, Touchstone assumes that you have a User model
# in your application and will associate campaign signups
# with a user_id in the campaign_signups table. You can
# customise the association by using this configuration
# option.
c.association_name = "User"
# When viewing a campaign, Touchstone will show a list of
# users who have signed up as a result of that campaign.
# Use this option to set an array of fields that you would
# like to appear in the view. By default, Touchstone will
# only show the id and created_at fields.
c.column_names = [:id,:created_at]
# This sets the currency symbol that you would like
# displayed. By default it is $
c.currency = "$"
# If set to true, http_basic authentication will be in place
# before you can access Touchstone. You should create a YAML
# file in Rails.root/config called touchstone.yml containing
# a name and password
c.authenticate = true
end | mit |
JaredShay/aus_post_api | spec/aus_post_api/pac/international_parcel_weight_spec.rb | 185 | require 'spec_helper'
describe AusPostAPI::PAC::InternationalParcelWeight do
let(:required_attributes) { {} }
let(:optional_attributes) { {} }
it_behaves_like 'an endpoint'
end
| mit |
mandarin6b0/rpush | lib/rpush/client/active_model.rb | 1357 | require 'active_model'
require 'rpush/client/active_model/notification'
require 'rpush/client/active_model/payload_data_size_validator'
require 'rpush/client/active_model/registration_ids_count_validator'
require 'rpush/client/active_model/apns/binary_notification_validator'
require 'rpush/client/active_model/apns/device_token_format_validator'
require 'rpush/client/active_model/apns/app'
require 'rpush/client/active_model/apns/notification'
require 'rpush/client/active_model/apns2/app'
require 'rpush/client/active_model/apns2/notification'
require 'rpush/client/active_model/apnsp8/app'
require 'rpush/client/active_model/apnsp8/notification'
require 'rpush/client/active_model/adm/data_validator'
require 'rpush/client/active_model/adm/app'
require 'rpush/client/active_model/adm/notification'
require 'rpush/client/active_model/gcm/expiry_collapse_key_mutual_inclusion_validator'
require 'rpush/client/active_model/gcm/app'
require 'rpush/client/active_model/gcm/notification'
require 'rpush/client/active_model/wpns/app'
require 'rpush/client/active_model/wpns/notification'
require 'rpush/client/active_model/wns/app'
require 'rpush/client/active_model/wns/notification'
require 'rpush/client/active_model/pushy/app'
require 'rpush/client/active_model/pushy/notification'
require 'rpush/client/active_model/pushy/time_to_live_validator'
| mit |
nohros/must | src/base/common/data/readers/DataField.cs | 2034 | using System;
using System.Data;
using Nohros.Resources;
namespace Nohros.Data
{
/// <summary>
/// Provides a skeletal implementation of the <see cref="IDataField{T}"/>
/// interface to minimize the effort required to implement that interface.
/// </summary>
/// <typeparam name="T">
/// The type of the underlying value.
/// </typeparam>
public abstract class DataField<T> : IDataField<T>
{
/// <summary>
/// The field's name.
/// </summary>
protected readonly string name;
/// <summary>
/// The zero-based ordinal column of the field.
/// </summary>
protected readonly int position;
#region .ctor
/// <summary>
/// Initializes a new instance of the <see cref="DataField{T}"/> class by
/// using the specified field <paramref name="name"/> and
/// ordinal <paramref name="position"/>.
/// </summary>
/// <param name="name">
/// The name of the field.
/// </param>
/// <param name="position">
/// The zero based ordinal position of the field within an
/// <see cref="IDataReader"/>.
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="name"/> is <c>null</c>.
/// </exception>
/// <exception cref="IndexOutOfRangeException">
/// <paramref name="position"/> is negative.
/// </exception>
protected DataField(string name, int position) {
if (name == null) {
throw new ArgumentNullException("name");
}
if (position < 0) {
throw new IndexOutOfRangeException(
string.Format(StringResources.ArgumentOutOfRange_NeedNonNegNum));
}
this.name = name;
this.position = position;
}
#endregion
/// <inheritdoc/>
public int Position {
get { return position; }
}
/// <inheritdoc/>
public string Name {
get { return name; }
}
/// <inheritdoc/>
public abstract T GetValue(IDataReader reader);
}
}
| mit |
crobert/gesti-truc | application/controllers/collections.php | 6549 | <?php
class Collections extends MY_Auth {
function Collections()
{
parent::__construct();
}
function index()
{
$this->clearBreadcrumbs();
$this->load->model('collection');
$collections = $this->collection->getAll();
$data['collections'] = $collections;
$data['titre_page'] = 'Aperçu';
$data['vue'] = 'collections/collections.php';
$data['menu'] = 'collections';
$this->load->view('template', $data);
}
function add(){
//Règles pour tous les champs
$this->load->library('form_validation');
$this->form_validation->set_rules('name', 'Nom', 'trim|required|xss_clean');
//$this->form_validation->set_rules('description', 'Description', 'trim|required|xss_clean');
//$this->form_validation->set_rules('type', 'Type', 'trim|required|xss_clean');
if ($this->form_validation->run() == FALSE) {
$data['titre_page'] = 'Aperçu';
$data['vue'] = 'collections/add_view.php';
$data['menu'] = 'collections';
$this->load->helper('form');
$this->load->view('template', $data);
} else {
//$now = new DateTime("now", new DateTimeZone('Europe/Paris'));
$this->load->model('collection');
$id= $this->collection->add($this->input->post());
//We upload the picture
if(isset($_FILES['picture'])){
$configUpload['upload_path'] = './uploads/collections';
$configUpload['allowed_types'] = 'gif|jpg|png';
$configUpload['overwrite'] = true;
$configUpload['max_size'] = '10000';
$_FILES['picture']['name'] = $id."_".$_FILES['picture']['name'];
$this->load->library('upload', $configUpload);
if($this->upload->do_upload('picture'))
{
$configImage['image_library'] = 'gd2';
$configImage['source_image'] = './uploads/collections/'.$_FILES['picture']['name'];
$configImage['maintain_ratio'] = TRUE;
$configImage['width'] = 200;
$configImage['height'] = 200;
$this->load->library('image_lib', $configImage);
if ( ! $this->image_lib->resize())
{
//$this->SetMsg($this->image_lib->display_errors(), '', TypeMessage::Error, false);
}
$this->collection->update($id, array('picture'=> $_FILES['picture']['name'] ));
}else{
//On indique l'erreur, l'image reste la même
// $this->SetMsg($this->upload->display_errors(), '', TypeMessage::Error, false);
}
}
redirect('collections/detail/'.$id);
}
}
function edit($id){
$this->load->model('collection');
$c= $this->collection->getById($id);
//Règles pour tous les champs
$this->load->library('form_validation');
$this->form_validation->set_rules('name', 'Nom', 'trim|required|xss_clean');
//$this->form_validation->set_rules('description', 'Description', 'trim|required|xss_clean');
//$this->form_validation->set_rules('type', 'Type', 'trim|required|xss_clean');
if ($this->form_validation->run() == FALSE) {
$data['titre_page'] = 'Aperçu';
$data['vue'] = 'collections/edit_view.php';
$data['menu'] = 'collections';
$data['c'] = $c;
$this->load->helper('form');
$this->load->view('template', $data);
} else {
//$now = new DateTime("now", new DateTimeZone('Europe/Paris'));
$this->load->model('collection');
$id= $this->collection->update($id,$this->input->post());
//We upload the picture
if(isset($_FILES['picture'])){
$configUpload['upload_path'] = './uploads/collections';
$configUpload['allowed_types'] = 'gif|jpg|png';
$configUpload['overwrite'] = true;
$configUpload['max_size'] = '10000';
$_FILES['picture']['name'] = $id."_".$_FILES['picture']['name'];
$this->load->library('upload', $configUpload);
if($this->upload->do_upload('picture'))
{
$configImage['image_library'] = 'gd2';
$configImage['source_image'] = './uploads/collections/'.$_FILES['picture']['name'];
$configImage['maintain_ratio'] = TRUE;
$configImage['width'] = 200;
$configImage['height'] = 200;
$this->load->library('image_lib', $configImage);
if ( ! $this->image_lib->resize())
{
//$this->SetMsg($this->image_lib->display_errors(), '', TypeMessage::Error, false);
}
$this->collection->update($id, array('picture'=> $_FILES['picture']['name'] ));
}else{
//On indique l'erreur, l'image reste la même
// $this->SetMsg($this->upload->display_errors(), '', TypeMessage::Error, false);
}
}
redirect('collections/detail/'.$id);
}
}
function detail($id){
$this->load->model('collection');
$this->load->model('category');
$c= $this->collection->getById($id);
$this->addBreadcrumbs("collections/detail/".$id, $c->name);
//todo test si $c existe
$categories = $this->category->getByCollection($id);
$data['titre_page'] = 'Aperçu';
$data['vue'] = 'collections/detail_view.php';
$data['menu'] = 'collections';
$data['c'] = $c;
$data['categories'] = $categories;
$this->load->view('template', $data);
}
function delete($id)
{
$this->load->model('collection');
$this->load->model('category');
$this->load->model('item');
$categories = $this->category->getByCollection($id);
foreach($categories as $cat)
{
$this->item->deleteByCategory($cat->id);
$this->category->delete($cat->id);
}
$this->collection->delete($id);
redirect('collections/');
}
}
/* End of file users.php */
/* Location: ./application/controllers/users.php */ | mit |
zaqwes8811/micro-apps | buffer/win-admin-tools/vb-webm-wmi/cs.net/NetSettingsSet/NetSettingsSet2/Form1.cs | 18928 | using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Text;
using System.Management;
using System.Windows.Forms;
using System.Diagnostics;
using System.Threading;
using System.Xml;
using System.Xml.XPath;
using System.IO;
/**
* Логика работы:
* 1. Во время инициализации загружаются настройки из xml-файла и читаются текущие
* настройки сети.
*/
namespace NetSettingsSet2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
button2.Enabled = false;
button4.Enabled = false;
getNetWorkState(false, false);
if (!loadSaveNetSet(true)) {
loadSaveNetSet(true); // возникло исключение и нужно повторить
}
}
/// <summary>
/// Очень большой метод
/// </summary>
/// <param name="sets"></param>
/// <param name="LoadForForm"></param>
private void getNetWorkState(bool sets, bool LoadForForm) {
try {
ManagementClass objMC_ = new ManagementClass(
"Win32_NetworkAdapterConfiguration");
ManagementObjectCollection objMOC_ = objMC_.GetInstances();
// начало перебора
int NumNic = 0; int NumDHCP = 0;
foreach (ManagementObject objMO in objMOC_) {
if (!(bool)objMO["ipEnabled"])
continue;
// адаптер
if (!sets)
{
if (!LoadForForm) listBox1.Items.Add("Адаптер: ");
if (!LoadForForm) listBox1.Items.Add(objMO["Caption"]);
if (!LoadForForm) listBox1.Items.Add(objMO["MACAddress"]);
}
// сетевые настройки
string[] ipaddresses = (string[])objMO["IPAddress"];
string[] subnets = (string[])objMO["IPSubnet"];
string[] gateways = (string[])objMO["DefaultIPGateway"];
// IP-адрес
if (ipaddresses[0] != "0.0.0.0")
{
/// вводим настройки если задано
if (sets)
{
/// /// настройка ip-адреса и маски подсети
ManagementBaseObject setIP;
ManagementBaseObject newIP = objMO.GetMethodParameters("EnableStatic");
newIP["IPAddress"] = new string[] { textBoxIP.Text };
newIP["SubnetMask"] = new string[] { textBoxSM.Text };
setIP = objMO.InvokeMethod("EnableStatic", newIP, null);
if (setIP["returnValue"].ToString() == "0")
{
listBox1.Items.Add("IP-адрес и маска подсети установлены");
}
else
{
listBox1.Items.Add("Ошибка установки IP-адреса и маски подсети.");
listBox1.Items.Add("Воспользуйтесь стандартынм методом настройки.");
}
/// настройка шлюза
ManagementBaseObject setGateway;
ManagementBaseObject newGateway =
objMO.GetMethodParameters("SetGateways");
newGateway["DefaultIPGateway"] = new string[] { textBoxGW.Text };
newGateway["GatewayCostMetric"] = new int[] { 1 };
setGateway = objMO.InvokeMethod("SetGateways", newGateway, null);
// проверка возвращаемого занчения
if (setGateway["returnValue"].ToString() == "0")
{
listBox1.Items.Add("IP-адрес шлюза установлены.");
}
else
{
listBox1.Items.Add("Ошибка установки IP-адреса шлюза.");
listBox1.Items.Add("Воспользуйтесь стандартынм методом настройки.");
}
}
else
{
/// читаме настройки
bool dhcp_ena = (bool)objMO["DHCPEnabled"];
if (dhcp_ena)
{
listBox1.Items.Add("Включена служба DHCP.");
NumDHCP++;
}
else
{
// ip
if (ipaddresses != null)
{
if (LoadForForm) textBoxIP.Text = ipaddresses[0];
else listBox1.Items.Add("IP-адрес:" + ipaddresses[0]);
}
// маска
if (subnets != null)
{
if (LoadForForm) textBoxSM.Text = subnets[0];
else listBox1.Items.Add("Маска подсети:" + subnets[0]);
}
// шлюз
if (gateways != null)
{
if (LoadForForm) textBoxGW.Text = gateways[0];
else listBox1.Items.Add("IP-адрес шлюза по умолчанию:" + gateways[0]);
}
else
{
listBox1.Items.Add("IP-адрес шлюза по умолчанию не назначен.");
}
}
NumNic++; //
} // if(sets)..
} // if (ipad..
} // foreach (Mana..
if (!sets)
{
if (!LoadForForm) listBox1.Items.Add("Всего активных подключений: " + NumNic.ToString());
switch (NumNic)
{ // итого по сетям
case 1:
{
if (NumDHCP == 0)
{
if (!LoadForForm)
listBox1.Items.Add("Активное подключение одно и оно статическое.");
if (!LoadForForm)
listBox1.Items.Add("Настройки можно свободно менять.");
else
listBox1.Items.Add("Настройки считаны.");
button2.Enabled = true;
button4.Enabled = true;
}
else
{
listBox1.Items.Add("DHCP для работы должен быть отключен.");
listBox1.Items.Add("Из данной программы сделать это так, чтобы");
listBox1.Items.Add("соединение работало стабильно, нельзя.");
listBox1.Items.Add("Действия: оключаем DHCP, вводим в ручную настройки,");
listBox1.Items.Add("загружаем их в программу.");
listBox1.Items.Add("Подробно:");
listBox1.Items.Add("- Открываем <Панель управления>-><Сетевые подключения>");
listBox1.Items.Add("- Выбираем <подключение>-><Свойства>->");
listBox1.Items.Add(" <Протокол Интернета TCP/IP>-><Свойства>");
listBox1.Items.Add(" Выбираем <Использовать следующий IP-адрес>");
listBox1.Items.Add("- Вводим туда настройки, полученные от администратора.");
listBox1.Items.Add("В данной программе нажимаем <Получить текущее состояние>");
listBox1.Items.Add("Установленные настройки отобразятся на форме, ");
listBox1.Items.Add("и сохранятся в файле <cfg.xml>. Закрываем окно и входим в программу");
listBox1.Items.Add("управления передатчиком. Жмем <Обновить>. Теперь данные на форме");
listBox1.Items.Add("основного приложения соответсвуют настройкам сетевого адаптера.");
}
} break;
case 0:
{
listBox1.Items.Add("Активных подключений не обранужено");
} break;
default:
{
listBox1.Items.Add("Найдено несколько активных соединения по TCP/IP.");
listBox1.Items.Add("Возможно данный компьютер настроен как маршрутизатор.");
} break;
} // switch (Num..
} // if(sets..)
} // try {...
catch(Exception err){
listBox1.Items.Add("Исключение: " + err.ToString());
}
}
/// <summary>
/// создает файл с настройками по умолчанию
/// </summary>
private void createXmlCfg() {
XmlTextWriter tW = new XmlTextWriter("cfg.xml", null);
tW.WriteStartDocument();
///
tW.WriteStartElement("SaveData");
tW.WriteStartElement("SetConnection");
/// Настройки СОМ-порта
tW.WriteStartElement("RS_232");
string[] TagCom = new string[] {
"PortName", "Speed"
};
string[] TagComValue = new string[] {
"COM1", "9600"
};
for (int i = 0; i < 2; i++)
{
tW.WriteStartElement(TagCom[i]);
tW.WriteString(TagComValue[i]);
tW.WriteEndElement();
}
///
tW.WriteEndElement();
tW.WriteStartElement("Ethernet");
// настройки сети
string[] TagEt = new string[] {
"sIP", "sPort" , "dIP", "dPort",
"SubMask","Gateway" };
string[] TagEtValue = new string[] {
"172.23.132.223", "5000" ,
"127.0.0.1", "5001",
"255.255.224.0","172.23.128.254"
};
for (int i = 0; i < 6; i++)
{
tW.WriteStartElement(TagEt[i]);
tW.WriteString(TagEtValue[i]); tW.WriteEndElement();
}
tW.WriteEndElement(); // ethernet
tW.WriteEndElement();
// общие настройки
///
string[] TagsNames = new string[] {
"OutFrequency", "OutPower",
"AutoRun", "RegimeMS",
"RegimePP", "PreDistortion",
"FrequencyDivisionMultiplexing",
"Output", "AmplificationAB_dB"};
string[] Values = new string[] {
"103.05", "250",
"выключить", "моно",
"полярная модуляция", "выключить",
"выключить",
"аналоговый", "+3.5"};
tW.WriteStartElement("MainTransiver");
for (int i = 0; i < 9; i++)
{
tW.WriteStartElement(TagsNames[i]);
tW.WriteString(Values[i]);
tW.WriteEndElement();
}
tW.WriteEndElement(); /// StartElement("Ma..
///
tW.WriteStartElement("GlobalSets"); // общие настройки
string[] TagsGS = new string[] {
"ConnectionType", "Power", "Reserve"
};
string[] TagsGSV = new string[] {
"Ethernet", "10-500 Вт", "включено"
};
for (int i = 0; i < 3; i++) {
tW.WriteStartElement(TagsGS[i]);
tW.WriteString(TagsGSV[i]);
tW.WriteEndElement();
}
tW.WriteEndElement();
///
tW.WriteEndElement();
///
tW.WriteEndDocument();
tW.Close();
}
/// <summary>
/// загружает занчения из файла либо сохраняет в файл
/// </summary>
/// <param name="Load"></param>
/// <returns></returns>
private bool loadSaveNetSet(bool Load) {
bool itog = true;
XmlDocument xmlDoc; // заготовка
xmlDoc = new XmlDocument(); // без конкретизации
try
{
xmlDoc.Load("cfg.xml");
XmlNodeList xmlNodes;
XmlNode xmlElement;
string[] pathSet = new string[3];
pathSet[0] = "/SaveData/SetConnection/Ethernet/sIP";
pathSet[1] = "/SaveData/SetConnection/Ethernet/SubMask";
pathSet[2] = "/SaveData/SetConnection/Ethernet/Gateway";
string elementValue;
for (int j = 0; j < 3; j++)
{
xmlNodes = xmlDoc.SelectNodes(pathSet[j]);
// Производим циклический перебор найденных элементов,
for (int i = 0; i < xmlNodes.Count; i++)
{
xmlElement = xmlNodes[i];
if (xmlElement.HasChildNodes)
{
// чтение
elementValue = xmlElement.FirstChild.Value.Trim();
switch (j)
{
case 0:
{
if (Load) textBoxIP.Text = elementValue;
else xmlElement.InnerText = textBoxIP.Text;
} break;
case 1:
{
if (Load) textBoxSM.Text = elementValue;
else xmlElement.InnerText = textBoxSM.Text;
} break;
case 2:
{
if (Load) textBoxGW.Text = elementValue;
else xmlElement.InnerText = textBoxGW.Text;
} break;
default: { } break;
}
}
}
} // for (int j =..
if (!Load) xmlDoc.Save("cfg.xml");
}
catch (XPathException ex)
{
listBox1.Items.Add("Элемент не найден.");
}
catch (XmlException err)
{
listBox1.Items.Add("Исключения при работе с xml.");
}
catch (FileNotFoundException err2)
{
listBox1.Items.Add("Ошибка: Файл cfg.xml не найден и создан с настройками");
listBox1.Items.Add("по умолчанию и данные из него загружены");
createXmlCfg();
itog = false; // нужен еще проход
}
return itog;
}
/// <summary>
/// OnEvent
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button1_Click(object sender, EventArgs e)
{
button2.Enabled = false;
button4.Enabled = false;
getNetWorkState(false, false);
}
private void button2_Click(object sender, EventArgs e)
{
listBox1.Items.Add("Подождите. Смена настрек может занять несколько секунд.");
getNetWorkState(true, false); // установить, на форму не выводимть
}
private void button3_Click(object sender, EventArgs e)
{
listBox1.Items.Clear();
}
private void button4_Click(object sender, EventArgs e)
{
getNetWorkState(false, true); // читать и вывести на форму
}
private void button5_Click(object sender, EventArgs e)
{
}
private void ClosedForm(object sender, FormClosedEventArgs e)
{
loadSaveNetSet(false); // сохраняем настройки
}
private void ClosingForm(object sender, FormClosingEventArgs e)
{
loadSaveNetSet(false); // сохраняем настройки
}
}
}
| mit |
macbury/eter | db/migrate/20141204112542_add_default_values_to_users.rb | 198 | class AddDefaultValuesToUsers < ActiveRecord::Migration
def change
change_column :users, :first_name, :string, default: ""
change_column :users, :last_name, :string, default: ""
end
end
| mit |
qcubed/application | src/Jqui/Event/AutocompleteResponse.php | 1319 | <?php
/**
*
* Part of the QCubed PHP framework.
*
* @license MIT
*
*/
namespace QCubed\Jqui\Event;
/**
* Class AutocompleteResponse
*
* The abstract AutocompleteResponse class defined here is
* code-generated. The code to generate this file is
* in the /tools/jquery_ui_gen/jq_control_gen.php file
* and you can regenerate the files if you need to.
*
* The comments in this file are taken from the api reference site, so they do
* not always make sense with regard to QCubed. They are simply provided
* as reference.
* Triggered after a search completes, before the menu is shown. Useful
* for local manipulation of suggestion data, where a custom source
* option callback is not required. This event is always triggered when a
* search completes, even if the menu will not be shown because there are
* no results or the Autocomplete is disabled.
*
* * event Type: Event
*
* * ui Type: Object
*
* * content Type: Array Contains the response data and can be modified
* to change the results that will be shown. This data is already
* normalized, so if you modify the data, make sure to include both value
* and label properties for each item.
*
*
* @was QAutocomplete_ResponseEvent
*/
class AutocompleteResponse extends EventBase
{
const EVENT_NAME = 'autocompleteresponse';
}
| mit |
manjarb/ReduxSimpleStarter | src/components/app.js | 280 | import React, { Component } from 'react';
import CommentBox from './comment_box'
import CommentList from './comment_list'
export default class App extends Component {
render() {
return (
<div>
<CommentBox />
<CommentList />
</div>
);
}
}
| mit |
ktingvoar/PixiGlitch | src/CutSliderFilter.js | 1422 | /**
* @author Matt Smith http://gun.net.au @ktingvoar
*/
var core = require('../../node_modules/pixi.js/src/core');
// @see https://github.com/substack/brfs/issues/25
var fs = require('fs');
function CutSliderFilter() {
PIXI.AbstractFilter.call(this,
null,
fs.readFileSync(__dirname + '/cutslider.frag', 'utf8'),
{
rand: {type: '1f', value: 5},
val1: {type: '1f', value: 150},
val2: {type: '1f', value: 20},
dimensions: {type: '4fv', value: [0, 0, 0, 0]}
}
);
};
CutSliderFilter.prototype = Object.create(core.AbstractFilter.prototype);
CutSliderFilter.prototype.constructor = CutSliderFilter;
Object.defineProperty(CutSliderFilter.prototype, 'rand', {
get: function() {
return this.uniforms.rand.value;
},
set: function(value) {
this.dirty = true;
this.uniforms.rand.value = value;
}
});
Object.defineProperty(CutSliderFilter.prototype, 'val1', {
get: function() {
return this.uniforms.val1.value;
},
set: function(value) {
this.dirty = true;
this.uniforms.val1.value = value;
}
});
Object.defineProperty(CutSliderFilter.prototype, 'val2', {
get: function() {
return this.uniforms.val2.value;
},
set: function(value) {
this.dirty = true;
this.uniforms.val2.value = value;
}
});
module.exports = CutSliderFilter; | mit |
CatLabInteractive/charon | example/Petstore/Controllers/AbstractResourceController.php | 2022 | <?php
namespace App\Petstore\Controllers;
use CatLab\Charon\Collections\ResourceCollection;
use CatLab\Charon\InputParsers\JsonBodyInputParser;
use CatLab\Charon\InputParsers\PostInputParser;
use CatLab\Charon\Interfaces\RESTResource;
use CatLab\Charon\Models\Context;
/**
* Class AbstractResourceController
* @package App\Petstore\Controllers
*/
class AbstractResourceController
{
/**
* Output a list of resources
* @param ResourceCollection $resources
* @param $type
*/
protected function outputResources(ResourceCollection $resources, $type)
{
switch ($type) {
case 'json':
default:
$this->outputJson($resources->toArray());
return;
}
}
/**
* Output a list of resources
* @param RESTResource $resources
* @param $type
*/
protected function outputResource(RESTResource $resources, $type)
{
switch ($type) {
case 'json':
default:
$this->outputJson($resources->toArray());
return;
}
}
/**
* @param $action
* @return Context
*/
protected function getContext($action)
{
$context = new Context($action);
$context->addInputParser(JsonBodyInputParser::class);
if (isset($_GET['fields'])) {
$context->showFields(array_map('trim', explode(',', $_GET['fields'])));
}
if (isset($_GET['expand'])) {
$context->expandFields(array_map('trim', explode(',', $_GET['expand'])));
}
return $context;
}
/**
* @param $data
*/
protected function outputJson($data)
{
header('Content-type: application/json');
echo json_encode($data);
}
/**
* @param $entity
* @param $id
*/
protected function abortNotFound($entity, $id)
{
http_response_code(404);
echo $entity . ' with id ' . $id . ' not found';
exit;
}
}
| mit |
crmaxx/netscanner-ui | webpack.config.js | 3839 | /*eslint no-var:0 */
var fs = require('fs');
var path = require('path');
var webpack = require('webpack');
var rimraf = require('rimraf');
var autoprefixer = require('autoprefixer-core');
var mqpacker = require('css-mqpacker');
var csswring = require('csswring');
var cssvars = require('postcss-custom-properties');
var cssimport = require('postcss-import');
var cssmerge = require('postcss-merge-rules');
var nested = require('postcss-nested');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var packageJson = require('./package.json');
// figure out if we're running `webpack` or `webpack-dev-server`
// we'll use this as the default for `isDev`
var isDev = process.argv[1].indexOf('webpack-dev-server') !== -1;
var hostName = 'localhost';
var port = 3000;
var useHash = false;
var clearBeforeBuild = true;
var config;
var minifyOptions = {
removeComments: true,
collapseWhitespace: true
};
function buildFilename(pack, hash, ext) {
var middle;
if (hash) {
middle = ext === 'css' ? '[contenthash]' : '[hash]';
} else {
middle = pack.version;
}
return [pack.name, middle, (ext || 'js')].join('.');
}
config = {
entry: ['./src/app'],
output: {
path: path.join(__dirname, 'public'),
filename: isDev ? 'bundle.js' : buildFilename(packageJson, useHash, 'js'),
cssFilename: isDev ? 'bundle.css' : buildFilename(packageJson, useHash, 'css')
},
resolve: {
extensions: ['', '.js', '.json']
},
plugins: [
new HtmlWebpackPlugin({title: 'Hello React!', minify: minifyOptions}),
new HtmlWebpackPlugin({title: 'Hello React!', minify: minifyOptions, filename: '200.html'})
],
module: {
loaders: [
{
test: /(\.js$)|(\.jsx$)/,
exclude: /node_modules/,
loaders: ['babel']
},
{
test: /\.json$/,
loaders: ['json']
},
{
test: /\.(otf|eot|svg|ttf|woff)/,
loader: 'url?limit=10000'
}
]
}
};
if (isDev) {
config.devServer = {
port: port,
historyApiFallback: true,
host: hostName,
hot: true
};
config.entry.unshift(
'webpack-dev-server/client?http://' + hostName + ':' + port,
'webpack/hot/only-dev-server'
);
config.plugins.push(
new webpack.HotModuleReplacementPlugin(),
new webpack.NoErrorsPlugin(),
new webpack.SourceMapDevToolPlugin(
'[file].map',
null,
'[absolute-resource-path]',
'[absolute-resource-path]'
)
);
config.module.loaders[0].loaders.unshift('react-hot');
config.module.loaders.push(
{
test: /\.css$/,
loaders: ['style', 'css?sourceMap', 'postcss?sourceMap']
}
);
config.postcss = [
cssimport(),
nested(),
cssvars(),
autoprefixer({browsers: ['last 2 versions']})
];
} else {
// clear out output folder if so configured
if (clearBeforeBuild) {
rimraf.sync(config.output.path);
fs.mkdirSync(config.output.path);
}
config.plugins.push(
new webpack.optimize.DedupePlugin(),
new webpack.optimize.OccurenceOrderPlugin(true),
new webpack.optimize.UglifyJsPlugin({
compress: {
warnings: false
},
output: {
comments: false
},
sourceMap: false
}),
new ExtractTextPlugin(config.output.cssFilename, {
allChunks: true
}),
new webpack.DefinePlugin({
'process.env': {NODE_ENV: JSON.stringify('production')}
})
);
// extract in production
config.module.loaders.push(
{
test: /\.css$/,
loader: ExtractTextPlugin.extract('style', 'css!postcss')
}
);
config.postcss = [
cssimport(),
nested(),
cssvars(),
cssmerge(),
autoprefixer({browsers: ['last 2 versions']}),
mqpacker(),
csswring()
];
}
module.exports = config;
| mit |
amudalab/concept-graphs | document retrieval/try.py | 1065 | from os import listdir
##fn=open("Corpus/intro/ds11.txt")
##raw=fn.read()
##raw2=raw.replace('subtree','sub tree')
##fn.close()
##fn=open("Corpus/intro/ds11.txt","w")
##fn.write(raw2)
##fn.close()
##fp = open('db/introhier.gdf')
##text=fp.read()
##pl=text.split('\n')
###print(p1)
##flag=0
##V=[]
##VN={}
##flag=0
##for each_line in pl:
## l=each_line.split(',')
## if len(l)==2:
## if flag!=0:
## V.append(l[1].replace("\n","").replace("\r",""))
## VN[l[0]]=l[1].replace("\n","").replace("\r","")
## flag=1
##
##print V
##lis1 = [f for f in listdir("C:/Users/Romauld/Desktop/final version 3/new_data_struct/Keys/intro/comp")]
##for j in lis1:
## f = open("Keys/intro/comp/"+j)
## raw=f.read().lower()
## w=raw.split("\n")
## f.close()
## f = open("Keys/intro/comp/"+j,"w")
## print w
## for x in w:
## print x
## if x in V:
## f.write(str(x)+"\n")
## f.close()
##
for i in range(5):
for j in range(i,5):
print i, j
| mit |
skela/linkedin-java | Main/src/org/linkedin/schema/MembershipStateCode.java | 2517 | /*
* Copyright 2010-2011 Nabeel Mukhtar
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.linkedin.schema;
import javax.xml.bind.annotation.XmlEnum;
import javax.xml.bind.annotation.XmlEnumValue;
/**
* <p>Java class for null.
*
* <p>The following schema fragment specifies the expected content contained within this class.
* <p>
* <pre>
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* <enumeration value="blocked"/>
* <enumeration value="non-member"/>
* <enumeration value="awaiting-confirmation"/>
* <enumeration value="awaiting-parent-group-confirmation"/>
* <enumeration value="member"/>
* <enumeration value="moderator"/>
* <enumeration value="manager"/>
* <enumeration value="owner"/>
* </restriction>
* </simpleType>
* </pre>
*
*/
@XmlEnum
public enum MembershipStateCode {
@XmlEnumValue("blocked")
BLOCKED("blocked"),
@XmlEnumValue("non-member")
NON_MEMBER("non-member"),
@XmlEnumValue("awaiting-confirmation")
AWAITING_CONFIRMATION("awaiting-confirmation"),
@XmlEnumValue("awaiting-parent-group-confirmation")
AWAITING_PARENT_GROUP_CONFIRMATION("awaiting-parent-group-confirmation"),
@XmlEnumValue("member")
MEMBER("member"),
@XmlEnumValue("moderator")
MODERATOR("moderator"),
@XmlEnumValue("manager")
MANAGER("manager"),
@XmlEnumValue("owner")
OWNER("owner");
private final String value;
MembershipStateCode(String v) {
value = v;
}
public String value() {
return value;
}
public static MembershipStateCode fromValue(String v) {
for (MembershipStateCode c: MembershipStateCode.values()) {
if (c.value.equals(v)) {
return c;
}
}
throw new IllegalArgumentException(v.toString());
}
}
| mit |
orocrm/platform | src/Oro/Bundle/ApiBundle/Tests/Unit/Processor/Delete/InitializeConfigExtrasTest.php | 1637 | <?php
namespace Oro\Bundle\ApiBundle\Tests\Unit\Processor\Delete;
use Oro\Bundle\ApiBundle\Config\Extra\EntityDefinitionConfigExtra;
use Oro\Bundle\ApiBundle\Config\Extra\FilterIdentifierFieldsConfigExtra;
use Oro\Bundle\ApiBundle\Processor\Delete\InitializeConfigExtras;
use Oro\Bundle\ApiBundle\Tests\Unit\Processor\TestConfigExtra;
class InitializeConfigExtrasTest extends DeleteProcessorTestCase
{
/** @var InitializeConfigExtras */
private $processor;
protected function setUp()
{
parent::setUp();
$this->processor = new InitializeConfigExtras();
}
public function testProcessWhenConfigExtrasAreAlreadyInitialized()
{
$this->context->setConfigExtras([]);
$this->context->addConfigExtra(new EntityDefinitionConfigExtra());
$this->context->setAction('test_action');
$this->processor->process($this->context);
self::assertEquals(
[new EntityDefinitionConfigExtra()],
$this->context->getConfigExtras()
);
}
public function testProcess()
{
$this->context->setConfigExtras([]);
$existingExtra = new TestConfigExtra('test');
$this->context->addConfigExtra($existingExtra);
$this->context->setAction('test_action');
$this->processor->process($this->context);
self::assertEquals(
[
new TestConfigExtra('test'),
new EntityDefinitionConfigExtra($this->context->getAction()),
new FilterIdentifierFieldsConfigExtra()
],
$this->context->getConfigExtras()
);
}
}
| mit |
gaearon/redux-devtools | extension/examples/todomvc/components/Footer.js | 1837 | import React, { Component } from 'react';
import PropTypes from 'prop-types';
import classnames from 'classnames';
import {
SHOW_ALL,
SHOW_COMPLETED,
SHOW_ACTIVE,
} from '../constants/TodoFilters';
const FILTER_TITLES = {
[SHOW_ALL]: 'All',
[SHOW_ACTIVE]: 'Active',
[SHOW_COMPLETED]: 'Completed',
};
class Footer extends Component {
renderTodoCount() {
const { activeCount } = this.props;
const itemWord = activeCount === 1 ? 'item' : 'items';
return (
<span className="todo-count">
<strong>{activeCount || 'No'}</strong> {itemWord} left
</span>
);
}
renderFilterLink(filter) {
const title = FILTER_TITLES[filter];
const { filter: selectedFilter, onShow } = this.props;
return (
<a
className={classnames({ selected: filter === selectedFilter })}
style={{ cursor: 'pointer' }}
onClick={() => onShow(filter)}
>
{title}
</a>
);
}
renderClearButton() {
const { completedCount, onClearCompleted } = this.props;
if (completedCount > 0) {
return (
<button className="clear-completed" onClick={onClearCompleted}>
Clear completed
</button>
);
}
}
render() {
return (
<footer className="footer">
{this.renderTodoCount()}
<ul className="filters">
{[SHOW_ALL, SHOW_ACTIVE, SHOW_COMPLETED].map((filter) => (
<li key={filter}>{this.renderFilterLink(filter)}</li>
))}
</ul>
{this.renderClearButton()}
</footer>
);
}
}
Footer.propTypes = {
completedCount: PropTypes.number.isRequired,
activeCount: PropTypes.number.isRequired,
filter: PropTypes.string.isRequired,
onClearCompleted: PropTypes.func.isRequired,
onShow: PropTypes.func.isRequired,
};
export default Footer;
| mit |
Talkdesk/desk | spec/desk/client/user_spec.rb | 1711 | require 'helper'
describe Desk::Client do
Desk::Configuration::VALID_FORMATS.each do |format|
context ".new(:format => '#{format}')" do
before do
@client = Desk::Client.new(:subdomain => "example", :format => format, :consumer_key => 'CK', :consumer_secret => 'CS', :oauth_token => 'OT', :oauth_token_secret => 'OS')
end
describe ".user" do
context "with id passed" do
before do
stub_get("users/1.#{format}").
to_return(:body => fixture("user.#{format}"), :headers => {:content_type => "application/#{format}; charset=utf-8"})
end
it "should get the correct resource" do
@client.user(1)
a_get("users/1.#{format}").
should have_been_made
end
it "should return extended information of a given user" do
user = @client.user(1)
user.name.should == "Chris Warren"
end
end
end
describe ".users" do
context "lookup" do
before do
stub_get("users.#{format}").
to_return(:body => fixture("users.#{format}"), :headers => {:content_type => "application/#{format}; charset=utf-8"})
end
it "should get the correct resource" do
@client.users
a_get("users.#{format}").
should have_been_made
end
it "should return up to 100 users worth of extended information" do
users = @client.users
users.results.should be_a Array
users.results.first.user.name.should == "Test User"
end
end
end
end
end
end
| mit |
exu/symfony2-jobeet | src/Ens/JobeetBundle/Entity/Category.php | 2837 | <?php
namespace Ens\JobeetBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Ens\JobeetBundle\Utils\Jobeet;
/**
* Category
*
* @ORM\Table()
* @ORM\Entity(repositoryClass="Ens\JobeetBundle\Entity\CategoryRepository")
* @ORM\HasLifecycleCallbacks
*/
class Category
{
/**
* @var integer
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @var string
*
* @ORM\Column(name="name", type="string", length=255)
*/
private $name;
/**
* @var string
*
* @ORM\Column(name="slug", type="string", length=255)
*/
private $slug;
/**
* @ORM\OneToMany(targetEntity="Job", mappedBy="category")
*/
private $jobs;
/**
* Constructor
*/
public function __construct()
{
$this->jobs = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* Get id
*
* @return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set name
*
* @param string $name
* @return Category
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* @return string
*/
public function getName()
{
return $this->name;
}
public function getSlug()
{
return $this->slug;
}
public function setSlug($slug)
{
$this->slug = $slug;
}
/**
* Add jobs
*
* @param \Ens\JobeetBundle\Entity\Job $jobs
* @return Category
*/
public function addJob(\Ens\JobeetBundle\Entity\Job $jobs)
{
$this->jobs[] = $jobs;
return $this;
}
/**
* Remove jobs
*
* @param \Ens\JobeetBundle\Entity\Job $jobs
*/
public function removeJob(\Ens\JobeetBundle\Entity\Job $jobs)
{
$this->jobs->removeElement($jobs);
}
/**
* Get jobs
*
* @return \Doctrine\Common\Collections\Collection
*/
public function getJobs()
{
return $this->jobs;
}
public function __toString()
{
return '(' . $this->getId() . ') ' . $this->getName();
}
private $activeJobs;
public function setActiveJobs($jobs)
{
$this->activeJobs = $jobs;
}
public function getActiveJobs()
{
return $this->activeJobs;
}
private $moreJobs;
public function setMoreJobs($jobs)
{
$this->moreJobs = $jobs >= 0 ? $jobs : 0;
}
public function getMoreJobs()
{
return $this->moreJobs;
}
/**
* @ORM\PrePersist
* @ORM\PreUpdate
*/
public function setSlugValue()
{
$this->slug = Jobeet::slugify($this->getName());
}
}
| mit |
bigdig/vnpy | vnpy/api/oes/generator/generate_api_functions_td.py | 16429 | """"""
import importlib
class ApiGenerator:
"""API生成器"""""
def __init__(self, filename: str, prefix: str, name: str, class_name: str):
"""Constructor"""
self.filename = filename
self.prefix = prefix
self.name = name
self.class_name = class_name
self.callbacks = {}
self.functions = {}
self.lines = {}
self.subs = {}
self.final = {}
self.final_structs = {}
self.structs = {}
def load_struct_todo(self):
"""加载Struct"""
self.load_base_model()
self.load_packets()
self.load_qry_packets()
def load_packets(self):
""""""
module_name = "oes_struct_packets_td"
module = importlib.import_module(module_name)
for name in dir(module):
if "__" not in name:
self.final_structs[name] = getattr(module, name)
def load_qry_packets(self):
""""""
module_name = "oes_struct_qry_packets_td"
module = importlib.import_module(module_name)
for name in dir(module):
if "__" not in name:
self.structs[name] = getattr(module, name)
module_name_ = "oes_substruct_base_model_td"
module_ = importlib.import_module(module_name_)
for name_ in dir(module_):
self.subs[name_] = getattr(module_, name_)
for struct_name, fields in self.structs.items():
if not fields:
continue
d = {}
for name, type_ in fields.items():
if type_ != "dict":
d[name] = type_
else:
value = self.subs[name]
d.update(value)
self.final[struct_name] = d
for struct_name, fields in self.final.items():
if not fields:
continue
d = {}
for name, type_ in fields.items():
if type_ != "dict":
d[name] = type_
else:
value = self.subs[name]
d.update(value)
self.final_structs[struct_name] = d
def load_base_model(self):
""""""
module_name = "oes_struct_base_model_td"
module = importlib.import_module(module_name)
for name in dir(module):
if "__" not in name:
self.structs[name] = getattr(module, name)
module_name_ = "oes_substruct_base_model_td"
module_ = importlib.import_module(module_name_)
for name_ in dir(module_):
self.subs[name_] = getattr(module_, name_)
# 1 times
for struct_name, fields in self.structs.items():
if not fields:
continue
d = {}
for name, type_ in fields.items():
if type_ != "dict":
d[name] = type_
else:
value = self.subs[name]
d.update(value)
self.final[struct_name] = d
# 2 times
for struct_name, fields in self.final.items():
if not fields:
continue
d = {}
for name, type_ in fields.items():
if type_ != "dict":
d[name] = type_
else:
value = self.subs[name]
d.update(value)
self.final_structs[struct_name] = d
def run(self):
"""运行生成"""
self.load_struct_todo()
self.f_cpp = open(self.filename, "r", encoding="UTF-8")
for line in self.f_cpp:
self.process_line(line)
self.f_cpp.close()
# print(self.functions, "\n")
# print(self.callbacks, "\n")
self.generate_header_define()
self.generate_header_process()
self.generate_header_on()
self.generate_header_function()
self.generate_source_task()
self.generate_source_switch()
self.generate_source_process()
self.generate_source_function()
self.generate_source_on()
self.generate_source_module()
print("API生成成功")
def process_line(self, line: str):
"""处理每行"""
line = line.replace(";", "")
line = line.replace("\n", "")
line = line.replace("\t", "")
line = line.replace("{}", "")
if "virtual void On" in line or "virtual int32 On" in line:
self.process_callback(line)
elif "int32 Query" in line:
self.process_function(line)
def process_callback(self, line: str):
"""处理回掉函数"""
name = line[line.index("On"):line.index("(")]
self.lines[name] = line
d = self.generate_arg_dict(line)
self.callbacks[name] = d
def process_function(self, line: str):
"""处理主动函数"""
name = line[line.index("Query"):line.index("(")]
d = self.generate_arg_dict(line)
self.functions[name] = d
def generate_arg_dict(self, line: str):
"""生成参数字典"""
args_str = line[line.index("(") + 1:line.index(")")]
if not args_str:
return {}
args = args_str.split(",")
d = {}
for arg in args:
arg = arg.replace("const", "")
words = arg.split(" ")
words = [word for word in words if word]
d[words[1].replace("*", "")] = words[0]
return d
def generate_header_define(self):
""""""
filename = f"{self.prefix}_{self.name}_header_define.h"
with open(filename, "w") as f:
for n, name in enumerate(self.callbacks.keys()):
line = f"#define {name.upper()} {n}\n"
f.write(line)
def generate_header_process(self):
""""""
filename = f"{self.prefix}_{self.name}_header_process.h"
with open(filename, "w") as f:
for name in self.callbacks.keys():
name = name.replace("On", "process")
line = f"void {name}(Task *task);\n\n"
f.write(line)
def generate_header_on(self):
""""""
filename = f"{self.prefix}_{self.name}_header_on.h"
with open(filename, "w") as f:
for name, d in self.callbacks.items():
name = name.replace("On", "on")
args_list = []
for type_ in d.values():
if type_ == "int32":
args_list.append("int reqid")
elif type_ == "OesRptMsgHeadT" or type_ == "OesQryCursorT":
args_list.append("const dict &error")
else:
args_list.append("const dict &data")
args_str = ", ".join(args_list)
line = f"virtual void {name}({args_str}) {{}};\n\n"
f.write(line)
def generate_header_function(self):
""""""
filename = f"{self.prefix}_{self.name}_header_function.h"
with open(filename, "w") as f:
for name in self.functions.keys():
name = name.replace("Query", "query")
line = f"int {name}(const dict &req, int reqid);\n\n"
f.write(line)
def generate_source_task(self):
""""""
filename = f"{self.prefix}_{self.name}_source_task.cpp"
with open(filename, "w") as f:
for name, d in self.callbacks.items():
line = self.lines[name]
f.write(line.replace("virtual void ",
f"void {self.class_name}::") + "\n")
f.write("{\n")
f.write("\tTask task = Task();\n")
f.write(f"\ttask.task_name = {name.upper()};\n")
for field, type_ in d.items():
if type_ == "int32":
f.write(f"\ttask.task_id = {field};\n")
elif type_ == "OesRptMsgHeadT" or type_ == "OesQryCursorT":
f.write(f"\tif ({field})\n")
f.write("\t{\n")
f.write(f"\t\t{type_} *task_error = new {type_}();\n")
f.write(f"\t\t*task_error = *{field};\n")
f.write(f"\t\ttask.task_error = task_error;\n")
f.write("\t}\n")
else:
f.write(f"\tif ({field})\n")
f.write("\t{\n")
f.write(f"\t\t{type_} *task_data = new {type_}();\n")
f.write(f"\t\t*task_data = *{field};\n")
f.write(f"\t\ttask.task_data = task_data;\n")
f.write("\t}\n")
f.write(f"\tthis->task_queue.push(task);\n")
f.write("};\n\n")
def generate_source_switch(self):
""""""
filename = f"{self.prefix}_{self.name}_source_switch.cpp"
with open(filename, "w") as f:
for name in self.callbacks.keys():
process_name = name.replace("On", "process")
f.write(f"case {name.upper()}:\n")
f.write("{\n")
f.write(f"\tthis->{process_name}(&task);\n")
f.write(f"\tbreak;\n")
f.write("}\n\n")
def generate_source_process(self):
""""""
filename = f"{self.prefix}_{self.name}_source_process.cpp"
with open(filename, "w") as f:
for name, d in self.callbacks.items():
process_name = name.replace("On", "process")
on_name = name.replace("On", "on")
f.write(
f"void {self.class_name}::{process_name}(Task *task)\n")
f.write("{\n")
f.write("\tgil_scoped_acquire acquire;\n")
args = []
for field, type_ in d.items():
if type_ == "int32":
args.append("task->task_id")
elif type_ == "OesRptMsgHeadT" or type_ == "OesQryCursorT":
args.append("error")
f.write("\tdict error;\n")
f.write("\tif (task->task_error)\n")
f.write("\t{\n")
f.write(
f"\t\t{type_} *task_error = ({type_}*)task->task_error;\n")
struct_fields = self.final_structs[type_]
for struct_field, struct_type in struct_fields.items():
if struct_type == "string":
f.write(
f"\t\terror[\"{struct_field}\"] = toUtf(task_error->{struct_field});\n")
else:
f.write(
f"\t\terror[\"{struct_field}\"] = task_error->{struct_field};\n")
f.write("\t\tdelete task_error;\n")
f.write("\t}\n")
else:
args.append("data")
f.write("\tdict data;\n")
f.write("\tif (task->task_data)\n")
f.write("\t{\n")
f.write(
f"\t\t{type_} *task_data = ({type_}*)task->task_data;\n")
if type_ not in [
"OesMarketStateItemT", "OesTrdItemT", "OesLotWinningItemT",
"OesOrdItemT", "OesCustItemT", "OesFundTransferSerialItemT",
"OesIssueItemT", "OesStockItemT", "OesOptExerciseAssignItemT",
"OesEtfItemT", "OesOptionItemT", "OesOptUnderlyingHoldingItemT",
"OesNotifyInfoItemT", "eOesApiChannelTypeT", "OesApiSessionInfoT",
"pSubscribeInfo", "OesApiSubscribeInfoT"
]:
struct_fields = self.final_structs[type_]
for struct_field, struct_type in struct_fields.items():
if struct_type == "string":
f.write(
f"\t\tdata[\"{struct_field}\"] = toUtf(task_data->{struct_field});\n")
else:
f.write(
f"\t\tdata[\"{struct_field}\"] = task_data->{struct_field};\n")
f.write("\t\tdelete task_data;\n")
f.write("\t}\n")
args_str = ", ".join(args)
f.write(f"\tthis->{on_name}({args_str});\n")
f.write("};\n\n")
def generate_source_function(self):
""""""
filename = f"{self.prefix}_{self.name}_source_function.cpp"
with open(filename, "w") as f:
for name, d in self.functions.items():
req_name = name.replace("Query", "query")
type_ = list(d.values())[0]
f.write(
f"int {self.class_name}::{req_name}(const dict &req, int reqid)\n")
f.write("{\n")
f.write(f"\t{type_} myreq = {type_}();\n")
f.write("\tmemset(&myreq, 0, sizeof(myreq));\n")
struct_fields = self.final_structs.get(type_, None)
if not struct_fields:
line = f"\tgetString(req, \"{type_}\", myreq.{type_});\n"
f.write(line)
else:
for struct_field, struct_type in struct_fields.items():
if struct_type == "string":
line = f"\tgetString(req, \"{struct_field}\", myreq.{struct_field});\n"
else:
line = f"\tget{struct_type.capitalize()}(req, \"{struct_field}\", &myreq.{struct_field});\n"
f.write(line)
f.write(f"\tint i = this->api->{name}(&myreq, reqid);\n")
f.write("\treturn i;\n")
f.write("};\n\n")
def generate_source_on(self):
""""""
filename = f"{self.prefix}_{self.name}_source_on.cpp"
with open(filename, "w") as f:
for name, d in self.callbacks.items():
on_name = name.replace("On", "on")
args = []
bind_args = ["void", self.class_name, on_name]
for field, type_ in d.items():
if type_ == "int32":
args.append("int reqid")
bind_args.append("reqid")
elif type_ == "OesRptMsgHeadT" or type_ == "OesQryCursorT":
args.append("const dict &error")
bind_args.append("error")
else:
args.append("const dict &data")
bind_args.append("data")
args_str = ", ".join(args)
bind_args_str = ", ".join(bind_args)
f.write(f"void {on_name}({args_str}) override\n")
f.write("{\n")
f.write("\ttry\n")
f.write("\t{\n")
f.write(f"\t\tPYBIND11_OVERLOAD({bind_args_str});\n")
f.write("\t}\n")
f.write("\tcatch (const error_already_set &e)\n")
f.write("\t{\n")
f.write(f"\t\tcout << e.what() << endl;\n")
f.write("\t}\n")
f.write("};\n\n")
def generate_source_module(self):
""""""
filename = f"{self.prefix}_{self.name}_source_module.cpp"
with open(filename, "w") as f:
for name in self.functions.keys():
name = name.replace("Query", "query")
f.write(f".def(\"{name}\", &{self.class_name}::{name})\n")
f.write("\n")
for name in self.callbacks.keys():
name = name.replace("On", "on")
f.write(f".def(\"{name}\", &{self.class_name}::{name})\n")
f.write(";\n")
if __name__ == "__main__":
td_generator = ApiGenerator("../include_for_generator/oes/oes_client_sample.h", "oes", "td", "TdApi")
td_generator.run()
| mit |
tgallice/wit-php-example | src/Action/QuickAction.php | 2516 | <?php
namespace Tgallice\WitDemo\Action;
use Symfony\Component\Console\Output\OutputInterface;
use Tgallice\Wit\ActionMapping;
use Tgallice\Wit\Helper;
use Tgallice\Wit\Model\Context;
use Tgallice\Wit\Model\Step\Action;
use Tgallice\Wit\Model\Step\Message;
use Tgallice\Wit\Model\Step\Merge;
use Tgallice\Wit\Model\Step\Stop;
class QuickAction extends ActionMapping
{
private $output;
public function __construct(OutputInterface $output)
{
$this->output = $output;
}
/**
* @inheritdoc
*/
public function action($sessionId, Context $context, Action $step)
{
$this->output->writeln(sprintf('<info>+ (%f) Action : %s</info>', $step->getConfidence(), $step->getAction()));
if (!empty($step->getEntities())) {
$this->output->writeln('<info>+ Entities provided:</info>');
$this->output->writeln('<comment>'.json_encode($step->getEntities(), JSON_PRETTY_PRINT).'</comment>');
}
if ($step->getAction() === 'getForecast') {
$context = $this->getForecast($context, $step->getEntities());
}
return $context;
}
/**
* @inheritdoc
*/
public function say($sessionId, Context $context, Message $step)
{
$this->output->writeln(sprintf('<info>+ (%f) Say : %s</info>', $step->getConfidence(), $step->getMessage()));
$this->output->writeln('+++ '.$step->getMessage());
}
/**
* @inheritdoc
*/
public function error($sessionId, Context $context, $error = '', array $step = null)
{
$this->output->writeln('<error>'.$error.'</error>');
}
/**
* @inheritdoc
*/
public function merge($sessionId, Context $context, Merge $step)
{
$this->output->writeln(sprintf('<info>+ (%f) Merge context with :</info>', $step->getConfidence()));
$this->output->writeln('<comment>'.json_encode($step->getEntities(), JSON_PRETTY_PRINT).'</comment>');
return $context;
}
/**
* @inheritdoc
*/
public function stop($sessionId, Context $context, Stop $step)
{
$this->output->writeln(sprintf('<info>+ (%f) Stop</info>', $step->getConfidence()));
}
private function getForecast(Context $context, array $entities = [])
{
$loc = Helper::getFirstEntityValue('location', $entities);
if (!$loc) {
return new Context(['missingLocation' => true]);
}
return new Context(['forecast' => 'sunny in '.$loc]);
}
}
| mit |
willopez/domainsjs | shared/components/reports-view/config.js | 398 | export default {
chart: {
type: 'pie'
},
title: {
text: 'Top Level Domain types'
},
tooltip: {
pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>'
},
plotOptions: {
pie: {
allowPointSelect: true,
cursor: 'pointer',
dataLabels: {
enabled: true,
format: '<b>{point.name}</b>: {point.percentage:.1f} %',
},
},
},
};
| mit |
foomango/antex | chapter3_example_irssibot/irssibot/src/irssibot/modules/TopicTools.java | 20489 | /*
* $Id: TopicTools.java,v 1.1.1.1 2001/03/26 10:57:42 matti Exp $
*
* IrssiBot - An advanced IRC automation ("bot")
* Copyright (C) 2000 Matti Dahlbom
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*
* mdahlbom@cc.hut.fi
*/
package irssibot.modules;
import java.util.*;
import java.text.SimpleDateFormat;
/* imports */
import irssibot.core.*;
import irssibot.user.*;
import irssibot.util.*;
/**
* Represents an topic entry in topic list.
*/
class TopicEntry
{
private String content = null;
private String author = null;
private Date timeStamp = null;
private String dateFormatString = null;
public TopicEntry(String content,String author,Date timeStamp,String dateFormatString)
{
this.timeStamp = timeStamp;
this.content = content;
this.dateFormatString = dateFormatString;
if( author != null )
this.author = author;
else
this.author = "Unknown";
}
public String getContent() { return content; }
public String getAuthor() { return author; }
public Date getTimeStamp() { return timeStamp; }
public TopicEntry(String content,String author,String dateFormatString) {
this(content,author,new Date(),dateFormatString);
}
public String toString()
{
String ret = null;
SimpleDateFormat sdf = new SimpleDateFormat(dateFormatString);
ret = content+" ("+sdf.format(timeStamp)+", "+author+")";
return ret;
}
}
/**
* Implements a series of utilities to edit channel topic.
*
* @author Matti Dahlbom
* @version $Name: $ $Revision: 1.1.1.1 $
*/
public class TopicTools /*implements Module */extends AbstractModule
{
/* statics */
private static String moduleInfo = "Topic Tools 1.0.0 for IrssiBot";
private Hashtable topicStore = null;
private boolean hasChanged = false;
private String dateFormatString = null;
/* per-request temp data */
private Host botHost = null;
private Host host = null;
private String source = null;
private ServerConnection caller = null;
public TopicTools()
{
}
public boolean onLoad(Properties state,Core core)
{
topicStore = new Hashtable();
dateFormatString = core.getDateFormatString();
if( state != null )
loadInitialState(state,core);
else
getAllTopics(core);
return true;
}
/**
* Initializes the module from the given state.
*
* @param state initial state
*/
private void loadInitialState(Properties state,Core core)
{
Vector v = core.getServerInstances();
ServerConnection connection = null;
Enumeration channels = null;
Channel channel = null;
String key = null;
String tmp = null;
int numTopics ;
Date timestamp = null;
/* go through the server connections */
for( int i = 0; i < v.size(); i++ ) {
connection = (ServerConnection)v.elementAt(i);
channels = connection.getChannels().elements();
/* go through channels for this server connection */
while( channels.hasMoreElements() ) {
channel = (Channel)channels.nextElement();
key = connection.getInstanceData().getNetwork()+"-"+channel.getChannelName();
/* get the number of topic entries for this channel */
tmp = state.getProperty(key+"-numTopics");
if( tmp != null ) {
try {
numTopics = Integer.parseInt(tmp);
} catch( NumberFormatException e ) {
numTopics = -1;
}
if( numTopics > 0 ) {
TopicEntry values[] = new TopicEntry[numTopics];
/* get all topic entries for channel */
for( int j = 0; j < numTopics; j++ ) {
String content = state.getProperty(key+"-topic"+j);
String author = state.getProperty(key+"-author"+j);
String timeStampStr = state.getProperty(key+"-timestamp"+j);
try {
timestamp = new Date(Long.parseLong(timeStampStr));
} catch( NumberFormatException e ) {
timestamp = new Date();
}
values[j] = new TopicEntry(content,author,timestamp,dateFormatString);
}
topicStore.put(key,values);
}
}
}
}
}
/**
* Gets (same as !tg) topics of all channels of all server connections.
*
* @param core Core instance
*/
private void getAllTopics(Core core)
{
Vector v = core.getServerInstances();
source = null;
Enumeration channels = null;
Channel channel = null;
for( int i = 0; i < v.size(); i++ ) {
caller = (ServerConnection)v.elementAt(i);
channels = caller.getChannels().elements();
while( channels.hasMoreElements() ) {
channel = (Channel)channels.nextElement();
commandTG(null,null,null,channel);
}
}
}
public void onUnload()
{
topicStore = null;
}
public Properties getState()
{
Properties props = null;
if( hasChanged ) {
hasChanged = false;
props = constructState();
}
return props;
}
/**
* Constructs a Properties object representing the state of this module.
* Stored in the Properties for each channel of each server connection:<ul>
* <li>number of channel topics as network-channel-numTopics
* <li>each topic entry as network-channel-topicN (N = {0,1,2,..,numTopics-1})
* <li>time stamp of each topic entry as network-channel-timestampN (see above)
* <li>author of each topic entry as network-channel-authorN (see above)</ul>
*
* @return the constructed Properties object
*/
private Properties constructState()
{
Enumeration keys = topicStore.keys();
Properties props = new Properties();
String key = null;
TopicEntry value[] = null;
while( keys.hasMoreElements() ) {
key = (String)keys.nextElement();
value = (TopicEntry[])topicStore.get(key);
props.put(key+"-numTopics",String.valueOf(value.length));
for( int i = 0; i < value.length; i++ ) {
props.put(key+"-topic"+i,value[i].getContent());
props.put(key+"-timestamp"+i,String.valueOf(value[i].getTimeStamp().getTime()));
props.put(key+"-author"+i,value[i].getAuthor());
}
}
return props;
}
/**
* returns a module info string
*/
public String getModuleInfo()
{
return moduleInfo;
}
/**
* combine topics and send channel topic to server
*
* @param value entries of topic
* @param channel to set topic on
*/
private void constructTopic(TopicEntry value[],Channel channel)
{
String sep = "";
String topic = "";
/* do nothing if not op on channel */
if( channel.isOp() && value != null ) {
for( int i = 0; i < value.length; i++ ) {
topic += sep + value[i].getContent();
sep = " | ";
}
caller.write("TOPIC "+channel.getChannelName()+" :"+topic+"\n");
}
}
/**
* deletes a topic
*
* @param host host of invoker
* @param invoker invoking User
* @param args arguments of command
* @param channel target channel
*/
private void commandTD(Host host,User invoker,String args[],Channel channel)
{
String key = null;
TopicEntry value[] = null;
TopicEntry newValue[] = null;
int index = -1;
boolean isOk = true;
/* construct hash key from server instance name and channel name */
key = caller.getInstanceData().getNetwork()+"-"+channel.getChannelName();
if( topicStore.containsKey(key) ) {
/* get & remove old value */
value = (TopicEntry[])topicStore.get(key);
if( value.length < 1 ) {
/* already null topic */
isOk = false;
} else {
newValue = new TopicEntry[value.length - 1];
}
if( isOk && (args != null) && (args.length == 1) && (args[0] != null)) {
try {
index = Integer.parseInt(args[0]);
} catch( NumberFormatException e ) {
/* bad argument */
isOk = false;
}
if( isOk && (index > -1) ) {
System.out.println(index);
if( index >= value.length )
index = value.length - 1;
if( index < 0 )
index = 0;
for( int i = 0,j = 0; i < value.length; i++ ) {
if( i != index ) {
newValue[j] = value[i];
j++;
} else {
write("deleted topic #"+i+": "+value[i].toString());
}
}
topicStore.put(key,newValue);
constructTopic(newValue,channel);
hasChanged = true;
}
}
}
}
/**
* lists all topics
*
* @param host host of invoker
* @param invoker invoking User
* @param args arguments of command
* @param channel target channel
*/
private void commandTL(Host host,User invoker,String args[],Channel channel)
{
String key = null;
TopicEntry value[] = null;
TopicEntry newValue[] = null;
/* construct hash key from server instance name and channel name */
key = caller.getInstanceData().getNetwork()+"-"+channel.getChannelName();
if( topicStore.containsKey(key) ) {
value = (TopicEntry[])topicStore.get(key);
for( int i = 0; i < value.length; i++ ) {
write("topic #"+i+": "+value[i].toString());
}
}
}
/**
* inserts a new topic
*
* @param host host of invoker
* @param invoker invoking User
* @param args arguments of command
* @param channel target channel
*/
private void commandTI(Host host,User invoker,String args[],Channel channel)
{
String key = null;
TopicEntry value[] = null;
TopicEntry newValue[] = null;
int index = 0;
boolean isOk = true;
if( (args != null) && args.length >= 2 ) {
try {
index = Integer.parseInt(args[0]);
} catch( NumberFormatException e ) {
/* bad arguments */
isOk = false;
}
if( isOk ) {
/* construct hash key from server instance name and channel name */
key = caller.getInstanceData().getNetwork()+"-"+channel.getChannelName();
if( topicStore.containsKey(key) ) {
value = (TopicEntry[])topicStore.get(key);
if( (index >= 0) && (index < value.length) ) {
newValue = new TopicEntry[value.length+1];
for( int i = 0,j = 0; i < newValue.length; i++ ) {
if( i == index ) {
/* insert new topic here */
newValue[i] = new TopicEntry(StringUtil.join(args,1),invoker.getName(),dateFormatString);
} else {
newValue[i] = value[j++];
}
}
topicStore.put(key,newValue);
constructTopic(newValue,channel);
hasChanged = true;
}
}
}
}
}
/**
* swaps two topics
*
* @param host host of invoker
* @param invoker invoking User
* @param args arguments of command
* @param channel target channel
*/
private void commandTS(Host host,User invoker,String args[],Channel channel)
{
String key = null;
TopicEntry value[] = null;
TopicEntry tmp = null;
int index1 = 0;
int index2 = 0;
boolean isOk = true;
if( (args != null) && args.length == 2 ) {
try {
index1 = Integer.parseInt(args[0]);
index2 = Integer.parseInt(args[1]);
} catch( NumberFormatException e ) {
/* bad arguments */
isOk = false;
}
if( isOk ) {
/* construct hash key from server instance name and channel name */
key = caller.getInstanceData().getNetwork()+"-"+channel.getChannelName();
if( topicStore.containsKey(key) ) {
value = (TopicEntry[])topicStore.get(key);
if( (index1 >= 0) && (index1 < value.length) &&
(index2 >= 0) && (index2 < value.length) ) {
/* swap topics */
tmp = value[index1];
value[index1] = value[index2];
value[index2] = tmp;
/* write back to topic store */
topicStore.put(key,value);
hasChanged = true;
constructTopic(value,channel);
}
}
}
}
}
/**
* sets a new topic
*
* @param host host of invoker
* @param invoker invoking User
* @param args arguments of command
* @param channel target channel
*/
private void commandTOPIC(Host host,User invoker,String args[],Channel channel)
{
String key = null;
TopicEntry value[] = null;
if( (args != null) && args.length > 0 ) {
/* construct hash key from server instance name and channel name */
key = caller.getInstanceData().getNetwork()+"-"+channel.getChannelName();
/* add new topic to store as single-entry array */
value = new TopicEntry[1];
value[0] = new TopicEntry(StringUtil.join(args),invoker.getName(),dateFormatString);
topicStore.put(key,value);
constructTopic(value,channel);
}
}
/**
* appends a new topic
*
* @param host host of invoker
* @param invoker invoking User
* @param args arguments of command
* @param channel target channel
*/
private void commandTA(Host host,User invoker,String args[],Channel channel)
{
String key = null;
TopicEntry value[] = null;
TopicEntry newValue[] = null;
if( (args != null) && (args.length > 0) ) {
/* construct hash key from server instance name and channel name */
key = caller.getInstanceData().getNetwork()+"-"+channel.getChannelName();
if( topicStore.containsKey(key) ) {
value = (TopicEntry[])topicStore.get(key);
newValue = new TopicEntry[value.length+1];
/* copy existing entries */
for( int i = 0; i < value.length; i++ )
newValue[i] = value[i];
/* setup new entry and replace to topic store */
newValue[value.length] = new TopicEntry(StringUtil.join(args),invoker.getName(),dateFormatString);
topicStore.put(key,newValue);
hasChanged = true;
constructTopic(newValue,channel);
}
}
}
/**
* Edits a topic
*
* @param host host of invoker
* @param invoker invoking User
* @param args arguments of command
* @param channel target channel
*/
private void commandTE(Host host,User invoker,String args[],Channel channel)
{
String key = null;
TopicEntry value[] = null;
if( (args != null) && (args.length >= 2) ) {
/* construct hash key from server instance name and channel name */
key = caller.getInstanceData().getNetwork()+"-"+channel.getChannelName();
if( topicStore.containsKey(key) ) {
value = (TopicEntry[])topicStore.get(key);
int i = -1;
try {
i = Integer.parseInt(args[0]);
} catch( NumberFormatException e ) {
return;
}
if( (i >= 0) && (i < value.length) ) {
value[i] = new TopicEntry(StringUtil.join(args,1),invoker.getName(),dateFormatString);
topicStore.put(key,value);
hasChanged = true;
constructTopic(value,channel);
}
}
}
}
/**
* sets (refreshes) channel topic from store
*
* @param host host of invoker
* @param invoker invoking User
* @param args arguments of command
* @param channel target channel
*/
private void commandTR(Host host,User invoker,String args[],Channel channel)
{
String key = null;
TopicEntry value[] = null;
/* construct hash key from server instance name and channel name */
key = caller.getInstanceData().getNetwork()+"-"+channel.getChannelName();
if( topicStore.containsKey(key) ) {
value = (TopicEntry[])topicStore.get(key);
constructTopic(value,channel);
}
}
/**
* gets the current channel topic
*
* @param host host of invoker
* @param invoker invoking User
* @param args arguments of command
* @param channel target channel
*/
private void commandTG(Host host,User invoker,String args[],Channel channel)
{
String key = null;
TopicEntry value[] = null;
/* construct hash key from server instance name and channel name */
key = caller.getInstanceData().getNetwork()+"-"+channel.getChannelName();
if( topicStore.contains(key) ) {
/* remove existing topic */
topicStore.remove(key);
}
/* add new topic to store as single-entry array */
if( channel.getChannelTopic() == null ) {
/* on a null topic, remove the topic entries completely */
topicStore.remove(key);
} else {
write("Getting topic: "+channel.getChannelTopic());
value = new TopicEntry[1];
value[0] = new TopicEntry(channel.getChannelTopic(),null,dateFormatString);
topicStore.put(key,value);
hasChanged = true;
}
}
/**
* Processes command message. assuming valid channel argument.
*
* @param msg command msg string
* @param channel valid channel name
*/
private void processCmdMsg(Host host,String cmd,Channel channel,String args[])
{
User user = caller.findUser(host);
/* all commands require user in bot */
if( user != null ) {
/* bot needs to be ON channel */
if( channel.isJoined() ) {
/* select command */
if( cmd.equals("ta") ) {
commandTA(host,user,args,channel);
} else if( cmd.equals("td") ) {
commandTD(host,user,args,channel);
} else if( cmd.equals("tl") ) {
commandTL(host,user,args,channel);
} else if( cmd.equals("tg") ) {
commandTG(host,user,args,channel);
} else if( cmd.equals("ti") ) {
commandTI(host,user,args,channel);
} else if( cmd.equals("ts") ) {
commandTS(host,user,args,channel);
} else if( cmd.equals("te") ) {
commandTE(host,user,args,channel);
} else if( cmd.equals("topic") ) {
commandTOPIC(host,user,args,channel);
} else if( cmd.equals("tr") ) {
/* dont bother to call if not op */
if( channel.isOp() ) {
commandTR(host,user,args,channel);
}
}
}
}
}
/**
* Handles PRIVMSGs
*
* @param message PRIVMSG IrcMessage to process
*/
private void doPrivmsg(IrcMessage message)
{
Host host = new Host(message.prefix);
Channel channel = null;
String args[] = null;
String cmd = null;
if( message.arguments[0].equals(caller.getHost().getNick()) ) {
/* PRIVMSG to bot */
this.source = host.getNick();
args = StringUtil.separate(message.trailing,' ');
if( (args != null) && (args.length >= 2) ) {
channel = caller.findChannel(args[1]);
cmd = args[0];
args = StringUtil.range(args,2);
}
} else {
/* PRIVMSG to channel */
channel = caller.findChannel(message.arguments[0]);
this.source = message.arguments[0];
if( (message.trailing.charAt(0) == '!') &&
(message.trailing.length() > 1) ) {
args = StringUtil.separate(message.trailing.substring(1),' ');
if( args != null ) {
cmd = args[0];
args = StringUtil.range(args,1);
}
}
}
if( (channel != null) && (cmd != null) ) {
processCmdMsg(host,cmd,channel,args);
}
}
/**
* Processes incoming IrcMessages from a ServerConnection
*
* @param message IrcMessage to process
* @param serverConnection invoking ServerConnection
*/
protected void processMessage(IrcMessage message,ServerConnection serverConnection)
{
this.caller = serverConnection;
if( message.command.equals("PRIVMSG") ) {
if( (message.trailing != null) &&
(message.trailing.length() > 0) ) {
doPrivmsg(message);
}
}
/* set per-request vars to null */
this.caller = null;
this.source = null;
}
/**
* Sends message to source (channel/user)
*
* @param message message to send
*/
private void write(String message)
{
if( source != null ) {
caller.write("PRIVMSG "+source+" :"+message+"\n");
}
}
}
| mit |
ayeletshpigelman/azure-sdk-for-net | sdk/servicebus/Azure.Messaging.ServiceBus/src/Processor/ServiceBusProcessorOptions.cs | 6896 | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.ComponentModel;
using Azure.Core;
namespace Azure.Messaging.ServiceBus
{
/// <summary>
/// The set of options that can be specified when creating a
/// <see cref="ServiceBusProcessor" /> to configure its behavior.
/// </summary>
public class ServiceBusProcessorOptions
{
/// <summary>
/// Gets or sets the number of messages that will be eagerly requested
/// from Queues or Subscriptions and queued locally, intended to help
/// maximize throughput by allowing the processor to receive
/// from a local cache rather than waiting on a service request.
/// </summary>
/// <exception cref="ArgumentOutOfRangeException">
/// A negative value is attempted to be set for the property.
/// </exception>
public int PrefetchCount
{
get
{
return _prefetchCount;
}
set
{
Argument.AssertAtLeast(value, 0, nameof(PrefetchCount));
_prefetchCount = value;
}
}
private int _prefetchCount;
/// <summary>
/// Gets or sets the <see cref="ReceiveMode"/> used to specify how messages
/// are received. Defaults to PeekLock mode.
/// </summary>
public ServiceBusReceiveMode ReceiveMode { get; set; } = ServiceBusReceiveMode.PeekLock;
/// <summary>
/// Gets or sets a value that indicates whether the processor
/// should automatically complete messages after the <see cref="ServiceBusProcessor.ProcessMessageAsync"/> handler has
/// completed processing. If the message handler triggers an exception, the message will not be automatically completed.
/// The default value is true.
/// </summary>
///
/// <value>true to complete the message automatically on successful execution of the message handler; otherwise, false.</value>
public bool AutoCompleteMessages { get; set; } = true;
/// <summary>
/// Gets or sets the maximum duration within which the lock will be renewed automatically. This
/// value should be greater than the longest message lock duration; for example, the LockDuration Property.
/// </summary>
///
/// <value>The maximum duration during which message locks are automatically renewed.</value>
///
/// <remarks>The message renew can continue for sometime in the background
/// after completion of message and result in a few false MessageLockLostExceptions temporarily.</remarks>
/// <exception cref="ArgumentOutOfRangeException">
/// A negative value is attempted to be set for the property.
/// </exception>
public TimeSpan MaxAutoLockRenewalDuration
{
get => _maxAutoRenewDuration;
set
{
Argument.AssertNotNegative(value, nameof(MaxAutoLockRenewalDuration));
_maxAutoRenewDuration = value;
}
}
private TimeSpan _maxAutoRenewDuration = TimeSpan.FromMinutes(5);
/// <summary>
/// The maximum amount of time to wait for each Receive call using the processor's underlying receiver.
/// If not specified, the <see cref="ServiceBusRetryOptions.TryTimeout"/> will be used.
/// </summary>
/// <exception cref="ArgumentOutOfRangeException">
/// A value that is not positive is attempted to be set for the property.
/// </exception>
internal TimeSpan? MaxReceiveWaitTime
{
get => _maxReceiveWaitTime;
set
{
if (value.HasValue)
{
Argument.AssertPositive(value.Value, nameof(MaxReceiveWaitTime));
}
_maxReceiveWaitTime = value;
}
}
private TimeSpan? _maxReceiveWaitTime;
/// <summary>Gets or sets the maximum number of concurrent calls to the
/// message handler the processor should initiate.
/// The default is 1.
/// </summary>
///
/// <value>The maximum number of concurrent calls to the message handler.</value>
/// <exception cref="ArgumentOutOfRangeException">
/// A value that is not positive is attempted to be set for the property.
/// </exception>
public int MaxConcurrentCalls
{
get => _maxConcurrentCalls;
set
{
Argument.AssertAtLeast(value, 1, nameof(MaxConcurrentCalls));
_maxConcurrentCalls = value;
}
}
private int _maxConcurrentCalls = 1;
/// <summary>
/// Determines whether the specified <see cref="System.Object" /> is equal to this instance.
/// </summary>
///
/// <param name="obj">The <see cref="System.Object" /> to compare with this instance.</param>
///
/// <returns><c>true</c> if the specified <see cref="System.Object" /> is equal to this instance; otherwise, <c>false</c>.</returns>
[EditorBrowsable(EditorBrowsableState.Never)]
public override bool Equals(object obj) => base.Equals(obj);
/// <summary>
/// Returns a hash code for this instance.
/// </summary>
///
/// <returns>A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table.</returns>
///
[EditorBrowsable(EditorBrowsableState.Never)]
public override int GetHashCode() => base.GetHashCode();
/// <summary>
/// Converts the instance to string representation.
/// </summary>
///
/// <returns>A <see cref="System.String" /> that represents this instance.</returns>
///
[EditorBrowsable(EditorBrowsableState.Never)]
public override string ToString() => base.ToString();
/// <summary>
/// Creates a new copy of the current <see cref="ServiceBusProcessorOptions" />, cloning its attributes into a new instance.
/// </summary>
///
/// <returns>A new copy of <see cref="ServiceBusProcessorOptions" />.</returns>
internal ServiceBusProcessorOptions Clone()
{
return new ServiceBusProcessorOptions
{
ReceiveMode = ReceiveMode,
PrefetchCount = PrefetchCount,
AutoCompleteMessages = AutoCompleteMessages,
MaxAutoLockRenewalDuration = MaxAutoLockRenewalDuration,
MaxReceiveWaitTime = MaxReceiveWaitTime,
MaxConcurrentCalls = MaxConcurrentCalls,
};
}
}
}
| mit |
nkt/atom-autocomplete-modules | lib/main.js | 470 | 'use babel';
class AutocompleteModulesPlugin {
constructor() {
this.config = require('./package-configs').registrar;
this.completionProvider = null;
}
activate() {
this.completionProvider = new (require('./completion-provider'));
}
deactivate() {
delete this.completionProvider;
this.completionProvider = null;
}
getCompletionProvider() {
return this.completionProvider;
}
}
module.exports = new AutocompleteModulesPlugin();
| mit |
pretzelfisch/Silent-Silver | SilentSilver/default.aspx.cs | 434 | using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace SilentSilver
{
public partial class _default : System.Web.UI.Page
{
public int currentCount=-1;
protected void Page_Load(object sender, EventArgs e)
{
currentCount = WebApiApplication.ValueRequestCount;
}
}
} | mit |
czaks/bitcoin-jruby | examples/forwarding_service.rb | 349 | require "bitcoin-jruby"
# This is a loose adaptation of:
# https://code.google.com/p/bitcoinj/source/browse/examples/src/main/java/com/google/bitcoin/examples/ForwardingService.java
if ARGV.count < 1
puts "Usage: address-to-send-back-to"
end
params = BJR::Params::MainNetParams.get
forwarding_address = BJR::Core::Address.new(params, ARGV[0])
| mit |
axtheset/rest-client | spec/app_spec.rb | 661 | require 'spec_helper'
describe AccelaRestClient::App do
subject { AccelaRestClient::App.new(app_id,app_secret,access_token,environment,agency) }
let(:app_id) { 'app_id' }
let(:app_secret) { 'app_secret' }
let(:access_token) { 'access_token' }
let(:environment) { 'environment' }
let(:agency) { 'agency' }
describe '#get_app_settings' do
let(:params) { Hash.new }
it 'get_app_settings should call send_request and return true' do
subject.should_receive(:send_request).with("/v4/appsettings/", AccelaRestClient::App::AuthTypes::APP_CREDENTIALS, params).and_return(true)
subject.get_app_settings(params)
end
end
end
| mit |
whitescape/react-admin-components | src/ui/format/bool.js | 73 | export default function formatBool(x) {
return x ? 'да' : 'нет'
}
| mit |
apo-j/Projects_Working | AC/AnnuaireCertifies/AC.BackOffice/AnnuaireCertifies.BackOffice.Web.ViewModels/ModelBuilders/Administration/Structures/IStructureModelBuilder.cs | 487 | using AnnuaireCertifies.BackOffice.Web.ViewModels.Pages.Administration.Structures.Details;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AnnuaireCertifies.BackOffice.Web.ViewModels.ModelBuilders.Administration.Structures
{
public interface IStructureModelBuilder : IModelBuilderBase
{
InfosGeneralesViewModel BuildInfosGeneralesViewModel(Context context, long id);
}
}
| mit |
williamliew/brokerApp | src/components/button.js | 440 | import React, { Component } from 'react';
import BidActions from '../actions/bidactions';
export default React.createClass ({
handleClick: function() {
BidActions.addToArray(this.props.name);
},
render: function() {
return (
<button
className="button-primary"
value={this.props.value}
name={this.props.name}
onClick={this.handleClick}>
{this.props.text}
</button>
);
}
});
| mit |
zcoding/hello-go-lang | vfs/command/cp.go | 366 | package command
import (
// "fmt"
// "errors"
)
/**
* change working directory
* @param {map[string]string} options
* command options
* @param {[]string} rest
* rest arguments
* @param {string} cwd
* current working directory
* @return {error}
*
*/
func CommandCp(options map[string]string, rest []string, cwd string) error {
return nil
}
| mit |
pritchardtw/ReactPersonalSite | src/components/Web/data_viewer.js | 798 | import React, { Component } from 'react';
import Project from '../project';
export default class DataViewer extends Component {
render() {
const images = [
'../../static/images/web/dataviewer1.png',
'../../static/images/web/dataviewer2.png',
'../../static/images/web/dataviewer3.png'
];
return(
<Project
title="Data Viewer!"
link=""
description="I built a data viewer using React and Typescript. It has a filter feature to filter through
the data sources, and a date range filter to view data within a specific range. I am querying an API for data sources,
then I query the api with the selected source and date range for the data. This app uses Chart.js to display the data."
images={images} />
);
}
}
| mit |