repo_name stringlengths 4 116 | path stringlengths 4 379 | size stringlengths 1 7 | content stringlengths 3 1.05M | license stringclasses 15
values |
|---|---|---|---|---|
iboss-ptk/cuse_theme | front-page.php | 9868 | <header id="header" data-type="background" data-speed="5">
<div id="header-overlay" class="overlay"></div>
<div id="header-label">
<div class="title-name">
<h1 style="color: white">Software Engineering</h1>
<p class="lv0">Master Program, Department of Computer Engineering, Faculty of Engineering</p>
</div>
<p class="title-name">Chulalongkorn University</p>
<div class="nowop animated fadeInUp" id="nowop">
<div class="announce-item">
<?php
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
$args = array(
"posts_per_page" =>10,
"post_type" => "announcement",
'orderby' => 'title',
'order' => 'DESC',
'paged'=>$paged);
$wp_query = new WP_Query($args);?>
<?php if ( $wp_query->have_posts() ) : $i = 0;?>
<?php while ( $wp_query->have_posts() ) : $wp_query->the_post(); if ($i==0) :// Start the Loop.?>
<div class="announce">
<p><?php the_content();$i=1;?></p>
<?php if (get_field('internal_link')): ?>
<a href="<?php the_field('internal_link');?>" class="mif">MORE INFO</a>
<?php elseif (get_field('external_link')): ?>
<a href="<?php the_field('external_link');?>" class="mif">MORE INFO</a>
<?php endif; ?>
</div>
<?php else : ?>
<div class="announce hide">
<p><?php the_content();?></p>
<?php if (get_field('internal_link')): ?>
<a href="<?php the_field('internal_link');?>" class="mif">MORE INFO</a>
<?php elseif (get_field('external_link')): ?>
<a href="<?php the_field('external_link');?>" class="mif">MORE INFO</a>
<?php endif; ?>
</div>
<?php endif; ?>
<?php endwhile; ?>
<?php
// clean up after our query
wp_reset_postdata();
?>
<?php else: ?>
<p><?php _e( 'Sorry, no posts matched your criteria.' ); ?></p>
<?php endif; ?>
<div id="arrow-left" class="arrow"></div>
<div id="arrow-right" class="arrow"></div>
</div>
</div>
<div id="arrow-down" class="arrow"></div>
</div>
</header>
<section id="news">
<div class="small-12 no-pad section-title section-title-news rows">
<a href="<?php echo get_permalink( get_page_by_title( 'News' ) ); ?>"><span class="section-title-pad small-1 columns">News</span></a>
</div>
<?php
$args = array(
'post_type' => 'news',
'posts_per_page' => 1,
'orderby' => 'the_date',
'order' => 'DESC',
'tax_query' => array(
array(
'taxonomy' => 'tags',
'field' => 'slug',
'terms' => 'first',
),
),
);
$wp_query = new WP_Query( $args );
?>
<div class="rows" data-equalizer>
<?php if ( $wp_query->have_posts() ) : ?>
<?php while ( $wp_query->have_posts() ) : $wp_query->the_post(); // Start the Loop.?>
<div class="post-card small-12 large-4 columns no-pad" data-equalizer-watch>
<a href=<?php the_permalink() ; ?>></a>
<div class='post-card-cover'></div>
<div class="seperate">
<div class="no-pad img-container">
<a href=<?php the_permalink() ; ?>>
<?php if ( has_post_thumbnail() ) {
the_post_thumbnail();}
?>
</a>
</div>
<div class="post-card-content small-offset-1 small-10" >
<a href=<?php the_permalink() ; ?>>
<h4><?php the_title(); ?></h4>
</a>
<p><?php the_content();?></p>
<p></p>
</div>
</div>
</div>
<?php endwhile; ?>
<?php
// clean up after our query
wp_reset_postdata();
?>
<?php else: ?>
<p><?php _e( 'Sorry, no posts matched your criteria.' ); ?></p>
<?php endif; ?>
<?php
$args = array(
'post_type' => 'news',
'posts_per_page' => 1,
'orderby' => 'the_date',
'order' => 'ASC',
'tax_query' => array(
array(
'taxonomy' => 'tags',
'field' => 'slug',
'terms' => 'second',
),
),
);
$wp_query = new WP_Query( $args );
?>
<?php if ( $wp_query->have_posts() ) : ?>
<?php while ( $wp_query->have_posts() ) : $wp_query->the_post(); // Start the Loop.?>
<div class="post-card small-12 large-4 columns no-pad" data-equalizer-watch>
<a href=<?php the_permalink() ; ?>></a>
<div class='post-card-cover'></div>
<div class="seperate">
<div class="no-pad img-container">
<a href=<?php the_permalink() ; ?>>
<?php if ( has_post_thumbnail() ) {
the_post_thumbnail();}
?>
</a>
</div>
<div class="post-card-content small-offset-1 small-10" >
<a href=<?php the_permalink() ; ?>>
<h4><?php the_title(); ?></h4>
</a>
<p><?php the_content();?></p>
</div>
</div>
</div>
<?php endwhile; ?>
<?php
// clean up after our query
wp_reset_postdata();
?>
<?php else: ?>
<p><?php _e( 'Sorry, no posts matched your criteria.' ); ?></p>
<?php endif; ?>
<?php
$args = array(
'post_type' => 'news',
'posts_per_page' => 1,
'orderby' => 'the_date',
'order' => 'ASC',
'tax_query' => array(
array(
'taxonomy' => 'tags',
'field' => 'slug',
'terms' => 'third',
),
),
);
$wp_query = new WP_Query( $args );
?>
<?php if ( $wp_query->have_posts() ) : ?>
<?php while ( $wp_query->have_posts() ) : $wp_query->the_post(); // Start the Loop.?>
<div class="post-card small-12 large-4 columns no-pad" data-equalizer-watch>
<a href=<?php the_permalink() ; ?>></a>
<div class='post-card-cover'></div>
<div class="seperate">
<div class="no-pad img-container">
<a href=<?php the_permalink() ; ?>>
<?php if ( has_post_thumbnail() ) {
the_post_thumbnail();}
?>
</a>
</div>
<div class="post-card-content small-offset-1 small-10" >
<a href=<?php the_permalink() ; ?>>
<h4><?php the_title(); ?></h4>
</a>
<p><?php the_content();?></p>
<p></p>
</div>
</div>
</div>
<?php endwhile; ?>
<?php
// clean up after our query
wp_reset_postdata();
?>
</div>
<?php else: ?>
<p><?php _e( 'Sorry, no posts matched your criteria.' ); ?></p>
<?php endif; ?>
</section>
<section>
<div class="rows" data-equalizer>
<section id="instragram" class="small-12 large-4 columns no-pad" data-equalizer-watch>
<div class="no-pad section-title section-title-instragram">
<a href="https://www.instagram.com/explore/tags/chulase/" style="color:white;">
<span class="section-title-pad">#ChulaSE on Instagram </span>
</a>
<span class="section-title-pad">
<?php if (is_user_logged_in()): ?>(<a href="<?php echo get_page_link(601) ?>">manage</a>)<?php endif ?>
</span>
</div>
<div class="instagram">
<?php
global $wpdb;
$table_name = $wpdb->prefix . 'igadmin';
$sql = "SELECT imgurl, igid, link FROM $table_name ORDER BY id DESC LIMIT 6";
$res = $wpdb->get_results($sql, OBJECT);
$bound = count($res);
for ($i=0; $i < $bound ; $i++) {
echo "<a href='" . $res[$i]->link . "' target='_blank'><img class='small-6 no-pad' id='". $res[$i]->igid ."' src = '" . $res[$i]->imgurl . "'></img></a>";
}
?>
</div>
</section>
</div>
</section>
<div class="rows" data-equalizer>
<section id="event" class="small-12 large-8 columns no-pad" data-equalizer-watch>
<div class="no-pad section-title section-title-event">
<a href="<?php echo "events" ?>" style="color:white;">
<span class="section-title-pad">
Upcoming Event
</span>
</a>
</div>
<div class="relative-wrapper">
<?php $event_archive_query = new WP_Query('showposts=10&post_type=tribe_events');
while ($event_archive_query->have_posts()) : $event_archive_query->the_post(); ?>
<div class="event-item">
<time datetime="2014-09-20" class="icon">
<em><?php echo tribe_get_start_date( null, false, 'l'); ?></em>
<strong><?php echo tribe_get_start_date( null, false, 'F'); ?></strong>
<span>
<?php echo tribe_get_start_date( null, false, 'd'); ?>
</span>
</time>
<div>
<div class="center">
<h4>
<a href="<?php the_permalink() ?>" title="<?php the_title(); ?>">
<?php the_title(); ?>
</a>
</h4>
</div>
</div>
</div>
<?php endwhile; ?>
<!-- end event -->
<?php if(!$event_archive_query->have_posts()): ?>
<div class="event-item text-center">
<h4>There is no upcoming event.</h4>
</div>
<?php endif; ?>
<div class="event-item">
<div class="center">
<a href="<?php echo "events" ?>"><h4><u>View all</u></h4></a>
</div>
</div>
</div>
</section>
</div>
<script type="text/javascript">
var arl = document.getElementById("arrow-left");
var arr = document.getElementById("arrow-right");
var nowop = document.getElementById("nowop");
var ard = document.getElementById("arrow-down");
ard.addEventListener("click", function(){
$('html,body').animate({
scrollTop: $(".section-title-news").offset().top - 100
}, 1000);
});
var announce = document.getElementsByClassName("announce");
var max = announce.length;
var i = 0;
function nav (i, max, dir) {
if (dir == 1) { i++ }
else if (dir == 0) { i-- };
if (i >= max) { return 0 };
if (i < 0) { return max-1 };
return i
}
function trans(direction){
var prev_dirname = (direction === 0) ? "Right":"Left"
var next_dirname = (direction === 1) ? "Right":"Left"
announce[i].className = "announce fadeOut" + prev_dirname +" animated"
setTimeout(function(){
announce[i].className = "announce hide"
i = nav(i, max, direction);
announce[i].className = "announce fadeIn" + next_dirname +" animated"
},200);
}
var transTimer = setInterval(function(){ trans(1) }, 5000);
arl.addEventListener("click", function(){
trans(0);
// console.log('<<')
clearInterval(transTimer);
});
arr.addEventListener("click", function(){
trans(1);
clearInterval(transTimer);
});
nowop.addEventListener("mouseover", function(){
clearInterval(transTimer);
});
nowop.addEventListener("mouseout", function(){
transTimer = setInterval(function(){ trans(1) }, 5000);
});
</script> | mit |
szelok/twister-android | src/szelok/app/twister/DirectMessageListViewAdapter.java | 3642 | package szelok.app.twister;
import java.util.Date;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.TreeMap;
import android.app.Fragment;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.method.LinkMovementMethod;
import android.text.style.URLSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class DirectMessageListViewAdapter extends BaseAdapter implements
DataModel.DirectMessagesListListener {
private final static String TAG = DirectMessageListViewAdapter.class.getSimpleName();
private final static long ONE_HOUR = 1000 * 60 * 60;
private final static long ONE_MIN = 1000 * 60;
private final static long ONE_SEC = 1000;
private static LayoutInflater inflater = null;
private TreeMap<DirectMessage, DirectMessage> directMessagesList;
private Map<String, User> profiles;
public DirectMessageListViewAdapter(Fragment a) {
inflater = (LayoutInflater) a.getActivity().getLayoutInflater();
directMessagesList = DataModel.INSTANCE.getCurrentWalletUserDirectMessagesList();
profiles = DataModel.INSTANCE.getProfiles();
DataModel.INSTANCE.addDirectMessagesListListener(this);
}
public int getCount() {
return directMessagesList.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
View vi = convertView;
if (convertView == null)
vi = inflater.inflate(R.layout.direct_message_list_row, null);
TextView name = (TextView) vi.findViewById(R.id.direct_message_view_name);
TextView msg = (TextView) vi.findViewById(R.id.direct_message_view_msg);
TextView timestamp = (TextView) vi.findViewById(R.id.direct_message_view_timestamp);
ImageView image = (ImageView) vi.findViewById(R.id.direct_message_view_image);
Iterator<Entry<DirectMessage, DirectMessage>> it = directMessagesList.entrySet().iterator();
for (int i = 0; i < position; i++) {
it.next();
}
DirectMessage dm = it.next().getValue();
User user = profiles.get(dm.getUserId());
if (dm.getFromMe()) {
name.setText("to: " + user.getName());
} else {
name.setText("from: " + user.getName());
}
SpannableString ss = new SpannableString(dm.getMsg());
//Pattern p = Pattern.compile("(^#\\w*|^@\\w*|http://\\S*|\\s#\\w*|\\s@\\w*)");
Pattern p = Pattern.compile("(http://\\S*)");
Matcher m = p.matcher(dm.getMsg());
while (m.find()) {
ss.setSpan(new URLSpan(m.group(1)), m.start(1), m.end(1),
Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}
msg.setText(ss);
msg.setMovementMethod(LinkMovementMethod.getInstance());
Date now = new Date();
long diff = now.getTime() - (dm.getTime() * ONE_SEC);
String displayTime = (new Date(dm.getTime() * ONE_SEC).toString());
if (diff <= 0) {
displayTime = "1 s";
} else if (diff < ONE_MIN) {
displayTime = ((long) diff/ONE_SEC) + " s";
} else if (diff < ONE_HOUR) {
long t = ((long)diff/ONE_MIN);
displayTime = t + (t > 1 ? " mins" : "min");
} else if (diff < 12 * ONE_HOUR) {
long t = ((long) diff/ONE_HOUR);
displayTime = t + (t > 1 ? " hr" : "hrs");
}
timestamp.setText(displayTime);
image.setImageBitmap(user.getAvatar());
return vi;
}
@Override
public void onDirectMessagesListChanged() {
notifyDataSetChanged();
}
} | mit |
VKCOM/vk-java-sdk | sdk/src/main/java/com/vk/api/sdk/objects/video/responses/UploadResponse.java | 1700 | // Autogenerated from vk-api-schema. Please don't edit it manually.
package com.vk.api.sdk.objects.video.responses;
import com.google.gson.Gson;
import com.google.gson.annotations.SerializedName;
import com.vk.api.sdk.objects.Validable;
import java.util.Objects;
/**
* UploadResponse object
*/
public class UploadResponse implements Validable {
/**
* Video size
*/
@SerializedName("size")
private Integer size;
/**
* Video ID
*/
@SerializedName("video_id")
private Integer videoId;
public Integer getSize() {
return size;
}
public UploadResponse setSize(Integer size) {
this.size = size;
return this;
}
public Integer getVideoId() {
return videoId;
}
public UploadResponse setVideoId(Integer videoId) {
this.videoId = videoId;
return this;
}
@Override
public int hashCode() {
return Objects.hash(size, videoId);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
UploadResponse uploadResponse = (UploadResponse) o;
return Objects.equals(size, uploadResponse.size) &&
Objects.equals(videoId, uploadResponse.videoId);
}
@Override
public String toString() {
final Gson gson = new Gson();
return gson.toJson(this);
}
public String toPrettyString() {
final StringBuilder sb = new StringBuilder("UploadResponse{");
sb.append("size=").append(size);
sb.append(", videoId=").append(videoId);
sb.append('}');
return sb.toString();
}
}
| mit |
Yeyti/Gwen.CS | Gwen.Renderer.OpenTK/OpenTKBase.cs | 13126 | using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using Gwen.Renderer.OpenTK;
using OpenTK.Graphics.OpenGL;
using OpenTK;
using OpenTK.Graphics;
using Bitmap = System.Drawing.Bitmap;
using PixelFormat = OpenTK.Graphics.OpenGL.PixelFormat;
using SizeF = System.Drawing.SizeF;
namespace Gwen.Renderer
{
public abstract class OpenTKBase : RendererBase
{
protected Color m_Color;
private readonly Dictionary<Tuple<String, Font>, TextRenderer> m_StringCache;
private readonly Graphics m_Graphics; // only used for text measurement
protected int m_DrawCallCount;
protected bool m_ClipEnabled;
protected bool m_TextureEnabled;
static protected int m_LastTextureID;
private StringFormat m_StringFormat;
private int m_GLVersion;
public OpenTKBase()
: base()
{
m_GLVersion = GL.GetInteger(GetPName.MajorVersion) * 10 + GL.GetInteger(GetPName.MinorVersion);
m_StringCache = new Dictionary<Tuple<String, Font>, TextRenderer>();
m_Graphics = Graphics.FromImage(new Bitmap(1024, 1024));
m_StringFormat = new StringFormat(StringFormat.GenericTypographic);
m_StringFormat.FormatFlags |= StringFormatFlags.MeasureTrailingSpaces;
}
public override void Dispose()
{
FlushTextCache();
base.Dispose();
}
protected override void OnScaleChanged(float oldScale)
{
FlushTextCache();
}
protected abstract void Flush();
/// <summary>
/// Returns number of cached strings in the text cache.
/// </summary>
public int TextCacheSize { get { return m_StringCache.Count; } }
public int DrawCallCount { get { return m_DrawCallCount; } }
public abstract int VertexCount { get; }
public int GLVersion { get { return m_GLVersion; } }
/// <summary>
/// Clears the text rendering cache. Make sure to call this if cached strings size becomes too big (check TextCacheSize).
/// </summary>
public void FlushTextCache()
{
// todo: some auto-expiring cache? based on number of elements or age
foreach (var textRenderer in m_StringCache.Values)
{
textRenderer.Dispose();
}
m_StringCache.Clear();
}
public override void DrawFilledRect(Rectangle rect)
{
if (m_TextureEnabled)
{
Flush();
GL.Disable(EnableCap.Texture2D);
m_TextureEnabled = false;
}
rect = Translate(rect);
DrawRect(rect);
}
public override Color DrawColor
{
get { return m_Color; }
set
{
m_Color = value;
}
}
public override void StartClip()
{
m_ClipEnabled = true;
}
public override void EndClip()
{
m_ClipEnabled = false;
}
public override void DrawTexturedRect(Texture t, Rectangle rect, float u1 = 0, float v1 = 0, float u2 = 1, float v2 = 1)
{
// Missing image, not loaded properly?
if (null == t.RendererData)
{
DrawMissingImage(rect);
return;
}
int tex = (int)t.RendererData;
rect = Translate(rect);
bool differentTexture = (tex != m_LastTextureID);
if (!m_TextureEnabled || differentTexture)
{
Flush();
}
if (!m_TextureEnabled)
{
GL.Enable(EnableCap.Texture2D);
m_TextureEnabled = true;
}
if (differentTexture)
{
GL.BindTexture(TextureTarget.Texture2D, tex);
m_LastTextureID = tex;
}
DrawRect(rect, u1, v1, u2, v2);
}
protected abstract void DrawRect(Rectangle rect, float u1 = 0, float v1 = 0, float u2 = 1, float v2 = 1);
public override bool LoadFont(Font font)
{
font.RealSize = (float)Math.Ceiling(font.Size * Scale);
System.Drawing.Font sysFont = font.RendererData as System.Drawing.Font;
if (sysFont != null)
sysFont.Dispose();
System.Drawing.FontStyle fontStyle = System.Drawing.FontStyle.Regular;
if (font.Bold) fontStyle |= System.Drawing.FontStyle.Bold;
if (font.Italic) fontStyle |= System.Drawing.FontStyle.Italic;
if (font.Underline) fontStyle |= System.Drawing.FontStyle.Underline;
if (font.Strikeout) fontStyle |= System.Drawing.FontStyle.Strikeout;
// apaprently this can't fail @_@
// "If you attempt to use a font that is not supported, or the font is not installed on the machine that is running the application, the Microsoft Sans Serif font will be substituted."
sysFont = new System.Drawing.Font(font.FaceName, font.RealSize, fontStyle);
font.RendererData = sysFont;
return true;
}
public override void FreeFont(Font font)
{
if (font.RendererData == null)
return;
System.Drawing.Font sysFont = font.RendererData as System.Drawing.Font;
if (sysFont == null)
throw new InvalidOperationException("Freeing empty font");
sysFont.Dispose();
font.RendererData = null;
}
public override FontMetrics GetFontMetrics(Font font)
{
System.Drawing.Font sysFont = font.RendererData as System.Drawing.Font;
if (sysFont == null || Math.Abs(font.RealSize - font.Size * Scale) > 2)
{
FreeFont(font);
LoadFont(font);
sysFont = font.RendererData as System.Drawing.Font;
}
// from: http://csharphelper.com/blog/2014/08/get-font-metrics-in-c
float emHeight = sysFont.FontFamily.GetEmHeight(sysFont.Style);
float emHeightPixels = ConvertToPixels(sysFont.Size, sysFont.Unit);
float designToPixels = emHeightPixels / emHeight;
float ascentPixels = designToPixels * sysFont.FontFamily.GetCellAscent(sysFont.Style);
float descentPixels = designToPixels * sysFont.FontFamily.GetCellDescent(sysFont.Style);
float cellHeightPixels = ascentPixels + descentPixels;
float internalLeadingPixels = cellHeightPixels - emHeightPixels;
float lineSpacingPixels = designToPixels * sysFont.FontFamily.GetLineSpacing(sysFont.Style);
float externalLeadingPixels = lineSpacingPixels - cellHeightPixels;
FontMetrics fm = new FontMetrics
(
emHeightPixels,
ascentPixels,
descentPixels,
cellHeightPixels,
internalLeadingPixels,
lineSpacingPixels,
externalLeadingPixels
);
return fm;
}
private float ConvertToPixels(float value, GraphicsUnit unit)
{
switch (unit)
{
case GraphicsUnit.Document: value *= m_Graphics.DpiX / 300; break;
case GraphicsUnit.Inch: value *= m_Graphics.DpiX; break;
case GraphicsUnit.Millimeter: value *= m_Graphics.DpiX / 25.4F; break;
case GraphicsUnit.Pixel: break;
case GraphicsUnit.Point: value *= m_Graphics.DpiX / 72; break;
default: throw new Exception("Unknown unit " + unit.ToString());
}
return value;
}
public override Size MeasureText(Font font, string text)
{
System.Drawing.Font sysFont = font.RendererData as System.Drawing.Font;
if (sysFont == null || Math.Abs(font.RealSize - font.Size * Scale) > 2)
{
FreeFont(font);
LoadFont(font);
sysFont = font.RendererData as System.Drawing.Font;
}
var key = new Tuple<String, Font>(text, font);
if (m_StringCache.ContainsKey(key))
{
var tex = m_StringCache[key].Texture;
return new Size(tex.Width, tex.Height);
}
SizeF TabSize = m_Graphics.MeasureString("....", sysFont); //Spaces are not being picked up, let's just use .'s.
m_StringFormat.SetTabStops(0f, new float[] { TabSize.Width });
SizeF size = m_Graphics.MeasureString(text, sysFont, System.Drawing.Point.Empty, m_StringFormat);
return new Size(Util.Ceil(size.Width), Util.Ceil(size.Height));
}
public override void RenderText(Font font, Point position, string text)
{
Flush();
System.Drawing.Font sysFont = font.RendererData as System.Drawing.Font;
if (sysFont == null || Math.Abs(font.RealSize - font.Size * Scale) > 2)
{
FreeFont(font);
LoadFont(font);
sysFont = font.RendererData as System.Drawing.Font;
}
var key = new Tuple<String, Font>(text, font);
if (!m_StringCache.ContainsKey(key))
{
// not cached - create text renderer
Size size = MeasureText(font, text);
TextRenderer tr = new TextRenderer(size.Width, size.Height, this);
tr.DrawString(text, sysFont, Brushes.White, Point.Zero, m_StringFormat); // renders string on the texture
DrawTexturedRect(tr.Texture, new Rectangle(position.X, position.Y, tr.Texture.Width, tr.Texture.Height));
m_StringCache[key] = tr;
}
else
{
TextRenderer tr = m_StringCache[key];
DrawTexturedRect(tr.Texture, new Rectangle(position.X, position.Y, tr.Texture.Width, tr.Texture.Height));
}
}
internal static void LoadTextureInternal(Texture t, System.Drawing.Bitmap bmp)
{
System.Drawing.Imaging.PixelFormat lock_format;
switch (bmp.PixelFormat)
{
case System.Drawing.Imaging.PixelFormat.Format32bppArgb:
lock_format = System.Drawing.Imaging.PixelFormat.Format32bppArgb;
break;
case System.Drawing.Imaging.PixelFormat.Format24bppRgb:
lock_format = System.Drawing.Imaging.PixelFormat.Format32bppArgb;
break;
default:
t.Failed = true;
return;
}
int glTex;
// Create the opengl texture
GL.GenTextures(1, out glTex);
GL.BindTexture(TextureTarget.Texture2D, glTex);
m_LastTextureID = glTex;
GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)TextureMinFilter.Linear);
GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)TextureMagFilter.Linear);
// Sort out our GWEN texture
t.RendererData = glTex;
t.Width = bmp.Width;
t.Height = bmp.Height;
var data = bmp.LockBits(new System.Drawing.Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.ReadOnly, lock_format);
GL.TexImage2D(TextureTarget.Texture2D, 0, PixelInternalFormat.Rgba, t.Width, t.Height, 0, PixelFormat.Bgra, PixelType.UnsignedByte, data.Scan0);
bmp.UnlockBits(data);
bmp.Dispose();
}
public override void LoadTexture(Texture t){
Bitmap bmp;
try{
bmp = ImageLoader.Load(t.Name);
}
catch (Exception){
t.Failed = true;
return;
}
LoadTextureInternal(t, bmp);
bmp.Dispose();
}
public override void LoadTextureStream(Texture t, System.IO.Stream data){
Bitmap bmp;
try{
bmp = ImageLoader.Load(t.Name);
}
catch (Exception){
t.Failed = true;
return;
}
LoadTextureInternal(t, bmp);
bmp.Dispose();
}
public override void LoadTextureRaw(Texture t, byte[] pixelData)
{
Bitmap bmp;
try
{
unsafe
{
fixed (byte* ptr = &pixelData[0])
bmp = new Bitmap(t.Width, t.Height, 4 * t.Width, System.Drawing.Imaging.PixelFormat.Format32bppArgb, (IntPtr)ptr);
}
}
catch (Exception)
{
t.Failed = true;
return;
}
int glTex;
// Create the opengl texture
GL.GenTextures(1, out glTex);
GL.BindTexture(TextureTarget.Texture2D, glTex);
GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)TextureMagFilter.Linear);
GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)TextureMagFilter.Linear);
// Sort out our GWEN texture
t.RendererData = glTex;
var data = bmp.LockBits(new System.Drawing.Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.ReadOnly,
System.Drawing.Imaging.PixelFormat.Format32bppArgb);
GL.TexImage2D(TextureTarget.Texture2D, 0, PixelInternalFormat.Rgba, t.Width, t.Height, 0, global::OpenTK.Graphics.OpenGL.PixelFormat.Rgba, PixelType.UnsignedByte, data.Scan0);
bmp.UnlockBits(data);
bmp.Dispose();
//[halfofastaple] Must rebind previous texture, to ensure creating a texture doesn't mess with the render flow.
// Setting m_LastTextureID isn't working, for some reason (even if you always rebind the texture,
// even if the previous one was the same), we are probably making draw calls where we shouldn't be?
// Eventually the bug needs to be fixed (color picker in a window causes graphical errors), but for now,
// this is fine.
GL.BindTexture(TextureTarget.Texture2D, m_LastTextureID);
}
public override void FreeTexture(Texture t)
{
if (t.RendererData == null)
return;
int tex = (int)t.RendererData;
if (tex == 0)
return;
GL.DeleteTextures(1, ref tex);
t.RendererData = null;
}
public override unsafe Color PixelColor(Texture texture, uint x, uint y, Color defaultColor)
{
if (texture.RendererData == null)
return defaultColor;
int tex = (int)texture.RendererData;
if (tex == 0)
return defaultColor;
Color pixel;
GL.BindTexture(TextureTarget.Texture2D, tex);
m_LastTextureID = tex;
long offset = 4 * (x + y * texture.Width);
byte[] data = new byte[4 * texture.Width * texture.Height];
fixed (byte* ptr = &data[0])
{
GL.GetTexImage(TextureTarget.Texture2D, 0, global::OpenTK.Graphics.OpenGL.PixelFormat.Rgba, PixelType.UnsignedByte, (IntPtr)ptr);
pixel = new Color(data[offset + 3], data[offset + 0], data[offset + 1], data[offset + 2]);
}
return pixel;
}
public abstract void Resize(int width, int height);
}
}
| mit |
themarshallproject/pony | spec/controllers/templates_controller_spec.rb | 5882 | require 'rails_helper'
# This spec was generated by rspec-rails when you ran the scaffold generator.
# It demonstrates how one might use RSpec to specify the controller code that
# was generated by Rails when you ran the scaffold generator.
#
# It assumes that the implementation code is generated by the rails scaffold
# generator. If you are using any extension libraries to generate different
# controller code, this generated spec may or may not pass.
#
# It only uses APIs available in rails and/or rspec-rails. There are a number
# of tools you can use to make these specs even more expressive, but we're
# sticking to rails and rspec-rails APIs to keep things simple and stable.
#
# Compared to earlier versions of this generator, there is very limited use of
# stubs and message expectations in this spec. Stubs are only used when there
# is no simpler way to get a handle on the object needed for the example.
# Message expectations are only used when there is no simpler way to specify
# that an instance is receiving a specific message.
RSpec.describe TemplatesController, type: :controller do
# This should return the minimal set of attributes required to create a valid
# Template. As you add validations to Template, be sure to
# adjust the attributes here as well.
let(:valid_attributes) {
skip("Add a hash of attributes valid for your model")
}
let(:invalid_attributes) {
skip("Add a hash of attributes invalid for your model")
}
# This should return the minimal set of values that should be in the session
# in order to pass any filters (e.g. authentication) defined in
# TemplatesController. Be sure to keep this updated too.
let(:valid_session) { {} }
before(:each) do
allow_any_instance_of(ApplicationController).to receive(:authorize!).and_return(true)
end
describe "GET #index" do
it "assigns all templates as @templates" do
template = Template.create! valid_attributes
get :index, {}, valid_session
expect(assigns(:templates)).to eq([template])
end
end
describe "GET #show" do
it "assigns the requested template as @template" do
template = Template.create! valid_attributes
get :show, {:id => template.to_param}, valid_session
expect(assigns(:template)).to eq(template)
end
end
describe "GET #new" do
it "assigns a new template as @template" do
get :new, {}, valid_session
expect(assigns(:template)).to be_a_new(Template)
end
end
describe "GET #edit" do
it "assigns the requested template as @template" do
template = Template.create! valid_attributes
get :edit, {:id => template.to_param}, valid_session
expect(assigns(:template)).to eq(template)
end
end
describe "POST #create" do
context "with valid params" do
it "creates a new Template" do
expect {
post :create, {:template => valid_attributes}, valid_session
}.to change(Template, :count).by(1)
end
it "assigns a newly created template as @template" do
post :create, {:template => valid_attributes}, valid_session
expect(assigns(:template)).to be_a(Template)
expect(assigns(:template)).to be_persisted
end
it "redirects to the created template" do
post :create, {:template => valid_attributes}, valid_session
expect(response).to redirect_to(Template.last)
end
end
context "with invalid params" do
it "assigns a newly created but unsaved template as @template" do
post :create, {:template => invalid_attributes}, valid_session
expect(assigns(:template)).to be_a_new(Template)
end
it "re-renders the 'new' template" do
post :create, {:template => invalid_attributes}, valid_session
expect(response).to render_template("new")
end
end
end
describe "PUT #update" do
context "with valid params" do
let(:new_attributes) {
skip("Add a hash of attributes valid for your model")
}
it "updates the requested template" do
template = Template.create! valid_attributes
put :update, {:id => template.to_param, :template => new_attributes}, valid_session
template.reload
skip("Add assertions for updated state")
end
it "assigns the requested template as @template" do
template = Template.create! valid_attributes
put :update, {:id => template.to_param, :template => valid_attributes}, valid_session
expect(assigns(:template)).to eq(template)
end
it "redirects to the template" do
template = Template.create! valid_attributes
put :update, {:id => template.to_param, :template => valid_attributes}, valid_session
expect(response).to redirect_to(template)
end
end
context "with invalid params" do
it "assigns the template as @template" do
template = Template.create! valid_attributes
put :update, {:id => template.to_param, :template => invalid_attributes}, valid_session
expect(assigns(:template)).to eq(template)
end
it "re-renders the 'edit' template" do
template = Template.create! valid_attributes
put :update, {:id => template.to_param, :template => invalid_attributes}, valid_session
expect(response).to render_template("edit")
end
end
end
describe "DELETE #destroy" do
it "destroys the requested template" do
template = Template.create! valid_attributes
expect {
delete :destroy, {:id => template.to_param}, valid_session
}.to change(Template, :count).by(-1)
end
it "redirects to the templates list" do
template = Template.create! valid_attributes
delete :destroy, {:id => template.to_param}, valid_session
expect(response).to redirect_to(templates_url)
end
end
end
| mit |
PatrickWalker/scullery | lib/scullery/couchdb/monitor.rb | 3545 | module Scullery
module CouchDB
class Monitor
# Creates the CouchDBMonitor
def initialize()
c = ParseConfig.new('conf/scullery.conf') #Read conf File
##read
notification_type=(c.params['notification_type'])
@db_server = Scullery::CouchDB::Server.new( c.params['couchDBHost'], c.params['couchDBPort'])
@database_uri = c.params['database_uri']
@file_fetcher = Scullery::FileFetcher.new( c.params['checkSumHost'], c.params['user'], c.params['password'])
@git_client = Scullery::Git.new( c.params['gitRepo'])
seq_id = @git_client.get_latest_sequence_number()
@listener = Scullery::CouchDB::Listener.new(@db_server, \
@database_uri, \
notification_type, \
seq_id, \
self)
end
#Event handler to react on change_event
# == Parameters:
# change_event::
# Change event from couchdb which we are reacting to
def notify(change_event)
retrieve_document(change_event)
end
#Fetches the document identified in the change_event from the DB
# == Parameters:
# change_event::
# Change event from couchdb which we are reacting to
# == Returns
# json_document::
# CouchDB Document updated in related change event
def retrieve_document(change_event)
result = @db_server.get("#{@database_uri}#{change_event.id()}?rev=#{change_event.rev()}")
json_document = result.body
process_document(json_document, change_event)
return json_document
end
#Saves the retrieved document locally and adds to git
#Fetches the document identified in the change_event from the DB
# == Parameters:
# change_event::
# Change event from couchdb which we are reacting to
# document::
# Document fetched from couchdb
def process_document(document, change_event)
JSON.create_id = nil
seq_id = change_event.seq
document = JSON.parse(document)
doc_type= document["chef_type"]
json_class = document["json_class"]
if !doc_type.nil?
case doc_type.downcase
when "checksum"
checksum_value = document["checksum"]
@file_fetcher.fetch_checksum_file(checksum_value, seq_id)
end
else
doc_type = "design"
end
if ( (change_event.delete_operation?.nil?) && (!change_event.delete_operation?.eql?("true")))
@git_client.add_document(doc_type, change_event.id, document.to_json())
@git_client.commit(seq_id)
else
#Only Delete Document if it exists in file system
puts "Checking if File Exists #{File.join(@git_client.repo_path,@git_client.get_couchdb_document_path(change_event.id))}"
if ::File.exists?(File.join(@git_client.repo_path,@git_client.get_couchdb_document_path(change_event.id)))
@git_client.delete_document(doc_type, change_event.id)
end
end
end
end
end
end
| mit |
telendt/fmaze | cmd/fmaze/integration_test.go | 56 | // +build integration
package main
// TODO: implement
| mit |
alexmon1989/schools_kr | fuel/app/modules/admin/views/template.php | 3555 | <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title><?php echo $title; ?></title>
<?php echo Asset::css('//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css'); ?>
<style>
body { margin: 50px; }
</style>
<?php echo Asset::js(array(
'//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js',
'//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js'
)); ?>
<script>
$(function(){ $('.topbar').dropdown(); });
</script>
</head>
<body>
<?php if ($current_user): ?>
<div class="navbar navbar-inverse navbar-fixed-top">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#">Админ-часть</a>
</div>
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li class="<?php echo Uri::segment(2) == '' ? 'active' : '' ?>">
<?php echo Html::anchor('admin', 'Начало работы') ?>
</li>
<li><a href="#">Муниципальные образования</a></li>
<li><a href="#">Учреждения</a></li>
<li class="dropdown">
<a href="#" data-toggle="dropdown" class="dropdown-toggle">Списки <span class="caret"></span></a>
<ul role="menu" class="dropdown-menu">
<li><a href="#">Виды учреждений</a></li>
<li><a href="#">Типы учреждений</a></li>
</ul>
</li>
<li><a href="#">Настройки</a></li>
</ul>
<ul class="nav navbar-nav pull-right">
<li class="dropdown">
<a data-toggle="dropdown" class="dropdown-toggle" href="#"><?php echo $current_user->username ?> <b class="caret"></b></a>
<ul class="dropdown-menu">
<li><?php echo Html::anchor('admin/logout', 'Logout') ?></li>
</ul>
</li>
</ul>
</div>
</div>
</div>
<?php endif; ?>
<div class="container">
<div class="row">
<div class="col-md-12">
<h1><?php echo $title; ?></h1>
<hr>
<?php if (Session::get_flash('success')): ?>
<div class="alert alert-success alert-dismissable">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
<p>
<?php echo implode('</p><p>', (array) Session::get_flash('success')); ?>
</p>
</div>
<?php endif; ?>
<?php if (Session::get_flash('error')): ?>
<div class="alert alert-danger alert-dismissable">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
<p>
<?php echo implode('</p><p>', (array) Session::get_flash('error')); ?>
</p>
</div>
<?php endif; ?>
</div>
<div class="col-md-12">
<?php echo $content; ?>
</div>
</div>
<hr/>
<footer>
<p class="pull-right">Page rendered in {exec_time}s using {mem_usage}mb of memory.</p>
<p>
<a href="http://fuelphp.com">FuelPHP</a> is released under the MIT license.<br>
<small>Version: <?php echo e(Fuel::VERSION); ?></small>
</p>
</footer>
</div>
</body>
</html>
| mit |
helixyte/TheLMA | thelma/repositories/rdb/mappers/compoundchemicalstructure.py | 766 | """
This file is part of the TheLMA (THe Laboratory Management Application) project.
See LICENSE.txt for licensing, CONTRIBUTORS.txt for contributor information.
Compound chemical structure mapper.
"""
from sqlalchemy.orm import mapper
from thelma.entities.chemicalstructure import CHEMICAL_STRUCTURE_TYPE_IDS
from thelma.entities.chemicalstructure import CompoundChemicalStructure
__docformat__ = 'reStructuredText en'
__all__ = ['create_mapper']
def create_mapper(chemical_structure_mapper, chemical_structure_tbl):
"Mapper factory."
m = mapper(CompoundChemicalStructure, chemical_structure_tbl,
inherits=chemical_structure_mapper,
polymorphic_identity=CHEMICAL_STRUCTURE_TYPE_IDS.COMPOUND
)
return m
| mit |
msieker/MicroBlog | src/Dropbox.Api/Files/SearchResult.cs | 5615 | // <auto-generated>
// Auto-generated by StoneAPI, do not modify.
// </auto-generated>
namespace Dropbox.Api.Files
{
using sys = System;
using col = System.Collections.Generic;
using re = System.Text.RegularExpressions;
using enc = Dropbox.Api.Stone;
/// <summary>
/// <para>The search result object</para>
/// </summary>
public class SearchResult
{
#pragma warning disable 108
/// <summary>
/// <para>The encoder instance.</para>
/// </summary>
internal static enc.StructEncoder<SearchResult> Encoder = new SearchResultEncoder();
/// <summary>
/// <para>The decoder instance.</para>
/// </summary>
internal static enc.StructDecoder<SearchResult> Decoder = new SearchResultDecoder();
/// <summary>
/// <para>Initializes a new instance of the <see cref="SearchResult" /> class.</para>
/// </summary>
/// <param name="matches">A list (possibly empty) of matches for the query.</param>
/// <param name="more">Used for paging. If true, indicates there is another page of
/// results available that can be fetched by calling <see
/// cref="Dropbox.Api.Files.Routes.FilesRoutes.SearchAsync" /> again.</param>
/// <param name="start">Used for paging. Value to set the start argument to when
/// calling <see cref="Dropbox.Api.Files.Routes.FilesRoutes.SearchAsync" /> to fetch
/// the next page of results.</param>
public SearchResult(col.IEnumerable<SearchMatch> matches,
bool more,
ulong start)
{
var matchesList = enc.Util.ToList(matches);
if (matches == null)
{
throw new sys.ArgumentNullException("matches");
}
this.Matches = matchesList;
this.More = more;
this.Start = start;
}
/// <summary>
/// <para>Initializes a new instance of the <see cref="SearchResult" /> class.</para>
/// </summary>
/// <remarks>This is to construct an instance of the object when
/// deserializing.</remarks>
public SearchResult()
{
}
/// <summary>
/// <para>A list (possibly empty) of matches for the query.</para>
/// </summary>
public col.IList<SearchMatch> Matches { get; protected set; }
/// <summary>
/// <para>Used for paging. If true, indicates there is another page of results
/// available that can be fetched by calling <see
/// cref="Dropbox.Api.Files.Routes.FilesRoutes.SearchAsync" /> again.</para>
/// </summary>
public bool More { get; protected set; }
/// <summary>
/// <para>Used for paging. Value to set the start argument to when calling <see
/// cref="Dropbox.Api.Files.Routes.FilesRoutes.SearchAsync" /> to fetch the next page
/// of results.</para>
/// </summary>
public ulong Start { get; protected set; }
#region Encoder class
/// <summary>
/// <para>Encoder for <see cref="SearchResult" />.</para>
/// </summary>
private class SearchResultEncoder : enc.StructEncoder<SearchResult>
{
/// <summary>
/// <para>Encode fields of given value.</para>
/// </summary>
/// <param name="value">The value.</param>
/// <param name="writer">The writer.</param>
public override void EncodeFields(SearchResult value, enc.IJsonWriter writer)
{
WriteListProperty("matches", value.Matches, writer, Dropbox.Api.Files.SearchMatch.Encoder);
WriteProperty("more", value.More, writer, enc.BooleanEncoder.Instance);
WriteProperty("start", value.Start, writer, enc.UInt64Encoder.Instance);
}
}
#endregion
#region Decoder class
/// <summary>
/// <para>Decoder for <see cref="SearchResult" />.</para>
/// </summary>
private class SearchResultDecoder : enc.StructDecoder<SearchResult>
{
/// <summary>
/// <para>Create a new instance of type <see cref="SearchResult" />.</para>
/// </summary>
/// <returns>The struct instance.</returns>
protected override SearchResult Create()
{
return new SearchResult();
}
/// <summary>
/// <para>Set given field.</para>
/// </summary>
/// <param name="value">The field value.</param>
/// <param name="fieldName">The field name.</param>
/// <param name="reader">The json reader.</param>
protected override void SetField(SearchResult value, string fieldName, enc.IJsonReader reader)
{
switch (fieldName)
{
case "matches":
value.Matches = ReadList<SearchMatch>(reader, Dropbox.Api.Files.SearchMatch.Decoder);
break;
case "more":
value.More = enc.BooleanDecoder.Instance.Decode(reader);
break;
case "start":
value.Start = enc.UInt64Decoder.Instance.Decode(reader);
break;
default:
reader.Skip();
break;
}
}
}
#endregion
}
}
| mit |
ThetaGroup/JooBase | src/main/java/org/theta/joobase/info/JooMethodInfo.java | 1239 | package org.theta.joobase.info;
import java.lang.reflect.Method;
/**
*
* @author ranger
* @date Jul 13, 2017
*
*/
public abstract class JooMethodInfo {
private Method method;
private String shard;
private JooMethodType methodType;
private Class<?> returnType;
public JooMethodInfo() {
}
public JooMethodInfo(Method method, String shard, JooMethodType methodType, Class<?> returnType) {
this.method = method;
this.shard = shard;
this.methodType = methodType;
this.returnType = returnType;
}
public String getShard() {
return shard;
}
public void setShard(String shard) {
this.shard = shard;
}
public Method getMethod() {
return method;
}
public void setMethod(Method method) {
this.method = method;
}
public JooMethodType getMethodType() {
return methodType;
}
public void setMethodType(JooMethodType methodType) {
this.methodType = methodType;
}
@Override
public String toString() {
return String.format("Method:%s,Shard:%s,JooMethodType:%s,ReturnType:%s", getMethod().getName(), getShard(),
methodType, returnType);
}
public Class<?> getReturnType() {
return returnType;
}
public void setReturnType(Class<?> returnType) {
this.returnType = returnType;
}
}
| mit |
collab-uniba/emotions-online-qa | build_dataset/sentiment/Sentiment.java | 2029 | import uk.ac.wlv.sentistrength.*;
import java.util.Properties;
import edu.stanford.nlp.ling.CoreAnnotations;
import edu.stanford.nlp.pipeline.Annotation;
import edu.stanford.nlp.pipeline.StanfordCoreNLP;
import edu.stanford.nlp.sentiment.SentimentCoreAnnotations;
import edu.stanford.nlp.util.CoreMap;
public class Sentiment {
public Sentiment() {
// TODO Auto-generated constructor stub
super();
}
public String SentiStrengthgetScore(String text){
SentiStrength sentiStrength = new SentiStrength();
String ssthInitialisation[] = {"sentidata", "lib/SentiStrength_Data/", "explain"};
sentiStrength.initialise(ssthInitialisation);
String score = sentiStrength.computeSentimentScores(text);
String[] split_res = score.split(" ");
String pos_score = split_res[0];
String neg_score = split_res[1];
//return pos_score + "," + neg_score;
return score;
}
public String NLPgetScore(String text){
Properties pipelineProps = new Properties();
//pipelineProps.setProperty("ssplit.eolonly", "true");
pipelineProps.setProperty("annotators", "tokenize,pos,cleanxml,parse,sentiment");
pipelineProps.setProperty("enforceRequirements", "false");
Properties tokenizerProps = new Properties();
tokenizerProps.setProperty("annotators", /*"tokenize, ssplit"*/"tokenize,cleanxml,ssplit,"+/*pos,lemma,*/"parse,sentiment");
System.out.println("Annotator loaded");
StanfordCoreNLP tokenizer = new StanfordCoreNLP(tokenizerProps);
StanfordCoreNLP pipeline = new StanfordCoreNLP(pipelineProps);
String score = new String();
String line = text.trim();
if (line.length() > 0) {
Annotation annotation = tokenizer.process(line);
pipeline.annotate(annotation);
for (CoreMap sentence : annotation.get(CoreAnnotations.SentencesAnnotation.class)) {
score = score + "," + sentence.get(SentimentCoreAnnotations.ClassName.class);
}
}
return score;
}
}
| mit |
luoboding/feiyu | app/components/common/directives/quick-date-picker.js | 24840 | "use strict";
module.exports = function (ngModule) {
ngModule.provider("ngQuickDateDefaults", function () {
return {
options: {
dateFormat: 'yyyy-MM-dd',
timeFormat: 'HH:mm',
labelFormat: null,
placeholder: 'Click to Set Date',
hoverText: null,
closeButtonHtml: "<i class='fa fa-times'></i>",
buttonIconHtml: "<i class='fa fa-calendar'></i>",
nextLinkHtml: "<i class='fa fa-chevron-right'></i>",
prevLinkHtml: "<i class='fa fa-chevron-left'></i>",
disableTimepicker: false,
disableClearButton: false,
defaultTime: null,
dayAbbreviations: ["quickdate.Su", "quickdate.M", "quickdate.Tu", "quickdate.W", "quickdate.Th", "quickdate.F", "quickdate.Sa"],
dateFilter: null,
parseDateFunction: function (str) {
var d = new Date(str);
return d;
}
},
$get: function () {
return this.options;
},
set: function (keyOrHash, value) {
var k, v, _results;
if (typeof keyOrHash === 'object') {
_results = [];
for (k in keyOrHash) {
v = keyOrHash[k];
_results.push(this.options[k] = v);
}
return _results;
} else {
this.options[keyOrHash] = value;
}
}
};
})
.directive('ngEnter', function () {
return function (scope, element, attr) {
return element.bind('keydown keypress', function (e) {
if (e.which === 13) {
scope.$apply(attr.ngEnter);
return e.preventDefault();
}
});
};
})
.directive('onTab', function () {
return {
restrict: 'A',
link: function (scope, element, attr) {
return element.bind('keydown keypress', function (e) {
if ((e.which === 9) && !e.shiftKey) {
return scope.$apply(attr.onTab);
}
});
}
};
})
.directive('quickDatepicker', function (ngQuickDateDefaults, $filter, $sce, $parse, $timeout) {
return {
restrict: "E",
require: "?ngModel",
scope: {
dateFilter: '=?',
onChange: "&",
required: '@',
},
replace: true,
link: function (scope, element, attrs, ngModelCtrl) {
var dateToString, datepickerClicked, datesAreEqual, datesAreEqualToMinute, debounce, getDaysInMonth, initialize, parseDateString, refreshView, setCalendarDate, setConfigOptions, setInputFieldValues, setupCalendarView, stringToDate;
initialize = function () {
var templateDate;
setConfigOptions();
scope.toggleCalendar(false);
scope.weeks = [];
scope.inputDate = null;
scope.inputTime = null;
scope.invalid = true;
if (typeof attrs.initValue === 'string') {
ngModelCtrl.$setViewValue(attrs.initValue);
}
if (!scope.defaultTime) {
templateDate = new Date();
scope.datePlaceholder = $filter('date')(templateDate, scope.dateFormat);
scope.timePlaceholder = $filter('date')(templateDate, scope.timeFormat);
}
setCalendarDate();
return refreshView();
};
var isClickable = function (currentDate) {
var disableTimepicker = scope.disableTimepicker;
if (disableTimepicker) {
currentDate.setHours(0);
currentDate.setMinutes(0);
currentDate.setSeconds(0);
}
var currentTime = parseInt((currentDate.getTime()) / 1000);
var maxTime, minTime;
if (scope.minDate) {
if (disableTimepicker) {
scope.minDate.setHours(0);
scope.minDate.setMinutes(0);
scope.minDate.setSeconds(0);
}
minTime = parseInt((scope.minDate.getTime()) / 1000);
}
if (scope.maxDate) {
if (disableTimepicker) {
scope.maxDate.setHours(0);
scope.maxDate.setMinutes(0);
scope.maxDate.setSeconds(0);
}
maxTime = parseInt((scope.maxDate.getTime()) / 1000);
}
if (!scope.minDate && !scope.maxDate) {
return true;
}
if (scope.minDate && !scope.maxDate) {
return currentTime >= minTime;
}
if (!scope.minDate && scope.maxDate) {
return currentTime < maxTime;
}
if (scope.minDate && scope.maxDate) {
return currentTime >= minTime && currentTime < maxTime;
}
};
//watch model
scope.watchData = {};
angular.forEach(['minDate', 'maxDate'], function (key) {
if (attrs[key]) {
scope.$parent.$watch(attrs[key], function (value) {
scope[key] = value;
return refreshView();
});
}
});
setConfigOptions = function () {
var key, value;
for (key in ngQuickDateDefaults) {
value = ngQuickDateDefaults[key];
if (key.match(/[Hh]tml/)) {
scope[key] = $sce.trustAsHtml(ngQuickDateDefaults[key] || "");
} else if (!scope[key] && attrs[key]) {
scope[key] = attrs[key];
} else if (!scope[key]) {
scope[key] = ngQuickDateDefaults[key];
}
}
if (!scope.labelFormat) {
scope.labelFormat = scope.dateFormat;
if (!scope.disableTimepicker) {
scope.labelFormat += " " + scope.timeFormat;
}
}
if (attrs.iconClass && attrs.iconClass.length) {
scope.buttonIconHtml = $sce.trustAsHtml("<i ng-show='iconClass' class='" + attrs.iconClass + "'></i>");
return;
}
};
datepickerClicked = false;
// window.document.addEventListener('click', function(event) {
// if (scope.calendarShown && !datepickerClicked) {
// scope.toggleCalendar(false);
// scope.$apply();
// }
// return datepickerClicked = false;
// });
angular.element(element[0])[0].addEventListener('click', function (event) {
datepickerClicked = true;
return;
});
refreshView = function () {
var date;
date = ngModelCtrl.$modelValue ? parseDateString(ngModelCtrl.$modelValue) : null;
setupCalendarView();
setInputFieldValues(date);
scope.mainButtonStr = date ? $filter('date')(date, scope.labelFormat) : scope.placeholder;
scope.invalid = ngModelCtrl.$invalid;
return;
};
setInputFieldValues = function (val) {
if (val) {
scope.inputDate = $filter('date')(val, scope.dateFormat);
scope.inputTime = $filter('date')(val, scope.timeFormat);
} else {
scope.inputDate = null;
scope.inputTime = null;
}
};
setCalendarDate = function (val) {
var d;
d = val ? new Date(val) : new Date();
if (d.toString() === "Invalid Date") {
d = new Date();
}
d.setDate(1);
scope.calendarDate = new Date(d);
return;
};
setupCalendarView = function () {
var curDate, d, day, daysInMonth, numRows, offset, row, selected, time, today, weeks, _i, _j, _ref;
offset = scope.calendarDate.getDay();
daysInMonth = getDaysInMonth(scope.calendarDate.getFullYear(), scope.calendarDate.getMonth());
numRows = Math.ceil((offset + daysInMonth) / 7);
weeks = [];
curDate = new Date(scope.calendarDate);
curDate.setDate(curDate.getDate() + (offset * -1));
for (row = _i = 0, _ref = numRows - 1; 0 <= _ref ? _i <= _ref : _i >= _ref; row = 0 <= _ref ? ++_i : --_i) {
weeks.push([]);
for (day = _j = 0; _j <= 6; day = ++_j) {
d = new Date(curDate);
if (scope.defaultTime) {
time = scope.defaultTime.split(':');
d.setHours(time[0] || 0);
d.setMinutes(time[1] || 0);
d.setSeconds(time[2] || 0);
}
selected = ngModelCtrl.$modelValue && d && datesAreEqual(d, ngModelCtrl.$modelValue);
today = datesAreEqual(d, new Date());
weeks[row].push({
date: d,
selected: selected,
disabled: typeof scope.dateFilter === 'function' ? !scope.dateFilter(d) : false,
other: d.getMonth() !== scope.calendarDate.getMonth(),
today: today,
isClickable: isClickable(d)
});
curDate.setDate(curDate.getDate() + 1);
}
}
scope.weeks = weeks;
return;
};
ngModelCtrl.$parsers.push(function (viewVal) {
if (scope.required && !viewVal) {
ngModelCtrl.$setValidity('required', false);
return null;
} else if (angular.isDate(viewVal)) {
ngModelCtrl.$setValidity('required', true);
return viewVal;
} else if (angular.isString(viewVal)) {
ngModelCtrl.$setValidity('required', true);
return scope.parseDateFunction(viewVal);
} else {
return null;
}
});
ngModelCtrl.$formatters.push(function (modelVal) {
if (angular.isDate(modelVal)) {
return modelVal;
} else if (angular.isString(modelVal)) {
return scope.parseDateFunction(modelVal);
} else {
return void 0;
}
});
dateToString = function (date, format) {
return $filter('date')(date, format);
};
stringToDate = function (date) {
if (typeof date === 'string') {
return parseDateString(date);
} else {
return date;
}
};
parseDateString = ngQuickDateDefaults.parseDateFunction;
datesAreEqual = function (d1, d2, compareTimes) {
if (!compareTimes) {
compareTimes = false;
}
if (compareTimes) {
return (d1 - d2) === 0;
} else {
d1 = stringToDate(d1);
d2 = stringToDate(d2);
return d1 && d2 && (d1.getYear() === d2.getYear()) && (d1.getMonth() === d2.getMonth()) && (d1.getDate() === d2.getDate());
}
};
datesAreEqualToMinute = function (d1, d2) {
if (!(d1 && d2)) {
return false;
}
return parseInt(d1.getTime() / 60000) === parseInt(d2.getTime() / 60000);
};
getDaysInMonth = function (year, month) {
return [31, ((year % 4 === 0 && year % 100 !== 0) || year % 400 === 0 ? 29 : 28), 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month];
};
debounce = function (func, wait) {
var args, context, later, result, timeout, timestamp;
timeout = args = context = timestamp = result = null;
later = function () {
var last;
last = +new Date() - timestamp;
if (last < wait && last > 0) {
timeout = setTimeout(later, wait - last);
} else {
timeout = null;
}
};
return function () {
context = this;
args = arguments;
timestamp = +new Date();
if (!timeout) {
timeout = setTimeout(later, wait);
result = func.apply(context, args);
context = args = null;
}
return result;
};
};
ngModelCtrl.$render = function () {
setCalendarDate(ngModelCtrl.$viewValue);
return refreshView();
};
ngModelCtrl.$viewChangeListeners.unshift(function () {
setCalendarDate(ngModelCtrl.$viewValue);
refreshView();
if (scope.onChange) {
return scope.onChange();
}
});
scope.$watch('calendarShown', function (newVal, oldVal) {
var dateInput;
if (newVal) {
dateInput = angular.element(element[0].querySelector(".quickdate-date-input"))[0];
return dateInput.select();
}
});
scope.toggleCalendar = debounce(function (show) {
if (isFinite(show)) {
scope.calendarShown = show;
} else {
scope.calendarShown = !scope.calendarShown;
}
return;
}, 150);
scope.selectDate = function (date, closeCalendar) {
var isTimeValid = false;
var changed;
if (!closeCalendar) {
closeCalendar = true;
}
if (date) {
var disableTimepicker = scope.disableTimepicker;
if (disableTimepicker) {
date.setHours(0);
date.setMinutes(0);
date.setSeconds(0);
}
var currentTime = parseInt((date.getTime()) / 1000);
var maxTime, minTime;
if (scope.minDate) {
if (disableTimepicker) {
scope.minDate.setHours(0);
scope.minDate.setMinutes(0);
scope.minDate.setSeconds(0);
}
minTime = parseInt((scope.minDate.getTime()) / 1000);
}
if (scope.maxDate) {
if (disableTimepicker) {
scope.maxDate.setHours(0);
scope.maxDate.setMinutes(0);
scope.maxDate.setSeconds(0);
}
maxTime = parseInt((scope.maxDate.getTime()) / 1000);
}
if (!scope.minDate && !scope.maxDate) {
isTimeValid = true;
}
if (scope.minDate && !scope.maxDate) {
isTimeValid = currentTime >= minTime;
}
if (!scope.minDate && scope.maxDate) {
isTimeValid = currentTime < maxTime;
}
if (scope.minDate && scope.maxDate) {
isTimeValid = currentTime >= minTime && currentTime < maxTime;
}
}
changed = (!ngModelCtrl.$viewValue && date) || (ngModelCtrl.$viewValue && !date) || ((date && ngModelCtrl.$viewValue) && (date.getTime() !== ngModelCtrl.$viewValue.getTime()));
if (typeof scope.dateFilter === 'function' && !scope.dateFilter(date)) {
return false;
}
if ((isTimeValid && date) || !date) {
ngModelCtrl.$setViewValue(date);
scope.toggleCalendar(false);
} else {
console.log('时间格式错误');
return isTimeValid;
}
if (closeCalendar) {
scope.toggleCalendar(false);
}
return true;
};
scope.selectDateFromInput = function (closeCalendar) {
var err, tmpDate, tmpDateAndTime, tmpTime;
if (!closeCalendar) {
closeCalendar = false;
}
try {
tmpDate = new Date(scope.inputDate.replace(/[-]/g, '/')); //Date.parse(scope.inputDate.replace(/[-]/g,'/'));//parseDateString(scope.inputDate);
if (!scope.inputDate) {
throw 'Invalid Date';
}
var date = scope.inputTime ? (scope.inputDate + " " + scope.inputTime) : scope.inputDate;
if (isNaN(Date.parse(date.replace(/[-]/g, '/')))) {
throw 'Invalid Date';
}
if (!scope.disableTimepicker && scope.inputTime && scope.inputTime.length && tmpDate) {
tmpTime = scope.disableTimepicker ? '00:00:00' : scope.inputTime;
tmpDateAndTime = new Date((scope.inputDate + " " + tmpTime).replace(/[-]/g, '/'));
if (!tmpDateAndTime) {
throw 'Invalid Time';
}
tmpDate = tmpDateAndTime;
}
if (!datesAreEqualToMinute(ngModelCtrl.$viewValue, tmpDate)) {
console.log(tmpDate);
if (!scope.selectDate(tmpDate, false)) {
throw 'Invalid Date';
}
}
if (closeCalendar) {
scope.toggleCalendar(false);
}
scope.inputDateErr = false;
scope.inputTimeErr = false;
return;
} catch (_error) {
err = _error;
if (err === 'Invalid Date') {
scope.inputDateErr = true;
return;
} else if (err === 'Invalid Time') {
scope.inputTimeErr = true;
return;
}
}
};
scope.onDateInputTab = function () {
if (scope.disableTimepicker) {
scope.toggleCalendar(false);
}
return true;
};
scope.onTimeInputTab = function () {
scope.toggleCalendar(false);
return true;
};
scope.nextMonth = function () {
setCalendarDate(new Date(new Date(scope.calendarDate).setMonth(scope.calendarDate.getMonth() + 1)));
return refreshView();
};
scope.prevMonth = function () {
setCalendarDate(new Date(new Date(scope.calendarDate).setMonth(scope.calendarDate.getMonth() - 1)));
return refreshView();
};
scope.clear = function () {
return scope.selectDate(null, true);
};
$('body').on('click', function (e) {
var $target = $(e.target);
if ($target !== element && $target.parents('.quickdate').length === 0) {
$timeout(function () {
scope.toggleCalendar(false);
refreshView();
}, 0);
}
});
return initialize();
},
template: require('./../templates/date-picker.jade')
};
});
};
| mit |
nadvamir/forgotten-story-mmorpg | game/modules/loc/pris.php | 2067 | <?php
// TJURMA
$locmap = 'eway';
$w = do_mysql ("SELECT weather FROM maps WHERE map = '".$locmap."';");
$w = mysql_result ($w, 0);
if ($w == 0 || $w == 1 || $w == 0.5) $temperature = -1;
if ($w == 2 || $w == 3 || $w == 4 || $w == 5) $temperature = 0;
if ($w == 6) $temperature = 1;
// vyhod:
global $LOGIN;
$q = do_mysql ("SELECT rase, qlvl, id_player, karma FROM players WHERE login = '".$LOGIN."';");
$pp = mysql_fetch_assoc ($q);
if ($pp['karma'] < -99) $out = '';
else
{
// nuzhno datq vyhod:
if ($pp['qlvl'] < 2)
{
if ($pp['rase'] == 1) $out = 'rele|8x8:4';
elseif ($pp['rase'] == 2) $out = 'elfc|5x1:4';
else $out = 'verg|4x1:4';
}
else
$out = 'mva1|7x1:4'; // adres tropinki v gorah
}
$l['1x1'] = 'pris|1x1~Тюрьма~тюрьма~'.$temperature.'~5~0~0~'.$out;
$l['1x2'] = 'pris|1x2~Бараки~Бараки~'.$temperature.'~5~0~0~';
$l['1x3'] = 'pris|1x3~бараки~бараки~'.$temperature.'~5~0~0~';
$l['2x1'] = 'pris|2x1~тюрьма~тюрьма~'.$temperature.'~245~0~0~';
$l['2x2'] = 'pris|2x2~бараки~бараки~'.$temperature.'~2457~0~0~';
$l['2x3'] = 'pris|2x3~бараки~бараки~'.$temperature.'~457~0~0~';
$l['3x1'] = 'pris|3x1~тюрьма~тюрьма~'.$temperature.'~45~0~0~';
$l['3x2'] = 'pris|3x2~бараки~бараки~'.$temperature.'~4~0~0~';
$l['3x3'] = 'pris|3x3~бараки~бараки~'.$temperature.'~4~0~0~';
$l['4x1'] = 'pris|4x1~камнеломня~камнеломня~'.$temperature.'~245~0~0~';
$l['4x2'] = 'pris|4x2~камнеломня~камнеломня~'.$temperature.'~2357~0~0~';
$l['4x3'] = 'pris|4x3~камнеломня~камнеломня~'.$temperature.'~7~0~0~';
$l['5x1'] = 'pris|5x1~камнеломня~камнеломня~'.$temperature.'~4~0~0~';
$l['5x2'] = 'pris|5x2~камнеломня~камнеломня~'.$temperature.'~4~0~0~';
$l['5x3'] = 'pris|5x3~камнеломня~камнеломня~'.$temperature.'~6~0~0~';
?> | mit |
IntAlert/chatplayer | app/containers/HomePage/reducer.js | 6910 | /*
*
* Gimp reducer
*
*/
import { fromJS } from 'immutable';
import {
SCRIPT_FETCH_SUCCEEDED,
SCRIPT_FETCH_FAILED,
RESPOND,
BOT_MESSAGE_INVISIBLE,
BOT_MESSAGE_WRITING,
BOT_MESSAGE_VISIBLE,
TIMER_TICK,
PRINT,
} from './constants';
const initialState = fromJS({
script_loaded: false,
current_stage_id: false,
show_user_choices: false,
script: {},
feed: [],
scores: {},
});
function homeReducer(state = initialState, action) {
switch (action.type) {
case SCRIPT_FETCH_SUCCEEDED:
let nextState = state
.merge({
script_loaded: true,
script: action.script,
current_stage_id: action.script.setup.initial_stage_id,
scores: action.script.setup.initial_scores,
});
nextState = addPromptMessages(nextState, action.script.setup.initial_stage_id);
return nextState;
case SCRIPT_FETCH_FAILED:
console.log('script fetch failed');
return state;
case RESPOND:
// get current and next place in script
const userResponse = state.getIn(['script', 'stages', action.stage_id, 'choices', action.choice_id]);
if (userResponse.getIn(['targetType']) === 'route') {
// just abort everything and change the location
window.location.href = userResponse.getIn(['target']);
return state;
}
// otherwise, assume that this was a response that requires a
// modification to the feed
// assume targetType === 'feed'
const next_stage_id = userResponse.getIn(['target']);
var nextState = state
// update current place in script
.set('current_stage_id', next_stage_id)
// hide user choices
.set('show_user_choices', false)
// add user's response
.update('feed', arr => arr.push({
speaker: 0,
type: "text",
content: userResponse.get('text'),
}));
// set current context
// .set('current_context', currentContext)
// add bot's immediate response (0+ messages)
nextState = addImmediateChoiceResponses(nextState, userResponse);
// add bot's prompts (0+ messages )
nextState = addPromptMessages(nextState, next_stage_id);
return nextState;
case TIMER_TICK:
// if none, find first element in feed with status=BOT_MESSAGE_WRITING, set to BOT_MESSAGE_VISIBLE
const firstWritingMessageIndex = state.get('feed').findIndex(message => {
return ( message.speaker == -1 || message.speaker == 1 ) && message.status == BOT_MESSAGE_WRITING;
})
if (firstWritingMessageIndex > -1) {
// update status of message
let updatedFeed = state.updateIn(['feed', firstWritingMessageIndex], (message) => {
const newMessage = Object.assign({}, message);
newMessage.status = BOT_MESSAGE_VISIBLE;
return newMessage;
});
// get score change if any
const scoreChange = state.getIn(['feed', firstWritingMessageIndex]).scoreChange;
if (scoreChange) {
// update score
updatedFeed = updatedFeed.updateIn(['scores'], (scores) => {
return calculateNewScores(scoreChange, scores);
});
} else {
}
return updatedFeed;
}
// find first element in feed with status=BOT_MESSAGE_INVISIBLE, set to BOT_MESSAGE_WRITING
const firstInvisibleMessageIndex = state.get('feed').findIndex(message => {
return (message.speaker == -1 || message.speaker == 1 ) && message.status == BOT_MESSAGE_INVISIBLE;
});
if (firstInvisibleMessageIndex > -1 ) {
return state.updateIn(['feed', firstInvisibleMessageIndex], message => {
let newMessage = Object.assign({}, message)
newMessage.status = BOT_MESSAGE_WRITING
return newMessage;
});
}
// // if none, show user choices if hidden and there are choices available
if ( state.get('show_user_choices') == false && state.get('current_stage_id') !== false ) {
return state.set('show_user_choices', true)
}
return state
case PRINT:
window.print();
break;
default:
return state;
}
}
// this adds immediate responses to a given choice
function addImmediateChoiceResponses(state, userResponse) {
var immediateResponses = userResponse.getIn(['responses'])
if ( immediateResponses == undefined) {
// no immediate responses
console.log('// no immediate responses')
return state
}
const nextState = state.update('feed', (arr) => {
var newArr = arr;
immediateResponses.toArray().forEach((response) => {
let speaker = 1;
if (response.get('speaker') !== undefined) {
speaker = response.get('speaker');
}
const feedMessage = {
speaker, // bot response code, TODO factor out as CONST
status: BOT_MESSAGE_INVISIBLE,
// TODO: do something with prompt.type, contentType?
type: response.get('type'),
content: response.get('content'),
more: response.get('more'),
scoreChange: response.get('scoreChange'),
}
newArr = newArr.push(feedMessage);
})
return newArr;
})
return nextState;
}
// this adds prompt messages for a given stage
function addPromptMessages(state, stage_id) {
var prompts = state.getIn(['script', 'stages', stage_id, 'prompts']);
const nextState = state.update('feed', arr => {
var newArr = arr;
prompts.toArray().forEach(prompt => {
let speaker = -1;
if (prompt.get('speaker') !== undefined) {
speaker = prompt.get('speaker');
}
const feedMessage = {
speaker: speaker, // narrator response code, TODO factor out as CONST
status: BOT_MESSAGE_INVISIBLE,
// TODO: do something with prompt.type, contentType?
type: prompt.get('type'),
content: prompt.get('content'),
more: prompt.get('more'),
scoreChange: prompt.get('scoreChange'),
}
newArr = newArr.push(feedMessage);
if (prompt.get('more')) {
console.log('***'+feedMessage.more);
console.log(newArr.toJS());
}
})
return newArr;
})
return nextState
}
function calculateNewScores(scoreChange, currentScores) {
const newScores = Object.assign({}, currentScores.toJS());
const scoreChangeJS = scoreChange.toJS();
for(let scoreName in scoreChangeJS) {
let change = scoreChangeJS[scoreName];
switch(change.operator) {
case 'multiply':
newScores[scoreName] = Math.ceil(newScores[scoreName] * change.amount);
break;
case 'add':
newScores[scoreName] += change.amount;
break;
case 'set':
newScores[scoreName] = change.amount;
break;
default:
throw('Unknown change operator ' + change.operator);
}
}
return fromJS(newScores);
}
export default homeReducer; | mit |
stonelasley/ionic-mocks | src/index.ts | 78 | export * from './native';
export * from './angular';
export * from './ionic';
| mit |
haizi-zh/Draft | nodeProject/routes/locality.js | 5473 | var express = require('express');
var router = express.Router();
var util = require('util')
var Locality = require('../models/locality').Locality;
var Album = require('../models/album').Album;
var Images = require('../models/images').Images;
var User = require('../models/user').User;
var pass = require('../auth/pass');
router.get('/', pass.ensureAuthenticated, function(req, res) {
res.render('picselection', {
user: req.user,
});
});
router.get('/cms', pass.ensureAuthenticated, function(req, res) {
res.render('picselection', {
user: req.user,
});
});
router.get('/search', pass.ensureAuthenticated, function(req, res) {
var seachText = req.query.search_text;
console.log(seachText);
Locality.searchByZhname(seachText, function(data){
if(!data) {
res.json({code: 1});
}
var poiId = data._id,
name = data.zhName;
console.log(poiId);
// 通过ID查询数据库,返回images数组!
Images.findById(poiId, function(images) {
var images = images;
Locality.countAll(function(total){
var totalDoc = total;
Locality.countDone(function(doneDocNum){
var done = doneDocNum,
rest = totalDoc - done,
result = {
code: 0,
poiId: poiId,
images: images,
name: name,
done: done,
rest: rest
};
res.json(result);
});
});
});
})
});
/* GET users listing. */
router.get('/ajax', pass.ensureAuthenticated, function(req, res) {
console.log('----get----');
Locality.getTargetData(function(data) {
if (!data) {
res.json({code: 1});
}
var poiId = data._id,
//images = data.images,
name = data.zhName;
console.log(poiId);
// 通过ID查询数据库,返回images数组!
Images.findById(poiId, function(images) {
var images = images;
Locality.countAll(function(total){
var totalDoc = total;
Locality.countDone(function(doneDocNum){
var done = doneDocNum,
rest = totalDoc - done,
result = {
code: 0,
poiId: poiId,
images: images,
name: name,
done: done,
rest: rest
};
res.json(result);
});
});
});
});
});
router.post('/ajax', pass.ensureAuthenticated, function(req, res) {
console.log('----post----');
console.log(req.user.username);
var postData = req.body,
id = postData.poiId,
images = postData.images;
if(isArray(images)) {
for(var i in images) {
images[i] = JSON.parse(images[i]);
}
}else{
var temp = JSON.parse(images);
images = [];
images.push(temp);
}
if(id && images && images.length) {
var workload = '';
Locality.findById(id, 'isDone', function(err, doc){
if(doc.isDone == true) {
workload = 'keep';
Locality.setDoneTag(id, images, function(data, state) {
if (!state) {
res.json({code: 1})
}
var count = 0;
images.forEach(function(elem) {
var key = elem.key;
if(elem.cropHint != undefined && elem.cropHint != null) {
var cropHint = elem.cropHint;
Images.findByKeyAndUpdate(key, cropHint, function(doc){
if(doc) {
count = count + 1;
}
})
}
});
res.json({
code: 0,
workload: workload
});
console.log(count);
console.log('更新成功');
});
}else{
User.addOne(req.user.username, function(err, data){
workload = parseInt(data.workload);
Locality.setDoneTag(id, images, function(data, state) {
if (!state) {
res.json({code: 1})
}
var count = 0;
images.forEach(function(elem) {
var key = elem.key;
if(elem.cropHint != undefined && elem.cropHint != null) {
var cropHint = elem.cropHint;
Images.findByKeyAndUpdate(key, cropHint, function(doc){
if(doc) {
count = count + 1;
}
})
}
});
res.json({
code: 0,
workload: workload
});
console.log('更新成功');
});
});
}
});
} else {
res.json({code: 1});
}
});
function isArray(obj){
return (typeof obj=='object') && obj.constructor==Array;
}
module.exports = router;
| mit |
alekskorolev/raving.core | auth-access/client/index.js | 583 | /*jslint browser: true, devel: true, node: true, nomen: true*/
/*global angular, $ */
var user = require('./user-collection'),
snippet = require('./auth-snippet');
module.exports = function (config) {
"use strict";
user(config);
snippet(config);
angular.module(config.core.appid)
.run(['$rootScope', 'socketIO', '$location', 'CollectionFactory', 'userAuth', function ($rootScope, io, $location, CollectionFactory, user) {
user.checkAuth().then(function (user) {
console.log(user);
}, function (err) {
console.log(err);
});
}]);
}; | mit |
kubii/ng-nativescript-sample | app/pages/login/login.component.ts | 588 | import {Component} from '../../util/Component';
import {LoginService} from '../../services/login.service';
import {Router} from '../../app.metadata';
import {PlatformMetadata} from './login.metadata';
@Component({
selector: 'my-login'
}, PlatformMetadata)
export class Login {
public name: string;
public password: string;
constructor(private _router: Router, private _loginService: LoginService) { }
public login() {
this._loginService
.login(this.name, this.password)
.then(() => this._router.navigate(['Start']));
}
} | mit |
Meee32/net2 | src/qt/coincontroldialog.cpp | 30880 | #include "coincontroldialog.h"
#include "ui_coincontroldialog.h"
#include "init.h"
#include "bitcoinunits.h"
#include "walletmodel.h"
#include "addresstablemodel.h"
#include "optionsmodel.h"
#include "coincontrol.h"
#include <QApplication>
#include <QCheckBox>
#include <QClipboard>
#include <QColor>
#include <QCursor>
#include <QDateTime>
#include <QDialogButtonBox>
#include <QFlags>
#include <QIcon>
#include <QString>
#include <QTreeWidget>
#include <QTreeWidgetItem>
using namespace std;
QList<qint64> CoinControlDialog::payAmounts;
CCoinControl* CoinControlDialog::coinControl = new CCoinControl();
CoinControlDialog::CoinControlDialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::CoinControlDialog),
model(0)
{
ui->setupUi(this);
// context menu actions
QAction *copyAddressAction = new QAction(tr("Copy address"), this);
QAction *copyLabelAction = new QAction(tr("Copy label"), this);
QAction *copyAmountAction = new QAction(tr("Copy amount"), this);
copyTransactionHashAction = new QAction(tr("Copy transaction ID"), this); // we need to enable/disable this
//lockAction = new QAction(tr("Lock unspent"), this); // we need to enable/disable this
//unlockAction = new QAction(tr("Unlock unspent"), this); // we need to enable/disable this
// context menu
contextMenu = new QMenu();
contextMenu->addAction(copyAddressAction);
contextMenu->addAction(copyLabelAction);
contextMenu->addAction(copyAmountAction);
contextMenu->addAction(copyTransactionHashAction);
//contextMenu->addSeparator();
//contextMenu->addAction(lockAction);
//contextMenu->addAction(unlockAction);
// context menu signals
connect(ui->treeWidget, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(showMenu(QPoint)));
connect(copyAddressAction, SIGNAL(triggered()), this, SLOT(copyAddress()));
connect(copyLabelAction, SIGNAL(triggered()), this, SLOT(copyLabel()));
connect(copyAmountAction, SIGNAL(triggered()), this, SLOT(copyAmount()));
connect(copyTransactionHashAction, SIGNAL(triggered()), this, SLOT(copyTransactionHash()));
//connect(lockAction, SIGNAL(triggered()), this, SLOT(lockCoin()));
//connect(unlockAction, SIGNAL(triggered()), this, SLOT(unlockCoin()));
// clipboard actions
QAction *clipboardQuantityAction = new QAction(tr("Copy quantity"), this);
QAction *clipboardAmountAction = new QAction(tr("Copy amount"), this);
QAction *clipboardFeeAction = new QAction(tr("Copy fee"), this);
QAction *clipboardAfterFeeAction = new QAction(tr("Copy after fee"), this);
QAction *clipboardBytesAction = new QAction(tr("Copy bytes"), this);
QAction *clipboardPriorityAction = new QAction(tr("Copy priority"), this);
QAction *clipboardLowOutputAction = new QAction(tr("Copy low output"), this);
QAction *clipboardChangeAction = new QAction(tr("Copy change"), this);
connect(clipboardQuantityAction, SIGNAL(triggered()), this, SLOT(clipboardQuantity()));
connect(clipboardAmountAction, SIGNAL(triggered()), this, SLOT(clipboardAmount()));
connect(clipboardFeeAction, SIGNAL(triggered()), this, SLOT(clipboardFee()));
connect(clipboardAfterFeeAction, SIGNAL(triggered()), this, SLOT(clipboardAfterFee()));
connect(clipboardBytesAction, SIGNAL(triggered()), this, SLOT(clipboardBytes()));
connect(clipboardPriorityAction, SIGNAL(triggered()), this, SLOT(clipboardPriority()));
connect(clipboardLowOutputAction, SIGNAL(triggered()), this, SLOT(clipboardLowOutput()));
connect(clipboardChangeAction, SIGNAL(triggered()), this, SLOT(clipboardChange()));
ui->labelCoinControlQuantity->addAction(clipboardQuantityAction);
ui->labelCoinControlAmount->addAction(clipboardAmountAction);
ui->labelCoinControlFee->addAction(clipboardFeeAction);
ui->labelCoinControlAfterFee->addAction(clipboardAfterFeeAction);
ui->labelCoinControlBytes->addAction(clipboardBytesAction);
ui->labelCoinControlPriority->addAction(clipboardPriorityAction);
ui->labelCoinControlLowOutput->addAction(clipboardLowOutputAction);
ui->labelCoinControlChange->addAction(clipboardChangeAction);
// toggle tree/list mode
connect(ui->radioTreeMode, SIGNAL(toggled(bool)), this, SLOT(radioTreeMode(bool)));
connect(ui->radioListMode, SIGNAL(toggled(bool)), this, SLOT(radioListMode(bool)));
// click on checkbox
connect(ui->treeWidget, SIGNAL(itemChanged( QTreeWidgetItem*, int)), this, SLOT(viewItemChanged( QTreeWidgetItem*, int)));
// click on header
ui->treeWidget->header()->setClickable(true);
connect(ui->treeWidget->header(), SIGNAL(sectionClicked(int)), this, SLOT(headerSectionClicked(int)));
// ok button
connect(ui->buttonBox, SIGNAL(clicked( QAbstractButton*)), this, SLOT(buttonBoxClicked(QAbstractButton*)));
// (un)select all
connect(ui->pushButtonSelectAll, SIGNAL(clicked()), this, SLOT(buttonSelectAllClicked()));
ui->treeWidget->setColumnWidth(COLUMN_CHECKBOX, 84);
ui->treeWidget->setColumnWidth(COLUMN_AMOUNT, 100);
ui->treeWidget->setColumnWidth(COLUMN_LABEL, 170);
ui->treeWidget->setColumnWidth(COLUMN_ADDRESS, 290);
ui->treeWidget->setColumnWidth(COLUMN_DATE, 110);
ui->treeWidget->setColumnWidth(COLUMN_CONFIRMATIONS, 100);
ui->treeWidget->setColumnWidth(COLUMN_PRIORITY, 100);
ui->treeWidget->setColumnHidden(COLUMN_TXHASH, true); // store transacton hash in this column, but dont show it
ui->treeWidget->setColumnHidden(COLUMN_VOUT_INDEX, true); // store vout index in this column, but dont show it
ui->treeWidget->setColumnHidden(COLUMN_AMOUNT_INT64, true); // store amount int64_t in this column, but dont show it
ui->treeWidget->setColumnHidden(COLUMN_PRIORITY_INT64, true); // store priority int64_t in this column, but dont show it
// default view is sorted by amount desc
sortView(COLUMN_AMOUNT_INT64, Qt::DescendingOrder);
}
CoinControlDialog::~CoinControlDialog()
{
delete ui;
}
void CoinControlDialog::setModel(WalletModel *model)
{
this->model = model;
if(model && model->getOptionsModel() && model->getAddressTableModel())
{
updateView();
//updateLabelLocked();
CoinControlDialog::updateLabels(model, this);
}
}
// helper function str_pad
QString CoinControlDialog::strPad(QString s, int nPadLength, QString sPadding)
{
while (s.length() < nPadLength)
s = sPadding + s;
return s;
}
// ok button
void CoinControlDialog::buttonBoxClicked(QAbstractButton* button)
{
if (ui->buttonBox->buttonRole(button) == QDialogButtonBox::AcceptRole)
done(QDialog::Accepted); // closes the dialog
}
// (un)select all
void CoinControlDialog::buttonSelectAllClicked()
{
Qt::CheckState state = Qt::Checked;
for (int i = 0; i < ui->treeWidget->topLevelItemCount(); i++)
{
if (ui->treeWidget->topLevelItem(i)->checkState(COLUMN_CHECKBOX) != Qt::Unchecked)
{
state = Qt::Unchecked;
break;
}
}
ui->treeWidget->setEnabled(false);
for (int i = 0; i < ui->treeWidget->topLevelItemCount(); i++)
if (ui->treeWidget->topLevelItem(i)->checkState(COLUMN_CHECKBOX) != state)
ui->treeWidget->topLevelItem(i)->setCheckState(COLUMN_CHECKBOX, state);
ui->treeWidget->setEnabled(true);
CoinControlDialog::updateLabels(model, this);
}
// context menu
void CoinControlDialog::showMenu(const QPoint &point)
{
QTreeWidgetItem *item = ui->treeWidget->itemAt(point);
if(item)
{
contextMenuItem = item;
// disable some items (like Copy Transaction ID, lock, unlock) for tree roots in context menu
if (item->text(COLUMN_TXHASH).length() == 64) // transaction hash is 64 characters (this means its a child node, so its not a parent node in tree mode)
{
copyTransactionHashAction->setEnabled(true);
//if (model->isLockedCoin(uint256(item->text(COLUMN_TXHASH).toStdString()), item->text(COLUMN_VOUT_INDEX).toUInt()))
//{
// lockAction->setEnabled(false);
// unlockAction->setEnabled(true);
//}
//else
//{
// lockAction->setEnabled(true);
// unlockAction->setEnabled(false);
//}
}
else // this means click on parent node in tree mode -> disable all
{
copyTransactionHashAction->setEnabled(false);
//lockAction->setEnabled(false);
//unlockAction->setEnabled(false);
}
// show context menu
contextMenu->exec(QCursor::pos());
}
}
// context menu action: copy amount
void CoinControlDialog::copyAmount()
{
QApplication::clipboard()->setText(contextMenuItem->text(COLUMN_AMOUNT));
}
// context menu action: copy label
void CoinControlDialog::copyLabel()
{
if (ui->radioTreeMode->isChecked() && contextMenuItem->text(COLUMN_LABEL).length() == 0 && contextMenuItem->parent())
QApplication::clipboard()->setText(contextMenuItem->parent()->text(COLUMN_LABEL));
else
QApplication::clipboard()->setText(contextMenuItem->text(COLUMN_LABEL));
}
// context menu action: copy address
void CoinControlDialog::copyAddress()
{
if (ui->radioTreeMode->isChecked() && contextMenuItem->text(COLUMN_ADDRESS).length() == 0 && contextMenuItem->parent())
QApplication::clipboard()->setText(contextMenuItem->parent()->text(COLUMN_ADDRESS));
else
QApplication::clipboard()->setText(contextMenuItem->text(COLUMN_ADDRESS));
}
// context menu action: copy transaction id
void CoinControlDialog::copyTransactionHash()
{
QApplication::clipboard()->setText(contextMenuItem->text(COLUMN_TXHASH));
}
// context menu action: lock coin
/*void CoinControlDialog::lockCoin()
{
if (contextMenuItem->checkState(COLUMN_CHECKBOX) == Qt::Checked)
contextMenuItem->setCheckState(COLUMN_CHECKBOX, Qt::Unchecked);
COutPoint outpt(uint256(contextMenuItem->text(COLUMN_TXHASH).toStdString()), contextMenuItem->text(COLUMN_VOUT_INDEX).toUInt());
model->lockCoin(outpt);
contextMenuItem->setDisabled(true);
contextMenuItem->setIcon(COLUMN_CHECKBOX, QIcon(":/icons/lock_closed"));
updateLabelLocked();
}*/
// context menu action: unlock coin
/*void CoinControlDialog::unlockCoin()
{
COutPoint outpt(uint256(contextMenuItem->text(COLUMN_TXHASH).toStdString()), contextMenuItem->text(COLUMN_VOUT_INDEX).toUInt());
model->unlockCoin(outpt);
contextMenuItem->setDisabled(false);
contextMenuItem->setIcon(COLUMN_CHECKBOX, QIcon());
updateLabelLocked();
}*/
// copy label "Quantity" to clipboard
void CoinControlDialog::clipboardQuantity()
{
QApplication::clipboard()->setText(ui->labelCoinControlQuantity->text());
}
// copy label "Amount" to clipboard
void CoinControlDialog::clipboardAmount()
{
QApplication::clipboard()->setText(ui->labelCoinControlAmount->text().left(ui->labelCoinControlAmount->text().indexOf(" ")));
}
// copy label "Fee" to clipboard
void CoinControlDialog::clipboardFee()
{
QApplication::clipboard()->setText(ui->labelCoinControlFee->text().left(ui->labelCoinControlFee->text().indexOf(" ")));
}
// copy label "After fee" to clipboard
void CoinControlDialog::clipboardAfterFee()
{
QApplication::clipboard()->setText(ui->labelCoinControlAfterFee->text().left(ui->labelCoinControlAfterFee->text().indexOf(" ")));
}
// copy label "Bytes" to clipboard
void CoinControlDialog::clipboardBytes()
{
QApplication::clipboard()->setText(ui->labelCoinControlBytes->text());
}
// copy label "Priority" to clipboard
void CoinControlDialog::clipboardPriority()
{
QApplication::clipboard()->setText(ui->labelCoinControlPriority->text());
}
// copy label "Low output" to clipboard
void CoinControlDialog::clipboardLowOutput()
{
QApplication::clipboard()->setText(ui->labelCoinControlLowOutput->text());
}
// copy label "Change" to clipboard
void CoinControlDialog::clipboardChange()
{
QApplication::clipboard()->setText(ui->labelCoinControlChange->text().left(ui->labelCoinControlChange->text().indexOf(" ")));
}
// treeview: sort
void CoinControlDialog::sortView(int column, Qt::SortOrder order)
{
sortColumn = column;
sortOrder = order;
ui->treeWidget->sortItems(column, order);
ui->treeWidget->header()->setSortIndicator((sortColumn == COLUMN_AMOUNT_INT64 ? COLUMN_AMOUNT : (sortColumn == COLUMN_PRIORITY_INT64 ? COLUMN_PRIORITY : sortColumn)), sortOrder);
}
// treeview: clicked on header
void CoinControlDialog::headerSectionClicked(int logicalIndex)
{
if (logicalIndex == COLUMN_CHECKBOX) // click on most left column -> do nothing
{
ui->treeWidget->header()->setSortIndicator((sortColumn == COLUMN_AMOUNT_INT64 ? COLUMN_AMOUNT : (sortColumn == COLUMN_PRIORITY_INT64 ? COLUMN_PRIORITY : sortColumn)), sortOrder);
}
else
{
if (logicalIndex == COLUMN_AMOUNT) // sort by amount
logicalIndex = COLUMN_AMOUNT_INT64;
if (logicalIndex == COLUMN_PRIORITY) // sort by priority
logicalIndex = COLUMN_PRIORITY_INT64;
if (sortColumn == logicalIndex)
sortOrder = ((sortOrder == Qt::AscendingOrder) ? Qt::DescendingOrder : Qt::AscendingOrder);
else
{
sortColumn = logicalIndex;
sortOrder = ((sortColumn == COLUMN_AMOUNT_INT64 || sortColumn == COLUMN_PRIORITY_INT64 || sortColumn == COLUMN_DATE || sortColumn == COLUMN_CONFIRMATIONS) ? Qt::DescendingOrder : Qt::AscendingOrder); // if amount,date,conf,priority then default => desc, else default => asc
}
sortView(sortColumn, sortOrder);
}
}
// toggle tree mode
void CoinControlDialog::radioTreeMode(bool checked)
{
if (checked && model)
updateView();
}
// toggle list mode
void CoinControlDialog::radioListMode(bool checked)
{
if (checked && model)
updateView();
}
// checkbox clicked by user
void CoinControlDialog::viewItemChanged(QTreeWidgetItem* item, int column)
{
if (column == COLUMN_CHECKBOX && item->text(COLUMN_TXHASH).length() == 64) // transaction hash is 64 characters (this means its a child node, so its not a parent node in tree mode)
{
COutPoint outpt(uint256(item->text(COLUMN_TXHASH).toStdString()), item->text(COLUMN_VOUT_INDEX).toUInt());
if (item->checkState(COLUMN_CHECKBOX) == Qt::Unchecked)
coinControl->UnSelect(outpt);
else if (item->isDisabled()) // locked (this happens if "check all" through parent node)
item->setCheckState(COLUMN_CHECKBOX, Qt::Unchecked);
else
coinControl->Select(outpt);
// selection changed -> update labels
if (ui->treeWidget->isEnabled()) // do not update on every click for (un)select all
CoinControlDialog::updateLabels(model, this);
}
}
// helper function, return human readable label for priority number
QString CoinControlDialog::getPriorityLabel(double dPriority)
{
if (dPriority > 576000ULL) // at least medium, this number is from AllowFree(), the other thresholds are kinda random
{
if (dPriority > 5760000000ULL) return tr("highest");
else if (dPriority > 576000000ULL) return tr("high");
else if (dPriority > 57600000ULL) return tr("medium-high");
else return tr("medium");
}
else
{
if (dPriority > 5760ULL) return tr("low-medium");
else if (dPriority > 58ULL) return tr("low");
else return tr("lowest");
}
}
// shows count of locked unspent outputs
/*void CoinControlDialog::updateLabelLocked()
{
vector<COutPoint> vOutpts;
model->listLockedCoins(vOutpts);
if (vOutpts.size() > 0)
{
ui->labelLocked->setText(tr("(%1 locked)").arg(vOutpts.size()));
ui->labelLocked->setVisible(true);
}
else ui->labelLocked->setVisible(false);
}*/
void CoinControlDialog::updateLabels(WalletModel *model, QDialog* dialog)
{
if (!model) return;
// nPayAmount
qint64 nPayAmount = 0;
bool fLowOutput = false;
bool fDust = false;
CTransaction txDummy;
foreach(const qint64 &amount, CoinControlDialog::payAmounts)
{
nPayAmount += amount;
if (amount > 0)
{
if (amount < CENT)
fLowOutput = true;
CTxOut txout(amount, (CScript)vector<unsigned char>(24, 0));
txDummy.vout.push_back(txout);
}
}
QString sPriorityLabel = "";
int64_t nAmount = 0;
int64_t nPayFee = 0;
int64_t nAfterFee = 0;
int64_t nChange = 0;
unsigned int nBytes = 0;
unsigned int nBytesInputs = 0;
double dPriority = 0;
double dPriorityInputs = 0;
unsigned int nQuantity = 0;
vector<COutPoint> vCoinControl;
vector<COutput> vOutputs;
coinControl->ListSelected(vCoinControl);
model->getOutputs(vCoinControl, vOutputs);
BOOST_FOREACH(const COutput& out, vOutputs)
{
// Quantity
nQuantity++;
// Amount
nAmount += out.tx->vout[out.i].nValue;
// Priority
dPriorityInputs += (double)out.tx->vout[out.i].nValue * (out.nDepth+1);
// Bytes
CTxDestination address;
if(ExtractDestination(out.tx->vout[out.i].scriptPubKey, address))
{
CPubKey pubkey;
CKeyID *keyid = boost::get< CKeyID >(&address);
if (keyid && model->getPubKey(*keyid, pubkey))
nBytesInputs += (pubkey.IsCompressed() ? 148 : 180);
else
nBytesInputs += 148; // in all error cases, simply assume 148 here
}
else nBytesInputs += 148;
}
// calculation
if (nQuantity > 0)
{
// Bytes
nBytes = nBytesInputs + ((CoinControlDialog::payAmounts.size() > 0 ? CoinControlDialog::payAmounts.size() + 1 : 2) * 34) + 10; // always assume +1 output for change here
// Priority
dPriority = dPriorityInputs / nBytes;
sPriorityLabel = CoinControlDialog::getPriorityLabel(dPriority);
// Fee
int64_t nFee = nTransactionFee * (1 + (int64_t)nBytes / 1000);
// Min Fee
int64_t nMinFee = txDummy.GetMinFee(1, GMF_SEND, nBytes,txDummy.AllowFree(dPriority));
nPayFee = max(nFee, nMinFee);
if (nPayAmount > 0)
{
nChange = nAmount - nPayFee - nPayAmount;
// if sub-cent change is required, the fee must be raised to at least CTransaction::nMinTxFee
if (nPayFee < CENT && nChange > 0 && nChange < CENT)
{
if (nChange < CENT) // change < 0.01 => simply move all change to fees
{
nPayFee = nChange;
nChange = 0;
}
else
{
nChange = nChange + nPayFee - CENT;
nPayFee = CENT;
}
}
if (nChange == 0)
nBytes -= 34;
}
// after fee
nAfterFee = nAmount - nPayFee;
if (nAfterFee < 0)
nAfterFee = 0;
}
// actually update labels
int nDisplayUnit = BitcoinUnits::BTC;
if (model && model->getOptionsModel())
nDisplayUnit = model->getOptionsModel()->getDisplayUnit();
QLabel *l1 = dialog->findChild<QLabel *>("labelCoinControlQuantity");
QLabel *l2 = dialog->findChild<QLabel *>("labelCoinControlAmount");
QLabel *l3 = dialog->findChild<QLabel *>("labelCoinControlFee");
QLabel *l4 = dialog->findChild<QLabel *>("labelCoinControlAfterFee");
QLabel *l5 = dialog->findChild<QLabel *>("labelCoinControlBytes");
QLabel *l6 = dialog->findChild<QLabel *>("labelCoinControlPriority");
QLabel *l7 = dialog->findChild<QLabel *>("labelCoinControlLowOutput");
QLabel *l8 = dialog->findChild<QLabel *>("labelCoinControlChange");
// enable/disable "low output" and "change"
dialog->findChild<QLabel *>("labelCoinControlLowOutputText")->setEnabled(nPayAmount > 0);
dialog->findChild<QLabel *>("labelCoinControlLowOutput") ->setEnabled(nPayAmount > 0);
dialog->findChild<QLabel *>("labelCoinControlChangeText") ->setEnabled(nPayAmount > 0);
dialog->findChild<QLabel *>("labelCoinControlChange") ->setEnabled(nPayAmount > 0);
// stats
l1->setText(QString::number(nQuantity)); // Quantity
l2->setText(BitcoinUnits::formatWithUnit(nDisplayUnit, nAmount)); // Amount
l3->setText(BitcoinUnits::formatWithUnit(nDisplayUnit, nPayFee)); // Fee
l4->setText(BitcoinUnits::formatWithUnit(nDisplayUnit, nAfterFee)); // After Fee
l5->setText(((nBytes > 0) ? "~" : "") + QString::number(nBytes)); // Bytes
l6->setText(sPriorityLabel); // Priority
l7->setText((fLowOutput ? (fDust ? tr("DUST") : tr("yes")) : tr("no"))); // Low Output / Dust
l8->setText(BitcoinUnits::formatWithUnit(nDisplayUnit, nChange)); // Change
// turn labels "red"
l5->setStyleSheet((nBytes >= 10000) ? "color:red;" : ""); // Bytes >= 10000
l6->setStyleSheet((dPriority <= 576000) ? "color:red;" : ""); // Priority < "medium"
l7->setStyleSheet((fLowOutput) ? "color:red;" : ""); // Low Output = "yes"
l8->setStyleSheet((nChange > 0 && nChange < CENT) ? "color:red;" : ""); // Change < 0.01BTC
// tool tips
l5->setToolTip(tr("This label turns red, if the transaction size is bigger than 10000 bytes.\n\n This means a fee of at least %1 per kb is required.\n\n Can vary +/- 1 Byte per input.").arg(BitcoinUnits::formatWithUnit(nDisplayUnit, CENT)));
l6->setToolTip(tr("Transactions with higher priority get more likely into a block.\n\nThis label turns red, if the priority is smaller than \"medium\".\n\n This means a fee of at least %1 per kb is required.").arg(BitcoinUnits::formatWithUnit(nDisplayUnit, CENT)));
l7->setToolTip(tr("This label turns red, if any recipient receives an amount smaller than %1.\n\n This means a fee of at least %2 is required. \n\n Amounts below 0.546 times the minimum relay fee are shown as DUST.").arg(BitcoinUnits::formatWithUnit(nDisplayUnit, CENT)).arg(BitcoinUnits::formatWithUnit(nDisplayUnit, CENT)));
l8->setToolTip(tr("This label turns red, if the change is smaller than %1.\n\n This means a fee of at least %2 is required.").arg(BitcoinUnits::formatWithUnit(nDisplayUnit, CENT)).arg(BitcoinUnits::formatWithUnit(nDisplayUnit, CENT)));
dialog->findChild<QLabel *>("labelCoinControlBytesText") ->setToolTip(l5->toolTip());
dialog->findChild<QLabel *>("labelCoinControlPriorityText") ->setToolTip(l6->toolTip());
dialog->findChild<QLabel *>("labelCoinControlLowOutputText")->setToolTip(l7->toolTip());
dialog->findChild<QLabel *>("labelCoinControlChangeText") ->setToolTip(l8->toolTip());
// Insufficient funds
QLabel *label = dialog->findChild<QLabel *>("labelCoinControlInsuffFunds");
if (label)
label->setVisible(nChange < 0);
}
void CoinControlDialog::updateView()
{
bool treeMode = ui->radioTreeMode->isChecked();
ui->treeWidget->clear();
ui->treeWidget->setEnabled(false); // performance, otherwise updateLabels would be called for every checked checkbox
ui->treeWidget->setAlternatingRowColors(!treeMode);
QFlags<Qt::ItemFlag> flgCheckbox=Qt::ItemIsSelectable | Qt::ItemIsEnabled | Qt::ItemIsUserCheckable;
QFlags<Qt::ItemFlag> flgTristate=Qt::ItemIsSelectable | Qt::ItemIsEnabled | Qt::ItemIsUserCheckable | Qt::ItemIsTristate;
int nDisplayUnit = BitcoinUnits::BTC;
if (model && model->getOptionsModel())
nDisplayUnit = model->getOptionsModel()->getDisplayUnit();
map<QString, vector<COutput> > mapCoins;
model->listCoins(mapCoins);
BOOST_FOREACH(PAIRTYPE(QString, vector<COutput>) coins, mapCoins)
{
QTreeWidgetItem *itemWalletAddress = new QTreeWidgetItem();
QString sWalletAddress = coins.first;
QString sWalletLabel = "";
if (model->getAddressTableModel())
sWalletLabel = model->getAddressTableModel()->labelForAddress(sWalletAddress);
if (sWalletLabel.length() == 0)
sWalletLabel = tr("(no label)");
if (treeMode)
{
// wallet address
ui->treeWidget->addTopLevelItem(itemWalletAddress);
itemWalletAddress->setFlags(flgTristate);
itemWalletAddress->setCheckState(COLUMN_CHECKBOX,Qt::Unchecked);
for (int i = 0; i < ui->treeWidget->columnCount(); i++)
itemWalletAddress->setBackground(i, QColor(248, 247, 246));
// label
itemWalletAddress->setText(COLUMN_LABEL, sWalletLabel);
// address
itemWalletAddress->setText(COLUMN_ADDRESS, sWalletAddress);
}
int64_t nSum = 0;
double dPrioritySum = 0;
int nChildren = 0;
int nInputSum = 0;
BOOST_FOREACH(const COutput& out, coins.second)
{
int nInputSize = 148; // 180 if uncompressed public key
nSum += out.tx->vout[out.i].nValue;
nChildren++;
QTreeWidgetItem *itemOutput;
if (treeMode) itemOutput = new QTreeWidgetItem(itemWalletAddress);
else itemOutput = new QTreeWidgetItem(ui->treeWidget);
itemOutput->setFlags(flgCheckbox);
itemOutput->setCheckState(COLUMN_CHECKBOX,Qt::Unchecked);
// address
CTxDestination outputAddress;
QString sAddress = "";
if(ExtractDestination(out.tx->vout[out.i].scriptPubKey, outputAddress))
{
sAddress = CBitcoinAddress(outputAddress).ToString().c_str();
// if listMode or change => show bitcoin address. In tree mode, address is not shown again for direct wallet address outputs
if (!treeMode || (!(sAddress == sWalletAddress)))
itemOutput->setText(COLUMN_ADDRESS, sAddress);
CPubKey pubkey;
CKeyID *keyid = boost::get< CKeyID >(&outputAddress);
if (keyid && model->getPubKey(*keyid, pubkey) && !pubkey.IsCompressed())
nInputSize = 180;
}
// label
if (!(sAddress == sWalletAddress)) // change
{
// tooltip from where the change comes from
itemOutput->setToolTip(COLUMN_LABEL, tr("change from %1 (%2)").arg(sWalletLabel).arg(sWalletAddress));
itemOutput->setText(COLUMN_LABEL, tr("(change)"));
}
else if (!treeMode)
{
QString sLabel = "";
if (model->getAddressTableModel())
sLabel = model->getAddressTableModel()->labelForAddress(sAddress);
if (sLabel.length() == 0)
sLabel = tr("(no label)");
itemOutput->setText(COLUMN_LABEL, sLabel);
}
// amount
itemOutput->setText(COLUMN_AMOUNT, BitcoinUnits::format(nDisplayUnit, out.tx->vout[out.i].nValue));
itemOutput->setText(COLUMN_AMOUNT_INT64, strPad(QString::number(out.tx->vout[out.i].nValue), 15, " ")); // padding so that sorting works correctly
// date
itemOutput->setText(COLUMN_DATE, QDateTime::fromTime_t(out.tx->GetTxTime()).toUTC().toString("yy-MM-dd hh:mm"));
// immature PoS reward
if (out.tx->IsCoinStake() && out.tx->GetBlocksToMaturity() > 0 && out.tx->GetDepthInMainChain() > 0) {
itemOutput->setBackground(COLUMN_CONFIRMATIONS, Qt::red);
itemOutput->setDisabled(true);
}
// confirmations
itemOutput->setText(COLUMN_CONFIRMATIONS, strPad(QString::number(out.nDepth), 8, " "));
// priority
double dPriority = ((double)out.tx->vout[out.i].nValue / (nInputSize + 78)) * (out.nDepth+1); // 78 = 2 * 34 + 10
itemOutput->setText(COLUMN_PRIORITY, CoinControlDialog::getPriorityLabel(dPriority));
itemOutput->setText(COLUMN_PRIORITY_INT64, strPad(QString::number((int64_t)dPriority), 20, " "));
dPrioritySum += (double)out.tx->vout[out.i].nValue * (out.nDepth+1);
nInputSum += nInputSize;
// transaction hash
uint256 txhash = out.tx->GetHash();
itemOutput->setText(COLUMN_TXHASH, txhash.GetHex().c_str());
// vout index
itemOutput->setText(COLUMN_VOUT_INDEX, QString::number(out.i));
// disable locked coins
/*if (model->isLockedCoin(txhash, out.i))
{
COutPoint outpt(txhash, out.i);
coinControl->UnSelect(outpt); // just to be sure
itemOutput->setDisabled(true);
itemOutput->setIcon(COLUMN_CHECKBOX, QIcon(":/icons/lock_closed"));
}*/
// set checkbox
if (coinControl->IsSelected(txhash, out.i))
itemOutput->setCheckState(COLUMN_CHECKBOX,Qt::Checked);
}
// amount
if (treeMode)
{
dPrioritySum = dPrioritySum / (nInputSum + 78);
itemWalletAddress->setText(COLUMN_CHECKBOX, "(" + QString::number(nChildren) + ")");
itemWalletAddress->setText(COLUMN_AMOUNT, BitcoinUnits::format(nDisplayUnit, nSum));
itemWalletAddress->setText(COLUMN_AMOUNT_INT64, strPad(QString::number(nSum), 15, " "));
itemWalletAddress->setText(COLUMN_PRIORITY, CoinControlDialog::getPriorityLabel(dPrioritySum));
itemWalletAddress->setText(COLUMN_PRIORITY_INT64, strPad(QString::number((int64_t)dPrioritySum), 20, " "));
}
}
// expand all partially selected
if (treeMode)
{
for (int i = 0; i < ui->treeWidget->topLevelItemCount(); i++)
if (ui->treeWidget->topLevelItem(i)->checkState(COLUMN_CHECKBOX) == Qt::PartiallyChecked)
ui->treeWidget->topLevelItem(i)->setExpanded(true);
}
// sort view
sortView(sortColumn, sortOrder);
ui->treeWidget->setEnabled(true);
}
| mit |
a7866353/MySharpNEAT | src/SharpNeatLib/Decoders/FastCyclicNetworkFactory.cs | 11528 | /* ***************************************************************************
* This file is part of SharpNEAT - Evolution of Neural Networks.
*
* Copyright 2004-2016 Colin Green (sharpneat@gmail.com)
*
* SharpNEAT is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SharpNEAT 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 SharpNEAT. If not, see <http://www.gnu.org/licenses/>.
*/
using System;
using System.Collections.Generic;
using System.Diagnostics;
using SharpNeat.Network;
using SharpNeat.Phenomes.NeuralNets;
namespace SharpNeat.Decoders
{
/// <summary>
/// Static factory for creating CyclicNetwork's from INetworkDefinition's.
/// </summary>
public class FastCyclicNetworkFactory
{
#region Public Static Methods
/// <summary>
/// Creates a CyclicNetwork from an INetworkDefinition.
/// </summary>
public static FastCyclicNetwork CreateFastCyclicNetwork(INetworkDefinition networkDef,
NetworkActivationScheme activationScheme)
{
FastConnection[] fastConnectionArray;
IActivationFunction[] activationFnArray;
double[][] neuronAuxArgsArray;
InternalDecode(networkDef,
activationScheme.RelaxingActivation ? activationScheme.MaxTimesteps : activationScheme.TimestepsPerActivation,
out fastConnectionArray, out activationFnArray, out neuronAuxArgsArray);
// Construct neural net.
if(activationScheme.RelaxingActivation)
{
return new FastRelaxingCyclicNetwork(fastConnectionArray,
activationFnArray,
neuronAuxArgsArray,
networkDef.NodeList.Count,
networkDef.InputNodeCount,
networkDef.OutputNodeCount,
activationScheme.MaxTimesteps,
activationScheme.SignalDeltaThreshold);
}
return new FastCyclicNetwork(fastConnectionArray,
activationFnArray,
neuronAuxArgsArray,
networkDef.NodeList.Count,
networkDef.InputNodeCount,
networkDef.OutputNodeCount,
activationScheme.TimestepsPerActivation);
}
#endregion
#region Private Static Methods
private static void InternalDecode(INetworkDefinition networkDef,
int timestepsPerActivation,
out FastConnection[] fastConnectionArray,
out IActivationFunction[] activationFnArray,
out double[][] neuronAuxArgsArray)
{
// Create an array of FastConnection(s) that represent the connectivity of the network.
fastConnectionArray = CreateFastConnectionArray(networkDef);
// TODO: Test/optimize heuristic - this is just back of envelope maths.
// A rough heuristic to decide if we should sort fastConnectionArray by source neuron index.
// The principle here is that each activation loop will be about 2x faster (unconfirmed) if we sort
// fastConnectionArray, but sorting takes about n*log2(n) operations. Therefore the decision to sort
// depends on length of fastConnectionArray and _timestepsPerActivation.
// Another factor here is that small networks will fit into CPU caches and therefore will not appear
// to speed up - however the unsorted data will 'scramble' CPU caches more than they otherwise would
// have and thus may slow down other threads (so we just keep it simple).
double len = fastConnectionArray.Length;
double timesteps = timestepsPerActivation;
if((len > 2) && (((len * Math.Log(len,2)) + ((timesteps * len)/2.0)) < (timesteps * len)))
{ // Sort fastConnectionArray by source neuron index.
Array.Sort(fastConnectionArray, delegate(FastConnection x, FastConnection y)
{ // Use simple/fast diff method.
return x._srcNeuronIdx - y._srcNeuronIdx;
});
}
// Construct an array of neuron activation functions. Skip bias and input neurons as
// these don't have an activation function (because they aren't activated).
INodeList nodeList = networkDef.NodeList;
int nodeCount = nodeList.Count;
IActivationFunctionLibrary activationFnLibrary = networkDef.ActivationFnLibrary;
activationFnArray = new IActivationFunction[nodeCount];
neuronAuxArgsArray = new double[nodeCount][];
for(int i=0; i<nodeCount; i++) {
activationFnArray[i] = activationFnLibrary.GetFunction(nodeList[i].ActivationFnId);
neuronAuxArgsArray[i] = nodeList[i].AuxState;
}
}
/// <summary>
/// Create an array of FastConnection(s) representing the connectivity of the provided INetworkDefinition.
/// </summary>
private static FastConnection[] CreateFastConnectionArray(INetworkDefinition networkDef)
{
// We vary the decode logic depending on the size of the genome. The most CPU intensive aspect of
// decoding is the conversion of the neuron IDs at connection endpoints into neuron indexes. For small
// genomes we simply use the BinarySearch() method on NeuronGeneList for each lookup; Each lookup is
// an operation with O(log n) time complexity. Thus for C connections and N neurons the number of operations
// to perform all lookups is approximately = 2*C*Log(N)
//
// For larger genomes we invest time in building a Dictionary that maps neuron IDs to their indexes, this on the
// basis that the time invested will be more than recovered in time saved performing lookups; The time complexity
// of a dictionary lookup is near constant O(1). Thus number of operations is approximately = O(2*C*1) + the time
// required to build the dictionary which is approximately O(N).
//
// Therefore the choice of lookup type is based on which of these two expressions gives the lowest value.
//
// Binary search. LookupOps = 2 * C * Log2(N) * x
// Dictionary Search. LookupOps = (N * y) + (2 * C * z)
//
// Where x, y and z are constants that adjust for the relative speeds of the lookup and dictionary building operations.
// Note that the actual time required to perform these separate algorithms is actually a far more complex problem, and
// for modern CPUs exact times cannot be calculated because of large memory caches and superscalar architecture that
// makes execution times in a real environment effectively non-deterministic. Thus these calculations are a rough
// guide/heuristic that estimate which algorithm will perform best. The constants can be found experimentally but will
// tend to vary depending on factors such as CPU and memory architecture, .Net framework version and what other tasks the
// CPU is currently doing which may affect our utilisation of memory caches.
// TODO: Experimentally determine reasonably good values for constants x,y and z in some common real world runtime platform.
IConnectionList connectionList = networkDef.ConnectionList;
INodeList nodeList = networkDef.NodeList;
int connectionCount = connectionList.Count;
int nodeCount = nodeList.Count;
FastConnection[] fastConnectionArray = new FastConnection[connectionCount];
if((2.0 * connectionCount * Math.Log(nodeCount, 2.0)) < ((2.0 * connectionCount) + nodeCount))
{
// Binary search requires items to be sorted.
Debug.Assert(nodeList.IsSorted());
// Loop the connections and lookup the neuron IDs for each connection's end points using a binary search
// on nGeneList. This is probably the quickest approach for small numbers of lookups.
for(int i=0; i<connectionCount; i++)
{
INetworkConnection conn = connectionList[i];
fastConnectionArray[i]._srcNeuronIdx = nodeList.BinarySearch(conn.SourceNodeId);
fastConnectionArray[i]._tgtNeuronIdx = nodeList.BinarySearch(conn.TargetNodeId);
fastConnectionArray[i]._weight = conn.Weight;
// Check that the correct neuron indexes were found.
Debug.Assert(
nodeList[fastConnectionArray[i]._srcNeuronIdx].Id == conn.SourceNodeId
&& nodeList[fastConnectionArray[i]._tgtNeuronIdx].Id == conn.TargetNodeId);
}
}
else
{
// Build dictionary of neuron indexes keyed on neuron innovation ID.
Dictionary<uint,int> neuronIndexDictionary = new Dictionary<uint,int>(nodeCount);
for(int i=0; i<nodeCount; i++) {
// ENHANCEMENT: Check if neuron innovation ID requires further manipulation to make a good hash code.
neuronIndexDictionary.Add(nodeList[i].Id, i);
}
// Loop the connections and lookup the neuron IDs for each connection's end points using neuronIndexDictionary.
// This is probably the quickest approach for large numbers of lookups.
for(int i=0; i<connectionCount; i++)
{
INetworkConnection conn = connectionList[i];
fastConnectionArray[i]._srcNeuronIdx = neuronIndexDictionary[conn.SourceNodeId];
fastConnectionArray[i]._tgtNeuronIdx = neuronIndexDictionary[conn.TargetNodeId];
fastConnectionArray[i]._weight = conn.Weight;
// Check that the correct neuron indexes were found.
Debug.Assert(
nodeList[fastConnectionArray[i]._srcNeuronIdx].Id == conn.SourceNodeId
&& nodeList[fastConnectionArray[i]._tgtNeuronIdx].Id == conn.TargetNodeId);
}
}
return fastConnectionArray;
}
#endregion
}
}
| mit |
sleepyparadox/SplitHunter.EXE | SplitHunter.EXE/SplitHunter.EXE/Properties/Resources.Designer.cs | 2789 | //------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace SplitHunter.EXE.Properties
{
/// <summary>
/// A strongly-typed resource class, for looking up localized strings, etc.
/// </summary>
// This class was auto-generated by the StronglyTypedResourceBuilder
// class via a tool like ResGen or Visual Studio.
// To add or remove a member, edit your .ResX file then rerun ResGen
// with the /str option, or rebuild your VS project.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Resources
{
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources()
{
}
/// <summary>
/// Returns the cached ResourceManager instance used by this class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager
{
get
{
if ((resourceMan == null))
{
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("SplitHunter.EXE.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Overrides the current thread's CurrentUICulture property for all
/// resource lookups using this strongly typed resource class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture
{
get
{
return resourceCulture;
}
set
{
resourceCulture = value;
}
}
}
}
| mit |
arseniy96/foreman_site | db/migrate/20160424205003_add_inspected.rb | 115 | class AddInspected < ActiveRecord::Migration
def change
add_column :messages, :inspected, :boolean
end
end
| mit |
firebluetom/Backbone-Desktop | public/js/app/collections/Collection.js | 432 | // Collection.js
// -------------
define(["jquery", "backbone", "../models/Model"],
function($, Backbone, Model) {
// Creates a new Backbone Collection class object
var Collection = Backbone.Collection.extend({
// Tells the Backbone Collection that all of it's models will be of type Model (listed up top as a dependency)
model: Model
});
// Returns the Model class
return Collection;
}
); | mit |
dblock/slack-ruby-client | spec/slack/web/api/endpoints/oauth_v2_spec.rb | 383 | # frozen_string_literal: true
# This file was auto-generated by lib/tasks/web.rake
require 'spec_helper'
RSpec.describe Slack::Web::Api::Endpoints::OauthV2 do
let(:client) { Slack::Web::Client.new }
context 'oauth.v2_access' do
it 'requires code' do
expect { client.oauth_v2_access }.to raise_error ArgumentError, /Required arguments :code missing/
end
end
end
| mit |
chrisGoad/prototypejungle | text/solar/naws.js | 475 |
core.require('/diagram/graph.js',function (graphP) {
let graph = graphP.instantiate();
core.setFunction('computeMessage', function (graph) {
if (graph.zub === undefined) {
graph.zub = 0;
}
return "Count "+graph.zub++;
});
graph.computeMessage = function () {
if (this.zum === undefined) {
this.zum = 0;
}
return "Count "+this.zum++;
}
graph.computeMessage.serializeMe = true;
graph.catalogUrl = '(sys)/catalog/solar.catalog';
return graph;
});
| mit |
crazycodr/data-grouper | src/CrazyCodr/Data/Grouper/GrouperNotFoundException.php | 698 | <?php
namespace CrazyCodr\Data\Grouper;
/**
* This exception is raised when an operation tries to access a grouper that doesn't exist in a grouper container
*
* @uses \OutOfRangeException
*
* @category Exceptions
* @package CrazyCodr/Data-Grouper
* @author CrazyOne@CrazyCoders
* @license MIT
* @link crazycoders.net
*/
class GrouperNotFoundException extends \OutOfRangeException
{
/**
* Builds a new exception
*
* @param mixed $name Name of the intended grouper that failed
*
* @access public
*/
public function __construct($name)
{
parent::__construct('Grouper named "'.htmlentities($name).'" not found in current grouper container');
}
} | mit |
darosh/glt | components/glt/generators/randomParams.js | 1315 | import {randomInt} from './randomInt';
import {rand} from './rand';
import {randomUniform} from 'd3-random';
export function randomParam(type, proto, decimals) {
if ((type === 'int') && proto[3]) {
return randomInt(proto[3][0], proto[3][1]);
} else if ((type === 'float') && proto[3]) {
// return randomUniform(proto[3][0], proto[3][1])();
return rand(proto[3][0], proto[2], proto[3][1]);
} else if ((type === 'vec2')) {
if (proto[3]) {
return [randomUniform(proto[3][0], proto[3][1])(), randomUniform(proto[3][0], proto[3][1])()];
} else {
return 'pos';
}
} else if ((type === 'vec3') && proto[3]) {
return [
precision(randomUniform(proto[3][0], proto[3][1])(), decimals),
precision(randomUniform(proto[3][0], proto[3][1])(), decimals),
precision(randomUniform(proto[3][0], proto[3][1])(), decimals)
];
} else if ((type === 'vec3') && !proto[2]) {
return [randomUniform(1)(), randomUniform(1)(), randomUniform(1)()];
} else if (type === 'bool') {
return Math.random() < 0.5;
}
return proto[2];
}
function precision(number, decimals) {
return !decimals ? number : Math.round(number * Math.pow(10, decimals)) / Math.pow(10, decimals);
}
| mit |
dannyrdalton/example_signup_flow | src/helpers/redux-form/field_renderers.js | 806 | import React from 'react'
import DropdownList from 'react-widgets/lib/DropdownList'
export const field = (field) => (
<div className={'form-group ' + (field.meta.error && field.meta.touched ? 'has-error ' : '') + (!field.meta.error && field.meta.touched ? 'has-success': '')}>
<label>{field.label}</label>
<div>
<input {...field.input}
placeholder={field.label}
type={field.type}
className='form-control' /
>
</div>
</div>
)
export const dropdownList = ({ input, meta, label, ...rest }) => (
<div className={'form-group'}>
{label && <label>{label}</label>}
<div>
<DropdownList {...input} {...rest}/>
</div>
</div>
)
export const REDUX_FORM_FIELD_RENDERERS = {
field,
dropdownList
}
export default REDUX_FORM_FIELD_RENDERERS | mit |
Paulli1989/mfd-angular | src/app/shared/demo-data.service.js | 1428 | "use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var core_1 = require('@angular/core');
var data_1 = require('./data');
var DemoDataService = (function () {
function DemoDataService() {
}
DemoDataService.prototype.getDemoData = function () {
return data_1.PRODUCTDATA;
};
DemoDataService.prototype.getDemoDataById = function (productid) {
return data_1.PRODUCTDATA.find(function (r) { return r.id == productid; });
};
DemoDataService = __decorate([
core_1.Injectable(),
__metadata('design:paramtypes', [])
], DemoDataService);
return DemoDataService;
}());
exports.DemoDataService = DemoDataService;
//# sourceMappingURL=demo-data.service.js.map | mit |
SkillsFundingAgency/das-commitments | src/SFA.DAS.Commitments.Api.Types/TrainingProgramme/GetAllTrainingProgrammeStandardsResponse.cs | 245 | using System.Collections.Generic;
namespace SFA.DAS.Commitments.Api.Types.TrainingProgramme
{
public class GetAllTrainingProgrammeStandardsResponse
{
public IEnumerable<TrainingProgramme> TrainingProgrammes { get; set; }
}
} | mit |
suripoori/SocialNetwork | src/twitter/Influence.java | 498 | package twitter;
import java.util.List;
public abstract class Influence {
protected TwitterNetwork t;
public Influence(TwitterNetwork t) {
this.t = t;
}
protected TwitterNetwork getTwitterNetwork() {
return t;
}
/* Gets ordering of the Users based on the followers */
public abstract List<Integer> getFollowersOrdering(Integer numIterations);
/* Gets ordering of the Users based on the retweets */
public abstract List<Integer> getRetweetOrdering(Integer numIterations);
}
| mit |
Nerketur/discordapi | permissions.go | 3051 | package discord
import (
//"fmt"
"encoding/json"
)
type Perm struct{
CreateInstantInvite bool
KickMembers bool
BanMembers bool
ManageRoles bool
ManageChannels bool
ManageGuild bool
// Text
ReadMessages bool
SendMessages bool
SendTssMessages bool
ManageMessages bool
EmbedLinks bool
AttachFiles bool
ReadMessageHistory bool
MentionEveryone bool
// Voice
Connect bool
Speak bool
MuteMembers bool
DeafenMembers bool
MoveMembers bool
UseVad bool
}
func (p Perm) ToInt() int {
i := 0
if p.CreateInstantInvite {i |= 1 << 0}
if p.KickMembers {i |= 1 << 1}// not in channel overwrites
if p.BanMembers {i |= 1 << 2}// not in channel overwrites
if p.ManageRoles {i |= 1 << 3}
if p.ManageChannels {i |= 1 << 4}
if p.ManageGuild {i |= 1 << 5}// not in channel overwrites (understandably)
// Text
if p.ReadMessages {i |= 1 << 10}
if p.SendMessages {i |= 1 << 11}
if p.SendTssMessages {i |= 1 << 12}
if p.ManageMessages {i |= 1 << 13}
if p.EmbedLinks {i |= 1 << 14}
if p.AttachFiles {i |= 1 << 15}
if p.ReadMessageHistory {i |= 1 << 16}
if p.MentionEveryone {i |= 1 << 17}
// Voice
if p.Connect {i |= 1 << 20}
if p.Speak {i |= 1 << 21}
if p.MuteMembers {i |= 1 << 22}
if p.DeafenMembers {i |= 1 << 23}
if p.MoveMembers {i |= 1 << 24}
if p.UseVad {i |= 1 << 25}
return i
}
func (p *Perm) FromInt(mask int) {
if (1<<0 & mask) != 0 {p.CreateInstantInvite = true}
if (1<<1 & mask) != 0 {p.KickMembers = true}
if (1<<2 & mask) != 0 {p.BanMembers = true}
if (1<<3 & mask) != 0 {p.ManageRoles = true}
if (1<<4 & mask) != 0 {p.ManageChannels = true}
if (1<<5 & mask) != 0 {p.ManageGuild = true}
// Text
if (1<<10 & mask) != 0 {p.ReadMessages = true}
if (1<<11 & mask) != 0 {p.SendMessages = true}
if (1<<12 & mask) != 0 {p.SendTssMessages = true}
if (1<<13 & mask) != 0 {p.ManageMessages = true}
if (1<<14 & mask) != 0 {p.EmbedLinks = true}
if (1<<15 & mask) != 0 {p.AttachFiles = true}
if (1<<16 & mask) != 0 {p.ReadMessageHistory = true}
if (1<<17 & mask) != 0 {p.MentionEveryone = true}
// Voice
if (1<<20 & mask) != 0 {p.Connect = true}
if (1<<21 & mask) != 0 {p.Speak = true}
if (1<<22 & mask) != 0 {p.MuteMembers = true}
if (1<<23 & mask) != 0 {p.DeafenMembers = true}
if (1<<24 & mask) != 0 {p.MoveMembers = true}
if (1<<25 & mask) != 0 {p.UseVad = true}
}
func FromInt(mask int) (p Perm) {
p.FromInt(mask)
return
}
func (p Perm) MarshalJSON() ([]byte, error) {
return json.Marshal(p.ToInt())
}
func (p *Perm) UnmarshalJSON(raw []byte) error {
var i int
err := json.Unmarshal(raw, &i)
if err != nil {
return err
}
p.FromInt(i)
//fmt.Printf("int: %v\nperm:\n%+v\n\n", i, p)
return nil
}
| mit |
wallBMW/TrackCat | app/models/item_history.rb | 414 | class ItemHistory < ActiveRecord::Base
belongs_to :item, :foreign_key => "item_id"
belongs_to :user, :foreign_key => "user_id"
belongs_to :old_area, class_name: "Area", :foreign_key => "old_area_id"
belongs_to :new_area, class_name: "Area", :foreign_key => "new_area_id"
def record(user, item, new_value)
self.user = user
self.item = item
self.new_area = new_value
self.save
end
end
| mit |
CYDpeter/104021003 | 20150805/src/Ex6.java | 576 | import java.util.Scanner;
public class Ex6 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner scn = new Scanner(System.in);
System.out.print("½Ð¿é¤J³ÌµuÃä");
int a = scn.nextInt();
System.out.print("½Ð¿é¤J²Ä¤GªøÃä");
int b = scn.nextInt();
System.out.print("½Ð¿é¤J³ÌªøÃä");
int c = scn.nextInt();
if(a*a+b*b<c*c){
System.out.print("¦¹¬°¶w¨¤¤T¨¤§Î");
}else{
if(a*a+b*b==c*c){
System.out.print("¦¹¬°ª½¨¤¤T¨¤§Î");
}else{
if(a*a+b*b>c*c){
System.out.print("¦¹¬°¶w¨¤¤T¨¤§Î");
}
}
}
}
}
| mit |
stoplightio/gitlabhq | app/assets/javascripts/blob/template_selectors/type_selector.js | 642 | import FileTemplateSelector from '../file_template_selector';
export default class FileTemplateTypeSelector extends FileTemplateSelector {
constructor({ mediator, dropdownData }) {
super(mediator);
this.mediator = mediator;
this.config = {
dropdown: '.js-template-type-selector',
wrapper: '.js-template-type-selector-wrap',
dropdownData,
};
}
initDropdown() {
this.$dropdown.glDropdown({
data: this.config.dropdownData,
filterable: false,
selectable: true,
clicked: options => this.mediator.selectTemplateTypeOptions(options),
text: item => item.name,
});
}
}
| mit |
yogeshsaroya/new-cdnjs | ajax/libs/openlayers/2.11/lib/OpenLayers/Control/Snapping.min.js | 129 | version https://git-lfs.github.com/spec/v1
oid sha256:190a9a1406c4f34ec80475c30e47b34333daaad54589164ffd3869afcb2e63b0
size 4545
| mit |
thoughtbit/node-web-starter | bear-api-express/server/src/core/errors/index.js | 504 | const clientError = require('./clientError')
const HttpError = require('./httpError')
const serverError = require('./serverError')
const {
BadRequest,
Unauthorized,
Forbidden,
NotFound,
MethodNotAllowed,
Conflict,
UserNotVerifiedError,
} = clientError
const { InternalServer, NotImplemented } = serverError
module.exports = {
BadRequest,
Unauthorized,
Forbidden,
NotFound,
MethodNotAllowed,
Conflict,
InternalServer,
NotImplemented,
UserNotVerifiedError,
HttpError,
}
| mit |
austonst/midi | timedivision.cpp | 1146 | /*
Copyright (c) 2014 Auston Sterling
See LICENSE for copying permissions.
-----TimeDivision Class Implementation-----
Auston Sterling
austonst@gmail.com
Contains the implementation for the TimeDivision class, for use in MIDI files.
*/
#include "timedivision.hpp"
namespace midi
{
//Default constructor
TimeDivision::TimeDivision()
{
data_.resize(2);
}
//Pulses Per Quarter Note constructor
TimeDivision::TimeDivision(std::uint16_t ppqn)
{
data_.resize(2);
set(ppqn);
}
//Frames Per Second and Ticks Per Frame constructor
TimeDivision::TimeDivision(std::uint8_t fps, std::uint8_t tpf)
{
data_.resize(2);
set(fps, tpf);
}
//Access the actual data
std::vector<std::uint8_t> TimeDivision::data() const
{
return data_;
}
//Set based on Pulses Per Quarter Note
void TimeDivision::set(std::uint16_t ppqn)
{
data_[0] = (ppqn & 0x7FFF) >> 8;
data_[1] = ppqn & 0xFF;
}
//Set based on Frames Per Second and Ticks Per Frame
void TimeDivision::set(std::uint8_t fps, std::uint8_t tpf)
{
data_[0] = -1 * char(fps);
data_[1] = tpf;
}
} //Namespace
| mit |
Dewire/dehub-react-native | eslint-plugin-dehub/index.js | 302 |
module.exports.rules = {
'no-props-navigator': context => ({
MemberExpression: (node) => {
if (node.object.name === 'props' && node.property.name === 'navigator') {
context.report(node, 'Do not use props.navigator directly. Use props.navigate() instead.');
}
},
}),
};
| mit |
vapits/jexia-simple-angular-chat | js/app.js | 1208 | angular.module('simpleChat', [
'ngRoute',
'luegg.directives',
'angularMoment',
'ui.bootstrap'])
.run(function($rootScope, $http){
// Let's get the configuration data
// You can edit them to config.js
$rootScope.credentials = angular.copy(jexia);
})
.config(function($routeProvider, $locationProvider, $httpProvider) {
// If token or credentials are wrong in any request then
// send user to login page
$httpProvider.interceptors.push(['$q', '$location', function($q, $location) {
return {
'responseError': function(response) {
if (response.status === 403) {
localStorage.removeItem('username');
localStorage.removeItem('userId');
localStorage.removeItem('token');
$location.path('/login');
}
return $q.reject(response);
}
};
}]);
// Now let's set two simple routes for our views
// a login page and the chat rooom
$routeProvider
.when('/login', {
templateUrl: 'templates/login.html',
controller: 'loginCtrl'
})
.when('/chat', {
templateUrl: 'templates/chat.html',
controller: 'appCtrl'
})
.otherwise({redirectTo: '/login'});
});
| mit |
aclissold/hooktftp | hooks/http_hook.go | 373 | package hooks
import (
"fmt"
"io"
"net/http"
)
var HTTPHook = HookComponents{
func(url string) (io.ReadCloser, error) {
res, err := http.Get(url)
if err != nil {
return nil, err
}
if res.StatusCode != 200 {
return nil, fmt.Errorf("Bad response '%v' from %v", res.Status, url)
}
return res.Body, nil
},
func(s string) string {
return s
},
}
| mit |
koobonil/Boss2D | Boss2D/addon/_old/webrtc-qt5.11.2_for_boss/modules/rtp_rtcp/source/rtp_format_vp9.cc | 26575 | /*
* Copyright (c) 2015 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "modules/rtp_rtcp/source/rtp_format_vp9.h"
#include <assert.h>
#include <string.h>
#include <cmath>
#include "modules/rtp_rtcp/source/rtp_packet_to_send.h"
#include BOSS_WEBRTC_U_rtc_base__bitbuffer_h //original-code:"rtc_base/bitbuffer.h"
#include BOSS_WEBRTC_U_rtc_base__checks_h //original-code:"rtc_base/checks.h"
#include BOSS_WEBRTC_U_rtc_base__logging_h //original-code:"rtc_base/logging.h"
#define RETURN_FALSE_ON_ERROR(x) \
if (!(x)) { \
return false; \
}
namespace webrtc {
namespace {
// Length of VP9 payload descriptors' fixed part.
const size_t kFixedPayloadDescriptorBytes = 1;
const uint32_t kReservedBitValue0 = 0;
uint8_t TemporalIdxField(const RTPVideoHeaderVP9& hdr, uint8_t def) {
return (hdr.temporal_idx == kNoTemporalIdx) ? def : hdr.temporal_idx;
}
uint8_t SpatialIdxField(const RTPVideoHeaderVP9& hdr, uint8_t def) {
return (hdr.spatial_idx == kNoSpatialIdx) ? def : hdr.spatial_idx;
}
int16_t Tl0PicIdxField(const RTPVideoHeaderVP9& hdr, uint8_t def) {
return (hdr.tl0_pic_idx == kNoTl0PicIdx) ? def : hdr.tl0_pic_idx;
}
// Picture ID:
//
// +-+-+-+-+-+-+-+-+
// I: |M| PICTURE ID | M:0 => picture id is 7 bits.
// +-+-+-+-+-+-+-+-+ M:1 => picture id is 15 bits.
// M: | EXTENDED PID |
// +-+-+-+-+-+-+-+-+
//
size_t PictureIdLength(const RTPVideoHeaderVP9& hdr) {
if (hdr.picture_id == kNoPictureId)
return 0;
return (hdr.max_picture_id == kMaxOneBytePictureId) ? 1 : 2;
}
bool PictureIdPresent(const RTPVideoHeaderVP9& hdr) {
return PictureIdLength(hdr) > 0;
}
// Layer indices:
//
// Flexible mode (F=1): Non-flexible mode (F=0):
//
// +-+-+-+-+-+-+-+-+ +-+-+-+-+-+-+-+-+
// L: | T |U| S |D| | T |U| S |D|
// +-+-+-+-+-+-+-+-+ +-+-+-+-+-+-+-+-+
// | TL0PICIDX |
// +-+-+-+-+-+-+-+-+
//
size_t LayerInfoLength(const RTPVideoHeaderVP9& hdr) {
if (hdr.temporal_idx == kNoTemporalIdx &&
hdr.spatial_idx == kNoSpatialIdx) {
return 0;
}
return hdr.flexible_mode ? 1 : 2;
}
bool LayerInfoPresent(const RTPVideoHeaderVP9& hdr) {
return LayerInfoLength(hdr) > 0;
}
// Reference indices:
//
// +-+-+-+-+-+-+-+-+ P=1,F=1: At least one reference index
// P,F: | P_DIFF |N| up to 3 times has to be specified.
// +-+-+-+-+-+-+-+-+ N=1: An additional P_DIFF follows
// current P_DIFF.
//
size_t RefIndicesLength(const RTPVideoHeaderVP9& hdr) {
if (!hdr.inter_pic_predicted || !hdr.flexible_mode)
return 0;
RTC_DCHECK_GT(hdr.num_ref_pics, 0U);
RTC_DCHECK_LE(hdr.num_ref_pics, kMaxVp9RefPics);
return hdr.num_ref_pics;
}
// Scalability structure (SS).
//
// +-+-+-+-+-+-+-+-+
// V: | N_S |Y|G|-|-|-|
// +-+-+-+-+-+-+-+-+ -|
// Y: | WIDTH | (OPTIONAL) .
// + + .
// | | (OPTIONAL) .
// +-+-+-+-+-+-+-+-+ . N_S + 1 times
// | HEIGHT | (OPTIONAL) .
// + + .
// | | (OPTIONAL) .
// +-+-+-+-+-+-+-+-+ -|
// G: | N_G | (OPTIONAL)
// +-+-+-+-+-+-+-+-+ -|
// N_G: | T |U| R |-|-| (OPTIONAL) .
// +-+-+-+-+-+-+-+-+ -| . N_G times
// | P_DIFF | (OPTIONAL) . R times .
// +-+-+-+-+-+-+-+-+ -| -|
//
size_t SsDataLength(const RTPVideoHeaderVP9& hdr) {
if (!hdr.ss_data_available)
return 0;
RTC_DCHECK_GT(hdr.num_spatial_layers, 0U);
RTC_DCHECK_LE(hdr.num_spatial_layers, kMaxVp9NumberOfSpatialLayers);
RTC_DCHECK_LE(hdr.gof.num_frames_in_gof, kMaxVp9FramesInGof);
size_t length = 1; // V
if (hdr.spatial_layer_resolution_present) {
length += 4 * hdr.num_spatial_layers; // Y
}
if (hdr.gof.num_frames_in_gof > 0) {
++length; // G
}
// N_G
length += hdr.gof.num_frames_in_gof; // T, U, R
for (size_t i = 0; i < hdr.gof.num_frames_in_gof; ++i) {
RTC_DCHECK_LE(hdr.gof.num_ref_pics[i], kMaxVp9RefPics);
length += hdr.gof.num_ref_pics[i]; // R times
}
return length;
}
size_t PayloadDescriptorLengthMinusSsData(const RTPVideoHeaderVP9& hdr) {
return kFixedPayloadDescriptorBytes + PictureIdLength(hdr) +
LayerInfoLength(hdr) + RefIndicesLength(hdr);
}
size_t PayloadDescriptorLength(const RTPVideoHeaderVP9& hdr) {
return PayloadDescriptorLengthMinusSsData(hdr) + SsDataLength(hdr);
}
void QueuePacket(size_t start_pos,
size_t size,
bool layer_begin,
bool layer_end,
RtpPacketizerVp9::PacketInfoQueue* packets) {
RtpPacketizerVp9::PacketInfo packet_info;
packet_info.payload_start_pos = start_pos;
packet_info.size = size;
packet_info.layer_begin = layer_begin;
packet_info.layer_end = layer_end;
packets->push(packet_info);
}
// Picture ID:
//
// +-+-+-+-+-+-+-+-+
// I: |M| PICTURE ID | M:0 => picture id is 7 bits.
// +-+-+-+-+-+-+-+-+ M:1 => picture id is 15 bits.
// M: | EXTENDED PID |
// +-+-+-+-+-+-+-+-+
//
bool WritePictureId(const RTPVideoHeaderVP9& vp9,
rtc::BitBufferWriter* writer) {
bool m_bit = (PictureIdLength(vp9) == 2);
RETURN_FALSE_ON_ERROR(writer->WriteBits(m_bit ? 1 : 0, 1));
RETURN_FALSE_ON_ERROR(writer->WriteBits(vp9.picture_id, m_bit ? 15 : 7));
return true;
}
// Layer indices:
//
// Flexible mode (F=1):
//
// +-+-+-+-+-+-+-+-+
// L: | T |U| S |D|
// +-+-+-+-+-+-+-+-+
//
bool WriteLayerInfoCommon(const RTPVideoHeaderVP9& vp9,
rtc::BitBufferWriter* writer) {
RETURN_FALSE_ON_ERROR(writer->WriteBits(TemporalIdxField(vp9, 0), 3));
RETURN_FALSE_ON_ERROR(writer->WriteBits(vp9.temporal_up_switch ? 1 : 0, 1));
RETURN_FALSE_ON_ERROR(writer->WriteBits(SpatialIdxField(vp9, 0), 3));
RETURN_FALSE_ON_ERROR(writer->WriteBits(vp9.inter_layer_predicted ? 1: 0, 1));
return true;
}
// Non-flexible mode (F=0):
//
// +-+-+-+-+-+-+-+-+
// L: | T |U| S |D|
// +-+-+-+-+-+-+-+-+
// | TL0PICIDX |
// +-+-+-+-+-+-+-+-+
//
bool WriteLayerInfoNonFlexibleMode(const RTPVideoHeaderVP9& vp9,
rtc::BitBufferWriter* writer) {
RETURN_FALSE_ON_ERROR(writer->WriteUInt8(Tl0PicIdxField(vp9, 0)));
return true;
}
bool WriteLayerInfo(const RTPVideoHeaderVP9& vp9,
rtc::BitBufferWriter* writer) {
if (!WriteLayerInfoCommon(vp9, writer))
return false;
if (vp9.flexible_mode)
return true;
return WriteLayerInfoNonFlexibleMode(vp9, writer);
}
// Reference indices:
//
// +-+-+-+-+-+-+-+-+ P=1,F=1: At least one reference index
// P,F: | P_DIFF |N| up to 3 times has to be specified.
// +-+-+-+-+-+-+-+-+ N=1: An additional P_DIFF follows
// current P_DIFF.
//
bool WriteRefIndices(const RTPVideoHeaderVP9& vp9,
rtc::BitBufferWriter* writer) {
if (!PictureIdPresent(vp9) ||
vp9.num_ref_pics == 0 || vp9.num_ref_pics > kMaxVp9RefPics) {
return false;
}
for (uint8_t i = 0; i < vp9.num_ref_pics; ++i) {
bool n_bit = !(i == vp9.num_ref_pics - 1);
RETURN_FALSE_ON_ERROR(writer->WriteBits(vp9.pid_diff[i], 7));
RETURN_FALSE_ON_ERROR(writer->WriteBits(n_bit ? 1 : 0, 1));
}
return true;
}
// Scalability structure (SS).
//
// +-+-+-+-+-+-+-+-+
// V: | N_S |Y|G|-|-|-|
// +-+-+-+-+-+-+-+-+ -|
// Y: | WIDTH | (OPTIONAL) .
// + + .
// | | (OPTIONAL) .
// +-+-+-+-+-+-+-+-+ . N_S + 1 times
// | HEIGHT | (OPTIONAL) .
// + + .
// | | (OPTIONAL) .
// +-+-+-+-+-+-+-+-+ -|
// G: | N_G | (OPTIONAL)
// +-+-+-+-+-+-+-+-+ -|
// N_G: | T |U| R |-|-| (OPTIONAL) .
// +-+-+-+-+-+-+-+-+ -| . N_G times
// | P_DIFF | (OPTIONAL) . R times .
// +-+-+-+-+-+-+-+-+ -| -|
//
bool WriteSsData(const RTPVideoHeaderVP9& vp9, rtc::BitBufferWriter* writer) {
RTC_DCHECK_GT(vp9.num_spatial_layers, 0U);
RTC_DCHECK_LE(vp9.num_spatial_layers, kMaxVp9NumberOfSpatialLayers);
RTC_DCHECK_LE(vp9.gof.num_frames_in_gof, kMaxVp9FramesInGof);
bool g_bit = vp9.gof.num_frames_in_gof > 0;
RETURN_FALSE_ON_ERROR(writer->WriteBits(vp9.num_spatial_layers - 1, 3));
RETURN_FALSE_ON_ERROR(
writer->WriteBits(vp9.spatial_layer_resolution_present ? 1 : 0, 1));
RETURN_FALSE_ON_ERROR(writer->WriteBits(g_bit ? 1 : 0, 1)); // G
RETURN_FALSE_ON_ERROR(writer->WriteBits(kReservedBitValue0, 3));
if (vp9.spatial_layer_resolution_present) {
for (size_t i = 0; i < vp9.num_spatial_layers; ++i) {
RETURN_FALSE_ON_ERROR(writer->WriteUInt16(vp9.width[i]));
RETURN_FALSE_ON_ERROR(writer->WriteUInt16(vp9.height[i]));
}
}
if (g_bit) {
RETURN_FALSE_ON_ERROR(writer->WriteUInt8(vp9.gof.num_frames_in_gof));
}
for (size_t i = 0; i < vp9.gof.num_frames_in_gof; ++i) {
RETURN_FALSE_ON_ERROR(writer->WriteBits(vp9.gof.temporal_idx[i], 3));
RETURN_FALSE_ON_ERROR(
writer->WriteBits(vp9.gof.temporal_up_switch[i] ? 1 : 0, 1));
RETURN_FALSE_ON_ERROR(writer->WriteBits(vp9.gof.num_ref_pics[i], 2));
RETURN_FALSE_ON_ERROR(writer->WriteBits(kReservedBitValue0, 2));
for (uint8_t r = 0; r < vp9.gof.num_ref_pics[i]; ++r) {
RETURN_FALSE_ON_ERROR(writer->WriteUInt8(vp9.gof.pid_diff[i][r]));
}
}
return true;
}
// Picture ID:
//
// +-+-+-+-+-+-+-+-+
// I: |M| PICTURE ID | M:0 => picture id is 7 bits.
// +-+-+-+-+-+-+-+-+ M:1 => picture id is 15 bits.
// M: | EXTENDED PID |
// +-+-+-+-+-+-+-+-+
//
bool ParsePictureId(rtc::BitBuffer* parser, RTPVideoHeaderVP9* vp9) {
uint32_t picture_id;
uint32_t m_bit;
RETURN_FALSE_ON_ERROR(parser->ReadBits(&m_bit, 1));
if (m_bit) {
RETURN_FALSE_ON_ERROR(parser->ReadBits(&picture_id, 15));
vp9->max_picture_id = kMaxTwoBytePictureId;
} else {
RETURN_FALSE_ON_ERROR(parser->ReadBits(&picture_id, 7));
vp9->max_picture_id = kMaxOneBytePictureId;
}
vp9->picture_id = picture_id;
return true;
}
// Layer indices (flexible mode):
//
// +-+-+-+-+-+-+-+-+
// L: | T |U| S |D|
// +-+-+-+-+-+-+-+-+
//
bool ParseLayerInfoCommon(rtc::BitBuffer* parser, RTPVideoHeaderVP9* vp9) {
uint32_t t, u_bit, s, d_bit;
RETURN_FALSE_ON_ERROR(parser->ReadBits(&t, 3));
RETURN_FALSE_ON_ERROR(parser->ReadBits(&u_bit, 1));
RETURN_FALSE_ON_ERROR(parser->ReadBits(&s, 3));
RETURN_FALSE_ON_ERROR(parser->ReadBits(&d_bit, 1));
vp9->temporal_idx = t;
vp9->temporal_up_switch = u_bit ? true : false;
vp9->spatial_idx = s;
vp9->inter_layer_predicted = d_bit ? true : false;
return true;
}
// Layer indices (non-flexible mode):
//
// +-+-+-+-+-+-+-+-+
// L: | T |U| S |D|
// +-+-+-+-+-+-+-+-+
// | TL0PICIDX |
// +-+-+-+-+-+-+-+-+
//
bool ParseLayerInfoNonFlexibleMode(rtc::BitBuffer* parser,
RTPVideoHeaderVP9* vp9) {
uint8_t tl0picidx;
RETURN_FALSE_ON_ERROR(parser->ReadUInt8(&tl0picidx));
vp9->tl0_pic_idx = tl0picidx;
return true;
}
bool ParseLayerInfo(rtc::BitBuffer* parser, RTPVideoHeaderVP9* vp9) {
if (!ParseLayerInfoCommon(parser, vp9))
return false;
if (vp9->flexible_mode)
return true;
return ParseLayerInfoNonFlexibleMode(parser, vp9);
}
// Reference indices:
//
// +-+-+-+-+-+-+-+-+ P=1,F=1: At least one reference index
// P,F: | P_DIFF |N| up to 3 times has to be specified.
// +-+-+-+-+-+-+-+-+ N=1: An additional P_DIFF follows
// current P_DIFF.
//
bool ParseRefIndices(rtc::BitBuffer* parser, RTPVideoHeaderVP9* vp9) {
if (vp9->picture_id == kNoPictureId)
return false;
vp9->num_ref_pics = 0;
uint32_t n_bit;
do {
if (vp9->num_ref_pics == kMaxVp9RefPics)
return false;
uint32_t p_diff;
RETURN_FALSE_ON_ERROR(parser->ReadBits(&p_diff, 7));
RETURN_FALSE_ON_ERROR(parser->ReadBits(&n_bit, 1));
vp9->pid_diff[vp9->num_ref_pics] = p_diff;
uint32_t scaled_pid = vp9->picture_id;
if (p_diff > scaled_pid) {
// TODO(asapersson): Max should correspond to the picture id of last wrap.
scaled_pid += vp9->max_picture_id + 1;
}
vp9->ref_picture_id[vp9->num_ref_pics++] = scaled_pid - p_diff;
} while (n_bit);
return true;
}
// Scalability structure (SS).
//
// +-+-+-+-+-+-+-+-+
// V: | N_S |Y|G|-|-|-|
// +-+-+-+-+-+-+-+-+ -|
// Y: | WIDTH | (OPTIONAL) .
// + + .
// | | (OPTIONAL) .
// +-+-+-+-+-+-+-+-+ . N_S + 1 times
// | HEIGHT | (OPTIONAL) .
// + + .
// | | (OPTIONAL) .
// +-+-+-+-+-+-+-+-+ -|
// G: | N_G | (OPTIONAL)
// +-+-+-+-+-+-+-+-+ -|
// N_G: | T |U| R |-|-| (OPTIONAL) .
// +-+-+-+-+-+-+-+-+ -| . N_G times
// | P_DIFF | (OPTIONAL) . R times .
// +-+-+-+-+-+-+-+-+ -| -|
//
bool ParseSsData(rtc::BitBuffer* parser, RTPVideoHeaderVP9* vp9) {
uint32_t n_s, y_bit, g_bit;
RETURN_FALSE_ON_ERROR(parser->ReadBits(&n_s, 3));
RETURN_FALSE_ON_ERROR(parser->ReadBits(&y_bit, 1));
RETURN_FALSE_ON_ERROR(parser->ReadBits(&g_bit, 1));
RETURN_FALSE_ON_ERROR(parser->ConsumeBits(3));
vp9->num_spatial_layers = n_s + 1;
vp9->spatial_layer_resolution_present = y_bit ? true : false;
vp9->gof.num_frames_in_gof = 0;
if (y_bit) {
for (size_t i = 0; i < vp9->num_spatial_layers; ++i) {
RETURN_FALSE_ON_ERROR(parser->ReadUInt16(&vp9->width[i]));
RETURN_FALSE_ON_ERROR(parser->ReadUInt16(&vp9->height[i]));
}
}
if (g_bit) {
uint8_t n_g;
RETURN_FALSE_ON_ERROR(parser->ReadUInt8(&n_g));
vp9->gof.num_frames_in_gof = n_g;
}
for (size_t i = 0; i < vp9->gof.num_frames_in_gof; ++i) {
uint32_t t, u_bit, r;
RETURN_FALSE_ON_ERROR(parser->ReadBits(&t, 3));
RETURN_FALSE_ON_ERROR(parser->ReadBits(&u_bit, 1));
RETURN_FALSE_ON_ERROR(parser->ReadBits(&r, 2));
RETURN_FALSE_ON_ERROR(parser->ConsumeBits(2));
vp9->gof.temporal_idx[i] = t;
vp9->gof.temporal_up_switch[i] = u_bit ? true : false;
vp9->gof.num_ref_pics[i] = r;
for (uint8_t p = 0; p < vp9->gof.num_ref_pics[i]; ++p) {
uint8_t p_diff;
RETURN_FALSE_ON_ERROR(parser->ReadUInt8(&p_diff));
vp9->gof.pid_diff[i][p] = p_diff;
}
}
return true;
}
} // namespace
RtpPacketizerVp9::RtpPacketizerVp9(const RTPVideoHeaderVP9& hdr,
size_t max_payload_length,
size_t last_packet_reduction_len)
: hdr_(hdr),
max_payload_length_(max_payload_length),
payload_(nullptr),
payload_size_(0),
last_packet_reduction_len_(last_packet_reduction_len) {}
RtpPacketizerVp9::~RtpPacketizerVp9() {
}
std::string RtpPacketizerVp9::ToString() {
return "RtpPacketizerVp9";
}
size_t RtpPacketizerVp9::SetPayloadData(
const uint8_t* payload,
size_t payload_size,
const RTPFragmentationHeader* fragmentation) {
payload_ = payload;
payload_size_ = payload_size;
GeneratePackets();
return packets_.size();
}
// Splits payload in minimal number of roughly equal in size packets.
void RtpPacketizerVp9::GeneratePackets() {
if (max_payload_length_ < PayloadDescriptorLength(hdr_) + 1) {
RTC_LOG(LS_ERROR) << "Payload header and one payload byte won't fit in the "
"first packet.";
return;
}
if (max_payload_length_ < PayloadDescriptorLengthMinusSsData(hdr_) + 1 +
last_packet_reduction_len_) {
RTC_LOG(LS_ERROR)
<< "Payload header and one payload byte won't fit in the last"
" packet.";
return;
}
if (payload_size_ == 1 &&
max_payload_length_ <
PayloadDescriptorLength(hdr_) + 1 + last_packet_reduction_len_) {
RTC_LOG(LS_ERROR) << "Can't fit header and payload into single packet, but "
"payload size is one: no way to generate packets with "
"nonzero payload.";
return;
}
// Instead of making last packet smaller, we pretend that we must write
// additional data into it. We account for this virtual payload while
// calculating packets number and sizes. We also pretend that all packets
// headers are the same length and extra SS header data in the fits packet
// is also treated as a payload here.
size_t ss_data_len = SsDataLength(hdr_);
// Payload, virtual payload and SS hdr data in the first packet together.
size_t total_bytes = ss_data_len + payload_size_ + last_packet_reduction_len_;
// Now all packets will have the same lenght of vp9 headers.
size_t per_packet_capacity =
max_payload_length_ - PayloadDescriptorLengthMinusSsData(hdr_);
// Integer division rounding up.
size_t num_packets =
(total_bytes + per_packet_capacity - 1) / per_packet_capacity;
// Average rounded down.
size_t per_packet_bytes = total_bytes / num_packets;
// Several last packets are 1 byte larger than the rest.
// i.e. if 14 bytes were split between 4 packets, it would be 3+3+4+4.
size_t num_larger_packets = total_bytes % num_packets;
size_t bytes_processed = 0;
size_t num_packets_left = num_packets;
while (bytes_processed < payload_size_) {
if (num_packets_left == num_larger_packets)
++per_packet_bytes;
size_t packet_bytes = per_packet_bytes;
// First packet also has SS hdr data.
if (bytes_processed == 0) {
// Must write at least one byte of the real payload to the packet.
if (packet_bytes > ss_data_len) {
packet_bytes -= ss_data_len;
} else {
packet_bytes = 1;
}
}
size_t rem_bytes = payload_size_ - bytes_processed;
if (packet_bytes >= rem_bytes) {
// All remaining payload fits into this packet.
packet_bytes = rem_bytes;
// If this is the penultimate packet, leave at least 1 byte of payload for
// the last packet.
if (num_packets_left == 2)
--packet_bytes;
}
QueuePacket(bytes_processed, packet_bytes, bytes_processed == 0,
rem_bytes == packet_bytes, &packets_);
--num_packets_left;
bytes_processed += packet_bytes;
// Last packet should be smaller
RTC_DCHECK(num_packets_left > 0 ||
per_packet_capacity >=
packet_bytes + last_packet_reduction_len_);
}
RTC_CHECK_EQ(bytes_processed, payload_size_);
}
bool RtpPacketizerVp9::NextPacket(RtpPacketToSend* packet) {
RTC_DCHECK(packet);
if (packets_.empty()) {
return false;
}
PacketInfo packet_info = packets_.front();
packets_.pop();
if (!WriteHeaderAndPayload(packet_info, packet, packets_.empty())) {
return false;
}
packet->SetMarker(packets_.empty() &&
(hdr_.spatial_idx == kNoSpatialIdx ||
hdr_.spatial_idx == hdr_.num_spatial_layers - 1));
return true;
}
// VP9 format:
//
// Payload descriptor for F = 1 (flexible mode)
// 0 1 2 3 4 5 6 7
// +-+-+-+-+-+-+-+-+
// |I|P|L|F|B|E|V|-| (REQUIRED)
// +-+-+-+-+-+-+-+-+
// I: |M| PICTURE ID | (RECOMMENDED)
// +-+-+-+-+-+-+-+-+
// M: | EXTENDED PID | (RECOMMENDED)
// +-+-+-+-+-+-+-+-+
// L: | T |U| S |D| (CONDITIONALLY RECOMMENDED)
// +-+-+-+-+-+-+-+-+ -|
// P,F: | P_DIFF |N| (CONDITIONALLY RECOMMENDED) . up to 3 times
// +-+-+-+-+-+-+-+-+ -|
// V: | SS |
// | .. |
// +-+-+-+-+-+-+-+-+
//
// Payload descriptor for F = 0 (non-flexible mode)
// 0 1 2 3 4 5 6 7
// +-+-+-+-+-+-+-+-+
// |I|P|L|F|B|E|V|-| (REQUIRED)
// +-+-+-+-+-+-+-+-+
// I: |M| PICTURE ID | (RECOMMENDED)
// +-+-+-+-+-+-+-+-+
// M: | EXTENDED PID | (RECOMMENDED)
// +-+-+-+-+-+-+-+-+
// L: | T |U| S |D| (CONDITIONALLY RECOMMENDED)
// +-+-+-+-+-+-+-+-+
// | TL0PICIDX | (CONDITIONALLY REQUIRED)
// +-+-+-+-+-+-+-+-+
// V: | SS |
// | .. |
// +-+-+-+-+-+-+-+-+
bool RtpPacketizerVp9::WriteHeaderAndPayload(const PacketInfo& packet_info,
RtpPacketToSend* packet,
bool last) const {
uint8_t* buffer = packet->AllocatePayload(
last ? max_payload_length_ - last_packet_reduction_len_
: max_payload_length_);
RTC_DCHECK(buffer);
size_t header_length;
if (!WriteHeader(packet_info, buffer, &header_length))
return false;
// Copy payload data.
memcpy(&buffer[header_length],
&payload_[packet_info.payload_start_pos], packet_info.size);
packet->SetPayloadSize(header_length + packet_info.size);
return true;
}
bool RtpPacketizerVp9::WriteHeader(const PacketInfo& packet_info,
uint8_t* buffer,
size_t* header_length) const {
// Required payload descriptor byte.
bool i_bit = PictureIdPresent(hdr_);
bool p_bit = hdr_.inter_pic_predicted;
bool l_bit = LayerInfoPresent(hdr_);
bool f_bit = hdr_.flexible_mode;
bool b_bit = packet_info.layer_begin;
bool e_bit = packet_info.layer_end;
bool v_bit = hdr_.ss_data_available && b_bit;
rtc::BitBufferWriter writer(buffer, max_payload_length_);
RETURN_FALSE_ON_ERROR(writer.WriteBits(i_bit ? 1 : 0, 1));
RETURN_FALSE_ON_ERROR(writer.WriteBits(p_bit ? 1 : 0, 1));
RETURN_FALSE_ON_ERROR(writer.WriteBits(l_bit ? 1 : 0, 1));
RETURN_FALSE_ON_ERROR(writer.WriteBits(f_bit ? 1 : 0, 1));
RETURN_FALSE_ON_ERROR(writer.WriteBits(b_bit ? 1 : 0, 1));
RETURN_FALSE_ON_ERROR(writer.WriteBits(e_bit ? 1 : 0, 1));
RETURN_FALSE_ON_ERROR(writer.WriteBits(v_bit ? 1 : 0, 1));
RETURN_FALSE_ON_ERROR(writer.WriteBits(kReservedBitValue0, 1));
// Add fields that are present.
if (i_bit && !WritePictureId(hdr_, &writer)) {
RTC_LOG(LS_ERROR) << "Failed writing VP9 picture id.";
return false;
}
if (l_bit && !WriteLayerInfo(hdr_, &writer)) {
RTC_LOG(LS_ERROR) << "Failed writing VP9 layer info.";
return false;
}
if (p_bit && f_bit && !WriteRefIndices(hdr_, &writer)) {
RTC_LOG(LS_ERROR) << "Failed writing VP9 ref indices.";
return false;
}
if (v_bit && !WriteSsData(hdr_, &writer)) {
RTC_LOG(LS_ERROR) << "Failed writing VP9 SS data.";
return false;
}
size_t offset_bytes = 0;
size_t offset_bits = 0;
writer.GetCurrentOffset(&offset_bytes, &offset_bits);
assert(offset_bits == 0);
*header_length = offset_bytes;
return true;
}
bool RtpDepacketizerVp9::Parse(ParsedPayload* parsed_payload,
const uint8_t* payload,
size_t payload_length) {
assert(parsed_payload != nullptr);
if (payload_length == 0) {
RTC_LOG(LS_ERROR) << "Payload length is zero.";
return false;
}
// Parse mandatory first byte of payload descriptor.
rtc::BitBuffer parser(payload, payload_length);
uint32_t i_bit, p_bit, l_bit, f_bit, b_bit, e_bit, v_bit;
RETURN_FALSE_ON_ERROR(parser.ReadBits(&i_bit, 1));
RETURN_FALSE_ON_ERROR(parser.ReadBits(&p_bit, 1));
RETURN_FALSE_ON_ERROR(parser.ReadBits(&l_bit, 1));
RETURN_FALSE_ON_ERROR(parser.ReadBits(&f_bit, 1));
RETURN_FALSE_ON_ERROR(parser.ReadBits(&b_bit, 1));
RETURN_FALSE_ON_ERROR(parser.ReadBits(&e_bit, 1));
RETURN_FALSE_ON_ERROR(parser.ReadBits(&v_bit, 1));
RETURN_FALSE_ON_ERROR(parser.ConsumeBits(1));
// Parsed payload.
parsed_payload->type.Video.width = 0;
parsed_payload->type.Video.height = 0;
parsed_payload->type.Video.simulcastIdx = 0;
parsed_payload->type.Video.codec = kRtpVideoVp9;
parsed_payload->frame_type = p_bit ? kVideoFrameDelta : kVideoFrameKey;
RTPVideoHeaderVP9* vp9 = &parsed_payload->type.Video.codecHeader.VP9;
vp9->InitRTPVideoHeaderVP9();
vp9->inter_pic_predicted = p_bit ? true : false;
vp9->flexible_mode = f_bit ? true : false;
vp9->beginning_of_frame = b_bit ? true : false;
vp9->end_of_frame = e_bit ? true : false;
vp9->ss_data_available = v_bit ? true : false;
// Parse fields that are present.
if (i_bit && !ParsePictureId(&parser, vp9)) {
RTC_LOG(LS_ERROR) << "Failed parsing VP9 picture id.";
return false;
}
if (l_bit && !ParseLayerInfo(&parser, vp9)) {
RTC_LOG(LS_ERROR) << "Failed parsing VP9 layer info.";
return false;
}
if (p_bit && f_bit && !ParseRefIndices(&parser, vp9)) {
RTC_LOG(LS_ERROR) << "Failed parsing VP9 ref indices.";
return false;
}
if (v_bit) {
if (!ParseSsData(&parser, vp9)) {
RTC_LOG(LS_ERROR) << "Failed parsing VP9 SS data.";
return false;
}
if (vp9->spatial_layer_resolution_present) {
// TODO(asapersson): Add support for spatial layers.
parsed_payload->type.Video.width = vp9->width[0];
parsed_payload->type.Video.height = vp9->height[0];
}
}
parsed_payload->type.Video.is_first_packet_in_frame =
b_bit && (!l_bit || !vp9->inter_layer_predicted);
uint64_t rem_bits = parser.RemainingBitCount();
assert(rem_bits % 8 == 0);
parsed_payload->payload_length = rem_bits / 8;
if (parsed_payload->payload_length == 0) {
RTC_LOG(LS_ERROR) << "Failed parsing VP9 payload data.";
return false;
}
parsed_payload->payload =
payload + payload_length - parsed_payload->payload_length;
return true;
}
} // namespace webrtc
| mit |
anthonyfuentes/hubzero-cms | core/components/com_users/site/controllers/auth.php | 26923 | <?php
/**
* @package hubzero-cms
* @copyright Copyright 2005-2019 HUBzero Foundation, LLC.
* @license http://opensource.org/licenses/MIT MIT
*/
namespace Components\Users\Site\Controllers;
use Hubzero\Component\SiteController;
use Hubzero\Config\Registry;
use Hubzero\Utility\Uri;
use Exception;
use Document;
use Request;
use Config;
use Plugin;
use Notify;
use Event;
use Route;
use Lang;
use User;
use App;
/**
* Login Controller
*/
class Auth extends SiteController
{
/**
* Default task
*
* @return void
*/
public function displayTask()
{
// Get the view data.
$user = User::getInstance();
$params = $this->config;
// Make sure we're using a secure connection
if (!isset($_SERVER['HTTPS']) || $_SERVER['HTTPS'] == 'off')
{
App::redirect( 'https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']);
die('insecure connection and redirection failed');
}
// Check for errors.
if ($this->getError())
{
App::abort(500, implode('<br />', $errors));
}
// Get the active menu
$menus = App::get('menu');
$menu = $menus->getActive();
$title = Config::get('sitename');
$description = Config::get('MetaDesc');
$rights = Config::get('MetaRights');
$robots = Config::get('robots');
// Lets cascade the parameters if we have menu item parameters
if (is_object($menu))
{
$temp = $menu->params;
$params->merge($temp);
$title = $menu->title;
}
else
{
// get com_menu global settings
$temp = clone \Component::params('com_menus');
$params->merge($temp);
// if supplied, use page title
$title = $temp->get('page_title', $title);
}
$params->def('page_title', $title);
$params->def('page_description', $description);
$params->def('page_rights', $rights);
$params->def('robots', $robots);
$this->view->setLayout('login');
// Escape strings for HTML output
$pageclass_sfx = htmlspecialchars($params->get('pageclass_sfx'));
$login = User::isGuest() ? true : false;
$title = null;
// Because the application sets a default page title,
// we need to get it from the menu item itself
if ($menu)
{
// Check for layout override
if (isset($menu->query['layout']))
{
$this->view->setLayout($menu->query['layout']);
}
$params->def('page_heading', $params->get('page_title', $menu->title));
}
else
{
$params->def('page_heading', $login ? Lang::txt('JLOGIN') : Lang::txt('JLOGOUT'));
}
$title = $params->get('page_title', '');
if (empty($title))
{
$title = Config::get('sitename');
}
elseif (Config::get('sitename_pagetitles', 0) == 1)
{
$title = Lang::txt('JPAGETITLE', Config::get('sitename'), $title);
}
elseif (Config::get('sitename_pagetitles', 0) == 2)
{
$title = Lang::txt('JPAGETITLE', $title, Config::get('sitename'));
}
Document::setTitle($title);
if ($params->get('menu-meta_description'))
{
Document::setDescription($params->get('menu-meta_description'));
}
if ($params->get('menu-meta_keywords'))
{
Document::setMetadata('keywords', $params->get('menu-meta_keywords'));
}
if ($params->get('robots'))
{
Document::setMetadata('robots', $params->get('robots'));
}
// Get the default return value
$defaultReturn = Route::url('index.php?option=com_members&task=myaccount');
$description = '';
if ($menu && isset($menu->params) && is_object($menu->params))
{
$defaultReturn = $menu->params->get('login_redirect_url', $defaultReturn);
// Assume redirect URLs that start with a slash are internal
// As such, we want to make sure the path has the appropriate root
$root = Request::root(true);
if (substr($defaultReturn, 0, 1) == '/'
&& substr($defaultReturn, 0, strlen($root)) != $root)
{
$defaultReturn = rtrim($root, '/') . $defaultReturn;
}
$description = $menu->params->get('login_description');
}
$defaultReturn = base64_encode($defaultReturn);
$uri = Uri::getInstance();
if ($rtrn = $uri->getVar('return'))
{
if (!$this->isBase64($rtrn))
{
// This isn't a base64 string and most likely is
// someone trying to do something nasty (XSS)
$uri->setVar('return', $defaultReturn);
}
}
$furl = base64_encode($uri->toString());
// HUBzero: If we have a return set with an authenticator in it, we're linking an existing account
// Parse the return to retrive the authenticator, and remove it from the list below
$auth = '';
if ($return = Request::getString('return', '', 'get'))
{
if (!$this->isBase64($return))
{
// This isn't a base64 string and most likely is someone trying to do something nasty (XSS)
$return = null;
Request::setVar('return', null);
}
else
{
$decoded_return = base64_decode($return);
$dr = new Uri($decoded_return);
if ($dr->hasVar('authenticator'))
{
$auth = $dr->getVar('authenticator');
}
/*$query = parse_url($decoded_return);
if (is_array($query) && isset($query['query']))
{
$query = $query['query'];
$query = explode('&', $query);
$auth = '';
foreach ($query as $q)
{
$n = explode('=', $q);
if ($n[0] == 'authenticator')
{
$auth = $n[1];
}
}
}*/
}
}
// Set return if it isn't already
if (!$return && is_object($menu))
{
$return = $defaultReturn;
}
// Figure out whether or not any of our third party auth plugins are turned on
// Don't include the 'hubzero' plugin, or the $auth plugin as described above
$multiAuth = false;
$local = false;
$plugins = Plugin::byType('authentication');
$authenticators = array();
$remember_me_default = 0;
foreach ($plugins as $p)
{
$client = App::get('client')->alias . '_login';
$pparams = new Registry($p->params);
// Make sure plugin is enabled for a given client
if (!$pparams->get($client, false))
{
continue;
}
if ($p->name != 'hubzero' && $p->name != $auth)
{
$display = $pparams->get('display_name', ucfirst($p->name));
$authenticators[$p->name] = array(
'name' => $p->name,
'display' => $display
);
$multiAuth = true;
}
else if ($p->name == 'hubzero')
{
$remember_me_default = $pparams->get('remember_me_default', 0);
$this->site_display = $pparams->get('display_name', Config::get('sitename'));
$local = true;
}
}
// Override $multiAuth if authenticator is set to hubzero
if (Request::getWord('authenticator') == 'hubzero')
{
$multiAuth = false;
}
// Set the return if we have it...
$returnQueryString = (!empty($return)) ? "&return={$return}" : '';
// if authenticator is specified call plugin display method, otherwise (or if method does not exist) use default
$authenticator = Request::getString('authenticator', '');
Plugin::import('authentication');
$status = array();
$tpl = null;
$this->return = $return;
foreach ($plugins as $plugin)
{
$className = 'plg' . $plugin->type . $plugin->name;
if (class_exists($className))
{
$myplugin = new $className($this, (array)$plugin);
if (method_exists($className, 'status'))
{
$status[$plugin->name] = $myplugin->status();
//$this->status = $status;
}
if ($plugin->name != $authenticator)
{
continue;
}
if (method_exists($className, 'display'))
{
return $myplugin->display($this, $tpl);
}
}
}
$this->view
->set('multiAuth', $multiAuth)
->set('authenticators', $authenticators)
->set('totalauths', count($plugins))
->set('remember_me_default', $remember_me_default)
->set('pageclass_sfx', $pageclass_sfx)
->set('description', $description)
->set('return', $return)
->set('freturn', $furl)
->set('status', $status)
->set('user', $user)
->set('params', $params)
->set('returnQueryString', $returnQueryString)
->set('local', $local)
->setName('login')
->setLayout('default')
->addTemplatePath($this->getTemplatePath())
->display();
}
/**
* Get users template override path
*
* @return string
**/
protected function getTemplatePath()
{
return App::get('template')->path . '/html/com_users/' . $this->view->getName();
}
/**
* Is the provided string base64 encoded?
*
* @param string $str
* @return bool
**/
protected function isBase64($str)
{
if (preg_match('/[^A-Za-z0-9\+\/\=]/', $str))
{
return false;
}
return true;
}
/**
* Method to log in a user.
*
* @return void
*/
public function loginTask()
{
// Populate the data array:
$options = array();
$data = array(
'username' => Request::getString('username', '', 'post'),
'password' => Request::getString('passwd', '', 'post'),
'return' => Request::getString('return', '', 'post')
);
if (!$this->isBase64($data['return']))
{
$data['return'] = '';
}
else
{
$data['return'] = base64_decode($data['return']);
}
$authenticator = Request::getString('authenticator', '');
// If a specific authenticator is specified try to call the login method for that plugin
if (!empty($authenticator))
{
Plugin::import('authentication');
$plugins = Plugin::byType('authentication');
foreach ($plugins as $plugin)
{
$className = 'plg' . $plugin->type . $plugin->name;
if ($plugin->name != $authenticator)
{
continue;
}
if (class_exists($className))
{
if (method_exists($className, 'login'))
{
$myplugin = new $className($this, (array)$plugin);
$myplugin->login($credentials, $options);
if (isset($options['return']))
{
$data['return'] = $options['return'];
}
}
$options['authenticator'] = $authenticator;
$options['action'] = 'core.login.site';
break;
}
}
}
// If no authenticator is specified, or the login method for that plugin did not exist then use default
if (!isset($myplugin))
{
// Check for request forgeries
Session::checkToken('request');
if ($return = Request::getString('return', ''))
{
if (!$this->isBase64($return))
{
$return = '';
}
else
{
$return = base64_decode($return);
if (!Uri::isInternal($return))
{
$return = '';
}
}
}
if ($freturn = Request::getString('freturn', ''))
{
if (!$this->isBase64($freturn))
{
$freturn = '';
}
else
{
$freturn = base64_decode($freturn);
if (!Uri::isInternal($freturn))
{
$freturn = '';
}
}
}
// Get the log in options.
$options = array();
$options['remember'] = Request::getBool('remember', false);
$options['return'] = $data['return'];
$options['action'] = 'core.login.site';
if (!empty($authenticator))
{
$options['authenticator'] = $authenticator;
}
// Get the log in credentials.
$credentials = array();
$credentials['username'] = $data['username'];
$credentials['password'] = $data['password'];
}
// Make sure return values are internal to the hub
// Guards against querystring tampering
if ($data['return'])
{
$return = $data['return'];
if (!Uri::isInternal($return))
{
$data['return'] = '';
}
}
// Set the return URL if empty.
if (empty($data['return']))
{
$data['return'] = 'index.php?option=com_members&task=myaccount';
}
// Set the return URL in the user state to allow modification by plugins
User::setState('login.form.return', $data['return']);
try
{
$result = App::get('auth')->login($credentials, $options);
}
catch (Exception $e)
{
$result = $e;
}
// Perform the log in.
if (true === $result)
{
// Success
User::setState('login.form.data', array());
$return = User::getState('login.form.return');
// If no_html is set, return json response
if (Request::getInt('no_html', 0))
{
echo json_encode(array(
'success' => true,
'redirect' => Route::url($return, false)
));
exit;
}
else
{
App::redirect(Route::url(User::getState('login.form.return'), false));
}
}
else
{
// Login failed !
$data['remember'] = isset($options['remember']) ? (int)$options['remember'] : 0;
User::setState('login.form.data', $data);
// Facilitate third party login forms
if (!isset($return) || !$return)
{
$return = Route::url('index.php?option=com_users&view=login');
}
if (isset($freturn))
{
$return = $freturn;
}
$error = ($result) ? $result->getMessage() : Lang::txt('An unknown error has occurred');
// If no_html is set, return json response
if (Request::getInt('no_html', 0))
{
echo json_encode(array(
'error' => $error,
'freturn' => Route::url($return, false)
));
exit;
}
else
{
// Redirect to a login form
App::redirect(Route::url($return, false), $error, 'error');
}
}
}
/**
* Multifactor authentication page
*
* @return void
**/
public function factorsTask()
{
$factors = Event::trigger('authfactors.onRenderChallenge');
$this->view
->set('factors', $factors)
->setName('factors')
->setLayout('default')
->addTemplatePath($this->getTemplatePath())
->display();
}
/**
* User consent form
*
* @return void
**/
public function userconsentTask()
{
$this->view
->setName('userconsent')
->setLayout('default')
->addTemplatePath($this->getTemplatePath())
->display();
}
/**
* Grant user consent
*
* @return void
**/
public function consentTask()
{
Session::set('user_consent', true);
$return = Request::getString('return');
if ($this->isBase64($return))
{
$return = base64_decode($return);
}
else
{
$return = Reoute::url('index.php');
}
App::redirect($return);
}
/**
* Grant user consent
*
* @return void
**/
public function linkTask()
{
$user = User::getInstance();
// If this is an auth_link account update, carry on, otherwise raise an error
if ($user->isGuest()
|| !$user->hasAttribute('auth_link_id')
|| !is_numeric($user->get('username'))
|| !$user->get('username') < 0)
{
App::abort(405, 'Method not allowed');
}
// Look up a few things
$hzal = \Hubzero\Auth\Link::find_by_id($user->get('auth_link_id'));
$hzad = \Hubzero\Auth\Domain::find_by_id($hzal->auth_domain_id);
$plugins = Plugin::byType('authentication');
// Get the display name for the current plugin being used
Plugin::import('authentication', $hzad->authenticator);
$plugin = Plugin::byType('authentication', $hzad->authenticator);
$pparams = new Registry($plugin->params);
$refl = new \ReflectionClass("plgAuthentication{$plugin->name}");
$display_name = $pparams->get('display_name', $refl->hasMethod('onGetLinkDescription') ? $refl->getMethod('onGetLinkDescription')->invoke(null) : ucfirst($plugin->name));
// Look for conflicts - first check in the hub accounts
$profile_conflicts = \Hubzero\User\User::all()
->whereEquals('email', $hzal->email)
->rows();
// Now check the auth_link table
$link_conflicts = \Hubzero\Auth\Link::find_by_email($hzal->email, array($hzad->id));
$conflict = array();
if ($profile_conflicts)
{
foreach ($profile_conflicts as $auser)
{
$auth_link = \Hubzero\Auth\Link::find_by_user_id($auser->id);
$dname = (is_object($auth_link) && $auth_link->auth_domain_name) ? $auth_link->auth_domain_name : 'hubzero';
$conflict[] = array(
'auth_domain_name' => $dname,
'name' => $auser->name,
'email' => $auser->email
);
}
}
if ($link_conflicts)
{
foreach ($link_conflicts as $l)
{
$auser = User::getInstance($l['user_id']);
$conflict[] = array(
'auth_domain_name' => $l['auth_domain_name'],
'name' => $auser->name,
'email' => $l['email']
);
}
}
// Make sure we don't somehow have any duplicate conflicts
$conflict = array_map('unserialize', array_unique(array_map('serialize', $conflict)));
// @TODO: Could also check for high probability of name matches???
// Get the site name
$sitename = Config::get('sitename');
// Assign variables to the view
$this->view
->set('hzal', $hzal)
->set('hzad', $hzad)
->set('plugins', $plugins)
->set('display_name', $display_name)
->set('conflict', $conflict)
->set('sitename', $sitename)
->set('user', $user)
->setName('link')
->setLayout('default')
->addTemplatePath($this->getTemplatePath())
->display();
}
/**
* Grant user consent
*
* @return void
**/
public function linkaccountsTask()
{
$user = User::getInstance();
// First, they should already be logged in, so check for that
if ($user->get('guest'))
{
App::abort(403, Lang::txt('You must be logged in to perform this function'));
}
// Do we have a return
$return = '';
$options = array();
if ($return = Request::getString('return', ''))
{
$return = base64_decode($return);
if (!Uri::isInternal($return))
{
$return = '';
}
else
{
$options['return'] = base64_encode($return);
}
}
$authenticator = Request::getString('authenticator', '');
// If a specific authenticator is specified try to call the link method for that plugin
if (!empty($authenticator))
{
Plugin::import('authentication');
$plugin = Plugin::byType('authentication', $authenticator);
$className = 'plg' . $plugin->type . $plugin->name;
if (class_exists($className))
{
if (method_exists($className, 'link'))
{
$myplugin = new $className($this, (array)$plugin);
$myplugin->link($options);
}
else
{
// No Link method is available
Notify::error(Lang::txt('Linked accounts are not currently available for this provider.'));
App::redirect(Route::url('index.php?option=com_members&id=' . $user->get('id') . '&active=account', false));
}
}
}
else
{
// No authenticator provided...
App::abort(400, Lang::txt('Missing authenticator'));
}
// Success! Redict with message
Notify::success(Lang::txt('Your account has been successfully linked!'));
App::redirect(Route::url('index.php?option=com_members&id=' . $user->get('id') . '&active=account', false));
}
/**
* End single sign-on
*
* @return void
**/
public function endsinglesignonTask()
{
// Assign variables to the view
$authenticator = Request::getWord('authenticator', false);
// Get the site name
$sitename = Config::get('sitename');
// Get the display name for the current plugin being used
$plugin = Plugin::byType('authentication', $authenticator);
$pparams = new Registry($plugin->params);
$display_name = $pparams->get('display_name', ucfirst($plugin->name));
$this->view
->set('authenticator', $authenticator)
->set('sitename', $sitename)
->set('display_name', $display_name)
->setName('endsinglesignon')
->setLayout('default')
->addTemplatePath($this->getTemplatePath())
->display();
}
/**
* Method to log out a user.
*
* @return void
*/
public function logoutTask()
{
if (Request::getCmd('view') == 'logout')
{
// Initialize variables
$image = '';
$menu = App::get('menu');
$item = $menu->getActive();
if ($item)
{
$params = $menu->getParams($item->id);
}
else
{
$params = new \Hubzero\Config\Registry('');
$template = App::get('template')->template;
$inifile = App::get('template')->path . DS . 'html' . DS . 'com_user' . DS . 'logout' . DS . 'config.ini';
if (file_exists($inifile))
{
$params->parse(file_get_contents($inifile));
}
$params->def('page_title', Lang::txt( 'Logout' ));
}
$type = 'logout';
// Set some default page parameters if not set
$params->def( 'show_page_title', 1 );
if (!$params->get( 'page_title'))
{
$params->set('page_title', Lang::txt( 'Logout' ));
}
if (!$item)
{
$params->def( 'header_logout', '' );
}
$params->def('pageclass_sfx', '');
$params->def('logout', '/');
$params->def('description_logout', 1);
$params->def('description_logout_text', Lang::txt('LOGOUT_DESCRIPTION'));
$params->def('image_logout', 'key.jpg');
$params->def('image_logout_align', 'right');
$usersConfig = Component::params('com_members');
$params->def('registration', $usersConfig->get('allowUserRegistration'));
$title = Lang::txt('Logout');
// Set page title
Document::setTitle($title);
// Build logout image if enabled
if ($params->get('image_' . $type) != -1)
{
$image = '/images/stories/'.$params->get('image_' . $type);
$image = '<img src="'. $image .'" align="'. $params->get('image_'.$type.'_align') .'" hspace="10" alt="" />';
}
// Get the return URL
if (!$url = Request::getString('return', ''))
{
$url = base64_encode($params->get($type));
}
$this->view->set('image', $image);
$this->view->set('type', $type);
$this->view->set('return', $url);
$this->view->set('params', $params);
$this->view->setName('logout');
$this->view->setLayout('default');
$this->view->display();
return;
}
$app = App::get('app');
$user = User::getInstance();
$authenticator = Request::getString('authenticator', '');
$singleSignOn = Request::getVar('sso', false);
if (empty($authenticator) || $authenticator == '')
{
$cookie = \Hubzero\Utility\Cookie::eat('authenticator');
if (isset($cookie->authenticator))
{
$authenticator = $cookie->authenticator;
}
else
{
$authenticator = null;
}
}
// If a specific authenticator is specified try to call the logout method for that plugin
if (!empty($authenticator))
{
Plugin::import('authentication');
$plugins = Plugin::byType('authentication');
foreach ($plugins as $plugin)
{
$className = 'plg' . $plugin->type . $plugin->name;
if ($plugin->name != $authenticator)
{
continue;
}
if (class_exists($className))
{
if (method_exists($className, 'logout'))
{
$myplugin = new $className($this, (array)$plugin);
// Redirect to user third party signout view
// Only do this for PUCAS for the time being (it's the one that doesn't lose session info after hub logout)
if ($authenticator == 'pucas')
{
// Get plugin params
$plugin = Plugin::byType('authentication', $authenticator);
$pparams = new Registry($plugin->params);
$auto_logoff = $pparams->get('auto_logoff', false);
if ($auto_logoff || $singleSignOn == 'all')
{
$result = $myplugin->logout();
break;
}
elseif ($singleSignOn === false)
{
App::redirect(Route::url('index.php?option=com_users&view=endsinglesignon&authenticator=' . $authenticator, false));
return;
}
else
{
break;
}
} // End PUCAS check
else
{
$result = $myplugin->logout();
break;
} // Normal path
} // End verification of logout() method
} // End plugin check
} // End foreach
} // End check for specified authenticator
// Perform the log out
//$error = $app->logout();
// Get a user object from the Application.
//$user = User::getInstance();
// Build the credentials array.
$parameters = array();
$parameters['username'] = $user->get('username');
$parameters['id'] = $user->get('id');
$options = array('clientid' => App::get('client')->id);
// Set clientid in the options array if it hasn't been set already.
//if (!isset($options['clientid']))
//{
//$options['clientid'] = App::get('client')->id;
//}
$error = false;
// OK, the credentials are built. Lets fire the onLogout event.
$results = Event::trigger('user.onUserLogout', array($parameters, $options));
// Check if any of the plugins failed. If none did, success.
if (!in_array(false, $results, true))
{
// Use domain and path set in config for cookie if it exists.
$cookie_domain = Config::get('cookie_domain', '');
$cookie_path = Config::get('cookie_path', '/');
setcookie(App::hash('JLOGIN_REMEMBER'), false, time() - 86400, $cookie_path, $cookie_domain);
}
else
{
// Trigger onUserLoginFailure Event.
Event::trigger('user.onUserLogoutFailure', array($parameters));
$error = true;
}
// Check if the log out succeeded.
if (!($error instanceof Exception))
{
// If the authenticator is empty, but they have an active third party session,
// redirect to a page indicating this and offering complete signout
if (isset($user->auth_link_id) && $user->auth_link_id && empty($authenticator))
{
$auth_domain_name = '';
$auth_domain = \Hubzero\Auth\Link::find_by_id($user->auth_link_id);
if (is_object($auth_domain))
{
$auth_domain_id = $auth_domain->auth_domain_id;
$auth_domain_name = \Hubzero\Auth\Domain::find_by_id($auth_domain_id)->authenticator;
}
// Redirect to user third party signout view
// Only do this for PUCAS for the time being (it's the one that doesn't lose session info after hub logout)
if ($auth_domain_name == 'pucas')
{
// Get plugin params
$plugin = Plugin::byType('authentication', $auth_domain_name);
$pparams = new Registry($plugin->params);
$auto_logoff = $pparams->get('auto_logoff', false);
if ($auto_logoff)
{
App::redirect(Route::url('index.php?option=com_users&task=user.logout&authenticator=' . $auth_domain_name, false));
return;
}
else
{
App::redirect(Route::url('index.php?option=com_users&view=endsinglesignon&authenticator=' . $auth_domain_name, false));
return;
}
}
}
// Get the return url from the request and validate that it is internal.
$return = Request::getString('return', 'index.php');
if ($this->isBase64($return))
{
$return = base64_decode($return);
}
// Assume redirect URLs that start with a slash are internal
// As such, we want to make sure the path has the appropriate root
$root = Request::root(true);
if (substr($return, 0, 1) == '/'
&& substr($return, 0, strlen($root)) != $root)
{
$return = rtrim($root, '/') . $return;
}
if (!$return || !Uri::isInternal($return))
{
$return = 'index.php';
}
}
else
{
$return = 'index.php?option=com_users&view=login';
}
// Try to prevent nasty redirect loops
/*if ($return == '/logout' || $return == '/index.php?option=com_users&task=user.logout')
{
$return = '/';
}*/
$return = Route::url($return, false);
// Redirect the user.
if (substr(Config::get('application_env', ''), -5) == 'cloud')
{
$return = base64_encode($return);
setcookie('jwt', '', -86400, '/', '.' . \Hubzero\Utility\Dns::domain(), true, true);
App::redirect(Route::url('/auth/logout&target=' . $return, false));
}
App::redirect($return);
}
}
| mit |
hazah/watchman | lib/watchman/permissions/set.rb | 904 | # encoding: utf-8
module Watchman
module Permissions
class Set
# :api: public
attr_reader :env, :scope, :permissions
include ::Watchman::Mixins::Common
# :api: private
def initialize(permissions, env, scope=nil) # :nodoc:
@env, @scope = env, scope
@permissions = permissions.inject({}) do |perms, current|
label = current.name.to_sym
context = current.context? ? current.context.constantize : nil
klass = Permissions[label]
permission = klass.new(env, scope, context)
perms[label] = permission
perms
end
end
def [](label)
permissions[label]
end
# :api: private
def permissions_for_session
permissions.map do |key, permission|
Struct.new(:name, :context).new(key, permission.context)
end
end
end
end
end
| mit |
lmazuel/azure-sdk-for-python | azure-mgmt-devtestlabs/azure/mgmt/devtestlabs/models/operation_error.py | 1060 | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
# --------------------------------------------------------------------------
from msrest.serialization import Model
class OperationError(Model):
"""Error details for the operation in case of a failure.
:param code: The error code of the operation error.
:type code: str
:param message: The error message of the operation error.
:type message: str
"""
_attribute_map = {
'code': {'key': 'code', 'type': 'str'},
'message': {'key': 'message', 'type': 'str'},
}
def __init__(self, code=None, message=None):
super(OperationError, self).__init__()
self.code = code
self.message = message
| mit |
JamesMGreene/nedboose | src/schema-types.js | 59 | function SchemaTypes() {
}
module.exports = SchemaTypes;
| mit |
tronsha/testphp | tests/FunctionStrposTest.php | 436 | <?php
/**
* Class FunctionStrposTest
* @link http://php.net/manual/en/function.strpos.php
*/
class FunctionStrposTest extends PHPUnit_Framework_TestCase
{
public function testFunctionStrpos()
{
$this->assertTrue(strpos('abc', 'a') !== false);
$this->assertEquals(0, strpos('abc', 'a'));
$this->assertEquals(7, strpos('abcdef abcdef', 'a', 1));
$this->assertFalse(strpos('abc', 'd'));
}
}
| mit |
marcaube/hex | tests/EventSourcing/EventSourcedEntityTest.php | 1458 | <?php
namespace Ob\Hex\Tests\EventSourcing;
use Ob\Hex\EventSourcing\EventSourcedEntity;
/**
* @covers Ob\Hex\EventSourcing\EventSourcedEntity
*/
class EventSourcedEntityTest extends \PHPUnit_Framework_TestCase
{
public function testCanBeCreatedFromAListOfEvents()
{
$entity = Entity::createFromEvents([
new EntitityWasCreated(),
]);
$this->assertInstanceOf(Entity::class, $entity);
$this->assertEquals(1, $entity->getFoo());
}
public function testIgnoresUnhandledEvents()
{
$entity = Entity::createFromEvents([
new FooWasChanged(),
]);
$this->assertInstanceOf(Entity::class, $entity);
$this->assertEquals(0, $entity->getFoo());
}
public function testEventsCanBeRetrieved()
{
$entity = Entity::create();
$this->assertEquals([new EntitityWasCreated()], $entity->getEvents());
}
}
class Entity extends EventSourcedEntity
{
private $foo = 0;
public static function create()
{
return new static([new EntitityWasCreated()]);
}
public function getFoo()
{
return $this->foo;
}
protected function applyEntitityWasCreated(EntitityWasCreated $event)
{
$this->foo = 1;
}
}
// This event sets the internal "foo" counter
class EntitityWasCreated
{
}
// This event is not handled, so it has no effect in the state of the entity
class FooWasChanged
{
}
| mit |
ARM-software/ComputeLibrary | tests/validation/NEON/DepthwiseConvolutionLayerNative.cpp | 9557 | /*
* Copyright (c) 2019-2021 Arm Limited.
*
* SPDX-License-Identifier: MIT
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include "src/cpu/kernels/CpuDepthwiseConv2dNativeKernel.h"
#include "tests/NEON/Accessor.h"
#include "tests/NEON/Helper.h"
#include "tests/framework/Macros.h"
#include "tests/framework/datasets/Datasets.h"
#include "tests/validation/Validation.h"
#include "tests/validation/fixtures/DepthwiseConvolutionLayerFixture.h"
namespace arm_compute
{
namespace test
{
namespace validation
{
using namespace arm_compute::misc::shape_calculator;
// Create function for CpuDepthwiseConvolutionKernel
using CpuDepthwiseConvolutionNative = NESynthetizeFunctionWithZeroConstantKernelBorder<cpu::kernels::CpuDepthwiseConv2dNativeKernel>;
// Fixture for NEDepthwiseConvolutionLayerKernel
template <typename T>
using CpuDepthwiseConvolutionNativeFixture = DepthwiseConvolutionLayerNativeValidationFixture<Tensor, Accessor, CpuDepthwiseConvolutionNative, T>;
namespace
{
// *INDENT-OFF*
// clang-format off
RelativeTolerance<float> rel_tolerance_f32(0.001f);
constexpr float abs_tolerance_f32(0.0001f);
/** Width values to test - Precommit */
const auto width_values_precommit = framework::dataset::make("width", { 17U } );
/** Width values to test - Nightly */
const auto width_values_nightly = framework::dataset::make("width", { 53U, 47U } );
/** Height values to test - Precommit */
const auto height_values_precommit = framework::dataset::make("height", { 19U } );
/** Height values to test - Nightly */
const auto height_values_nightly = framework::dataset::make("height", { 39U, 43U } );
/** Channel values to test - Precommit */
const auto channel_values_precommit = framework::dataset::make("channels", { 15U });
/** Channel values to test - Nightly */
const auto channel_values_nightly = framework::dataset::make("channels", { 33U, 19U });
/** Batch values to test - Precommit */
const auto batch_values_precommit = framework::dataset::make("batch", { 1U, 2U });
/** Batch values to test - Nightly */
const auto batch_values_nightly = framework::dataset::make("batch", { 1U, 3U });
/** Kernel size values to test - Precommit */
const auto kernel_sz_values_precommit = framework::dataset::make("kernel_size", { Size2D(1U, 1U), Size2D(1U, 3U) });
/** Kernel size values to test - Nightly */
const auto kernel_sz_values_nightly = framework::dataset::make("kernel_size", { Size2D(3U, 5U), Size2D(5U, 1U), Size2D(1U, 7U), Size2D(9U, 7U) });
/** Depth multiplier values to test - All */
const auto depth_multiplier_values = framework::dataset::make("depth_multiplier", { 1U, 3U });
/** Dilation values to test - All */
const auto dilation_values = framework::dataset::make("dilation", { Size2D(1U, 1U), Size2D(3U, 3U) });
/** Stride values to test - All */
const auto stride_values = framework::dataset::make("stride", { Size2D(1U, 1U), Size2D(3U, 2U) });
/** Padding values to test - All */
const auto padding_valid_values = framework::dataset::make("padding_valid", { true, false });
/** Data type values to test - All */
const auto data_type_values = framework::dataset::make("data_type", { DataType::F32 });
/** Data layout values to test - All */
const auto data_layout_values = framework::dataset::make("data_layout", { DataLayout::NHWC });
} // namespace
TEST_SUITE(NEON)
TEST_SUITE(DepthwiseConvolutionLayerNative)
TEST_CASE(ValidateNoPadding, framework::DatasetMode::ALL)
{
// this test case will ensure that the kernel is not adding implicit padding
constexpr uint32_t vector_size = 8; // Asummed vector size of the current native kernel
constexpr auto depth = vector_size * 2 + 1; // mis-aligned depth to force padding if exists.
constexpr auto data_layout = DataLayout::NHWC;
constexpr auto data_type = DataType::F32;
const auto input_size = Size2D{ 100, 100 }; // random plane size of the input
const auto kernel_size = Size2D{ 4, 4 }; // random plane size of the kernel
const auto pad_stride_info = PadStrideInfo(3, 3); // random convolution information to
TensorShape src_shape{ depth, input_size.x(), input_size.y() };
TensorShape weights_shape{ depth, kernel_size.x(), kernel_size.y() };
TensorShape bias_shape{ depth };
auto src = create_tensor<Tensor>(src_shape, data_type, 1, QuantizationInfo(), data_layout);
auto weights = create_tensor<Tensor>(weights_shape, data_type, 1, QuantizationInfo(), data_layout);
auto biases = create_tensor<Tensor>(bias_shape, data_type, 1, QuantizationInfo(), data_layout);
auto dst = create_tensor<Tensor>(TensorShape(), data_type, 1, QuantizationInfo(), data_layout);
cpu::kernels::CpuDepthwiseConv2dNativeKernel dwc;
const ConvolutionInfo info{pad_stride_info, 1, ActivationLayerInfo(), Size2D(1, 1)};
dwc.configure(src.info(), weights.info(), biases.info(), dst.info(), info);
ARM_COMPUTE_EXPECT(src.info()->padding().empty(), framework::LogLevel::ERRORS);
ARM_COMPUTE_EXPECT(weights.info()->padding().empty(), framework::LogLevel::ERRORS);
ARM_COMPUTE_EXPECT(biases.info()->padding().empty(), framework::LogLevel::ERRORS);
ARM_COMPUTE_EXPECT(dst.info()->padding().empty(), framework::LogLevel::ERRORS);
}
TEST_SUITE(Float)
TEST_SUITE(FP32)
FIXTURE_DATA_TEST_CASE_NEW(RunSmall, CpuDepthwiseConvolutionNativeFixture<float>, framework::DatasetMode::ALL,
combine(combine(combine(combine(combine(combine(combine(combine(combine(combine(width_values_precommit,
height_values_precommit),
channel_values_precommit),
batch_values_precommit),
kernel_sz_values_precommit),
depth_multiplier_values),
dilation_values),
stride_values),
padding_valid_values),
data_type_values),
data_layout_values))
{
// Validate output
validate(Accessor(_target), _reference, rel_tolerance_f32, 0.f, abs_tolerance_f32);
}
FIXTURE_DATA_TEST_CASE_NEW(RunLarge, CpuDepthwiseConvolutionNativeFixture<float>, framework::DatasetMode::NIGHTLY,
combine(combine(combine(combine(combine(combine(combine(combine(combine(combine(width_values_nightly,
height_values_nightly),
channel_values_nightly),
batch_values_nightly),
kernel_sz_values_nightly),
depth_multiplier_values),
dilation_values),
stride_values),
padding_valid_values),
data_type_values),
data_layout_values))
{
// Validate output
validate(Accessor(_target), _reference, rel_tolerance_f32, 0.f, abs_tolerance_f32);
}
TEST_SUITE_END() // FP32
TEST_SUITE_END() // Float
TEST_SUITE_END() // DepthwiseConvolutionLayerNative
TEST_SUITE_END() // Neon
} // namespace validation
} // namespace test
} // namespace arm_compute
| mit |
EthanR/HaloSharp | Source/HaloSharp.Test/Config.cs | 5823 | namespace HaloSharp.Test
{
public static class Config
{
public const string CampaignMissionsJsonPath = "JSON/Metadata/campaign-missions.json";
public const string CampaignMissionsJsonSchemaPath = "JSON/Metadata/campaign-missions.schema.json";
public const string CommendationJsonPath = "JSON/Metadata/commendations.json";
public const string CommendationJsonSchemaPath = "JSON/Metadata/commendations.schema.json";
public const string CompetitiveSkillRankDesignationsJsonPath = "JSON/Metadata/competitive-skill-rank-designations.json";
public const string CompetitiveSkillRankDesignationsJsonSchemaPath = "JSON/Metadata/competitive-skill-rank-designations.schema.json";
public const string EnemyJsonPath = "JSON/Metadata/enemies.json";
public const string EnemyJsonSchemaPath = "JSON/Metadata/enemies.schema.json";
public const string FlexibleStatJsonPath = "JSON/Metadata/flexible-stats.json";
public const string FlexibleStatJsonSchemaPath = "JSON/Metadata/flexible-stats.schema.json";
public const string GameBaseVariantJsonPath = "JSON/Metadata/game-base-variants.json";
public const string GameBaseVariantJsonSchemaPath = "JSON/Metadata/game-base-variants.schema.json";
public const string GameVariantJsonPath = "JSON/Metadata/game-variant.json";
public const string GameVariantJsonSchemaPath = "JSON/Metadata/game-variant.schema.json";
public const string ImpulseJsonPath = "JSON/Metadata/impulses.json";
public const string ImpulseJsonSchemaPath = "JSON/Metadata/impulses.schema.json";
public const string MapJsonPath = "JSON/Metadata/maps.json";
public const string MapJsonSchemaPath = "JSON/Metadata/maps.schema.json";
public const string MapVariantJsonPath = "JSON/Metadata/map-variant.json";
public const string MapVariantJsonSchemaPath = "JSON/Metadata/map-variant.schema.json";
public const string MedalJsonPath = "JSON/Metadata/medals.json";
public const string MedalJsonSchemaPath = "JSON/Metadata/medals.schema.json";
public const string PlaylistJsonPath = "JSON/Metadata/playlists.json";
public const string PlaylistJsonSchemaPath = "JSON/Metadata/playlists.schema.json";
public const string RequisitionJsonPath = "JSON/Metadata/requisition.json";
public const string RequisitionJsonSchemaPath = "JSON/Metadata/requisition.schema.json";
public const string RequisitionPackJsonPath = "JSON/Metadata/requisition-pack.json";
public const string RequisitionPackJsonSchemaPath = "JSON/Metadata/requisition-pack.schema.json";
public const string SeasonsJsonPath = "JSON/Metadata/seasons.json";
public const string SeasonsJsonSchemaPath = "JSON/Metadata/seasons.schema.json";
public const string SkullsJsonPath = "JSON/Metadata/skulls.json";
public const string SkullsJsonSchemaPath = "JSON/Metadata/skulls.schema.json";
public const string SpartanRanksJsonPath = "JSON/Metadata/spartan-ranks.json";
public const string SpartanRanksJsonSchemaPath = "JSON/Metadata/spartan-ranks.schema.json";
public const string TeamColorsJsonPath = "JSON/Metadata/team-colors.json";
public const string TeamColorsJsonSchemaPath = "JSON/Metadata/team-colors.schema.json";
public const string VehiclesJsonPath = "JSON/Metadata/vehicles.json";
public const string VehiclesJsonSchemaPath = "JSON/Metadata/vehicles.schema.json";
public const string WeaponsJsonPath = "JSON/Metadata/weapons.json";
public const string WeaponsJsonSchemaPath = "JSON/Metadata/weapons.schema.json";
public const string ArenaMatchJsonPath = "JSON/Stats/CarnageReport/arena-match.json";
public const string ArenaMatchJsonSchemaPath = "JSON/Stats/CarnageReport/arena-match.schema.json";
public const string CampaignMatchJsonPath = "JSON/Stats/CarnageReport/campaign-match.json";
public const string CampaignMatchJsonSchemaPath = "JSON/Stats/CarnageReport/campaign-match.schema.json";
public const string CustomMatchJsonPath = "JSON/Stats/CarnageReport/custom-match.json";
public const string CustomMatchJsonSchemaPath = "JSON/Stats/CarnageReport/custom-match.schema.json";
public const string WarzoneMatchJsonPath = "JSON/Stats/CarnageReport/warzone-match.json";
public const string WarzoneMatchJsonSchemaPath = "JSON/Stats/CarnageReport/warzone-match.schema.json";
public const string MatchEventsJsonPath = "JSON/Stats/CarnageReport/match-events.json";
public const string MatchEventsJsonSchemaPath = "JSON/Stats/CarnageReport/match-events.schema.json";
public const string ArenaServiceRecordJsonPath = "JSON/Stats/Lifetime/arena-service-record.json";
public const string ArenaServiceRecordJsonSchemaPath = "JSON/Stats/Lifetime/arena-service-record.schema.json";
public const string CampaignServiceRecordJsonPath = "JSON/Stats/Lifetime/campaign-service-record.json";
public const string CampaignServiceRecordJsonSchemaPath = "JSON/Stats/Lifetime/campaign-service-record.schema.json";
public const string CustomServiceRecordJsonPath = "JSON/Stats/Lifetime/custom-service-record.json";
public const string CustomServiceRecordJsonSchemaPath = "JSON/Stats/Lifetime/custom-service-record.schema.json";
public const string WarzoneServiceRecordJsonPath = "JSON/Stats/Lifetime/warzone-service-record.json";
public const string WarzoneServiceRecordJsonSchemaPath = "JSON/Stats/Lifetime/warzone-service-record.schema.json";
public const string MatchesJsonPath = "JSON/Stats/matches.json";
public const string MatchesJsonSchemaPath = "JSON/Stats/matches.schema.json";
}
} | mit |
notjrbauer/iterable-json-schema | common/unsubscriber.js | 175 | module.exports = {
type: 'object',
properties: {
email: {
type: 'string',
format: 'email',
required: true
}
},
additionalProperties: false
}
| mit |
re222dv/1DV402-C-sharp | 1DV402.S2.L3C/Properties/AssemblyInfo.cs | 1420 | 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("1DV402.S2.L3C")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("1DV402.S2.L3C")]
[assembly: AssemblyCopyright("Copyright © Microsoft 2013")]
[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("c9672388-c2bb-4bb5-85d0-fb14cc35dee3")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| mit |
costassarris/Javabuzz | src/Fizzbuzz.js | 674 | function Fizzbuzz() {
};
Fizzbuzz.prototype._isDivisibleBy = function (number, divisor){
return (number % divisor === 0);
};
Fizzbuzz.prototype.isDivisibleByThree = function(number) {
return this._isDivisibleBy(number, 3);
};
Fizzbuzz.prototype.isDivisibleByFive = function(number) {
return this._isDivisibleBy(number, 5);
};
Fizzbuzz.prototype.isDivisibleByFifteen = function(number) {
return this._isDivisibleBy(number, 15);
};
Fizzbuzz.prototype.says = function(number) {
if (this.isDivisibleByFifteen(number)) return "FizzBuzz";
if (this.isDivisibleByThree(number)) return "Fizz";
if (this.isDivisibleByFive(number)) return "Buzz";
return number;
}; | mit |
Ravenheart/driversolutions | DriverSolutions.BOL/Managers/ModuleDriver/IDriverCatalogManager.cs | 722 | using DriverSolutions.BOL.Models.ModuleDriver;
using DriverSolutions.BOL.Models.ModuleSystem;
using DriverSolutions.DAL;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DriverSolutions.BOL.Managers.ModuleDriver
{
public interface IDriverCatalogManager
{
bool IsFinder { get; set; }
DriverFilterModel Filter { get; set; }
BindingList<DriverModel> Drivers { get; set; }
DriverModel ActiveDriver { get; set; }
void RefreshDrivers();
void ClearFilter();
List<UtilityModel<uint>> GetLicenses();
List<UtilityModel<uint>> GetPermits();
}
}
| mit |
Aux/NTwitch | src/NTwitch.Core/TwitchConfig.cs | 1218 | using System.Reflection;
namespace NTwitch
{
public class TwitchConfig
{
public static string Version { get; } =
typeof(TwitchConfig).GetTypeInfo().Assembly.GetCustomAttribute<AssemblyInformationalVersionAttribute>()?.InformationalVersion ??
typeof(TwitchConfig).GetTypeInfo().Assembly.GetName().Version.ToString(3) ??
"Unknown";
public static string UserAgent { get; } = $"NTwitchApp (https://github.com/Aux/NTwitch, v{Version})";
public static readonly string DefaultApiUrl = "https://api.twitch.tv/kraken/";
public static readonly string DefaultChatUrl = "irc.chat.twitch.tv";
public static readonly string EmoteCdnUrl = "static-cdn.jtvnw.net";
public const int APIVersion = 5;
public const int DefaultRequestTimeout = 15000;
/// <summary> Gets or sets the provider used to cache entities. </summary>
public CacheClientProvider CacheClientProvider { get; set; } = DefaultCacheClientProvider.Instance;
/// <summary> Gets or sets the minimum log level severity that will be sent to the Log event. </summary>
public LogSeverity LogLevel { get; set; } = LogSeverity.Info;
}
}
| mit |
Exrik/tabell | www-src/scripts/reducers/users.js | 2177 | 'use strict';
const initialState = {
error: false,
loading: false,
data: {},
highscore: []
};
function users(state = initialState, action) {
const newState = JSON.parse(JSON.stringify(state));
switch (action.type) {
case 'USERS_REQUEST':
newState.loading = true;
newState.error = false;
break;
// Not in use atm, but we might want a way to list all users eventually?
case 'USERS_RECEIVED': {
const users = action.payload;
users.forEach(function(user) {
// Add the newly fetched to our store unless we already have them
if (!newState.data[user._id]) {
newState.data[user._id] = user;
}
});
newState.error = false;
newState.loading = false;
break;
}
case 'HIGHSCORE_RECEIVED':
newState.highscore = action.payload;
newState.error = false;
newState.loading = false;
break;
// Store a reference to the placed bet in the user object
case 'BET_PLACED': {
const bet = action.payload;
const user = newState.data[bet.user._id._id] || {};
const userBetIds = user.betIds || [];
userBetIds.push(bet._id);
break;
}
// Delete reference when bet is deleted
case 'BET_DELETED': {
const bet = action.payload;
const user = newState.data[bet.user._id._id] || {};
const userBetIds = user.betIds || [];
const betIndex = userBetIds.indexOf(bet._id);
if (betIndex > -1) {
userBetIds.splice(betIndex, 1);
}
break;
}
case 'FULLUSER_RECEIVED': {
const user = action.user;
newState.data[user._id] = user;
newState.error = false;
break;
}
case 'USER_ERROR': {
newState.error = action.error;
break;
}
default:
break;
}
return newState;
}
export default users;
| mit |
bleeding182/localized-screenshots | app/src/main/java/at/bleeding182/testing/instrumentationtest/modules/RandomModule.java | 1507 | /*
* The MIT License (MIT)
*
* Copyright (c) 2015 David Medenjak
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package at.bleeding182.testing.instrumentationtest.modules;
import java.util.Random;
import javax.inject.Named;
import dagger.Module;
import dagger.Provides;
/**
* @author David Medenjak on 12.12.2015.
*/
@Module
public class RandomModule {
@Named("random")
@Provides
int provideRandomInt() {
return new Random().nextInt();
}
}
| mit |
TheNoobCompany/NoWhere | HelloWorld.cpp | 101 | #include <iostream>
int main()
{
std::cout << "Hello, new world!" << std::endl;
return 0;
} | mit |
mrmans0n/smart-adapters | sample/src/main/java/io/nlopez/smartadapters/sample/view/PlaceView.java | 1486 | package io.nlopez.smartadapters.sample.view;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.squareup.picasso.Picasso;
import butterknife.ButterKnife;
import butterknife.InjectView;
import io.nlopez.smartadapters.sample.R;
import io.nlopez.smartadapters.sample.model.Place;
import io.nlopez.smartadapters.sample.util.Interactions;
import io.nlopez.smartadapters.views.BindableFrameLayout;
/**
* Created by mrm on 24/5/15.
*/
public class PlaceView extends BindableFrameLayout<Place> {
@InjectView(R.id.place_image)
ImageView placeImage;
@InjectView(R.id.place_text)
TextView placeText;
public PlaceView(Context context) {
super(context);
}
@Override
public int getLayoutId() {
return R.layout.view_place;
}
@Override
public void onViewInflated() {
ButterKnife.inject(this);
setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
}
@Override
public void bind(Place item) {
placeText.setText(item.getName());
Picasso.with(getContext()).load(item.getImageUrl()).into(placeImage);
setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
notifyItemAction(Interactions.PLACE_CLICKED);
}
});
}
}
| mit |
idlamane/ahgh | src/Amb/ContratBundle/Entity/Contrat.php | 6577 | <?php
namespace Amb\ContratBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
use Gedmo\Mapping\Annotation as Gedmo;
/**
* Amb\ContratBundle\Entity\Contrat
*
* @ORM\Table()
* @ORM\Entity(repositoryClass="Amb\ContratBundle\Entity\ContratRepository")
*/
class Contrat
{
/**
* @var integer $id
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @var integer $reference
*
* @ORM\Column(name="reference", type="string", length=255, nullable=true)
*
*/
private $reference;
/**
* @var \DateTime $date_debut
*
* @ORM\Column(name="date_debut", type="date", nullable=true)
*/
private $date_debut;
/**
* @var integer $montant
*
* @ORM\Column(name="montant", type="float")
* @Assert\NotBlank()
*/
private $montant;
/**
* @var string $commentaire
*
* @ORM\Column(name="commentaire", type="text", nullable=true)
*/
private $commentaire;
/**
* @var \DateTime $date_resiliation
*
* @ORM\Column(name="date_resiliation", type="date", nullable=true)
*/
private $date_resiliation;
/**
* @ORM\ManyToOne(targetEntity="Amb\DebitBundle\Entity\Fournisseur", inversedBy="contrats")
* @ORM\JoinColumn(onDelete="CASCADE", nullable=true)
*/
private $fournisseur;
/**
* @ORM\OneToMany(targetEntity="Amb\DebitBundle\Entity\Depense", mappedBy="contrat")
*/
private $depenses;
/**
* @var \DateTime $created_at
* @Gedmo\Timestampable(on="create")
* @ORM\Column(name="created_at", type="datetime", nullable=true)
*/
private $created_at;
/**
* @var \DateTime $updated_at
* @Gedmo\Timestampable(on="update")
* @ORM\Column(name="updated_at", type="datetime", nullable=true)
*/
private $updated_at;
/**
* Get id
*
* @return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set reference
*
* @param string $reference
* @return Contrat
*/
public function setReference($reference)
{
$this->reference = $reference;
return $this;
}
/**
* Get reference
*
* @return string
*/
public function getReference()
{
return $this->reference;
}
/**
* Set date_debut
*
* @param \DateTime $dateDebut
* @return Contrat
*/
public function setDateDebut($dateDebut)
{
$this->date_debut = $dateDebut;
return $this;
}
/**
* Get date_debut
*
* @return \DateTime
*/
public function getDateDebut()
{
return $this->date_debut;
}
/**
* Set montant
*
* @param float $montant
* @return Contrat
*/
public function setMontant($montant)
{
$this->montant = $montant;
return $this;
}
/**
* Get montant
*
* @return float
*/
public function getMontant()
{
return $this->montant;
}
/**
* Set commentaire
*
* @param string $commentaire
* @return Contrat
*/
public function setCommentaire($commentaire)
{
$this->commentaire = $commentaire;
return $this;
}
/**
* Get commentaire
*
* @return string
*/
public function getCommentaire()
{
return $this->commentaire;
}
/**
* Set date_resiliation
*
* @param \DateTime $dateResiliation
* @return Contrat
*/
public function setDateResiliation($dateResiliation)
{
$this->date_resiliation = $dateResiliation;
return $this;
}
/**
* Get date_resiliation
*
* @return \DateTime
*/
public function getDateResiliation()
{
return $this->date_resiliation;
}
/**
* Set fournisseur
*
* @param \Amb\DebitBundle\Entity\Fournisseur $fournisseur
* @return Contrat
*/
public function setFournisseur(\Amb\DebitBundle\Entity\Fournisseur $fournisseur = null)
{
$this->fournisseur = $fournisseur;
return $this;
}
/**
* Get fournisseur
*
* @return \Amb\DebitBundle\Entity\Fournisseur
*/
public function getFournisseur()
{
return $this->fournisseur;
}
/**
* Set created_at
*
* @param \DateTime $createdAt
* @return Contrat
*/
public function setCreatedAt($createdAt)
{
$this->created_at = $createdAt;
return $this;
}
/**
* Get created_at
*
* @return \DateTime
*/
public function getCreatedAt()
{
return $this->created_at;
}
/**
* Set updated_at
*
* @param \DateTime $updatedAt
* @return Contrat
*/
public function setUpdatedAt($updatedAt)
{
$this->updated_at = $updatedAt;
return $this;
}
/**
* Get updated_at
*
* @return \DateTime
*/
public function getUpdatedAt()
{
return $this->updated_at;
}
/**
* Constructor
*/
public function __construct()
{
$this->depenses = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* Add depenses
*
* @param \Amb\DebitBundle\Entity\Depense $depenses
* @return Contrat
*/
public function addDepense(\Amb\DebitBundle\Entity\Depense $depenses)
{
$this->depenses[] = $depenses;
$depenses->setContrat($this);
return $this;
}
/**
* Remove depenses
*
* @param \Amb\DebitBundle\Entity\Depense $depenses
*/
public function removeDepense(\Amb\DebitBundle\Entity\Depense $depenses)
{
$this->depenses->removeElement($depenses);
}
/**
* Get depenses
*
* @return \Doctrine\Common\Collections\Collection
*/
public function getDepenses()
{
return $this->depenses;
}
} | mit |
zhwsh00/DirectFire-android | directfire_github/trunk/gameui/battle.net/herospage.cpp | 15152 | #include "herospage.h"
#include "herostitle.h"
#include "utils/sysutils.h"
#include "prop/propdef.h"
#include "gamecore/sounds/soundmgr.h"
#include "herositem.h"
#include "gamecore/utils/ccutils.h"
HerosPage::HerosPage(uilib::BasWidget *container) : BasPage(container)
{
m_serverIface = ServerInterface::getInstance();
m_id = m_serverIface->getLoginAccountInfo()->m_id;
m_title = new HerosTitle;
m_title->setTypeCB(this,callfuncND_selector(HerosPage::onSortTypeClicked));
m_title->setRefreshCB(this,callfuncND_selector(HerosPage::onRefreshClicked));
this->addChild(m_title);
float srate = getAdaptResourceScale();
m_title->setLeft("parent",uilib::Left);
m_title->setBottom("parent",uilib::Top);
m_title->setLeftMargin(20);
m_title->setRightMargin(20);
m_title->setWidth(610 * srate);
m_title->setHeight(92 * srate);
this->setTopMargin(30);
m_itemInit = false;
}
HerosPage::~HerosPage()
{
}
void HerosPage::moveinPage()
{
if(!m_itemInit){
init();
this->scheduleOnce(schedule_selector(HerosPage::startHerosInfo),0.5);
}
}
void HerosPage::moveoutPage()
{
}
void HerosPage::startGetHerosInfo()
{
if(m_title)
m_title->setRefreshing(true);
}
void HerosPage::endGetHerosInfo()
{
if(m_title)
m_title->setRefreshing(false);
}
void HerosPage::updateHeroInfo()
{
float width = m_anchorWidth * 0.94;
for(int i = UiMsgEv::HeroLevel;i <= UiMsgEv::HeroLose;i++){
const UiMsgEv::HerosInfo *heros = m_serverIface->getHerosDataByType((UiMsgEv::HerosType)i);
if(heros == 0)
continue;
VerScrollWidget *ver = m_cates[i - UiMsgEv::HeroLevel];
if(ver->scrollItemCount() != 0){
ver->delAllChild();
}
for(unsigned int k = 0;k < heros->m_heros.size();k++){
const UiMsgEv::HeroInfo &hero = heros->m_heros[k];
HerosItem *border = new HerosItem;
border->setId(hero.m_userId);
border->setWidth(width);
border->setHeight(100);
FSizeWidgetDelegate *itemDele = new FSizeWidgetDelegate(border,CCSizeMake(width,100));
ver->addFixedSizeWidget(itemDele);
fillItem(border,i,k+1,hero);
}
ver->setSpacing(20);
ver->layout(true);
ver->scrollToBegin(true);
}
}
void HerosPage::updateUserInfo()
{
float width = m_anchorWidth * 0.94;
UiMsgEv::AccountInfoEv *ev = m_serverIface->getLoginAccountInfo();
UiMsgEv::HeroInfo hero;
hero.m_userId = ev->m_id;
hero.m_userMail = ev->m_mail;
hero.m_nickName = ev->m_name;
UiMsgEv::PlayerInfoEv *playEv = m_serverIface->getPlayerInfoByUid(m_id);
hero.m_level = playEv->m_level;
hero.m_exp = playEv->m_exp;
hero.m_wonNum = playEv->m_wonNum;
hero.m_losedNum = playEv->m_losedNum;
hero.m_playedNum = playEv->m_playedNum;
hero.m_propCount = m_serverIface->getPropNumByUid(m_id,PropDef::Props_Gold);
const std::vector<UiMsgEv::UserRank> *ranks = m_serverIface->getUserRankInfo();
for(int i = 0;i < ranks->size();i++){
const UiMsgEv::UserRank &rank = ranks->at(i);
VerScrollWidget *ver = 0;
switch(rank.m_sortType){
case UiMsgEv::HeroLevel:{
ver = m_cates[0];
break;
}
case UiMsgEv::HeroGold:{
ver = m_cates[UiMsgEv::HeroGold - UiMsgEv::HeroLevel];
break;
}
case UiMsgEv::HeroPlayed:{
ver = m_cates[UiMsgEv::HeroPlayed - UiMsgEv::HeroLevel];
break;
}
case UiMsgEv::HeroWon:{
ver = m_cates[UiMsgEv::HeroWon - UiMsgEv::HeroLevel];
break;
}
case UiMsgEv::HeroLose:{
ver = m_cates[UiMsgEv::HeroLose - UiMsgEv::HeroLevel];
break;
}
default:{
break;
}
}
if(ver == 0)
continue;
int scrollCount = ver->scrollItemCount();
if(scrollCount == 0){
continue;
}else if(scrollCount >= rank.m_sortNum){
continue;
}
HerosItem *etcitem = new HerosItem;
etcitem->setTheme("","");
etcitem->setWidth(width);
etcitem->setHeight(100);
FSizeWidgetDelegate *itemDele = new FSizeWidgetDelegate(etcitem);
ver->addFixedSizeWidget(itemDele);
CCSprite *etcsprite = CCSprite::createWithSpriteFrameName("veretc.png");
FSizeCCNodeDelegate *etcdele = new FSizeCCNodeDelegate(etcsprite);
etcitem->addChild(etcdele);
etcdele->setCenterIn("parent");
HerosItem *userItem = new HerosItem;
userItem->setWidth(width);
userItem->setHeight(100);
FSizeWidgetDelegate *userDele = new FSizeWidgetDelegate(userItem);
ver->addFixedSizeWidget(userDele);
fillItem(userItem,rank.m_sortType,rank.m_sortNum,hero);
ver->layout(true);
}
}
void HerosPage::startHerosInfo(float dt)
{
m_serverIface->getAllHeros();
m_serverIface->getUserAllRank();
}
void HerosPage::init(int dummy)
{
if(m_itemInit)
return;
for(int i = UiMsgEv::HeroLevel;i <= UiMsgEv::HeroLose;i++){
VerScrollWidget *ver = new VerScrollWidget;
this->addChild(ver);
ver->setVerticalScrollPolicy(ScrollShow_Need);
ver->setHorizontalScrollPolicy(ScrollShow_Never);
ver->setLeft("parent",uilib::Left);
ver->setRight("parent",uilib::Right);
ver->setTop("parent",uilib::Top);
ver->setTopMargin(20);
ver->setBottom("parent",uilib::Bottom);
ver->setVisible(false);
m_cates.push_back(ver);
}
this->layout(true);
m_itemInit = true;
m_currIndex = 0;
m_cates[m_currIndex]->setVisible(true);
m_title->setSelectIndex(m_currIndex + (int)UiMsgEv::HeroLevel);
}
void HerosPage::onRefreshClicked(CCNode *node,void *data)
{
SoundMgr::getInstance()->playEffect(SoundEnum::BTN_EFFECT_NORMAL);
if(m_title->isRefreshing()){
return;
}else{
m_serverIface->getAllHeros();
m_serverIface->getUserAllRank();
m_title->setRefreshing(true);
}
}
void HerosPage::onSortTypeClicked(CCNode *node,void *data)
{
SoundMgr::getInstance()->playEffect(SoundEnum::BTN_EFFECT_NORMAL);
int index = *(int*)data - (int)UiMsgEv::HeroLevel;
if(m_currIndex == index){
m_title->setSelectIndex(*(int*)data);
return;
}
m_cates[m_currIndex]->setVisible(false);
m_cates[index]->setVisible(true);
m_currIndex = index;
m_title->setSelectIndex(*(int*)data);
}
void HerosPage::fillItem(BasWidget *parent,int type,int sortnum,const UiMsgEv::HeroInfo &hero)
{
switch(type){
case UiMsgEv::HeroLevel:{
fillLevelItem(parent,sortnum,hero);
break;
}
case UiMsgEv::HeroGold:{
fillGoldItem(parent,sortnum,hero);
break;
}
case UiMsgEv::HeroPlayed:{
fillPlayedItem(parent,sortnum,hero);
break;
}
case UiMsgEv::HeroWon:{
fillWonItem(parent,sortnum,hero);
break;
}
case UiMsgEv::HeroLose:{
fillLoseItem(parent,sortnum,hero);
break;
}
default:{
break;
}
}
}
void HerosPage::fillLevelItem(BasWidget *parent,int sortnum,const UiMsgEv::HeroInfo &hero)
{
fillItemSortNum(parent,sortnum,m_id == hero.m_userId);
std::string name = hero.m_nickName;
if(name.empty()){
mailToNickName(hero.m_userMail,name);
}
if(name.empty()){
name = hero.m_userId;
}
fillItemPlayerName(parent,name,m_id == hero.m_userId);
ss.str("");ss << "medal" << hero.m_level << ".png";
CCSpriteFrame *frame = CCSpriteFrameCache::sharedSpriteFrameCache()->spriteFrameByName(ss.str().data());
if(frame){
CCSprite *medal = CCSprite::createWithSpriteFrame(frame);
FSizeCCNodeDelegate *medalDele = new FSizeCCNodeDelegate(medal);
parent->addChild(medalDele);
medalDele->setCenterIn("parent");
ss.str("");ss << "Level" << hero.m_level;
CCLabelBMFont *level = CCLabelBMFont::create(ss.str().data(),"fonts/uifont24.fnt");
FSizeCCNodeDelegate *levelDele = new FSizeCCNodeDelegate(level);
parent->addChild(levelDele);
levelDele->setLeft(medalDele->getName(),uilib::Right);
levelDele->setVertical("parent",0.5);
}else{
CCSprite *medal = CCSprite::createWithSpriteFrameName("medal2.png");
FSizeCCNodeDelegate *medalDele = new FSizeCCNodeDelegate(medal);
parent->addChild(medalDele);
medalDele->setCenterIn("parent");
medalDele->setVisible(false);
ss.str("");ss << "Level" << hero.m_level;
CCLabelBMFont *level = CCLabelBMFont::create(ss.str().data(),"fonts/uifont24.fnt");
FSizeCCNodeDelegate *levelDele = new FSizeCCNodeDelegate(level);
parent->addChild(levelDele);
levelDele->setLeft(medalDele->getName(),uilib::Right);
levelDele->setVertical("parent",0.5);
}
float wrate = 1.0 * hero.m_wonNum / hero.m_playedNum;
int wonrate = (int)(wrate*100);
fillItemWonRate(parent,wonrate);
}
void HerosPage::fillGoldItem(BasWidget *parent,int sortnum,const UiMsgEv::HeroInfo &hero)
{
fillItemSortNum(parent,sortnum,m_id == hero.m_userId);
std::string name = hero.m_nickName;
if(name.empty()){
mailToNickName(hero.m_userMail,name);
}
if(name.empty()){
name = hero.m_userId;
}
fillItemPlayerName(parent,name,m_id == hero.m_userId);
std::string goldName;
PropDef::getVirtualPropsName(PropDef::Props_Gold,goldName);
goldName += ".png";
CCSprite *goldSprite = CCSprite::createWithSpriteFrameName(goldName.data());
FSizeCCNodeDelegate *goldDele = new FSizeCCNodeDelegate(goldSprite,CCSizeMake(40,40));
parent->addChild(goldDele);
goldDele->setCenterIn("parent");
ss.str("");ss << hero.m_propCount;
CCLabelBMFont *numSprite = CCLabelBMFont::create(ss.str().data(),"fonts/uifont24.fnt");
FSizeCCNodeDelegate *numDele = new FSizeCCNodeDelegate(numSprite);
parent->addChild(numDele);
numDele->setLeftMargin(5);
numDele->setLeft(goldDele->getName(),uilib::Right);
numDele->setVertical("parent",0.5);
float wrate = 1.0 * hero.m_wonNum / hero.m_playedNum;
int wonrate = (int)(wrate*100);
fillItemWonRate(parent,wonrate);
}
void HerosPage::fillPlayedItem(BasWidget *parent,int sortnum,const UiMsgEv::HeroInfo &hero)
{
fillItemSortNum(parent,sortnum,m_id == hero.m_userId);
std::string name = hero.m_nickName;
if(name.empty()){
mailToNickName(hero.m_userMail,name);
}
if(name.empty()){
name = hero.m_userId;
}
fillItemPlayerName(parent,name,m_id == hero.m_userId);
CCSprite *playedSprite = CCSprite::createWithSpriteFrameName("heroplayed.png");
FSizeCCNodeDelegate *playedDele = new FSizeCCNodeDelegate(playedSprite,CCSizeMake(40,40));
parent->addChild(playedDele);
playedDele->setCenterIn("parent");
ss.str("");ss << hero.m_playedNum;
CCLabelBMFont *numSprite = CCLabelBMFont::create(ss.str().data(),"fonts/uifont24.fnt");
FSizeCCNodeDelegate *numDele = new FSizeCCNodeDelegate(numSprite);
parent->addChild(numDele);
numDele->setLeft(playedDele->getName(),uilib::Right);
numDele->setLeftMargin(5);
numDele->setVertical("parent",0.5);
float wrate = 1.0 * hero.m_wonNum / hero.m_playedNum;
int wonrate = (int)(wrate*100);
fillItemWonRate(parent,wonrate);
}
void HerosPage::fillWonItem(BasWidget *parent,int sortnum,const UiMsgEv::HeroInfo &hero)
{
fillItemSortNum(parent,sortnum,m_id == hero.m_userId);
std::string name = hero.m_nickName;
if(name.empty()){
mailToNickName(hero.m_userMail,name);
}
if(name.empty()){
name = hero.m_userId;
}
fillItemPlayerName(parent,name,m_id == hero.m_userId);
CCSprite *wonSprite = CCSprite::createWithSpriteFrameName("herowin.png");
FSizeCCNodeDelegate *wonDele = new FSizeCCNodeDelegate(wonSprite,CCSizeMake(40,40));
parent->addChild(wonDele);
wonDele->setCenterIn("parent");
ss.str("");ss << hero.m_wonNum;
CCLabelBMFont *numSprite = CCLabelBMFont::create(ss.str().data(),"fonts/uifont24.fnt");
FSizeCCNodeDelegate *numDele = new FSizeCCNodeDelegate(numSprite);
parent->addChild(numDele);
numDele->setLeft(wonDele->getName(),uilib::Right);
numDele->setLeftMargin(5);
numDele->setVertical("parent",0.5);
float wrate = 1.0 * hero.m_wonNum / hero.m_playedNum;
int wonrate = (int)(wrate*100);
fillItemWonRate(parent,wonrate);
}
void HerosPage::fillLoseItem(BasWidget *parent,int sortnum,const UiMsgEv::HeroInfo &hero)
{
fillItemSortNum(parent,sortnum,m_id == hero.m_userId);
std::string name = hero.m_nickName;
if(name.empty()){
mailToNickName(hero.m_userMail,name);
}
if(name.empty()){
name = hero.m_userId;
}
fillItemPlayerName(parent,name,m_id == hero.m_userId);
CCSprite *loseSprite = CCSprite::createWithSpriteFrameName("herolose.png");
FSizeCCNodeDelegate *loseDele = new FSizeCCNodeDelegate(loseSprite,CCSizeMake(40,40));
parent->addChild(loseDele);
loseDele->setCenterIn("parent");
ss.str("");ss << hero.m_losedNum;
CCLabelBMFont *numSprite = CCLabelBMFont::create(ss.str().data(),"fonts/uifont24.fnt");
FSizeCCNodeDelegate *numDele = new FSizeCCNodeDelegate(numSprite);
parent->addChild(numDele);
numDele->setLeft(loseDele->getName(),uilib::Right);
numDele->setLeftMargin(5);
numDele->setVertical("parent",0.5);
float wrate = 1.0 * hero.m_wonNum / hero.m_playedNum;
int wonrate = (int)(wrate*100);
fillItemWonRate(parent,wonrate);
}
void HerosPage::fillItemSortNum(BasWidget *parent,int sortnum,bool isSelf)
{
std::stringstream ss;
ss.str("");ss << sortnum;
CCLabelBMFont *sortLabel = CCLabelBMFont::create(ss.str().data(),"fonts/uifont35.fnt");
FSizeCCNodeDelegate *sortDele = new FSizeCCNodeDelegate(sortLabel,CCSizeMake(40,40));
parent->addChild(sortDele);
sortDele->setLeft("parent",uilib::Left);
sortDele->setLeftMargin(15);
sortDele->setVertical("parent",0.5);
if(isSelf)
sortDele->setScale(2);
}
void HerosPage::fillItemPlayerName(BasWidget *parent,const std::string &name,bool isSelf)
{
CCLabelBMFont *nameFont = CCLabelBMFont::create(name.data(),"fonts/uifont24.fnt");
if(isSelf)
nameFont->setColor(ccGREEN);
FSizeCCNodeDelegate *nameDele = new FSizeCCNodeDelegate(nameFont);
parent->addChild(nameDele);
nameDele->setVertical("parent",0.5);
nameDele->setHorizontal("parent",0.3);
}
void HerosPage::fillItemWonRate(BasWidget *parent,int wonrate)
{
if(wonrate > 100 || wonrate < 0){
wonrate = 0;
}
ss.str("");ss << wonrate << "%";
CCLabelBMFont *wonSprite = CCLabelBMFont::create(ss.str().data(),"fonts/uifont35.fnt");
FSizeCCNodeDelegate *wonDele = new FSizeCCNodeDelegate(wonSprite);
parent->addChild(wonDele);
wonDele->setRight("parent",uilib::Right);
wonDele->setRightMargin(15);
wonDele->setVertical("parent",0.5);
}
| mit |
shooterman/ideasbulb | db/migrate/20111122074919_create_users_favor_ideas.rb | 246 | class CreateUsersFavorIdeas < ActiveRecord::Migration
def change
create_table :favors do |t|
t.integer :user_id
t.integer :idea_id
t.timestamps
end
add_index :favors,[:user_id,:idea_id],:unique => true
end
end
| mit |
velialarm/PHP-and-MySQL | 18-PHP from scratch/controllers/albums.php | 86 | <?php
namespace Controllers;
class Albums_Controller extends Master_Controller {
} | mit |
Baddum/Factory418 | test/bootstrap.php | 266 | <?php
$composerAutoloadFilePathList = [
__DIR__.'/../vendor/autoload.php',
__DIR__.'/../../../autoload.php',
];
foreach ($composerAutoloadFilePathList as $filePath) {
if (file_exists($filePath)) {
require_once $filePath;
break;
}
}
| mit |
ajbrzoz/Head-First-Design-Patterns | strategy/main.py | 338 | # STRATEGY pattern
from ducks import MallardDuck, ModelDuck
from fly_behaviours import FlyRocketPowered
if __name__ == "__main__":
mallard = MallardDuck()
mallard.perform_quack()
mallard.perform_fly()
model = ModelDuck()
model.perform_fly()
model.set_fly_behaviour(FlyRocketPowered())
model.perform_fly()
| mit |
SanguPackage/TWTactics | TribalWars/Maps/Publisher.cs | 7910 | #region Using
using System;
using System.Collections.Generic;
using System.ComponentModel;
using TribalWars.Browsers.Reporting;
using TribalWars.Maps.AttackPlans;
using TribalWars.Maps.AttackPlans.EventArg;
using TribalWars.Maps.Manipulators;
using TribalWars.Maps.Manipulators.Implementations;
using TribalWars.Maps.Manipulators.Implementations.Church;
using TribalWars.Maps.Polygons;
using TribalWars.Villages;
using TribalWars.Worlds;
using TribalWars.Worlds.Events;
using TribalWars.Worlds.Events.Impls;
#endregion
namespace TribalWars.Maps
{
/// <summary>
/// Raises events for a specific map
/// </summary>
public class Publisher
{
#region Fields
private readonly Map _map;
#endregion
#region Events
public event EventHandler<EventArgs> VillagesDeselected;
public event EventHandler<VillagesEventArgs> VillagesSelected;
public event EventHandler<PlayerEventArgs> PlayerSelected;
public event EventHandler<TribeEventArgs> TribeSelected;
public event EventHandler<ReportEventArgs> ReportSelected;
public event EventHandler<PolygonEventArgs> PolygonActivated;
public event EventHandler<MapLocationEventArgs> LocationChanged;
public event EventHandler<ManipulatorEventArgs> ManipulatorChanged;
public event EventHandler<AttackEventArgs> TargetAdded;
public event EventHandler<AttackUpdateEventArgs> TargetUpdated;
public event EventHandler<AttackEventArgs> TargetRemoved;
public event EventHandler<AttackEventArgs> TargetSelected;
public event EventHandler<ChurchEventArgs> ChurchChanged;
#endregion
#region Constructors
public Publisher(Map map)
{
_map = map;
}
#endregion
#region Publish Methods
#region Church
public void ChurchChange(Village village, int level, bool redrawMaps = true)
{
if (ChurchChanged != null)
{
var church = _map.Manipulators.ChurchManipulator.GetChurch(village);
if (church == null)
{
church = new ChurchInfo(village, level);
}
else
{
church.ChurchLevel = level;
}
ChurchChanged(null, new ChurchEventArgs(church));
if (redrawMaps)
{
World.Default.DrawMaps(false);
}
}
}
#endregion
#region Selection Events
/// <summary>
/// Deselect villages previously selected with SelectVillages events
/// </summary>
public void Deselect(object sender)
{
if (VillagesDeselected != null)
{
VillagesDeselected(sender, EventArgs.Empty);
}
}
/// <summary>
/// Publishes an event for several villages
/// </summary>
public void SelectVillages(object sender, IEnumerable<Village> vil, VillageTools action)
{
if (VillagesSelected != null)
{
VillagesSelected(sender, new VillagesEventArgs(vil, action));
}
}
/// <summary>
/// Publishes an event for one village
/// </summary>
public void SelectVillages(object sender, Village village, VillageCommand action)
{
if (VillagesSelected != null)
VillagesSelected(sender, new VillagesEventArgs(village, action));
}
/// <summary>
/// Publishes an event for the villages of one player
/// </summary>
public void SelectVillages(object sender, Player ply, VillageTools action)
{
if (ply != null)
VillagesSelected(sender, new PlayerEventArgs(ply, action));
}
/// <summary>
/// Publishes an event for all the villages in one tribe
/// </summary>
public void SelectVillages(object sender, Tribe tribe, VillageTools action)
{
if (tribe != null)
VillagesSelected(sender, new TribeEventArgs(tribe, action));
}
/// <summary>
/// Publishes an event for one tribe
/// </summary>
public void SelectTribe(object sender, Tribe tribe, VillageTools tool)
{
if (TribeSelected != null)
{
TribeSelected(sender, new TribeEventArgs(tribe, tool));
}
}
/// <summary>
/// Publishes an event for one player
/// </summary>
public void SelectPlayer(object sender, Player player, VillageTools tool)
{
if (PlayerSelected != null)
{
PlayerSelected(sender, new PlayerEventArgs(player, tool));
}
}
/// <summary>
/// Publishes an event for a report
/// </summary>
public void SelectReport(object sender, Report report)
{
if (ReportSelected != null)
{
ReportSelected(sender, new ReportEventArgs(report));
}
}
#endregion
#region Attack Events
public void AttackAddTarget(object sender, Village village)
{
DateTime arrivalTime = World.Default.Map.Manipulators.AttackManipulator.GetDefaultArrivalTime();
AddTarget(sender, new AttackEventArgs(new AttackPlan(village, arrivalTime), null));
}
public void AttackUpdateTarget(object sender, AttackUpdateEventArgs e)
{
if (TargetUpdated != null)
TargetUpdated(sender, e);
}
private void AddTarget(object sender, AttackEventArgs e)
{
if (TargetAdded != null)
TargetAdded(sender, e);
AttackSelect(sender, e);
}
public void AttackRemoveTarget(object sender, AttackPlan plan)
{
var e = new AttackEventArgs(plan, null);
if (TargetRemoved != null)
TargetRemoved(sender, e);
}
public void AttackSelect(object sender, AttackPlan plan)
{
var e = new AttackEventArgs(plan, null);
AttackSelect(sender, e);
}
public void AttackSelect(object sender, AttackPlanFrom attacker)
{
var e = new AttackEventArgs(attacker.Plan, attacker);
AttackSelect(sender, e);
}
private void AttackSelect(object sender, AttackEventArgs e)
{
if (TargetSelected != null)
TargetSelected(sender, e);
}
#endregion
#region Action Events
// EditorBrowsableState.Never: A design error.
/// <summary>
/// Should be called only from one location: <see cref="Map"/>.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
internal void SetMapCenter(object sender, MapLocationEventArgs e)
{
if (LocationChanged != null)
LocationChanged(sender, e);
}
/// <summary>
/// Should be called only from one location: <see cref="ManipulatorManagerController"/>
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
public void ChangeManipulator(object sender, ManipulatorEventArgs e)
{
if (ManipulatorChanged != null)
ManipulatorChanged(sender, e);
}
/// <summary>
/// Ship villages to the Polygon control
/// </summary>
public void ActivatePolygon(object sender, IEnumerable<Polygon> polygons)
{
if (PolygonActivated != null)
PolygonActivated(sender, new PolygonEventArgs(polygons));
}
#endregion
#endregion
}
}
| mit |
sundaramss/rcp | index.js | 1356 | #! /usr/bin/env node
var FileReceiver = require('./lib/tar-receiver');
var fileSender = require('./lib/tar-sender');
var commandLineArgs = require('command-line-args');
var cli = commandLineArgs([
{ name: 'server', alias: 's', type: Boolean, description:"Start receive file server" },
{ name: 'fpath', alias: 'f', type: String, defaultOption: true, description:"Upload file/directory path" },
{ name: 'dpath', alias: 'd', type: String, description:"Destination directory path" },
{ name: 'host', alias:'h', type: String, description:"default server hostname is localhost", defaultValue: 'localhost' },
{ name: 'port', alias:'p', type: Number, description:"default server port number is 3131", defaultValue: '3131'},
{ name: 'resume', alias:'r', type: Boolean, description:"resume file/folder upload.", defaultValue: false}
]);
var options = {}
try {
options = cli.parse();
}catch(e) {
console.log('Unable to read the options')
console.log(cli.getUsage());
process.exit(1);
}
if(!(options.server || options.fpath)) {
console.log(cli.getUsage());
} else if (options.server){
var fileReceiver = new FileReceiver(options.port, options.dpath);
fileReceiver.startServer();
console.log('File Receiver Ready ... ...');
} else if (options.fpath) {
fileSender.sendFiles(options.host, options.port, options.fpath, {resume:options.resume});
}
| mit |
ripeCo/citiSell | application/config/config.php | 17777 | <?php
defined('BASEPATH') OR exit('No direct script access allowed');
/*
|--------------------------------------------------------------------------
| Base Site URL
|--------------------------------------------------------------------------
|
| URL to your CodeIgniter root. Typically this will be your base URL,
| WITH a trailing slash:
|
| http://example.com/
|
| If this is not set then CodeIgniter will try guess the protocol, domain
| and path to your installation. However, you should always configure this
| explicitly and never rely on auto-guessing, especially in production
| environments.
|
*/
$config['base_url'] = ((isset($_SERVER['HTTPS']) && $_SERVER['HTTP'] == "on") ? "https" : "http");
$config['base_url'] .= "://".$_SERVER['HTTP_HOST'];
$config['base_url'] .= str_replace(basename($_SERVER['SCRIPT_NAME']),"",$_SERVER['SCRIPT_NAME']);
/*
|--------------------------------------------------------------------------
| Index File
|--------------------------------------------------------------------------
|
| Typically this will be your index.php file, unless you've renamed it to
| something else. If you are using mod_rewrite to remove the page set this
| variable so that it is blank.
|
*/
$config['index_page'] = '';
/*
|--------------------------------------------------------------------------
| URI PROTOCOL
|--------------------------------------------------------------------------
|
| This item determines which server global should be used to retrieve the
| URI string. The default setting of 'REQUEST_URI' works for most servers.
| If your links do not seem to work, try one of the other delicious flavors:
|
| 'REQUEST_URI' Uses $_SERVER['REQUEST_URI']
| 'QUERY_STRING' Uses $_SERVER['QUERY_STRING']
| 'PATH_INFO' Uses $_SERVER['PATH_INFO']
|
| WARNING: If you set this to 'PATH_INFO', URIs will always be URL-decoded!
*/
$config['uri_protocol'] = 'AUTO';
/*
|--------------------------------------------------------------------------
| URL suffix
|--------------------------------------------------------------------------
|
| This option allows you to add a suffix to all URLs generated by CodeIgniter.
| For more information please see the user guide:
|
| http://codeigniter.com/user_guide/general/urls.html
*/
$config['url_suffix'] = '';
/*
|--------------------------------------------------------------------------
| Default Language
|--------------------------------------------------------------------------
|
| This determines which set of language files should be used. Make sure
| there is an available translation if you intend to use something other
| than english.
|
*/
$config['language'] = 'english';
/*
|--------------------------------------------------------------------------
| Default Character Set
|--------------------------------------------------------------------------
|
| This determines which character set is used by default in various methods
| that require a character set to be provided.
|
| See http://php.net/htmlspecialchars for a list of supported charsets.
|
*/
$config['charset'] = 'UTF-8';
/*
|--------------------------------------------------------------------------
| Enable/Disable System Hooks
|--------------------------------------------------------------------------
|
| If you would like to use the 'hooks' feature you must enable it by
| setting this variable to TRUE (boolean). See the user guide for details.
|
*/
$config['enable_hooks'] = FALSE;
/*
|--------------------------------------------------------------------------
| Class Extension Prefix
|--------------------------------------------------------------------------
|
| This item allows you to set the filename/classname prefix when extending
| native libraries. For more information please see the user guide:
|
| http://codeigniter.com/user_guide/general/core_classes.html
| http://codeigniter.com/user_guide/general/creating_libraries.html
|
*/
$config['subclass_prefix'] = 'MY_';
/*
|--------------------------------------------------------------------------
| Composer auto-loading
|--------------------------------------------------------------------------
|
| Enabling this setting will tell CodeIgniter to look for a Composer
| package auto-loader script in application/vendor/autoload.php.
|
| $config['composer_autoload'] = TRUE;
|
| Or if you have your vendor/ directory located somewhere else, you
| can opt to set a specific path as well:
|
| $config['composer_autoload'] = '/path/to/vendor/autoload.php';
|
| For more information about Composer, please visit http://getcomposer.org/
|
| Note: This will NOT disable or override the CodeIgniter-specific
| autoloading (application/config/autoload.php)
*/
$config['composer_autoload'] = TRUE;
/*
|--------------------------------------------------------------------------
| Allowed URL Characters
|--------------------------------------------------------------------------
|
| This lets you specify which characters are permitted within your URLs.
| When someone tries to submit a URL with disallowed characters they will
| get a warning message.
|
| As a security measure you are STRONGLY encouraged to restrict URLs to
| as few characters as possible. By default only these are allowed: a-z 0-9~%.:_-
|
| Leave blank to allow all characters -- but only if you are insane.
|
| The configured value is actually a regular expression character group
| and it will be executed as: ! preg_match('/^[<permitted_uri_chars>]+$/i
|
| DO NOT CHANGE THIS UNLESS YOU FULLY UNDERSTAND THE REPERCUSSIONS!!
|
*/
//$config['permitted_uri_chars'] = 'a-z 0-9~%.:_\-';
$config['permitted_uri_chars'] = 'a-z 0-9~%.:&_\-(),';
/*
|--------------------------------------------------------------------------
| Enable Query Strings
|--------------------------------------------------------------------------
|
| By default CodeIgniter uses search-engine friendly segment based URLs:
| example.com/who/what/where/
|
| By default CodeIgniter enables access to the $_GET array. If for some
| reason you would like to disable it, set 'allow_get_array' to FALSE.
|
| You can optionally enable standard query string based URLs:
| example.com?who=me&what=something&where=here
|
| Options are: TRUE or FALSE (boolean)
|
| The other items let you set the query string 'words' that will
| invoke your controllers and its functions:
| example.com/index.php?c=controller&m=function
|
| Please note that some of the helpers won't work as expected when
| this feature is enabled, since CodeIgniter is designed primarily to
| use segment based URLs.
|
*/
$config['allow_get_array'] = TRUE;
$config['enable_query_strings'] = FALSE;
$config['controller_trigger'] = 'c';
$config['function_trigger'] = 'm';
$config['directory_trigger'] = 'd';
/*
|--------------------------------------------------------------------------
| Error Logging Threshold
|--------------------------------------------------------------------------
|
| If you have enabled error logging, you can set an error threshold to
| determine what gets logged. Threshold options are:
| You can enable error logging by setting a threshold over zero. The
| threshold determines what gets logged. Threshold options are:
|
| 0 = Disables logging, Error logging TURNED OFF
| 1 = Error Messages (including PHP errors)
| 2 = Debug Messages
| 3 = Informational Messages
| 4 = All Messages
|
| You can also pass an array with threshold levels to show individual error types
|
| array(2) = Debug Messages, without Error Messages
|
| For a live site you'll usually only enable Errors (1) to be logged otherwise
| your log files will fill up very fast.
|
*/
$config['log_threshold'] = 0;
/*
|--------------------------------------------------------------------------
| Error Logging Directory Path
|--------------------------------------------------------------------------
|
| Leave this BLANK unless you would like to set something other than the default
| application/logs/ directory. Use a full server path with trailing slash.
|
*/
$config['log_path'] = '';
/*
|--------------------------------------------------------------------------
| Log File Extension
|--------------------------------------------------------------------------
|
| The default filename extension for log files. The default 'php' allows for
| protecting the log files via basic scripting, when they are to be stored
| under a publicly accessible directory.
|
| Note: Leaving it blank will default to 'php'.
|
*/
$config['log_file_extension'] = '';
/*
|--------------------------------------------------------------------------
| Log File Permissions
|--------------------------------------------------------------------------
|
| The file system permissions to be applied on newly created log files.
|
| IMPORTANT: This MUST be an integer (no quotes) and you MUST use octal
| integer notation (i.e. 0700, 0644, etc.)
*/
$config['log_file_permissions'] = 0644;
/*
|--------------------------------------------------------------------------
| Date Format for Logs
|--------------------------------------------------------------------------
|
| Each item that is logged has an associated date. You can use PHP date
| codes to set your own date formatting
|
*/
$config['log_date_format'] = 'Y-m-d H:i:s';
/*
|--------------------------------------------------------------------------
| Error Views Directory Path
|--------------------------------------------------------------------------
|
| Leave this BLANK unless you would like to set something other than the default
| application/views/errors/ directory. Use a full server path with trailing slash.
|
*/
$config['error_views_path'] = '';
/*
|--------------------------------------------------------------------------
| Cache Directory Path
|--------------------------------------------------------------------------
|
| Leave this BLANK unless you would like to set something other than the default
| application/cache/ directory. Use a full server path with trailing slash.
|
*/
$config['cache_path'] = 'application/cache/';
/*
|--------------------------------------------------------------------------
| Cache Include Query String
|--------------------------------------------------------------------------
|
| Set this to TRUE if you want to use different cache files depending on the
| URL query string. Please be aware this might result in numerous cache files.
|
*/
$config['cache_query_string'] = TRUE;
/*
|--------------------------------------------------------------------------
| Encryption Key
|--------------------------------------------------------------------------
|
| If you use the Encryption class, you must set an encryption key.
| See the user guide for more info.
|
| http://codeigniter.com/user_guide/libraries/encryption.html
|
*/
$config['encryption_key'] = 'Wan@IT';
/*
|--------------------------------------------------------------------------
| Session Variables
|--------------------------------------------------------------------------
|
| 'sess_driver'
|
| The storage driver to use: files, database, redis, memcached
|
| 'sess_cookie_name'
|
| The session cookie name, must contain only [0-9a-z_-] characters
|
| 'sess_expiration'
|
| The number of SECONDS you want the session to last.
| Setting to 0 (zero) means expire when the browser is closed.
|
| 'sess_save_path'
|
| The location to save sessions to, driver dependant.
|
| For the 'files' driver, it's a path to a writable directory.
| WARNING: Only absolute paths are supported!
|
| For the 'database' driver, it's a table name.
| Please read up the manual for the format with other session drivers.
|
| IMPORTANT: You are REQUIRED to set a valid save path!
|
| 'sess_match_ip'
|
| Whether to match the user's IP address when reading the session data.
|
| 'sess_time_to_update'
|
| How many seconds between CI regenerating the session ID.
|
| 'sess_regenerate_destroy'
|
| Whether to destroy session data associated with the old session ID
| when auto-regenerating the session ID. When set to FALSE, the data
| will be later deleted by the garbage collector.
|
| Other session cookie settings are shared with the rest of the application,
| except for 'cookie_prefix' and 'cookie_httponly', which are ignored here.
|
*/
$config['sess_driver'] = 'files';
$config['sess_cookie_name'] = 'bsd';
$config['sess_expiration'] = 7200;
$config['sess_save_path'] = BASEPATH.'cache/';
$config['sess_match_ip'] = FALSE;
$config['sess_time_to_update'] = 300;
$config['sess_regenerate_destroy'] = FALSE;
/*
|--------------------------------------------------------------------------
| Cookie Related Variables
|--------------------------------------------------------------------------
|
| 'cookie_prefix' = Set a cookie name prefix if you need to avoid collisions
| 'cookie_domain' = Set to .your-domain.com for site-wide cookies
| 'cookie_path' = Typically will be a forward slash
| 'cookie_secure' = Cookie will only be set if a secure HTTPS connection exists.
| 'cookie_httponly' = Cookie will only be accessible via HTTP(S) (no javascript)
|
| Note: These settings (with the exception of 'cookie_prefix' and
| 'cookie_httponly') will also affect sessions.
|
*/
$config['cookie_prefix'] = '';
$config['cookie_domain'] = '';
$config['cookie_path'] = '/';
$config['cookie_secure'] = FALSE;
$config['cookie_httponly'] = FALSE;
/*
|--------------------------------------------------------------------------
| Standardize newlines
|--------------------------------------------------------------------------
|
| Determines whether to standardize newline characters in input data,
| meaning to replace \r\n, \r, \n occurences with the PHP_EOL value.
|
| This is particularly useful for portability between UNIX-based OSes,
| (usually \n) and Windows (\r\n).
|
*/
$config['standardize_newlines'] = FALSE;
/*
|--------------------------------------------------------------------------
| Global XSS Filtering
|--------------------------------------------------------------------------
|
| Determines whether the XSS filter is always active when GET, POST or
| COOKIE data is encountered
|
| WARNING: This feature is DEPRECATED and currently available only
| for backwards compatibility purposes!
|
*/
$config['global_xss_filtering'] = TRUE;
/*
|--------------------------------------------------------------------------
| Cross Site Request Forgery
|--------------------------------------------------------------------------
| Enables a CSRF cookie token to be set. When set to TRUE, token will be
| checked on a submitted form. If you are accepting user data, it is strongly
| recommended CSRF protection be enabled.
|
| 'csrf_token_name' = The token name
| 'csrf_cookie_name' = The cookie name
| 'csrf_expire' = The number in seconds the token should expire.
| 'csrf_regenerate' = Regenerate token on every submission
| 'csrf_exclude_uris' = Array of URIs which ignore CSRF checks
*/
$config['csrf_protection'] = FALSE;
$config['csrf_token_name'] = 'csrf_test_name';
$config['csrf_cookie_name'] = 'csrf_cookie_name';
$config['csrf_expire'] = 7200;
$config['csrf_regenerate'] = TRUE;
$config['csrf_exclude_uris'] = array();
/*
|--------------------------------------------------------------------------
| Output Compression
|--------------------------------------------------------------------------
|
| Enables Gzip output compression for faster page loads. When enabled,
| the output class will test whether your server supports Gzip.
| Even if it does, however, not all browsers support compression
| so enable only if you are reasonably sure your visitors can handle it.
|
| Only used if zlib.output_compression is turned off in your php.ini.
| Please do not use it together with httpd-level output compression.
|
| VERY IMPORTANT: If you are getting a blank page when compression is enabled it
| means you are prematurely outputting something to your browser. It could
| even be a line of whitespace at the end of one of your scripts. For
| compression to work, nothing can be sent before the output buffer is called
| by the output class. Do not 'echo' any values with compression enabled.
|
*/
$config['compress_output'] = FALSE;
/*
|--------------------------------------------------------------------------
| Master Time Reference
|--------------------------------------------------------------------------
|
| Options are 'local' or any PHP supported timezone. This preference tells
| the system whether to use your server's local time as the master 'now'
| reference, or convert it to the configured one timezone. See the 'date
| helper' page of the user guide for information regarding date handling.
|
*/
$config['time_reference'] = 'local';
/*
|--------------------------------------------------------------------------
| Rewrite PHP Short Tags
|--------------------------------------------------------------------------
|
| If your PHP installation does not have short tag support enabled CI
| can rewrite the tags on-the-fly, enabling you to utilize that syntax
| in your view files. Options are TRUE or FALSE (boolean)
|
*/
$config['rewrite_short_tags'] = FALSE;
/*
|--------------------------------------------------------------------------
| Reverse Proxy IPs
|--------------------------------------------------------------------------
|
| If your server is behind a reverse proxy, you must whitelist the proxy
| IP addresses from which CodeIgniter should trust headers such as
| HTTP_X_FORWARDED_FOR and HTTP_CLIENT_IP in order to properly identify
| the visitor's IP address.
|
| You can use both an array or a comma-separated list of proxy addresses,
| as well as specifying whole subnets. Here are a few examples:
|
| Comma-separated: '10.0.1.200,192.168.5.0/24'
| Array: array('10.0.1.200', '192.168.5.0/24')
*/
$config['proxy_ips'] = '';
| mit |
christophwille/wlapimonitoring | Source/IsQandoUp/IsQandoUp/Areas/HelpPage/SampleGeneration/HelpPageSampleKey.cs | 6940 | using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Net.Http.Headers;
namespace IsQandoUp.Areas.HelpPage
{
/// <summary>
/// This is used to identify the place where the sample should be applied.
/// </summary>
public class HelpPageSampleKey
{
/// <summary>
/// Creates a new <see cref="HelpPageSampleKey"/> based on media type and CLR type.
/// </summary>
/// <param name="mediaType">The media type.</param>
/// <param name="type">The CLR type.</param>
public HelpPageSampleKey(MediaTypeHeaderValue mediaType, Type type)
{
if (mediaType == null)
{
throw new ArgumentNullException("mediaType");
}
if (type == null)
{
throw new ArgumentNullException("type");
}
ControllerName = String.Empty;
ActionName = String.Empty;
ParameterNames = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
ParameterType = type;
MediaType = mediaType;
}
/// <summary>
/// Creates a new <see cref="HelpPageSampleKey"/> based on <see cref="SampleDirection"/>, controller name, action name and parameter names.
/// </summary>
/// <param name="sampleDirection">The <see cref="SampleDirection"/>.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public HelpPageSampleKey(SampleDirection sampleDirection, string controllerName, string actionName, IEnumerable<string> parameterNames)
{
if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection))
{
throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection));
}
if (controllerName == null)
{
throw new ArgumentNullException("controllerName");
}
if (actionName == null)
{
throw new ArgumentNullException("actionName");
}
if (parameterNames == null)
{
throw new ArgumentNullException("parameterNames");
}
ControllerName = controllerName;
ActionName = actionName;
ParameterNames = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase);
SampleDirection = sampleDirection;
}
/// <summary>
/// Creates a new <see cref="HelpPageSampleKey"/> based on media type, <see cref="SampleDirection"/>, controller name, action name and parameter names.
/// </summary>
/// <param name="mediaType">The media type.</param>
/// <param name="sampleDirection">The <see cref="SampleDirection"/>.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public HelpPageSampleKey(MediaTypeHeaderValue mediaType, SampleDirection sampleDirection, string controllerName, string actionName, IEnumerable<string> parameterNames)
{
if (mediaType == null)
{
throw new ArgumentNullException("mediaType");
}
if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection))
{
throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection));
}
if (controllerName == null)
{
throw new ArgumentNullException("controllerName");
}
if (actionName == null)
{
throw new ArgumentNullException("actionName");
}
if (parameterNames == null)
{
throw new ArgumentNullException("parameterNames");
}
ControllerName = controllerName;
ActionName = actionName;
MediaType = mediaType;
ParameterNames = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase);
SampleDirection = sampleDirection;
}
/// <summary>
/// Gets the name of the controller.
/// </summary>
/// <value>
/// The name of the controller.
/// </value>
public string ControllerName { get; private set; }
/// <summary>
/// Gets the name of the action.
/// </summary>
/// <value>
/// The name of the action.
/// </value>
public string ActionName { get; private set; }
/// <summary>
/// Gets the media type.
/// </summary>
/// <value>
/// The media type.
/// </value>
public MediaTypeHeaderValue MediaType { get; private set; }
/// <summary>
/// Gets the parameter names.
/// </summary>
public HashSet<string> ParameterNames { get; private set; }
public Type ParameterType { get; private set; }
/// <summary>
/// Gets the <see cref="SampleDirection"/>.
/// </summary>
public SampleDirection? SampleDirection { get; private set; }
public override bool Equals(object obj)
{
HelpPageSampleKey otherKey = obj as HelpPageSampleKey;
if (otherKey == null)
{
return false;
}
return String.Equals(ControllerName, otherKey.ControllerName, StringComparison.OrdinalIgnoreCase) &&
String.Equals(ActionName, otherKey.ActionName, StringComparison.OrdinalIgnoreCase) &&
(MediaType == otherKey.MediaType || (MediaType != null && MediaType.Equals(otherKey.MediaType))) &&
ParameterType == otherKey.ParameterType &&
SampleDirection == otherKey.SampleDirection &&
ParameterNames.SetEquals(otherKey.ParameterNames);
}
public override int GetHashCode()
{
int hashCode = ControllerName.ToUpperInvariant().GetHashCode() ^ ActionName.ToUpperInvariant().GetHashCode();
if (MediaType != null)
{
hashCode ^= MediaType.GetHashCode();
}
if (SampleDirection != null)
{
hashCode ^= SampleDirection.GetHashCode();
}
if (ParameterType != null)
{
hashCode ^= ParameterType.GetHashCode();
}
foreach (string parameterName in ParameterNames)
{
hashCode ^= parameterName.ToUpperInvariant().GetHashCode();
}
return hashCode;
}
}
}
| mit |
bdowning/retween | test/preprocessors/colorPreprocessor.spec.js | 2764 | import expect from 'expect';
import { identity } from '../../src/index';
import createColorPreprocessor from '../../src/preprocessors/createColorPreprocessor';
describe('colorPreprocessor', () => {
it('passes states with no strings through unchanged', () => {
const colorPreprocessor = createColorPreprocessor();
const state = { x: 1, y: 4 };
const easing = { x: identity, y: identity };
const [ outState, outEasing, decode ] = colorPreprocessor(state, easing);
expect(outState).toBe(state);
expect(outEasing).toBe(easing);
expect(decode).toBe(identity);
});
it('passes states with no non-tweenable colors through unchanged', () => {
const colorPreprocessor = createColorPreprocessor();
const state = { x: 'translate(4em)', y: 'rgb(12%, 45%, 13%)' };
const easing = { x: identity, y: identity };
const [ outState, outEasing, decode ] = colorPreprocessor(state, easing);
expect(outState).toBe(state);
expect(outEasing).toBe(easing);
expect(decode).toBe(identity);
});
it('converts CSS/CSS4 hex colors to rgb/rgba percentages', () => {
const colorPreprocessor = createColorPreprocessor();
const state = {
x: '#379',
y: '#4F2c',
a: '#1a47c8',
b: '#d6398B16',
};
const easing = { x: identity, y: identity };
const [ outState, outEasing, decode ] = colorPreprocessor(state, easing);
expect(outState).toEqual({
x: 'rgb(20.00%, 46.67%, 60.00%)',
y: 'rgba(26.67%, 100.00%, 13.33%, 0.800)',
a: 'rgb(10.20%, 27.84%, 78.43%)',
b: 'rgba(83.92%, 22.35%, 54.51%, 0.086)',
});
expect(outEasing).toBe(easing);
expect(decode).toBe(identity);
});
it('does not convert hex colors with incorrect digits', () => {
const colorPreprocessor = createColorPreprocessor();
const state = {
x: '#379',
y: '#4F2c4',
a: '#37g',
};
const easing = { x: identity, y: identity };
const [ outState, outEasing, decode ] = colorPreprocessor(state, easing);
expect(outState).toEqual({
x: 'rgb(20.00%, 46.67%, 60.00%)',
y: '#4F2c4',
a: '#37g',
});
expect(outEasing).toBe(easing);
expect(decode).toBe(identity);
});
it('converts rgb/rgba with integers to floats', () => {
const colorPreprocessor = createColorPreprocessor();
const state = {
x: 'rgb(127, 45, 87)',
y: 'rgba(34, 90, 245, 0.23)',
};
const easing = { x: identity, y: identity };
const [ outState, outEasing, decode ] = colorPreprocessor(state, easing);
expect(outState).toEqual({
x: 'rgb(49.80%, 17.65%, 34.12%)',
y: 'rgba(13.33%, 35.29%, 96.08%, 0.23)',
});
expect(outEasing).toBe(easing);
expect(decode).toBe(identity);
});
});
| mit |
h136799711/itboye2015gd | guangda_android/src/com/itboye/guangda/utils/ToastTime.java | 602 | package com.itboye.guangda.utils;
import java.util.Timer;
import java.util.TimerTask;
import android.widget.Toast;
public class ToastTime extends TimerTask {
Toast toast = null;
Timer timer=null;
public ToastTime(Toast toast,Timer timer) {
// TODO Auto-generated constructor stub
this.toast = toast;
this.timer=timer;
}
@Override
public void run() {
// TODO Auto-generated method stub
//获取当前时间
long firstTime = System.currentTimeMillis();
while(System.currentTimeMillis()-firstTime < 5000){//显示十秒
toast.show();
}
timer.cancel();
}
}
| mit |
navneetzz/classicware | sandbox/ecommerce/New_folder/admin/users/show.php | 1389 | <?php
/**
* User admin - show a user
*/
// Initialisation
require_once('../../includes/init.php');
// Require the user to be logged in before they can see this page.
Auth::getInstance()->requireLogin();
// Require the user to be an administrator before they can see this page.
Auth::getInstance()->requireAdmin();
// Find the user or show a 404 page.
$user = User::getByIDor404($_GET);
// Show the page header, then the rest of the HTML
include('../../includes/header.php');
?>
<h1>User</h1>
<p><a href="/login2/New_folder/admin/users">« back to list of users</a></p>
<dl class="uk-description-list-horizontal">
<dt>Name</dt>
<dd><?php echo htmlspecialchars($user->name); ?></dd>
<dt>email address</dt>
<dd><?php echo htmlspecialchars($user->email); ?></dd>
<dt>Active</dt>
<dd><?php echo $user->is_active ? '✔' : '✘'; ?></dd>
<dt>Administrator</dt>
<dd><?php echo $user->is_admin ? '✔' : '✘'; ?></dd>
</dl>
<a href="/login2/New_folder/admin/users/edit.php?id=<?php echo $user->id; ?>" class="uk-button uk-button-primary">Edit</a></li>
<?php if ($user->id == Auth::getInstance()->getCurrentUser()->id): ?>
Delete
<?php else: ?>
<a href="/login2/New_folder/admin/users/delete.php?id=<?php echo $user->id; ?>" class="uk-button uk-button-danger">Delete</a>
<?php endif; ?>
<?php include('../../includes/footer.php'); ?>
| mit |
Krushelnitskiy/bug_tracker | src/Tracker/IssueBundle/Tests/Controller/DefaultControllerTest.php | 5825 | <?php
namespace Tracker\IssueBundle\Tests\Controller;
use Tracker\TestBundle\Test\WebTestCase;
/**
* Class DefaultControllerTest
* @package Tracker\IssueBundle\Tests\Controller
*/
class DefaultControllerTest extends WebTestCase
{
public function testShow()
{
$client = static::createClient(array(), array(
'PHP_AUTH_USER' => 'admin',
'PHP_AUTH_PW' => 'test'
));
$crawler = $client->request('GET', '/issue/'.$this->getReference('issue.story')->getCode());
self::assertContains($this->getReference('issue.story')->getSummary(), $crawler->html());
}
public function testCreate()
{
$client = static::createClient(array(), array(
'PHP_AUTH_USER' => 'admin',
'PHP_AUTH_PW' => 'test'
));
$crawler = $client->request('GET', '/issue/new');
$form = $crawler->selectButton('Create')->form();
$form['tracker_issueBundle_issue[project]'] = $this->getReference('project.first')->getId();
$form['tracker_issueBundle_issue[type]'] = $this->getReference('type.story')->getId();
$form['tracker_issueBundle_issue[summary]'] = 'issue test summary 1';
$form['tracker_issueBundle_issue[summary]'] = 'issue test summary 1';
$form['tracker_issueBundle_issue[priority]'] = $this->getReference('priority.trivial')->getId();
$form['tracker_issueBundle_issue[description]'] = 'issue test description 1';
$form['tracker_issueBundle_issue[reporter]'] = $this->getReference('user.manager')->getId();
$form['tracker_issueBundle_issue[assignee]'] = $this->getReference('user.operator')->getId();
$client->followRedirects();
$client->submit($form);
$crawler = $client->getCrawler();
self::assertContains('issue test summary 1', $crawler->html());
}
public function testEdit()
{
$client = static::createClient(array(), array(
'PHP_AUTH_USER' => 'admin',
'PHP_AUTH_PW' => 'test'
));
$issueId = $this->getReference('issue.story')->getCode();
$crawler = $client->request('GET', '/issue/'.$issueId.'/edit');
$form = $crawler->selectButton('Update')->form();
$form['tracker_issueBundle_issue[summary]'] = 'issue test summary 2';
$form['tracker_issueBundle_issue[reporter]'] = $this->getReference('user.manager')->getId();
$form['tracker_issueBundle_issue[status]'] = $this->getReference('status.inProgress')->getId();
$client->followRedirects();
$client->submit($form);
$crawler = $client->getCrawler();
self::assertContains('In progress', $crawler->html());
}
public function testCreateComment()
{
$client = static::createClient(array(), array(
'PHP_AUTH_USER' => 'operator',
'PHP_AUTH_PW' => 'test'
));
$issueCode = $this->getReference('issue.story')->getCode();
$crawler = $client->request('GET', '/issue/'.$issueCode);
$form = $crawler->selectButton('Create')->form();
$form['tracker_issueBundle_comment_form[body]'] = 'issue test comment';
$client->followRedirects();
$client->submit($form);
$crawler = $client->getCrawler();
$this->assertContains('issue test comment', $crawler->html());
$link = $crawler->filter('a:contains("Delete")')->eq(0)->link();
$client->click($link);
$crawler = $client->getCrawler();
$this->assertCount(0, $crawler->filter('a:contains("Delete")'));
}
public function testEditComment()
{
$client = static::createClient(array(), array(
'PHP_AUTH_USER' => 'operator',
'PHP_AUTH_PW' => 'test'
));
$issueId = $this->getReference('issue.story')->getCode();
$crawler = $client->request('GET', '/issue/'.$issueId);
$form = $crawler->selectButton('Create')->form();
$form['tracker_issueBundle_comment_form[body]'] = 'issue test comment';
$client->followRedirects();
$client->submit($form);
$crawler = $client->getCrawler();
$this->assertContains('issue test comment', $crawler->html());
$link = $crawler->filter('.list-comments a:contains("Edit")')->link();
$crawler= $client->click($link);
$form = $crawler->selectButton('Update')->form();
$form['tracker_issueBundle_comment_form[body]'] = 'issue test comment 222';
$client->submit($form);
$crawler = $client->getCrawler();
$this->assertContains('issue test comment 222', $crawler->html());
}
public function testCreateSubTask()
{
$client = static::createClient(array(), array(
'PHP_AUTH_USER' => 'operator',
'PHP_AUTH_PW' => 'test'
));
$issueId = $this->getReference('issue.story')->getCode();
$crawler = $client->request('GET', '/issue/'.$issueId);
$link = $crawler->filter('a:contains("Create sub task")')->link();
$crawler= $client->click($link);
$form = $crawler->selectButton('Create')->form();
$form['tracker_issueBundle_issue[summary]'] = 'issue test summary 1';
$form['tracker_issueBundle_issue[priority]'] = $this->getReference('priority.trivial')->getId();
$form['tracker_issueBundle_issue[description]'] = 'issue test description 1';
$form['tracker_issueBundle_issue[reporter]'] = $this->getReference('user.manager')->getId();
$form['tracker_issueBundle_issue[assignee]'] = $this->getReference('user.operator')->getId();
$client->followRedirects();
$client->submit($form);
$crawler = $client->getCrawler();
$this->assertEquals(0, $crawler->filter('a:contains("Delete")')->count());
}
}
| mit |
Titifonky/DXFLibrary | Arc.cs | 472 |
namespace DXFLibrary
{
class Arc : DXFLibrary.Entity
{
public Arc(double x, double y, double radius, double startAngle, double endAngle, string layer):base("ARC",layer)
{
this.dataAcceptanceList.AddRange(new int[] { 39, 10, 20, 30, 40, 100, 50, 51, 210, 220, 230 });
this.AddReplace(10, x);
this.AddReplace(20, y);
this.AddReplace(40, radius);
this.AddReplace(50, startAngle);
this.AddReplace(51, endAngle);
}
}
} | mit |
icejs-team/icejs | test/unit/loadModule/module-files/plugin/demo1.js | 84 | am.install ( {
name : "demo1",
build : function () {
return {o:"demo1"};
}
} ); | mit |
amplify-education/test-drive | lib/test/drive/jenkins_client.rb | 1946 | require 'jenkins_api_client'
module Test
module Drive
class JenkinsClient
attr_accessor :client
def initialize jenkins_url, user, api_key
@server_url = jenkins_url
@user = user
@api_key = api_key
@client = JenkinsApi::Client.new :server_url => jenkins_url,
:username => user,
:password => api_key,
:log_level => 1
end
def get_build_number(target_job, tracking_id, timeout_in_seconds, sleep_interval=10)
(timeout_in_seconds/10).times do
sleep sleep_interval
build_details = @client.job.get_build_details(target_job, 0)
if build_details['actions'][0]['parameters'].include?(tracking_id)
return build_details['number']
end
end
raise 'Build number not found within the time specified!'
end
def print_output(build_number, target_job, sleep_interval=5)
offset = 0
loop do
job_output = @client.job.get_console_output(target_job, build_number, offset)
print job_output['output']
break unless job_output['more']
offset = job_output['size']
sleep sleep_interval
end
end
def wait_for_job_status(target_job, build_number)
loop do
details = @client.job.get_build_details(target_job, build_number)
return details['result'] if details['result']
sleep 5
end
end
def upload_file_to_job(target_job, tracking_id, path_to_file)
res = `curl -i #{@server_url}/job/#{target_job}/build -F file0=@#{path_to_file} -F json='{"parameter": [{"name":"#{path_to_file}", "file":"file0"}, {"name":"TRACKING_ID", "value":"#{tracking_id}"}]}' --user '#{@user}':'#{@api_key}'`
raise "Failed to send patch to Jenkins: \n#{res}" unless $? == 0
end
end
end
end
| mit |
RAStacy/ryanstacy.net | rs_web_dev/template-parts/content-page.php | 1018 | <?php
/**
* Template part for displaying page content in page.php.
*
* @link https://codex.wordpress.org/Template_Hierarchy
*
* @package rs_web_dev
*/
?>
<article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
<header class="entry-header">
<?php the_title( '<h1 class="entry-title">', '</h1>' ); ?>
</header><!-- .entry-header -->
<div class="entry-content">
<?php
the_content();
wp_link_pages( array(
'before' => '<div class="page-links">' . esc_html__( 'Pages:', 'rs_web_dev' ),
'after' => '</div>',
) );
?>
</div><!-- .entry-content -->
<?php if ( get_edit_post_link() ) : ?>
<footer class="entry-footer">
<?php
edit_post_link(
sprintf(
/* translators: %s: Name of current post */
esc_html__( 'Edit %s', 'rs_web_dev' ),
the_title( '<span class="screen-reader-text">"', '"</span>', false )
),
'<span class="edit-link">',
'</span>'
);
?>
</footer><!-- .entry-footer -->
<?php endif; ?>
</article><!-- #post-## -->
| mit |
daxsorbito/meanMammoth | public/modules/items/controllers/items.client.controller.js | 1443 | 'use strict';
// Items controller
angular.module('items').controller('ItemsController', ['$scope', '$stateParams', '$location', 'Authentication', 'Items',
function($scope, $stateParams, $location, Authentication, Items ) {
$scope.authentication = Authentication;
// Create new Item
$scope.create = function() {
// Create new Item object
var item = new Items ({
name: this.name
});
// Redirect after save
item.$save(function(response) {
$location.path('items/' + response._id);
// Clear form fields
$scope.name = '';
}, function(errorResponse) {
$scope.error = errorResponse.data.message;
});
};
// Remove existing Item
$scope.remove = function( item ) {
if ( item ) { item.$remove();
for (var i in $scope.items ) {
if ($scope.items [i] === item ) {
$scope.items.splice(i, 1);
}
}
} else {
$scope.item.$remove(function() {
$location.path('items');
});
}
};
// Update existing Item
$scope.update = function() {
var item = $scope.item ;
item.$update(function() {
$location.path('items/' + item._id);
}, function(errorResponse) {
$scope.error = errorResponse.data.message;
});
};
// Find a list of Items
$scope.find = function() {
$scope.items = Items.query();
};
// Find existing Item
$scope.findOne = function() {
$scope.item = Items.get({
itemId: $stateParams.itemId
});
};
}
]); | mit |
aurelia/ux | packages/slider/dist/amd/index.js | 745 | define(["require", "exports", "aurelia-framework", "./ux-slider-theme", "./ux-slider"], function (require, exports, aurelia_framework_1, ux_slider_theme_1, ux_slider_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.configure = void 0;
Object.defineProperty(exports, "UxSliderTheme", { enumerable: true, get: function () { return ux_slider_theme_1.UxSliderTheme; } });
Object.defineProperty(exports, "UxSlider", { enumerable: true, get: function () { return ux_slider_1.UxSlider; } });
function configure(config) {
config.globalResources(aurelia_framework_1.PLATFORM.moduleName('./ux-slider'));
}
exports.configure = configure;
});
//# sourceMappingURL=index.js.map | mit |
RobinClowers/photo-album | app/assets/javascripts/application.js | 694 | // This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file.
//
// Read Sprockets README (https://github.com/sstephenson/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require jquery_ujs
//= require jquery.tooltipster.js
//= require spin
//= require run_loop
//= require_tree .
| mit |
localfoodnodes/localfoodnodes | resources/views/account/user/product-orders.blade.php | 3023 | @extends('account.layout')
@section('title', join(array_keys($breadcrumbs), ' - '))
@section('content')
@include('account.page-header')
<div class="row">
<div class="col-12">
<div class="card">
<div class="card-header">{{ $orderDateItemLinks->first()->getItem()->product['name'] }}</div>
<div class="card-body">
<div class="table-responsive">
<table class="table">
<thead>
<tr>
<th>{{ trans('admin/producer.order') }}</th>
<th>{{ trans('admin/producer.product') }}</th>
<th class="text-right">{{ trans('admin/producer.quantity') }}</th>
<th>{{ trans('admin/producer.node') }}</th>
<th>{{ trans('admin/producer.delivery') }}</th>
<th class="text-right">{{ trans('admin/producer.total_price') }}</th>
<th class="text-right">{{ trans('admin/producer.status') }}</th>
</tr>
</thead>
<tbody>
@foreach ($orderDateItemLinks as $orderDateItemLink)
<tr>
<td>
<a href="/account/producer/{{ $orderDateItemLink->producer_id }}/order/{{ $orderDateItemLink->getItem()->product_id }}">{{ $orderDateItemLink->ref }}</a>
</td>
<td>{{ $orderDateItemLink->getItem()->getName() }}</td>
<td class="text-right">{{ $orderDateItemLink->quantity }}</td>
<td>{{ $orderDateItemLink->getItem()->node['name'] }}</td>
<td>
@if ($orderDateItemLink->getDate())
{{ $orderDateItemLink->getDate()->date('Y-m-d') }}
@else
-
@endif
</td>
<td class="text-right">{!! $orderDateItemLink->getPriceWithUnit() !!}</td>
<td class="text-right"><span class="{{ $orderDateItemLink->getItem()->getCurrentStatus()->getHtmlClass() }}">{{ $orderDateItemLink->getItem()->getCurrentStatus() }}</span></td>
</tr>
@endforeach
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
@endsection
| mit |
johnhenry/node-uuid | uuid.js | 7332 | // uuid.js
//
// Copyright (c) 2010-2012 Robert Kieffer
// MIT License - http://opensource.org/licenses/mit-license.php
(function() {
var _global = this || global;
// Unique ID creation requires a high quality random # generator. We feature
// detect to determine the best RNG source, normalizing to a function that
// returns 128-bits of randomness, since that's what's usually required
var _rng;
// Allow for MSIE11 msCrypto
var _crypto = _global.crypto || _global.msCrypto;
// Node.js crypto-based RNG - http://nodejs.org/docs/v0.6.2/api/crypto.html
//
// Moderately fast, high quality
if (typeof(_global.require) == 'function') {
try {
var _rb = _global.require('crypto').randomBytes;
_rng = _rb && function() {return _rb(16);};
} catch(e) {}
}
if (!_rng && _crypto && _crypto.getRandomValues) {
// WHATWG crypto-based RNG - http://wiki.whatwg.org/wiki/Crypto
//
// Moderately fast, high quality
var _rnds8 = new Uint8Array(16);
_rng = function whatwgRNG() {
_crypto.getRandomValues(_rnds8);
return _rnds8;
};
}
if (!_rng) {
// Math.random()-based (RNG)
//
// If all else fails, use Math.random(). It's fast, but is of unspecified
// quality.
var _rnds = new Array(16);
_rng = function() {
for (var i = 0, r; i < 16; i++) {
if ((i & 0x03) === 0) r = Math.random() * 0x100000000;
_rnds[i] = r >>> ((i & 0x03) << 3) & 0xff;
}
return _rnds;
};
}
// Buffer class to use
var BufferClass = typeof(_global.Buffer) == 'function' ? _global.Buffer : Array;
// Maps for number <-> hex string conversion
var _byteToHex = [];
var _hexToByte = {};
for (var i = 0; i < 256; i++) {
_byteToHex[i] = (i + 0x100).toString(16).substr(1);
_hexToByte[_byteToHex[i]] = i;
}
// **`parse()` - Parse a UUID into it's component bytes**
function parse(s, buf, offset) {
var i = (buf && offset) || 0, ii = 0;
buf = buf || [];
s.toLowerCase().replace(/[0-9a-f]{2}/g, function(oct) {
if (ii < 16) { // Don't overflow!
buf[i + ii++] = _hexToByte[oct];
}
});
// Zero out remaining bytes if string was short
while (ii < 16) {
buf[i + ii++] = 0;
}
return buf;
}
// **`unparse()` - Convert UUID byte array (ala parse()) into a string**
function unparse(buf, offset) {
var i = offset || 0, bth = _byteToHex;
return bth[buf[i++]] + bth[buf[i++]] +
bth[buf[i++]] + bth[buf[i++]] + '-' +
bth[buf[i++]] + bth[buf[i++]] + '-' +
bth[buf[i++]] + bth[buf[i++]] + '-' +
bth[buf[i++]] + bth[buf[i++]] + '-' +
bth[buf[i++]] + bth[buf[i++]] +
bth[buf[i++]] + bth[buf[i++]] +
bth[buf[i++]] + bth[buf[i++]];
}
// **`v1()` - Generate time-based UUID**
//
// Inspired by https://github.com/LiosK/UUID.js
// and http://docs.python.org/library/uuid.html
// random #'s we need to init node and clockseq
var _seedBytes = _rng();
// Per 4.5, create and 48-bit node id, (47 random bits + multicast bit = 1)
var _nodeId = [
_seedBytes[0] | 0x01,
_seedBytes[1], _seedBytes[2], _seedBytes[3], _seedBytes[4], _seedBytes[5]
];
// Per 4.2.2, randomize (14 bit) clockseq
var _clockseq = (_seedBytes[6] << 8 | _seedBytes[7]) & 0x3fff;
// Previous uuid creation time
var _lastMSecs = 0, _lastNSecs = 0;
// See https://github.com/broofa/node-uuid for API details
function v1(options, buf, offset) {
var i = buf && offset || 0;
var b = buf || [];
options = options || {};
var clockseq = options.clockseq != null ? options.clockseq : _clockseq;
// UUID timestamps are 100 nano-second units since the Gregorian epoch,
// (1582-10-15 00:00). JSNumbers aren't precise enough for this, so
// time is handled internally as 'msecs' (integer milliseconds) and 'nsecs'
// (100-nanoseconds offset from msecs) since unix epoch, 1970-01-01 00:00.
var msecs = options.msecs != null ? options.msecs : new Date().getTime();
// Per 4.2.1.2, use count of uuid's generated during the current clock
// cycle to simulate higher resolution clock
var nsecs = options.nsecs != null ? options.nsecs : _lastNSecs + 1;
// Time since last uuid creation (in msecs)
var dt = (msecs - _lastMSecs) + (nsecs - _lastNSecs)/10000;
// Per 4.2.1.2, Bump clockseq on clock regression
if (dt < 0 && options.clockseq == null) {
clockseq = clockseq + 1 & 0x3fff;
}
// Reset nsecs if clock regresses (new clockseq) or we've moved onto a new
// time interval
if ((dt < 0 || msecs > _lastMSecs) && options.nsecs == null) {
nsecs = 0;
}
// Per 4.2.1.2 Throw error if too many uuids are requested
if (nsecs >= 10000) {
throw new Error('uuid.v1(): Can\'t create more than 10M uuids/sec');
}
_lastMSecs = msecs;
_lastNSecs = nsecs;
_clockseq = clockseq;
// Per 4.1.4 - Convert from unix epoch to Gregorian epoch
msecs += 12219292800000;
// `time_low`
var tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000;
b[i++] = tl >>> 24 & 0xff;
b[i++] = tl >>> 16 & 0xff;
b[i++] = tl >>> 8 & 0xff;
b[i++] = tl & 0xff;
// `time_mid`
var tmh = (msecs / 0x100000000 * 10000) & 0xfffffff;
b[i++] = tmh >>> 8 & 0xff;
b[i++] = tmh & 0xff;
// `time_high_and_version`
b[i++] = tmh >>> 24 & 0xf | 0x10; // include version
b[i++] = tmh >>> 16 & 0xff;
// `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant)
b[i++] = clockseq >>> 8 | 0x80;
// `clock_seq_low`
b[i++] = clockseq & 0xff;
// `node`
var node = options.node || _nodeId;
for (var n = 0; n < 6; n++) {
b[i + n] = node[n];
}
return buf ? buf : unparse(b);
}
// **`v4()` - Generate random UUID**
// See https://github.com/broofa/node-uuid for API details
function v4(options, buf, offset) {
// Deprecated - 'format' argument, as supported in v1.2
var i = buf && offset || 0;
if (typeof(options) == 'string') {
buf = options == 'binary' ? new BufferClass(16) : null;
options = null;
}
options = options || {};
var rnds = options.random || (options.rng || _rng)();
// Per 4.4, set bits for version and `clock_seq_hi_and_reserved`
rnds[6] = (rnds[6] & 0x0f) | 0x40;
rnds[8] = (rnds[8] & 0x3f) | 0x80;
// Copy bytes to buffer, if provided
if (buf) {
for (var ii = 0; ii < 16; ii++) {
buf[i + ii] = rnds[ii];
}
}
return buf || unparse(rnds);
}
// Export public API
var uuid = v4;
uuid.v1 = v1;
uuid.v4 = v4;
uuid.parse = parse;
uuid.unparse = unparse;
uuid.BufferClass = BufferClass;
if (typeof(module) != 'undefined' && module.exports) {
// Publish as node.js module
module.exports = uuid;
} else if (typeof define === 'function' && define.amd) {
// Publish as AMD module
define(function() {return uuid;});
} else {
// Publish as global (in browsers)
var _previousRoot = _global.uuid;
// **`noConflict()` - (browser only) to reset global 'uuid' var**
uuid.noConflict = function() {
_global.uuid = _previousRoot;
return uuid;
};
_global.uuid = uuid;
}
}).call(this);
| mit |
herschel666/phox | lib/definitions/exif.ts | 453 | declare module 'exif' {
export type TYPE_NO_EXIF_SEGMENT = 'NO_EXIF_SEGMENT';
interface ExifImageArgs {
image: string;
}
export interface Exif {
[x: string]: any;
}
export interface ExifError extends Error {
code: TYPE_NO_EXIF_SEGMENT | string;
}
type callback = (err: ExifError | null, exif: Exif) => void;
export class ExifImage {
public exifData: Exif;
constructor(args: ExifImageArgs, cb: callback);
}
}
| mit |
eileenzhuang1/mozu-java | mozu-java-test/src/main/java/com/mozu/test/framework/datafactory/LocationUsageFactory.java | 5138 | /**
* This code was auto-generated by a tool.
*
* Changes to this file may cause incorrect behavior and will be lost if
* the code is regenerated.
*/
package com.mozu.test.framework.datafactory;
import java.util.List;
import java.util.ArrayList;
import com.mozu.api.ApiException;
import com.mozu.api.ApiContext;
import com.mozu.test.framework.core.TestFailException;
import com.mozu.api.resources.commerce.settings.LocationUsageResource;
/** <summary>
* Use the Location Usages resource to define the locations and location types that interact with the specified site. The system creates three default location usage types for each site after provisioning a new tenant - one for direct ship (DS), one for in-store pickup (SP), and one for store finder (storeFinder). Each site can only use a single location for the direct ship location usage type, and the location must support the direct ship fulfillment type (DS). For the in-store pickup location usage type, each site can use one or more location types. The location service identifies all locations of the specified type that support the in-store pickup fulfillment type (SP). For the store finder location usage type, each site can use one or more location types. The location service identifies all locations of the type. Locations configured for the store finder type do not typically maintain inventory. You cannot create additional location usage types at this time.
* </summary>
*/
public class LocationUsageFactory
{
public static com.mozu.api.contracts.location.LocationUsageCollection getLocationUsages(ApiContext apiContext, int expectedCode, int successCode) throws Exception
{
return getLocationUsages(apiContext, null, expectedCode, successCode );
}
public static com.mozu.api.contracts.location.LocationUsageCollection getLocationUsages(ApiContext apiContext, String responseFields, int expectedCode, int successCode) throws Exception
{
com.mozu.api.contracts.location.LocationUsageCollection returnObj = new com.mozu.api.contracts.location.LocationUsageCollection();
LocationUsageResource resource = new LocationUsageResource(apiContext);
try
{
returnObj = resource.getLocationUsages( responseFields);
}
catch (ApiException e)
{
if(e.getHttpStatusCode() != expectedCode)
throw new TestFailException(e.getHttpStatusCode(), Thread.currentThread().getStackTrace()[2].getMethodName(), expectedCode, "");
else
return null;
}
if(expectedCode != successCode)
throw new TestFailException(successCode, Thread.currentThread().getStackTrace()[2].getMethodName(), expectedCode, "");
return returnObj;
}
public static com.mozu.api.contracts.location.LocationUsage getLocationUsage(ApiContext apiContext, String code, int expectedCode, int successCode) throws Exception
{
return getLocationUsage(apiContext, code, null, expectedCode, successCode );
}
public static com.mozu.api.contracts.location.LocationUsage getLocationUsage(ApiContext apiContext, String code, String responseFields, int expectedCode, int successCode) throws Exception
{
com.mozu.api.contracts.location.LocationUsage returnObj = new com.mozu.api.contracts.location.LocationUsage();
LocationUsageResource resource = new LocationUsageResource(apiContext);
try
{
returnObj = resource.getLocationUsage( code, responseFields);
}
catch (ApiException e)
{
if(e.getHttpStatusCode() != expectedCode)
throw new TestFailException(e.getHttpStatusCode(), Thread.currentThread().getStackTrace()[2].getMethodName(), expectedCode, "");
else
return null;
}
if(expectedCode != successCode)
throw new TestFailException(successCode, Thread.currentThread().getStackTrace()[2].getMethodName(), expectedCode, "");
return returnObj;
}
public static com.mozu.api.contracts.location.LocationUsage updateLocationUsage(ApiContext apiContext, com.mozu.api.contracts.location.LocationUsage usage, String code, int expectedCode, int successCode) throws Exception
{
return updateLocationUsage(apiContext, usage, code, null, expectedCode, successCode );
}
public static com.mozu.api.contracts.location.LocationUsage updateLocationUsage(ApiContext apiContext, com.mozu.api.contracts.location.LocationUsage usage, String code, String responseFields, int expectedCode, int successCode) throws Exception
{
com.mozu.api.contracts.location.LocationUsage returnObj = new com.mozu.api.contracts.location.LocationUsage();
LocationUsageResource resource = new LocationUsageResource(apiContext);
try
{
returnObj = resource.updateLocationUsage( usage, code, responseFields);
}
catch (ApiException e)
{
if(e.getHttpStatusCode() != expectedCode)
throw new TestFailException(e.getHttpStatusCode(), Thread.currentThread().getStackTrace()[2].getMethodName(), expectedCode, "");
else
return null;
}
if(expectedCode != successCode)
throw new TestFailException(successCode, Thread.currentThread().getStackTrace()[2].getMethodName(), expectedCode, "");
return returnObj;
}
}
| mit |
modmore/ClientConfig | core/components/clientconfig/model/clientconfig/clientconfig.class.php | 6036 | <?php
/**
* ClientConfig
*
* Copyright 2011-2014 by Mark Hamstra <hello@markhamstra.com>
*
* ClientConfig 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.
*
* ClientConfig 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
* ClientConfig; if not, write to the Free Software Foundation, Inc., 59 Temple Place,
* Suite 330, Boston, MA 02111-1307 USA
*
* @package clientconfig
*/
class ClientConfig {
/**
* @var modX|null $modx
*/
public $modx = null;
/**
* @var array
*/
public $config = array();
/**
* @var bool
*/
public $debug = false;
/**
* @param \modX $modx
* @param array $config
*/
public function __construct(modX &$modx,array $config = array()) {
$this->modx =& $modx;
$corePath = $this->modx->getOption('clientconfig.core_path',$config,$this->modx->getOption('core_path').'components/clientconfig/');
$assetsUrl = $this->modx->getOption('clientconfig.assets_url',$config,$this->modx->getOption('assets_url').'components/clientconfig/');
$assetsPath = $this->modx->getOption('clientconfig.assets_path',$config,$this->modx->getOption('assets_path').'components/clientconfig/');
$this->config = array_merge(array(
'basePath' => $corePath,
'corePath' => $corePath,
'modelPath' => $corePath.'model/',
'processorsPath' => $corePath.'processors/',
'elementsPath' => $corePath.'elements/',
'templatesPath' => $corePath.'templates/',
'assetsPath' => $assetsPath,
'jsUrl' => $assetsUrl.'js/',
'cssUrl' => $assetsUrl.'css/',
'assetsUrl' => $assetsUrl,
'connectorUrl' => $assetsUrl.'connector.php',
'verticalTabs' => (bool)$this->modx->getOption('clientconfig.vertical_tabs', null, false),
),$config);
$modelPath = $this->config['modelPath'];
$this->modx->addPackage('clientconfig',$modelPath);
$this->modx->lexicon->load('clientconfig:default');
$this->debug = (bool)$this->modx->getOption('clientconfig.debug',null,false);
}
/**
* Grab settings (from cache if possible) as key => value pairs.
* @param string $context
* @return array|mixed
*/
public function getSettings($context = '') {
/* Attempt to get from cache */
$cacheOptions = array(xPDO::OPT_CACHE_KEY => 'system_settings');
$settings = $this->modx->getCacheManager()->get('clientconfig', $cacheOptions);
if (!is_array($settings) || !array_key_exists('global', $settings)) {
$settings = array(
'global' => array(),
'contexts' => array(),
);
$collection = $this->modx->getCollection('cgSetting');
/* @var cgSetting[] $collection */
foreach ($collection as $setting) {
$isMedia = in_array($setting->get('xtype'), ['modx-panel-tv-image', 'modx-panel-tv-file'], true);
$value = $setting->get('value');
if ($isMedia) {
$value = $setting->prefixSourceUrl($value);
}
$settings['global'][$setting->get('key')] = $value;
/** @var cgContextValue[] $contextValues */
$contextValues = $setting->getMany('ContextValues');
if (is_array($contextValues)) {
foreach ($contextValues as $cVal) {
$cKey = $cVal->get('context');
if (!array_key_exists($cKey, $settings['contexts'])) {
$settings['contexts'][$cKey] = array();
}
$value = $cVal->get('value');
if ($isMedia) {
$value = $setting->prefixSourceUrl($value);
}
if (!empty($value)) {
$settings['contexts'][$cKey][$setting->get('key')] = $value;
}
}
}
}
/* Write to cache again */
$this->modx->cacheManager->set('clientconfig', $settings, 0, $cacheOptions);
}
if (!is_array($settings)) {
return array();
}
$return = array_key_exists('global', $settings) ? $settings['global'] : array();
if ($context !== ''
&& array_key_exists('contexts', $settings)
&& array_key_exists($context, $settings['contexts'])
&& $this->modx->getOption('clientconfig.context_aware')
) {
$return = array_merge($return, $settings['contexts'][$context]);
}
return $return;
}
/**
* Indicates if the logged in user has admin permissions.
* @return bool
*/
public function hasAdminPermission() {
if (!$this->modx->user || ($this->modx->user->get('id') < 1)) {
return false;
}
$usergroups = $this->modx->getOption('clientconfig.admin_groups', null, 'Administrator');
$usergroups = explode(',', $usergroups);
$isMember = $this->modx->user->isMember($usergroups, false);
/* If we're not a member of the usergroup(s), check for sudo */
if (!$isMember) {
$v = $this->modx->getVersionData();
if (version_compare($v['full_version'], '2.2.1-pl') == 1) {
$isMember = (bool)$this->modx->user->get('sudo');
}
}
return $isMember;
}
}
| mit |
tip4commit/tip4commit | features/support/to_ostruct.rb | 378 | # frozen_string_literal: true
require 'ostruct'
class Hash
def to_ostruct
o = OpenStruct.new(self)
each do |k, v|
o.send(:"#{k}=", v.to_ostruct) if v.respond_to? :to_ostruct
end
o
end
end
class Array
def to_ostruct
map do |item|
if item.respond_to? :to_ostruct
item.to_ostruct
else
item
end
end
end
end
| mit |
quepasso/qblog | src/Fil/CoreBundle/Entity/CategoryRepository.php | 262 | <?php
namespace Fil\CoreBundle\Entity;
use Doctrine\ORM\EntityRepository;
/**
* CategoryRepository
*
* This class was generated by the Doctrine ORM. Add your own custom
* repository methods below.
*/
class CategoryRepository extends EntityRepository
{
}
| mit |
mmiddleton3301/intersproc | Meridian.InterSproc/Meridian.InterSproc/Definitions/IStubClassGenerator.cs | 1601 | // ----------------------------------------------------------------------------
// <copyright file="IStubClassGenerator.cs" company="MTCS">
// Copyright (c) MTCS 2018.
// MTCS is a trading name of Meridian Technology Consultancy Services Ltd.
// Meridian Technology Consultancy Services Ltd is registered in England and
// Wales. Company number: 11184022.
// </copyright>
// ----------------------------------------------------------------------------
namespace Meridian.InterSproc.Definitions
{
using System;
using System.CodeDom;
using System.Collections.Generic;
using Meridian.InterSproc.Models;
/// <summary>
/// Describes the operations provided by the stub class generator.
/// </summary>
public interface IStubClassGenerator
{
/// <summary>
/// Creates a dapper-based implementation of the
/// <paramref name="databaseContractType" /> based on the array
/// <see cref="ContractMethodInformation" /> instances passed in.
/// </summary>
/// <param name="databaseContractType">
/// A <see cref="Type" /> instance, describing the database contract.
/// </param>
/// <param name="contractMethodInformations">
/// A collection of <see cref="ContractMethodInformation" /> instances.
/// </param>
/// <returns>
/// An instance of <see cref="CodeTypeDeclaration" />.
/// </returns>
CodeTypeDeclaration CreateClass(
Type databaseContractType,
IEnumerable<ContractMethodInformation> contractMethodInformations);
}
} | mit |
peq/rustyeclipse | rustyeclipse_plugin/src/rustyeclipse/editors/autocomplete/RustContentAssistant.java | 5633 | package rustyeclipse.editors.autocomplete;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.core.resources.IProject;
import org.eclipse.jdt.annotation.NonNull;
import org.eclipse.jdt.annotation.Nullable;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.ITextViewer;
import org.eclipse.jface.text.contentassist.CompletionProposal;
import org.eclipse.jface.text.contentassist.ICompletionProposal;
import org.eclipse.jface.text.contentassist.IContentAssistProcessor;
import org.eclipse.jface.text.contentassist.IContentAssistant;
import org.eclipse.jface.text.contentassist.IContextInformation;
import org.eclipse.jface.text.contentassist.IContextInformationValidator;
import org.eclipse.jface.text.source.ISourceViewer;
import org.eclipse.swt.graphics.Image;
import com.google.common.base.Charsets;
import com.google.common.io.Files;
import rustyeclipse.builder.SourcePos;
import rustyeclipse.editor.RustHyperlink;
import rustyeclipse.editors.RustEditor;
import rustyeclipse.preferences.RustPrefs;
import rustyeclipse.ui.Icons;
import rustyeclipse.util.Utils;
public class RustContentAssistant implements IContentAssistProcessor {
private RustEditor editor;
public RustContentAssistant(RustEditor editor) {
this.editor = editor;
}
@Override
public ICompletionProposal @Nullable [] computeCompletionProposals(@Nullable ITextViewer viewer, int offset) {
File tempFile = null;
try {
IDocument document = viewer.getDocument();
int lineNr = document.getLineOfOffset(offset);
int columnNr = offset - document.getLineOffset(lineNr);
lineNr++;
// columnNr++;
File file = editor.getFile().getLocation().toFile();
tempFile = new File(file.getParent(), file.getName() + ".racertmp");
String text = document.get();
Files.write(text, tempFile, Charsets.UTF_8);
List<String> command = new ArrayList<>();
command.add(RustPrefs.get().getRacerCommand());
command.add("complete");
command.add("" + lineNr);
command.add("" + columnNr);
command.add(tempFile.getAbsolutePath());
ProcessBuilder pb = new ProcessBuilder(command);
pb.environment().put("RUST_SRC_PATH", RustPrefs.get().getRustSrcPath());
Process proc = pb.start();
List<String> output = Utils.streamToList(proc.getInputStream());
List<String> errors = Utils.streamToList(proc.getErrorStream());
for (String msg : errors) {
System.out.println("ERROR: " + msg);
}
List<ICompletionProposal> completions = new ArrayList<>();
int replacementOffset = 0;
String alreadyEntered = "";
System.out.println(command);
for (String msg : output) {
try {
System.out.println(msg);
if (msg.startsWith("PREFIX ")) {
msg = msg.substring("PREFIX ".length());
String[] parts = msg.split(",");
int line = Integer.parseInt(parts[0]);
int column = Integer.parseInt(parts[1]);
if (parts.length > 2) {
alreadyEntered = parts[2];
}
replacementOffset = offset-alreadyEntered.length();
// correct
// replacementOffset = Utils.findPosOfString(text, alreadyEntered, replacementOffset);
} else if (msg.startsWith("MATCH ")) {
msg = msg.substring("MATCH ".length());
String[] parts = msg.split(",");
String matched = parts[0];
int line = Integer.parseInt(parts[1]);
int column = Integer.parseInt(parts[2]);
String declFile = parts[3];
String type = parts[4];
String preview = parts[5];
if (new File(declFile).equals(tempFile)) {
declFile = file.getAbsolutePath();
// TODO remove duplicates
}
String replacementString = matched;
int replacementLength = alreadyEntered.length();
int cursorPosition = matched.length();
Image image = null;
String displayString = matched;
IContextInformation contextInformation = null;
String additionalProposalInfo = null;
if (type.equals("Function")) {
replacementString += "()";
cursorPosition += 1;
image = Icons.function;
} else if (type.equals("Module")) {
image = Icons.wpackage;
} else if (type.equals("Struct")) {
image = Icons.wclass;
} else if (type.equals("Enum") || type.equals("EnumVariant")) {
image = Icons.wenum;
} else if (type.equals("Type") || type.equals("Trait")) {
image = Icons.winterface; // TODO better icon?
} else {
displayString = type + " " + displayString;
}
completions.add(new CompletionProposal(replacementString, replacementOffset, replacementLength,
cursorPosition, image, displayString, contextInformation, additionalProposalInfo));
}
} catch (Throwable t) {
//
t.printStackTrace();
}
}
if (!completions.isEmpty()) {
return completions.toArray(new ICompletionProposal[0]);
}
} catch (IOException | BadLocationException e) {
e.printStackTrace();
} finally {
if (tempFile != null) {
tempFile.delete();
}
}
return null;
}
@Override
public IContextInformation[] computeContextInformation(@Nullable ITextViewer viewer, int offset) {
return null;
}
@Override
public char[] getCompletionProposalAutoActivationCharacters() {
return new char[] { '.', ':' };
}
@Override
public char[] getContextInformationAutoActivationCharacters() {
return null;
}
@Override
public String getErrorMessage() {
return null;
}
@Override
public IContextInformationValidator getContextInformationValidator() {
return null;
}
}
| mit |
tvetan/android | WorkHoursTracker/src/com/cai/workhourstracker/TagsAddDialogFragment.java | 3611 | package com.cai.workhourstracker;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import com.cai.workhourstracker.adapters.TagsArrayAdapter;
import com.cai.workhourstracker.model.TagRow;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;
public class TagsAddDialogFragment extends DialogFragment {
public interface TagsChangeListener {
public void onTagsChangeTime(String time);
}
TagsChangeListener mListener;
private ImageView addTagButton;
private TextView tagName;
private ListView tags;
private List<TagRow> tagRows;
static TagsAddDialogFragment newInstance() {
TagsAddDialogFragment f = new TagsAddDialogFragment();
// Supply num input as an argument.
// Bundle args = new Bundle();
// args.putInt("num", num);
// f.setArguments(args);
return f;
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();
final View view = inflater.inflate(R.layout.dialog_tags, null);
tagName = (TextView) view.findViewById(R.id.tag_name_dialog);
tags = (ListView) view.findViewById(R.id.tags_dialog);
tagRows = new ArrayList<TagRow>();
tagRows.add(new TagRow("test", true));
tagRows.add(new TagRow("tes1", false));
tagRows.add(new TagRow("tes3", true));
TagsArrayAdapter adapter = new TagsArrayAdapter(getActivity(),
tagRows.toArray(new TagRow[tagRows.size()]));
tags.setAdapter(adapter);
addTagButton = (ImageView) view.findViewById(R.id.add_tag_dialog);
addTagButton.setClickable(true);
addTagButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String name = tagName.getText().toString();
tagName.setText("");
if (name == null || name.isEmpty()) {
Toast.makeText(getActivity(),
"No tag name", Toast.LENGTH_SHORT)
.show();
}else{
TagRow addedRow = new TagRow(name, false);
tagRows.add(addedRow);
TagsArrayAdapter newAdapter = new TagsArrayAdapter(getActivity(),
tagRows.toArray(new TagRow[tagRows.size()]));
tags.setAdapter(newAdapter);
}
}
});
builder.setView(view)
.setPositiveButton(R.string.stop_clock,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
}
})
.setNegativeButton(R.string.cancel,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
return builder.create();
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
// Verify that the host activity implements the callback interface
try {
// Instantiate the NoticeDialogListener so we can send events to the
// host
mListener = (TagsChangeListener) activity;
} catch (ClassCastException e) {
// The activity doesn't implement the interface, throw exception
throw new ClassCastException(activity.toString()
+ " must implement TagsChangeListener");
}
}
}
| mit |
BorisPenev/TelerikAcademy | CSharp-part1/Operators and Expressions/14.ModifyABitAtGivenPosition/Properties/AssemblyInfo.cs | 1432 | 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("14.ModifyABitAtGivenPosition")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("14.ModifyABitAtGivenPosition")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[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("4d71d771-1093-444f-9d0a-9c21e2900e9c")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| mit |
DzianisPasiukou/StuckPointPlacement | typings/tsd.d.ts | 299 | /// <reference path="angularjs/angular.d.ts" />
/// <reference path="jquery/jquery.d.ts" />
/// <reference path="jasmine/jasmine.d.ts" />
/// <reference path="rx/rx-lite.d.ts" />
/// <reference path="rx/rx.d.ts" />
/// <reference path="d3/d3.d.ts" />
/// <reference path="requirejs/require.d.ts" />
| mit |
aliyun/fc-java-sdk | src/main/java/com/aliyuncs/fc/response/ListCustomDomainsResponse.java | 793 | package com.aliyuncs.fc.response;
import com.aliyuncs.fc.http.HttpResponse;
import com.aliyuncs.fc.model.CustomDomainMetaData;
import com.aliyuncs.fc.model.ServiceMetadata;
public class ListCustomDomainsResponse extends HttpResponse {
private CustomDomainMetaData[] customDomains = null;
private String nextToken = null;
public CustomDomainMetaData[] getCustomDomains() {
return customDomains;
}
public ListCustomDomainsResponse setCustomDomains(CustomDomainMetaData[] customDomains) {
this.customDomains = customDomains;
return this;
}
public String getNextToken() {
return nextToken;
}
public ListCustomDomainsResponse setNextToken(String nextToken) {
this.nextToken = nextToken;
return this;
}
}
| mit |
ccampo133/TestsAndDesignPatternsDemos | MVPDemo/Models/Capitalizer.cs | 191 | namespace MVPDemo.Models
{
public class Capitalizer : ICapitalizer
{
public string Capitalize(string input)
{
return input.ToUpper();
}
}
}
| mit |
cloverstudio/Spika-Android | app/src/main/java/com/clover_studio/spikachatmodule/models/FileModel.java | 1406 | package com.clover_studio.spikachatmodule.models;
import android.os.Parcel;
import android.os.Parcelable;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
/**
* Created by ubuntu_ivo on 22.07.15..
*/
@JsonIgnoreProperties(ignoreUnknown = true)
public class FileModel implements Parcelable{
public FileModelDetails file;
public FileModelDetails thumb;
public FileModel() {
}
@Override
public String toString() {
return "UploadFile{" +
"file=" + file +
", thumb=" + thumb +
'}';
}
protected FileModel(Parcel in) {
file = (FileModelDetails) in.readValue(FileModelDetails.class.getClassLoader());
thumb = (FileModelDetails) in.readValue(FileModelDetails.class.getClassLoader());
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeValue(file);
dest.writeValue(thumb);
}
@SuppressWarnings("unused")
public static final Parcelable.Creator<FileModel> CREATOR = new Parcelable.Creator<FileModel>() {
@Override
public FileModel createFromParcel(Parcel in) {
return new FileModel(in);
}
@Override
public FileModel[] newArray(int size) {
return new FileModel[size];
}
};
}
| mit |
RealImage/QLedger | controllers/transactions_test.go | 6314 | package controllers
import (
"bytes"
"database/sql"
"log"
"net/http"
"net/http/httptest"
"os"
"testing"
ledgerContext "github.com/RealImage/QLedger/context"
"github.com/RealImage/QLedger/middlewares"
_ "github.com/lib/pq"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/suite"
)
var (
TransactionsAPI = "/v1/transactions"
)
type TransactionsSuite struct {
suite.Suite
context *ledgerContext.AppContext
}
func (ts *TransactionsSuite) SetupSuite() {
log.Println("Connecting to the test database")
databaseURL := os.Getenv("TEST_DATABASE_URL")
assert.NotEmpty(ts.T(), databaseURL)
db, err := sql.Open("postgres", databaseURL)
if err != nil {
log.Panic("Unable to connect to Database:", err)
}
log.Println("Successfully established connection to database.")
ts.context = &ledgerContext.AppContext{DB: db}
}
func (ts *TransactionsSuite) TestValidAndRepeatedTransaction() {
t := ts.T()
// Valid transaction
payload := `{
"id": "t001",
"lines": [
{
"account": "alice",
"delta": 100
},
{
"account": "bob",
"delta": -100
}
],
"data": {
"tag_one": "val1",
"tag_two": "val2"
}
}`
handler := middlewares.ContextMiddleware(MakeTransaction, ts.context)
req, err := http.NewRequest("POST", TransactionsAPI, bytes.NewBufferString(payload))
if err != nil {
t.Fatal(err)
}
rr1 := httptest.NewRecorder()
handler.ServeHTTP(rr1, req)
assert.Equal(t, http.StatusCreated, rr1.Code, "Invalid response code")
// Duplicate transaction
req, err = http.NewRequest("POST", TransactionsAPI, bytes.NewBufferString(payload))
if err != nil {
t.Fatal(err)
}
rr2 := httptest.NewRecorder()
handler.ServeHTTP(rr2, req)
assert.Equal(t, http.StatusAccepted, rr2.Code, "Invalid response code")
// Conflict transaction
payload = `{
"id": "t001",
"lines": [
{
"account": "alice",
"delta": 200
},
{
"account": "bob",
"delta": -200
}
]
}`
req, err = http.NewRequest("POST", TransactionsAPI, bytes.NewBufferString(payload))
if err != nil {
t.Fatal(err)
}
rr3 := httptest.NewRecorder()
handler.ServeHTTP(rr3, req)
assert.Equal(t, http.StatusConflict, rr3.Code, "Invalid response code")
}
func (ts *TransactionsSuite) TestNoOpTransaction() {
t := ts.T()
rr := httptest.NewRecorder()
payload := `{
"id": "t002",
"lines": []
}`
handler := middlewares.ContextMiddleware(MakeTransaction, ts.context)
req, err := http.NewRequest("POST", TransactionsAPI, bytes.NewBufferString(payload))
if err != nil {
t.Fatal(err)
}
handler.ServeHTTP(rr, req)
assert.Equal(t, http.StatusCreated, rr.Code, "Invalid response code")
}
func (ts *TransactionsSuite) TestInvalidTransaction() {
t := ts.T()
rr := httptest.NewRecorder()
payload := `{
"id": "t003",
"lines": [
{
"account": "alice",
"delta": 100
},
{
"account": "bob",
"delta": -101
}
]
}`
handler := middlewares.ContextMiddleware(MakeTransaction, ts.context)
req, err := http.NewRequest("POST", TransactionsAPI, bytes.NewBufferString(payload))
if err != nil {
t.Fatal(err)
}
handler.ServeHTTP(rr, req)
assert.Equal(t, http.StatusBadRequest, rr.Code, "Invalid response code")
}
func (ts *TransactionsSuite) TestBadTransaction() {
t := ts.T()
rr := httptest.NewRecorder()
payload := `{
INVALID PAYLOAD
}`
handler := middlewares.ContextMiddleware(MakeTransaction, ts.context)
req, err := http.NewRequest("POST", TransactionsAPI, bytes.NewBufferString(payload))
if err != nil {
t.Fatal(err)
}
handler.ServeHTTP(rr, req)
assert.Equal(t, http.StatusBadRequest, rr.Code, "Invalid response code")
}
func (ts *TransactionsSuite) TestFailTransaction() {
t := ts.T()
rr := httptest.NewRecorder()
payload := `{
"id": "t004",
"lines": [
{
"account": "alice",
"delta": 100
},
{
"account": "bob",
"delta": -100
}
]
}`
// database is not available
db, _ := sql.Open("postgres", "")
invalidContext := &ledgerContext.AppContext{DB: db}
handler := middlewares.ContextMiddleware(MakeTransaction, invalidContext)
req, err := http.NewRequest("POST", TransactionsAPI, bytes.NewBufferString(payload))
if err != nil {
t.Fatal(err)
}
handler.ServeHTTP(rr, req)
assert.Equal(t, http.StatusInternalServerError, rr.Code, "Invalid response code")
}
func (ts *TransactionsSuite) TestCreateTransactionWithBoundaryValues() {
t := ts.T()
// In-boundary value transaction
payload := `{
"id": "t005",
"lines": [
{
"account": "carly",
"delta": 9223372036854775807
},
{
"account": "dev",
"delta": -9223372036854775807
}
],
"data": {
"tag_one": "val1",
"tag_two": "val2"
}
}`
handler := middlewares.ContextMiddleware(MakeTransaction, ts.context)
req, err := http.NewRequest("POST", TransactionsAPI, bytes.NewBufferString(payload))
if err != nil {
t.Fatal(err)
}
rr1 := httptest.NewRecorder()
handler.ServeHTTP(rr1, req)
assert.Equal(t, http.StatusCreated, rr1.Code, "Invalid response code")
// Out-of-boundary value transaction
payload = `{
"id": "t006",
"lines": [
{
"account": "eve",
"delta": 9223372036854775808
},
{
"account": "foo",
"delta": -9223372036854775808
}
],
"data": {
"tag_one": "val1",
"tag_two": "val2"
}
}`
handler = middlewares.ContextMiddleware(MakeTransaction, ts.context)
req, err = http.NewRequest("POST", TransactionsAPI, bytes.NewBufferString(payload))
if err != nil {
t.Fatal(err)
}
rr1 = httptest.NewRecorder()
handler.ServeHTTP(rr1, req)
assert.Equal(t, http.StatusBadRequest, rr1.Code, "Invalid response code")
}
func (ts *TransactionsSuite) TearDownSuite() {
log.Println("Cleaning up the test database")
t := ts.T()
_, err := ts.context.DB.Exec(`DELETE FROM lines`)
if err != nil {
t.Fatal("Error deleting lines:", err)
}
_, err = ts.context.DB.Exec(`DELETE FROM transactions`)
if err != nil {
t.Fatal("Error deleting transactions:", err)
}
_, err = ts.context.DB.Exec(`DELETE FROM accounts`)
if err != nil {
t.Fatal("Error deleting accounts:", err)
}
}
func TestTransactionsSuite(t *testing.T) {
suite.Run(t, new(TransactionsSuite))
}
| mit |
gregwym/joos-compiler-java | src/ca/uwaterloo/joos/ast/descriptor/ChildDescriptor.java | 215 | /**
*
*/
package ca.uwaterloo.joos.ast.descriptor;
/**
* @author wenzhuman
*
*/
public class ChildDescriptor extends Descriptor {
public ChildDescriptor(Class<?> elementType) {
super(elementType);
}
}
| mit |
ThorConzales/AoE2HDLobbyCompanion | Client/Client/src/app/players/index.ts | 91 | export * from './players.module';
export * from './players-page/players-page.component'; | mit |
dillonliang224/React-CMS | src/common/reducers/articles.js | 288 | import { handleActions } from 'redux-actions';
import { fetchArticles } from '../actions/index.js';
export default handleActions({
FETCH_ARTICLES: (state, action) => {
let payload = action.payload;
return {...state, isFetching: false, articles: payload.articles};
}
}, {});
| mit |