repo_name
stringlengths
4
116
path
stringlengths
4
379
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
limikael/netpoker
adapters/wpnetpoker/src/utils/Template.php
2737
<?php namespace wpnetpoker; /** * Echo for attribute. */ function echo_attr($s) { echo htmlspecialchars($s); } /** * Echo for html. */ function echo_html($s) { echo htmlspecialchars($s); } /** * A simple templating engine. This is a simple example of how to use this class: * * <code> * $t=new Template("templatefile.php"); * $t->set("hello","hello world"); * $t->show(); * </code> * * In this example, we have a template called `templatefile.php` that gets loaded * and rendered using the `show` call. The variables registered using the `set` method * will be made available to the template in the global scope. The contents of * the `templatefile.php` for this example could be: * * <code> * <html> * <body> * We say hello like this: <?php echo $hello; ?> * </body> * </html> * </code> */ class Template { private $filename; private $vars; /** * Create a Template for the specified file. * @param mixed $filename The file to use as template. */ public function __construct($filename) { $this->filename=$filename; $this->vars=array(); } /** * Set a variable that can be accessed by the template. * * The variable will be available to the template in the global scope. * @param mixed $name The name of the variable. * @param mixed $value The value that the variable should take. */ public function set($name, $value) { $this->vars[$name]=$value; } /** * Render the template and output it to the browser. */ public function show() { foreach ($this->vars as $key=>$value) $$key=$value; require $this->filename; } /** * Render template, but don't ouput it to the browser. * * This is useful if we want to * use a template inside another template. For example, we might have a * page template that defaines header and footer for our page. Inside the page * template we want to display the content generated by a content template. * We can do this by first rendering the content template: * * <code> * $contentTemplate=new Template("the_content_templte.php"); * // Set any variables used by the content template. * $content=$contentTemplate->render(); * </code> * * Now, we use the rendered content as input for our page template and output * everything to the browser: * * <code> * $pageTemplate=new Template("the_page_template.php"); * $pageTemplate->set("content",$content); * $pageTemplate->show(); * </code> */ public function render() { foreach ($this->vars as $key=>$value) $$key=$value; ob_start(); require $this->filename; return ob_get_clean(); } }
gpl-3.0
minego/wTerm
src/plugin/sdl/sdlfontgl.cpp
11569
/** * This file is part of SDLTerminal. * Copyright (C) 2012 Will Dietz <webos@wdtz.org> * * SDLTerminal 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. * * SDLTerminal 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 SDLTerminal. If not, see <http://www.gnu.org/licenses/>. */ #include "sdl/sdlfontgl.h" #include <syslog.h> // Log assertion failures to syslog #define assert(c) \ do { \ if (!(c)) \ syslog(LOG_ERR, "Assertion \"%s\" failed at %s:%d", \ __STRING(c), __FILE__, __LINE__); \ } while(0) // For debugging #define checkGLError() \ do { \ int err = glGetError(); \ if (err) syslog(LOG_ERR, "GL Error %x at %s:%d", \ err, __FILE__, __LINE__); \ } while(0) // How many characters do we support? static const int nChars = 128; // Helper functions static void getRGBAMask(Uint32 &rmask, Uint32 &gmask, Uint32 &bmask, Uint32 &amask) { #if SDL_BYTEORDER == SDL_BIG_ENDIAN rmask = 0xff000000; gmask = 0x00ff0000; bmask = 0x0000ff00; amask = 0x000000ff; #else rmask = 0x000000ff; gmask = 0x0000ff00; bmask = 0x00ff0000; amask = 0xff000000; #endif } static int getGLFormat() { SDL_Surface *s = SDL_GetVideoSurface(); if (s->format->BytesPerPixel == 3) return GL_RGB; if (s->format->BytesPerPixel == 4) return GL_RGBA; assert(0 && "Unsupported bpp"); return -1; } static unsigned nextPowerOfTwo(int n) { assert(n > 0); unsigned res = 1; while (res < (unsigned)n) res <<= 1; return res; } void SDLFontGL::setupFontGL(int fnCount, TTF_Font** fnts, int colCount, SDL_Color *cols) { clearGL(); assert(fnts && cols); assert((fnCount > 0) && (colCount > 0)); nFonts = fnCount; nCols = colCount; this->fnts = (TTF_Font**)malloc(nFonts*sizeof(TTF_Font*)); memcpy(this->fnts, fnts, nFonts*sizeof(TTF_Font*)); this->cols = (SDL_Color*)malloc(nCols*sizeof(SDL_Color)); memcpy(this->cols, cols, nCols*sizeof(SDL_Color)); GlyphCache = 0; haveCacheLine = (bool*)malloc(nFonts*MAX_CHARSETS*sizeof(bool)); memset(haveCacheLine, 0, nFonts*MAX_CHARSETS*sizeof(bool)); const Uint16 OStr[] = {'O', 0}; if (TTF_SizeUNICODE(fnts[0], OStr, &nWidth, &nHeight) != 0) assert(0 && "Failed to size font"); assert((nWidth > 0) && (nHeight > 0)); } void SDLFontGL::createTexture() { // Create Big GL texture: glGenTextures(1,&GlyphCache); glBindTexture(GL_TEXTURE_2D, GlyphCache); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); // Set size of the texture, but no data. // We want 1 extra row of pixel data // so we can draw solid colors as part // of the same operations. texW = nextPowerOfTwo(nChars*nWidth); texH = nextPowerOfTwo(nFonts*MAX_CHARSETS*nHeight + 1); int nMode = getGLFormat(); glTexImage2D(GL_TEXTURE_2D, 0, nMode, texW, texH, 0, nMode, GL_UNSIGNED_BYTE, NULL); checkGLError(); // Put a single white pixel at bottom of texture. // We use this as the 'texture' data for blitting // solid backgrounds. char whitepixel[] = { 255, 255, 255, 255 }; assert(nFonts && nHeight); glTexSubImage2D(GL_TEXTURE_2D, 0, 0,nFonts*MAX_CHARSETS*nHeight, 1, 1, GL_RGBA, GL_UNSIGNED_BYTE, whitepixel); checkGLError(); } SDLFontGL::~SDLFontGL() { clearGL(); } void SDLFontGL::clearGL() { if (GlyphCache) { glDeleteTextures(1, &GlyphCache); GlyphCache = 0; } free(haveCacheLine); free(fnts); free(cols); free(colorValues); free(texValues); free(vtxValues); haveCacheLine = 0; fnts = NULL; cols = NULL; colorValues = NULL; texValues = NULL; vtxValues = NULL; nFonts = nCols = 0; screenRows = screenCols = 0; numChars = 0; } void SDLFontGL::ensureCacheLine(int fnt, int slot) { assert(fnt >= 0 && fnt < nFonts); assert(slot >= 0 && slot < MAX_CHARSETS); assert(fnts && cols && GlyphCache && haveCacheLine); bool & have = hasCacheLine(fnt, slot); if (have) { return; } have = true; // Lookup requested font TTF_Font * font = fnts[fnt]; assert(font); // Grab the native video surface (so we can match its bpp) SDL_Surface* videoSurface = SDL_GetVideoSurface(); assert(videoSurface); assert(videoSurface->format->BitsPerPixel == 32); // Create a surface for all the characters Uint32 rmask, gmask, bmask, amask; getRGBAMask(rmask, gmask, bmask, amask); SDL_Surface* mainSurface = SDL_CreateRGBSurface(SDL_SWSURFACE, nChars*nWidth, nHeight, videoSurface->format->BitsPerPixel, rmask, gmask, bmask, amask); assert(mainSurface); // Render font in white, will colorize on-the-fly SDL_Color fg = { 255, 255, 255 }; // Set texture to entirely clear // TODO: Needed? Uint32 fillColor = SDL_MapRGBA(mainSurface->format, 0, 0, 0, SDL_ALPHA_TRANSPARENT); SDL_FillRect(mainSurface, NULL, fillColor); // For each character, render the glyph, and put in the appropriate location for(int i = 0; i < nChars; ++i) { // Lookup this character, and make a single-char string out of it. Uint16 C = charMappings[slot].map[i]; if (!C) C = (Uint16)i; Uint16 buf[2] = { C, 0 }; SDL_Surface* surface = TTF_RenderUNICODE_Blended(font, (const Uint16*)buf, fg); if (surface) { SDL_SetAlpha(surface, 0, 0); SDL_Rect dstRect = { 0, 0, nWidth, nHeight }; dstRect.x = i*nWidth; SDL_BlitSurface(surface, 0, mainSurface, &dstRect); SDL_FreeSurface(surface); } } // Now upload the big set of characters as a single texture: { int nMode = getGLFormat(); glBindTexture(GL_TEXTURE_2D, GlyphCache); // Upload this font to its place in the big texture glTexSubImage2D(GL_TEXTURE_2D, 0, 0, (slot*nFonts + fnt)*nHeight, mainSurface->w, mainSurface->h, nMode, GL_UNSIGNED_BYTE, mainSurface->pixels); glFlush(); } SDL_FreeSurface(mainSurface); } void SDLFontGL::drawBackground(int color, int nX, int nY, int cells) { // Blit a rectangle of the specified color at the specified coordinates // (Err, don't blit, but insert into our arrays the equivalent) const int stride = 12; GLfloat *tex = &texValues[stride*numChars]; GLfloat *vtx = &vtxValues[stride*numChars]; GLfloat *clrs = &colorValues[2*stride*numChars]; ++numChars; GLfloat vtxCopy[] = { nX, nY, nX, nY + nHeight, nX + cells*nWidth, nY, nX, nY + nHeight, nX + cells*nWidth, nY, nX + cells*nWidth, nY + nHeight }; memcpy(vtx, vtxCopy, sizeof(vtxCopy)); float y_offset = ((float)nFonts*MAX_CHARSETS*nHeight)/(float)texH; float x1 = ((float)1)/(float)texW; float y1 = ((float)1)/(float)texH; GLfloat texCopy[] = { 0.0, y_offset, 0.0, y_offset + y1, x1, y_offset, 0.0, y_offset + y1, x1, y_offset, x1, y_offset + y1 }; memcpy(tex, texCopy, sizeof(texCopy)); // Duplicate color... SDL_Color bgc = cols[color]; GLfloat colorCopy[] = { ((float)bgc.r)/255.f, ((float)bgc.g)/255.f, ((float)bgc.b)/255.f, 1.f, }; for(unsigned i = 0; i < 6; ++i) { memcpy(&clrs[i*4], colorCopy, sizeof(colorCopy)); } } void SDLFontGL::drawTextGL(TextGraphicsInfo_t & graphicsInfo, int nX, int nY, const char * text) { if (!GlyphCache) createTexture(); int fnt = graphicsInfo.font; int fg = graphicsInfo.fg; int bg = graphicsInfo.bg; int blink = graphicsInfo.blink; assert(fnt >= 0 && fnt < nFonts); assert(fg >= 0 && fg < nCols); assert(bg >= 0 && bg < nCols); assert(fnts && cols && GlyphCache); unsigned len = strlen(text); // Ensure we have the needed font/slots: ensureCacheLine(fnt, graphicsInfo.slot1); ensureCacheLine(fnt, graphicsInfo.slot2); const int stride = 12; // GL_TRIANGLE_STRIP 2*6 drawBackground(bg, nX, nY, len); if (blink) return; GLfloat *tex = &texValues[stride*numChars]; GLfloat *vtx = &vtxValues[stride*numChars]; GLfloat *clrs = &colorValues[2*stride*numChars]; numChars += len; float x_scale = ((float)nWidth) / (float)texW; float y_scale = ((float)nHeight) / (float)texH; GLfloat texCopy[] = { 0.0, 0.0, 0.0, y_scale, x_scale, 0.0, 0.0, y_scale, x_scale, 0.0, x_scale, y_scale }; GLfloat vtxCopy[] = { nX, nY, nX, nY + nHeight, nX + nWidth, nY, nX, nY + nHeight, nX + nWidth, nY, nX + nWidth, nY + nHeight }; SDL_Color fgc = cols[fg]; GLfloat colorCopy[] = { ((float)fgc.r)/255.f, ((float)fgc.g)/255.f, ((float)fgc.b)/255.f, 1.f, ((float)fgc.r)/255.f, ((float)fgc.g)/255.f, ((float)fgc.b)/255.f, 1.f, ((float)fgc.r)/255.f, ((float)fgc.g)/255.f, ((float)fgc.b)/255.f, 1.f, ((float)fgc.r)/255.f, ((float)fgc.g)/255.f, ((float)fgc.b)/255.f, 1.f, ((float)fgc.r)/255.f, ((float)fgc.g)/255.f, ((float)fgc.b)/255.f, 1.f, ((float)fgc.r)/255.f, ((float)fgc.g)/255.f, ((float)fgc.b)/255.f, 1.f }; for (unsigned i = 0; i < len; ++i) { // Populate texture coordinates memcpy(&tex[i*stride],texCopy,sizeof(texCopy)); char c = text[i]; int x,y; getTextureCoordinates(graphicsInfo, c, x, y); float x_offset = ((float)x) / texW; float y_offset = ((float)y) / texH; for(unsigned j = 0; j < stride; j += 2) { tex[i*stride+j] += x_offset; tex[i*stride+j+1] += y_offset; } // Populate vertex coordinates memcpy(&vtx[i*stride],vtxCopy,sizeof(vtxCopy)); for(unsigned j = 0; j < stride; j += 2) { vtxCopy[j] += nWidth; } // Populate color coodinates memcpy(&clrs[i*2*stride], colorCopy, sizeof(colorCopy)); } } void SDLFontGL::startTextGL(int rows, int cols) { // If this is a new screen dimension, reset our data: if (rows != screenRows || cols != screenCols) { free(colorValues); free(texValues); free(vtxValues); screenRows = rows; screenCols = cols; // (at most) 2 operations per cell: background, foreground text int nCells = screenRows * screenCols * 2; colorValues = (GLfloat*)malloc(nCells*sizeof(GLfloat)*24); texValues = (GLfloat*)malloc(nCells*sizeof(GLfloat)*12); vtxValues = (GLfloat*)malloc(nCells*sizeof(GLfloat)*12); } // Start over numChars = 0; } void SDLFontGL::endTextGL() { // We've built up commands for the entire screen! // Tell GL where all the information is, and render! // Bind the master font texture glBindTexture(GL_TEXTURE_2D, GlyphCache); glEnableClientState(GL_COLOR_ARRAY); // Point GL to our arrays... glColorPointer(4, GL_FLOAT, 0, colorValues); glTexCoordPointer(2, GL_FLOAT, 0, texValues); glVertexPointer(2, GL_FLOAT, 0, vtxValues); // Go! glDrawArrays(GL_TRIANGLES, 0, 6*numChars); glFlush(); glDisableClientState(GL_COLOR_ARRAY); } void SDLFontGL::setCharMapping(int index, CharMapping_t map) { assert(index >= 0 && index < MAX_CHARSETS); memcpy(&charMappings[index], &map, sizeof(CharMapping_t)); // Invalidate the appropriate cache lines for(unsigned i = 0; i < nFonts; ++i) hasCacheLine(i, index) = false; } void SDLFontGL::getTextureCoordinates(TextGraphicsInfo_t & graphicsInfo, char c, int &x, int &y) { int slot = c > 127 ? graphicsInfo.slot1 : graphicsInfo.slot2; assert(hasCacheLine(graphicsInfo.font, slot)); // Set by reference x = (c % 128)*nWidth; y = (slot*nFonts + graphicsInfo.font)*nHeight; } bool &SDLFontGL::hasCacheLine(int font, int slot) { return haveCacheLine[slot*nFonts + font]; }
gpl-3.0
xzzpig/PigUtils
Data/src/main/java/com/github/xzzpig/pigutils/duck/LikeClass.java
527
package com.github.xzzpig.pigutils.duck; import static java.lang.annotation.RetentionPolicy.RUNTIME; import java.lang.annotation.Retention; import com.github.xzzpig.pigutils.reflect.MethodUtils; /** * 标识DuckObject的封装Object需要像某Class<br/> * 可用 {@link MethodUtils#checkArgs(Object...)} 或 * {@link DuckObject#isLike(Class, boolean, boolean)}检验 */ @Retention(RUNTIME) public @interface LikeClass { boolean checkField() default true; boolean checkMethod() default true; Class<?>[] value(); }
gpl-3.0
danielhams/mad-java
1PROJECTS/COMPONENTDESIGNER/component-designer-services/src/uk/co/modularaudio/componentdesigner/mainframe/actions/CheckAudioConfigurationAction.java
2604
/** * * Copyright (C) 2015 - Daniel Hams, Modular Audio Limited * daniel.hams@gmail.com * * Mad 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. * * Mad 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 Mad. If not, see <http://www.gnu.org/licenses/>. * */ package uk.co.modularaudio.componentdesigner.mainframe.actions; import java.awt.event.ActionEvent; import javax.swing.AbstractAction; import javax.swing.JOptionPane; import javax.swing.SwingUtilities; import uk.co.modularaudio.componentdesigner.controller.front.ComponentDesignerFrontController; import uk.co.modularaudio.componentdesigner.mainframe.MainFrame; import uk.co.modularaudio.componentdesigner.mainframe.MainFrameActions; import uk.co.modularaudio.componentdesigner.preferences.PreferencesDialog; import uk.co.modularaudio.componentdesigner.preferences.PreferencesDialogPageEnum; public class CheckAudioConfigurationAction extends AbstractAction { /** * */ private final MainFrame mainFrame; private final PreferencesDialog preferencesDialog; private static final long serialVersionUID = 3850927484100526941L; private final ComponentDesignerFrontController fc; public CheckAudioConfigurationAction( final ComponentDesignerFrontController fc, final PreferencesDialog preferencesDialog, final MainFrame mainFrame ) { this.preferencesDialog = preferencesDialog; this.mainFrame = mainFrame; this.fc = fc; this.putValue(NAME, "Check Audio Configuration" ); } @Override public void actionPerformed( final ActionEvent e ) { if( !fc.startAudioEngine() ) { preferencesDialog.loadPreferences(); preferencesDialog.choosePage( PreferencesDialogPageEnum.AUDIO_SYSTEM ); final Runnable r = new Runnable() { @Override public void run() { preferencesDialog.setLocationRelativeTo( mainFrame ); preferencesDialog.setVisible( true ); fc.showMessageDialog( preferencesDialog, MainFrameActions.TEXT_AUDIO_RECONFIG_WARNING, MainFrameActions.TEXT_AUDIO_RECONFIG_TITLE, JOptionPane.WARNING_MESSAGE, null ); } }; SwingUtilities.invokeLater( r ); } } }
gpl-3.0
Pgans/yii2a-devices
backend/modules/users/views/user/update.php
465
<?php use yii\helpers\Html; /* @var $this yii\web\View */ /* @var $model common\models\User */ $this->title = 'Update User: ' . $model->id; $this->params['breadcrumbs'][] = ['label' => 'Users', 'url' => ['index']]; $this->params['breadcrumbs'][] = ['label' => $model->id, 'url' => ['view', 'id' => $model->id]]; $this->params['breadcrumbs'][] = 'Update'; ?> <div class="user-update"> <?= $this->render('_form', [ 'model' => $model, ]) ?> </div>
gpl-3.0
shanot/imp
modules/kernel/src/SetLogState.cpp
1114
/** * \file Log.cpp \brief Logging and error reporting support. * * Copyright 2007-2017 IMP Inventors. All rights reserved. * */ #include <IMP/SetLogState.h> #include <IMP/Object.h> #include <IMP/log.h> IMPKERNEL_BEGIN_NAMESPACE void SetLogState::do_set(Object *o, LogLevel l) { if (l != DEFAULT) { obj_ = o; level_ = obj_->get_log_level(); obj_->set_log_level(l); } else { obj_ = nullptr; level_ = DEFAULT; } } SetLogState::SetLogState(LogLevel l) { obj_ = nullptr; level_ = DEFAULT; set(l); } void SetLogState::set(LogLevel l) { reset(); if (l != DEFAULT) { level_ = get_log_level(); set_log_level(l); } else { level_ = DEFAULT; } } void SetLogState::do_reset() { if (level_ != DEFAULT) { if (obj_) { obj_->set_log_level(level_); } else { set_log_level(level_); } obj_ = nullptr; level_ = DEFAULT; } } void SetLogState::do_show(std::ostream &out) const { out << "Setting from " << level_ << " to " << (obj_ ? obj_->get_log_level() : IMP::get_log_level()) << std::endl; } IMPKERNEL_END_NAMESPACE
gpl-3.0
halilkaya/markovy
markovy/__init__.py
3848
from collections import defaultdict from functools import wraps import random class MarkovChain(object): """ Parody generation with Markov Chain. """ # Default values: COUNT = 1 MIN = 5 MAX = 10 def __init__(self, dataset): """ Defines dataset and calls method to parse it. """ if hasattr(dataset, 'read'): f = dataset.read() self.words = [w for w in f.replace('\n', ' ').split(' ')] elif isinstance(dataset, str): self.words = [w for w in dataset.replace('\n', ' ').split(' ')] elif isinstance(dataset, list): self.words = dataset else: raise TypeError('Dataset must be string (as filename) or ' + 'list (word list)') self.ENDING_PUNCTUTATIONS = ['.', '?', '!', '...', '..', '?!'] self._parse() def _parse(self): """ Parses dataset into words. """ self.chain = defaultdict(list) for i, word in enumerate(self.words): try: if word not in self.chain: self.chain[word] = [self.words[i+1]] else: self.chain[word].append(self.words[i+1]) except IndexError: continue def _is_end_of(self, text): """ Checks if text ends with dot or not. """ return text and len(text) > 0 and text[-1] in self.ENDING_PUNCTUTATIONS def HandleIntTypes(func): """ Decorator to handle int types for the parameters. """ @wraps(func) def decorated_function(*args, **kwargs): for arg in kwargs.keys(): k = arg v = kwargs[k] if not isinstance(v, int): raise TypeError('%s must be integer.' % k) if v < 0: raise ValueError('%s must be greater than zero.' % k) return func(*args, **kwargs) return decorated_function @HandleIntTypes def make_word(self, count=COUNT): """ Generates irrelevant word from the dataset. """ return [random.choice(self.words) for _ in range(count)] @HandleIntTypes def make_sentence(self, count=COUNT): """ Generates random sentences from the dataset. """ output = [] for _ in range(count): word = self.make_word(1)[0] sentence = ''.join([word[0].upper(), word[1:]]) if self._is_end_of(sentence): output.append(sentence) else: while not self._is_end_of(sentence): word = random.choice(self.chain[word]) sentence += ''.join([' ', word]) output.append(sentence) return output @HandleIntTypes def make_paragraph(self, count=COUNT, minimum=MIN, maximum=MAX): """ Generates random paragraphs from the dataset. """ output = [] for _ in range(count): paragraph = '' for __ in range(random.randint(minimum, maximum)): paragraph += ''.join([self.make_sentence(1)[0], ' ']) output.append(paragraph[0:len(paragraph)-1]) return output @HandleIntTypes def make_text(self, count=COUNT, minimum=MIN, maximum=MAX): """ Generates random texts from the dataset. """ output = [] for _ in range(count): text = '' for __ in range(random.randint(minimum, maximum)): text += ''.join([self.make_paragraph(1, minimum, maximum)[0], \ '\n\n']) output.append(text[0:len(text)-2]) return output
gpl-3.0
GuillaumeDD/AdventOfCode2015
src/main/scala/aoc/day01/Part1.scala
1702
package aoc.day01 import io.IO object Part1 extends App { /* --- Day 1: Not Quite Lisp --- Santa was hoping for a white Christmas, but his weather machine's "snow" function is powered by stars, and he's fresh out! To save Christmas, he needs you to collect fifty stars by December 25th. Collect stars by helping Santa solve puzzles. Two puzzles will be made available on each day in the advent calendar; the second puzzle is unlocked when you complete the first. Each puzzle grants one star. Good luck! Here's an easy puzzle to warm you up. Santa is trying to deliver presents in a large apartment building, but he can't find the right floor - the directions he got are a little confusing. He starts on the ground floor (floor 0) and then follows the instructions one character at a time. An opening parenthesis, (, means he should go up one floor, and a closing parenthesis, ), means he should go down one floor. The apartment building is very tall, and the basement is very deep; he will never find the top or bottom floors. For example: (()) and ()() both result in floor 0. ((( and (()(()( both result in floor 3. ))((((( also results in floor 3. ()) and ))( both result in floor -1 (the first basement level). ))) and )())()) both result in floor -3. To what floor do the instructions take Santa? */ def step(road: List[Char], floor: Int = 0): Int = (road: @unchecked) match { case List() => floor case '(' :: remainingRoad => step(remainingRoad, floor + 1) case ')' :: remainingRoad => step(remainingRoad, floor - 1) } val input = IO.getLines().mkString.toList println(s"Santa is at floor: ${step(input)}") }
gpl-3.0
danielgarm/Chess
src/chess/connection/connectionFiles/GameServer.java
9070
package chess.connection.connectionFiles; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.net.ServerSocket; import java.net.Socket; import java.util.ArrayList; import java.util.List; import javax.swing.BorderFactory; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.SwingUtilities; import chess.game.mvc.controller.Controller; import chess.game.mvc.controller.commands.Command; import chess.game.mvc.model.genericGameFiles.Board; import chess.game.mvc.model.genericGameFiles.Game; import chess.game.mvc.model.genericGameFiles.GameError; import chess.game.mvc.model.genericGameFiles.GameFactory; import chess.game.mvc.model.genericGameFiles.GameObserver; import chess.game.mvc.model.genericGameFiles.Piece; import chess.game.mvc.model.genericGameFiles.Player; import chess.game.mvc.model.genericGameFiles.Game.State; public class GameServer extends Controller implements GameObserver { private int port; private int numPlayers; private int numOfConnectedPlayers; private GameFactory gameFactory; private List<Connection> clients; volatile private ServerSocket server; volatile private boolean stopped; volatile private boolean gameOver; private boolean firstTime; private JPanel msgPanel; private JTextArea msgArea; public GameServer(GameFactory gameFactory, List<Piece> pieces, List<Piece> pieceTypes, int port) { super(new Game(gameFactory.gameRules()), pieces, pieceTypes); this.port = port; this.numPlayers = pieces.size(); this.pieces = pieces; this.pieceTypes = pieceTypes; this.gameFactory = gameFactory; this.firstTime = true; this.numOfConnectedPlayers = 0; this.clients = new ArrayList<Connection>(); game.addObserver(this); } @Override public synchronized void makeMove(Player player) { try { super.makeMove(player); } catch (GameError e) { } } @Override public synchronized void stop() { try { super.stop(); } catch (GameError e) { } } @Override public synchronized void restart() { try { super.restart(); } catch (GameError e) { } } @Override public void start() { controlGUI(); log("Trying to start the server..."); startServer(); } private void controlGUI() { try { SwingUtilities.invokeAndWait(new Runnable() { @Override public void run() { constructGUI(); } }); } catch (InvocationTargetException | InterruptedException e) { throw new GameError("Something went wrong while constructing the GUI"); } } private void stopGame() { if(game.getState() == State.InPlay){ log("Game will be stopped..."); stop(); log("Game stopped."); } gameOver = true; log("Disconnecting all clients"); for(Connection c: clients){ try { c.stop(); } catch (IOException e) { e.printStackTrace(); } } this.clients.clear(); this.numOfConnectedPlayers = 0; } private void constructGUI() { JFrame window = new JFrame("Game Server"); window.setPreferredSize(new Dimension (600, 300)); window.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); window.pack(); msgArea = new JTextArea(); msgArea.setEditable(false); JScrollPane sp = new JScrollPane (msgArea); sp.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); msgPanel = new JPanel(); JButton quitButton = new JButton("Stop Server"); quitButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { int op = JOptionPane.showOptionDialog(new JFrame(), "Do you actually want to stop the server? ", "WARNING", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, null, null); if (op == 0) { try { stopGame(); } catch (GameError err) {} System.exit(0); } } }); msgPanel.setBorder(BorderFactory.createTitledBorder("Server log messages")); window.add(msgPanel); msgPanel.setLayout(new GridLayout (2, 1, 10, 10)); msgPanel.add(sp); msgPanel.add(quitButton); window.setVisible(true); log("Server GUI successfully created."); } private void log(final String msg) { SwingUtilities.invokeLater(new Runnable() { public void run () { msgArea.append(msg + System.getProperty("line.separator")); } }); } private void startServer() { try { log("Attempting to create socket on port " + this.port + "..."); this.server = new ServerSocket(this.port); this.stopped = false; log("Socket created on port " + this.port + ". Server is running now."); } catch (IOException e) { log("Error creating socket: " + e.getMessage()); } while (!stopped) { try { // 1. accept a connection into a socket s log("Waiting for a connection into socket... (Port " + this.port + ")"); Socket s = server.accept(); log("Connection request accepted."); log("Handling new connection..."); // 3. call handleRequest(s) to handle the request handleRequest(s); log("Client connected."); } catch (IOException e) { if (!stopped) { log("Error while waiting for a connection: " + e.getMessage()); } else { log("Server is stopped: " + e.getMessage()); } } } } private void handleRequest(Socket s) { try { Connection c = new Connection(s); Object clientRequest = c.getObject(); if (!(clientRequest instanceof String) && !((String) clientRequest).equalsIgnoreCase("Connect") ) { c.sendObject(new GameError("Invalid Request")); c.stop(); return; } // 1. � log("Checking for free player slots..."); if (numOfConnectedPlayers == this.numPlayers) { c.sendObject(new GameError("There are no free player slots.")); return; } log("Found a free slot."); // 2. log("New player connected."); this.numOfConnectedPlayers++; log(this.numOfConnectedPlayers + " of " + this.numPlayers + " players connected."); this.clients.add(c); // 3. � log("Sending OK signal..."); c.sendObject("Ok"); log("OK sent."); log("Sending Game Factory..."); c.sendObject(gameFactory); log("Game Factory sent."); log("Assigning a piece..."); c.sendObject(pieces.get(numOfConnectedPlayers - 1)); // 4. � log("Checking game start..."); if (numOfConnectedPlayers == numPlayers) { log("Player slots are full, starting game..."); if(this.firstTime){ super.start(); this.firstTime = false; } else{ restart(); } } else { log("Waiting for more players before the game starts..."); } // 5. log("Starting client listener..."); startClientListener(c); } catch (IOException | ClassNotFoundException _e) { log("Error handling connection"); } } private void startClientListener(final Connection c) { gameOver = false; final GameServer server = this; Thread t = new Thread() { public void run () { while (!stopped && !gameOver) { try { Command comando; log("Waiting for a command..."); comando = (Command) c.getObject(); log("Executing command..."); comando.execute(server); } catch (ClassNotFoundException | IOException e) { if (!stopped && !gameOver) { gameOver = true; server.log("Some error has been produced, the game will now stop!"); server.stop(); } } } } }; t.start(); } void forwardNotification(Response r) { // call c.sendObject(r) for each client connection �c� for (Connection c : clients) { try { c.sendObject(r); } catch (IOException e) { log(e.getMessage()); e.printStackTrace(); } } } @Override public void onGameStart(Board board, String gameDesc, List<Piece> pieces, Piece turn) { forwardNotification(new FWGameStartResponse(board, gameDesc, pieces, turn)); } @Override public void onGameOver(Board board, State state, Piece winner) { forwardNotification(new FWGameOverResponse(board, state, winner)); stopGame(); } @Override public void onMoveStart(Board board, Piece turn) { forwardNotification(new FWMoveStartResponse(board, turn)); } @Override public void onMoveEnd(Board board, Piece turn, boolean success) { forwardNotification(new FWMoveEndResponse(board, turn, success)); } @Override public void onChangeTurn(Board board, Piece turn) { forwardNotification(new FWChangeTurnResponse(board, turn)); } @Override public void onError(String msg) { forwardNotification(new FWErrorResponse(msg)); } }
gpl-3.0
ewijaya/ngsfeatures
ematch_src/utils/stl/try/tryStringUtils_startsEndsWith.cc
1329
/* * Author: Paul B. Horton * Organization: Computational Biology Research Center, AIST, Japan * Copyright (C) 2008, Paul B. Horton, All rights reserved. * Creation Date: 2008.11.16 * Last Modified: $Date: 2009/05/10 08:10:45 $ * * Purpose: try out StringUtils methods startsWith and endsWith */ #include <iostream> #include "utils/argvParsing/ArgvParser.hh" #include "../stringUtils.hh" struct argsT{ std::string text; std::string query; } args; namespace cbrc{ void tryStringUtils_startsEndsWith(){ /* ***** try out startsWith ***** */ bool isPrefix = stringUtils::startsWith( args.text, args.query ); std::cout << "\"" << args.query << "\" is" << ( isPrefix ? "" : " not" ) << " a prefix of " << "\"" << args.text << "\"\n"; /* ***** try out endsWith ***** */ bool isSuffix = stringUtils::endsWith( args.text, args.query ); std::cout << "\"" << args.query << "\" is" << ( isSuffix ? "" : " not" ) << " a suffix of " << "\"" << args.text << "\"\n"; } } // end namescape cbrc int main( int argc, const char* argv[] ){ cbrc::ArgvParser argP( argc, argv, "text query" ); argP.setOrDie( args.text, 1 ); argP.setOrDie( args.query, 2 ); argP.dieIfUnusedArgs(); cbrc::tryStringUtils_startsEndsWith(); return 1; }
gpl-3.0
NEMESIS13cz/Evercraft
java/evercraft/NEMESIS13cz/Items/Powders/ItemSilverPowder.java
699
package evercraft.NEMESIS13cz.Items.Powders; import net.minecraft.client.renderer.texture.IIconRegister; import net.minecraft.item.Item; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import evercraft.NEMESIS13cz.ModInformation; import evercraft.NEMESIS13cz.Main.ECTabs; public class ItemSilverPowder extends Item { public ItemSilverPowder() { setCreativeTab(ECTabs.tabECWGMaterials); //Tells the game what creative mode tab it goes in } @SideOnly(Side.CLIENT) public void registerIcons(IIconRegister par1IconRegister) { this.itemIcon = par1IconRegister.registerIcon(ModInformation.TEXTUREPATH + ":" + ModInformation.SILVER_POWDER); } }
gpl-3.0
wiiaboo/taiga
src/track/feed.cpp
5686
/* ** Taiga ** Copyright (C) 2010-2018, Eren Okka ** ** This program is free software: you can redistribute it and/or modify ** it under the terms of the GNU General Public License as published by ** the Free Software Foundation, either version 3 of the License, or ** (at your option) any later version. ** ** This program is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ** GNU General Public License for more details. ** ** You should have received a copy of the GNU General Public License ** along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "base/base64.h" #include "base/html.h" #include "base/string.h" #include "base/xml.h" #include "library/anime_util.h" #include "taiga/http.h" #include "taiga/path.h" #include "track/feed.h" #include "track/recognition.h" void FeedItem::Discard(int option) { switch (option) { default: case kFeedFilterOptionDefault: state = FeedItemState::DiscardedNormal; break; case kFeedFilterOptionDeactivate: state = FeedItemState::DiscardedInactive; break; case kFeedFilterOptionHide: state = FeedItemState::DiscardedHidden; break; } } bool FeedItem::IsDiscarded() const { switch (state) { case FeedItemState::DiscardedNormal: case FeedItemState::DiscardedInactive: case FeedItemState::DiscardedHidden: return true; default: return false; } } bool FeedItem::operator<(const FeedItem& item) const { // Initialize priority list static const int state_priorities[] = {1, 2, 3, 4, 0}; // Sort items by the priority of their state return state_priorities[static_cast<size_t>(this->state)] < state_priorities[static_cast<size_t>(item.state)]; } bool FeedItem::operator==(const FeedItem& item) const { // Check for guid element first if (permalink && item.permalink) if (!guid.empty() || !item.guid.empty()) if (guid == item.guid) return true; // Fall back to link element if (!link.empty() || !item.link.empty()) if (link == item.link) return true; // Fall back to title element if (!title.empty() || !item.title.empty()) if (title == item.title) return true; // Items are different return false; } TorrentCategory FeedItem::GetTorrentCategory() const { if (InStr(category, L"Batch") > -1) // Respect feed's own categorization return TorrentCategory::Batch; if (Meow.IsBatchRelease(episode_data)) return TorrentCategory::Batch; if (!Meow.IsValidAnimeType(episode_data)) return TorrentCategory::Other; if (anime::IsEpisodeRange(episode_data)) return TorrentCategory::Batch; if (!episode_data.file_extension().empty()) if (!Meow.IsValidFileExtension(episode_data.file_extension())) return TorrentCategory::Other; return TorrentCategory::Anime; } //////////////////////////////////////////////////////////////////////////////// Feed::Feed() : category(FeedCategory::Link), source(FeedSource::Unknown) { } std::wstring Feed::GetDataPath() { std::wstring path = taiga::GetPath(taiga::Path::Feed); if (!link.empty()) { Url url(link); path += Base64Encode(url.host, true) + L"\\"; } return path; } bool Feed::Load() { items.clear(); xml_document document; std::wstring file = GetDataPath() + L"feed.xml"; const unsigned int options = pugi::parse_default | pugi::parse_trim_pcdata; xml_parse_result parse_result = document.load_file(file.c_str(), options); if (parse_result.status != pugi::status_ok) return false; Load(document); return true; } bool Feed::Load(const std::wstring& data) { items.clear(); xml_document document; xml_parse_result parse_result = document.load(data.c_str()); if (parse_result.status != pugi::status_ok) return false; Load(document); return true; } void Feed::Load(const xml_document& document) { // Read channel information xml_node channel = document.child(L"rss").child(L"channel"); title = XmlReadStrValue(channel, L"title"); link = XmlReadStrValue(channel, L"link"); description = XmlReadStrValue(channel, L"description"); Aggregator.FindFeedSource(*this); // Read items foreach_xmlnode_(node, channel, L"item") { // Read data FeedItem item; item.category = XmlReadStrValue(node, L"category"); item.title = XmlReadStrValue(node, L"title"); item.link = XmlReadStrValue(node, L"link"); item.description = XmlReadStrValue(node, L"description"); item.category = XmlReadStrValue(node, L"category"); item.guid = XmlReadStrValue(node, L"guid"); item.pub_date = XmlReadStrValue(node, L"pubDate"); xml_node enclosure_node = node.child(L"enclosure"); if (!enclosure_node.empty()) { item.enclosure_url = enclosure_node.attribute(L"url").value(); item.enclosure_length = enclosure_node.attribute(L"length").value(); item.enclosure_type = enclosure_node.attribute(L"type").value(); } for (auto element : node.children()) { if (InStr(element.name(), L":") > -1) { item.elements[element.name()] = element.child_value(); } } auto permalink = XmlReadStrValue(node, L"isPermaLink"); if (!permalink.empty()) item.permalink = ToBool(permalink); if (category == FeedCategory::Link) if (item.title.empty() || item.link.empty()) continue; DecodeHtmlEntities(item.title); DecodeHtmlEntities(item.description); Aggregator.ParseFeedItem(source, item); Aggregator.CleanupDescription(item.description); items.push_back(item); } }
gpl-3.0
TeWu/krpc-rb
lib/krpc/version.rb
365
module KRPC module Version # Dear krpc-rb developer: Before bumping version below, please ensure that protobuf schema is up to date. MAJOR = 0 MINOR = 4 PATCH = 1 LABEL = nil IS_STABLE = false end VERSION = ([Version::MAJOR, Version::MINOR, Version::PATCH, Version::LABEL, Version::IS_STABLE ? nil : "next"].compact * '.').freeze end
gpl-3.0
JairFrancesco/easyGraph
html/search/all_2.js
1769
var searchData= [ ['booleano',['booleano',['../_parser_2include_2tipos_01de_01datos_8h.html#a49bc928212aebe46c57759ed709fe114',1,'tipos de datos.h']]], ['btnredraw',['btnRedraw',['../class_ui___main_window.html#a11e3b88f851cc38c95e233d684684ae8',1,'Ui_MainWindow']]], ['bulkfun1',['BulkFun1',['../example1_8cpp.html#a7676a7ad56ed56d590f82f7696ae17c3',1,'example1.cpp']]], ['bulkfun_5ftype0',['bulkfun_type0',['../namespacemu.html#aff9adf757e90a2398326a3cb10585cf1',1,'mu']]], ['bulkfun_5ftype1',['bulkfun_type1',['../namespacemu.html#a2bd588710432e6e34eae3e2af4ba3862',1,'mu']]], ['bulkfun_5ftype10',['bulkfun_type10',['../namespacemu.html#aebd99bafbd17761a9e13b8a7366ae1ce',1,'mu']]], ['bulkfun_5ftype2',['bulkfun_type2',['../namespacemu.html#a9faa755ea34c6e8de3895013e649a713',1,'mu']]], ['bulkfun_5ftype3',['bulkfun_type3',['../namespacemu.html#a441194d09cb0e9331dbfdaf74f59efd3',1,'mu']]], ['bulkfun_5ftype4',['bulkfun_type4',['../namespacemu.html#a6b7ce6e1f888b02222d2765d1f521507',1,'mu']]], ['bulkfun_5ftype5',['bulkfun_type5',['../namespacemu.html#a9343ce135e0a53897a67c6098d07a7b3',1,'mu']]], ['bulkfun_5ftype6',['bulkfun_type6',['../namespacemu.html#a1259e71ee6f8b9e3985ef0cda16dd433',1,'mu']]], ['bulkfun_5ftype7',['bulkfun_type7',['../namespacemu.html#a9726be97f12bc3b336884d462623ca8c',1,'mu']]], ['bulkfun_5ftype8',['bulkfun_type8',['../namespacemu.html#aa4e562060c2c2377266ec1cf274856fe',1,'mu']]], ['bulkfun_5ftype9',['bulkfun_type9',['../namespacemu.html#a51c71d5698d29b40688feaa8e968efc9',1,'mu']]], ['bulktest',['BulkTest',['../example2_8c.html#a0d4d89290ae65bcb985bd199b31dd112',1,'example2.c']]], ['buscar_5fope',['buscar_ope',['../class_interpretador.html#a94fa9d2449766953dbb3806f9f8cff00',1,'Interpretador']]] ];
gpl-3.0
clbr/stk
src/network/network_kart.hpp
1406
// // SuperTuxKart - a fun racing game with go-kart // Copyright (C) 2008 Joerg Henrichs // // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; either version 3 // of the License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. #ifndef HEADER_NETWORK_KART_HPP #define HEADER_NETWORK_KART_HPP #include "karts/kart.hpp" class Track; class NetworkKart : public Kart { private: int m_global_player_id; // to identify this kart to the network manager public: NetworkKart(const std::string& kart_name, unsigned int world_kart_id, int position, const btTransform& init_transform, int global_player_id, RaceManager::KartType type); void setControl(const KartControl& kc); virtual bool isNetworkKart() const { return true; } }; // NetworkKart #endif
gpl-3.0
mganeva/mantid
Framework/Algorithms/src/MostLikelyMean.cpp
3089
// Mantid Repository : https://github.com/mantidproject/mantid // // Copyright &copy; 2018 ISIS Rutherford Appleton Laboratory UKRI, // NScD Oak Ridge National Laboratory, European Spallation Source // & Institut Laue - Langevin // SPDX - License - Identifier: GPL - 3.0 + #include "MantidAlgorithms/MostLikelyMean.h" #include "MantidKernel/ArrayLengthValidator.h" #include "MantidKernel/ArrayProperty.h" #include "MantidKernel/MultiThreaded.h" #include "MantidKernel/PropertyWithValue.h" #include "boost/multi_array.hpp" namespace Mantid { namespace Algorithms { using Mantid::Kernel::ArrayLengthValidator; using Mantid::Kernel::ArrayProperty; using Mantid::Kernel::Direction; using Mantid::Kernel::PropertyWithValue; // Register the algorithm into the AlgorithmFactory DECLARE_ALGORITHM(MostLikelyMean) //---------------------------------------------------------------------------------------------- /// Algorithms name for identification. @see Algorithm::name const std::string MostLikelyMean::name() const { return "MostLikelyMean"; } /// Algorithm's version for identification. @see Algorithm::version int MostLikelyMean::version() const { return 1; } /// Algorithm's category for identification. @see Algorithm::category const std::string MostLikelyMean::category() const { return "Arithmetic"; } /// Algorithm's summary for use in the GUI and help. @see Algorithm::summary const std::string MostLikelyMean::summary() const { return "Computes the most likely mean of the array by minimizing the taxicab " "distance of the elements from the rest."; } //---------------------------------------------------------------------------------------------- /** Initialize the algorithm's properties. */ void MostLikelyMean::init() { auto lengthValidator = boost::make_shared<ArrayLengthValidator<double>>(); lengthValidator->setLengthMin(1); declareProperty(Kernel::make_unique<ArrayProperty<double>>( "InputArray", lengthValidator, Direction::Input), "An input array."); declareProperty(Kernel::make_unique<PropertyWithValue<double>>( "Output", 0., Direction::Output), "The output (mean)."); } //---------------------------------------------------------------------------------------------- /** Execute the algorithm. */ void MostLikelyMean::exec() { const std::vector<double> input = getProperty("InputArray"); const int size = static_cast<int>(input.size()); boost::multi_array<double, 2> cov(boost::extents[size][size]); PARALLEL_FOR_NO_WSP_CHECK() for (int i = 0; i < size; ++i) { for (int j = 0; j <= i; ++j) { double diff = sqrt(fabs(input[i] - input[j])); cov[i][j] = diff; cov[j][i] = diff; } } std::vector<double> sums(size); for (int i = 0; i < size; ++i) { sums[i] = std::accumulate(cov[i].begin(), cov[i].end(), 0.); } const auto minIndex = std::min_element(sums.cbegin(), sums.cend()); setProperty("Output", input[std::distance(sums.cbegin(), minIndex)]); } } // namespace Algorithms } // namespace Mantid
gpl-3.0
8278555/ProPra
ProPra/src/Release/WFEModelValue.java
279
package Release; public class WFEModelValue { String wert; public WFEModelValue(){ this.wert = ""; } public void setvalue(String value) { this.wert = value; } public String getvalue() { return wert; } }
gpl-3.0
GuillaumeGas/MyAccountOdoo
__openerp__.py
669
# -*- coding: utf-8 -*- { 'name': 'MyAccount', 'version': '0.2', 'category': 'custom', 'author': 'Guillaume Gas', 'website': 'https://guillaume.gas28.net', 'depends': [ 'base', 'email_template', ], 'data': [ 'data/email_template.xml', 'data/cron.xml', 'views/account.xml', 'views/transaction.xml', 'views/category.xml', 'views/prediction.xml', 'views/menu.xml', 'security/security.xml', 'security/ir.model.access.csv', ], 'demo': [ ], 'installable': True, 'application': False, 'auto_install': False, 'licence': 'GPL', }
gpl-3.0
fauconnier/LaToe
src/de/tudarmstadt/ukp/wikipedia/revisionmachine/index/indices/ChronoIndex.java
4141
/******************************************************************************* * Copyright (c) 2011 Ubiquitous Knowledge Processing Lab * * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser Public License v3 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * * Project Website: * http://jwpl.googlecode.com * * Contributors: * Torsten Zesch * Simon Kulessa * Oliver Ferschke ******************************************************************************/ package de.tudarmstadt.ukp.wikipedia.revisionmachine.index.indices; import java.util.ArrayList; import java.util.Collections; import java.util.List; /** * Index for the correct chonological order of revisions. * * * */ public class ChronoIndex extends AbstractIndex { /** ID of the last procesed article */ private int articleID; /** List of ChonoInfo's */ private List<ChronoIndexData> list; /** * (Constructor) Creates a new ChronoIndex object. * * @param MAX_ALLOWED_PACKET * MAX_ALLOWED_PACKET */ public ChronoIndex() { super(); this.list = null; } /** * (Constructor) Creates a new ChronoIndex object. * * @param MAX_ALLOWED_PACKET * MAX_ALLOWED_PACKET */ public ChronoIndex(final long MAX_ALLOWED_PACKET) { super("INSERT INTO index_chronological VALUES ", MAX_ALLOWED_PACKET); this.list = null; } /** * Adds the information for an new entry in the chrono index. * * @param articleID * ID of the article * @param revisionCounter * Revision counter * @param timestamp * Timestamp */ public void add(final int articleID, final int revisionCounter, final long timestamp) { if (this.articleID != articleID) { if (list != null) { addToBuffer(); } this.articleID = articleID; this.list = new ArrayList<ChronoIndexData>(); } this.list.add(new ChronoIndexData(timestamp, revisionCounter)); } /** * Creates the mapping and the reverse mapping. The generated information * will be added to the query buffer. This list will be cleared afterwards. */ private void addToBuffer() { if (list != null && !list.isEmpty()) { ChronoIndexData info; // Real index in revision history mapped to RevisionCounter // Sorted by real index (time) in ascending order Collections.sort(list); StringBuilder reverseMapping = new StringBuilder(); int size = list.size(); for (int i = 1; i <= size; i++) { info = list.get(i - 1); if (info.getRevisionCounter() != i) { if (reverseMapping.length() > 0) { reverseMapping.append(" "); } reverseMapping.append(i); reverseMapping.append(" "); reverseMapping.append(info.getRevisionCounter()); } info.setIndex(i); info.setSortFlag(false); } // RevisionCounter mapped to real index in revision history // Sorted by revisionCounters in ascending order Collections.sort(list); StringBuilder mapping = new StringBuilder(); while (!list.isEmpty()) { info = list.remove(0); if (info.getRevisionCounter() != info.getIndex()) { if (mapping.length() > 0) { mapping.append(" "); } mapping.append(info.getRevisionCounter()); mapping.append(" "); mapping.append(info.getIndex()); } } if (mapping.length() > 0) { boolean sql = !insertStatement.isEmpty(); String val = (sql?"(":"") + articleID + (sql?",'":",\"") + mapping.toString() + (sql?"','":"\",\"") + reverseMapping.toString() +(sql?"')":"\""); if (buffer.length() + val.length() >= MAX_ALLOWED_PACKET) { storeBuffer(); } if (sql&&buffer.length() > insertStatement.length()) { buffer.append(","); } buffer.append(val); if(!sql){ buffer.append("\n"); } } } } /** * Finalizes the query in the currently used buffer and creates a new one. * The finalized query will be added to the list of queries. */ @Override public void finalizeIndex() { addToBuffer(); storeBuffer(); } }
gpl-3.0
mixalturek/graphal
libgraphal/generated/nodeunarydecpre.cpp
2045
/* * Copyright 2008 Michal Turek * * This file is part of Graphal library. * http://graphal.sourceforge.net/ * * Graphal library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, version 3 of the License. * * Graphal library 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with Graphal library. If not, see <http://www.gnu.org/licenses/>. */ /**************************************************************************** * * * This file was generated by gen_operators.pl script. * * Don't update it manually! * * * ****************************************************************************/ #include "valuebool.h" #include "generated/nodeunarydecpre.h" #include "value.h" ///////////////////////////////////////////////////////////////////////////// //// NodeUnaryDecPre::NodeUnaryDecPre(Node* next) : NodeUnary(next) { } NodeUnaryDecPre::~NodeUnaryDecPre(void) { } ///////////////////////////////////////////////////////////////////////////// //// CountPtr<Value> NodeUnaryDecPre::execute(void) { CountPtr<Value> tmp(m_next->execute()); return tmp->assign(tmp->sub(*VALUEBOOL_TRUE)); } void NodeUnaryDecPre::dump(ostream& os, uint indent) const { dumpIndent(os, indent); os << "<NodeUnaryDecPre>" << endl; m_next->dump(os, indent+1); dumpIndent(os, indent); os << "</NodeUnaryDecPre>" << endl; } ostream& operator<<(ostream& os, const NodeUnaryDecPre& node) { node.dump(os, 0); return os; }
gpl-3.0
yogpstop/QuarryPlus
src/main/java/com/yogpc/qp/gui/GuiP_List.java
5575
/* * Copyright (C) 2012,2013 yogpstop This program is free software: you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as published by the Free * Software Foundation, either version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License along with this program. * If not, see <http://www.gnu.org/licenses/>. */ package com.yogpc.qp.gui; import net.minecraft.client.gui.GuiButton; import net.minecraft.client.gui.GuiYesNoCallback; import net.minecraft.util.StatCollector; import net.minecraftforge.common.util.ForgeDirection; import net.minecraftforge.fluids.FluidRegistry; import com.yogpc.qp.PacketHandler; import com.yogpc.qp.tile.TilePump; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; @SideOnly(Side.CLIENT) public class GuiP_List extends GuiScreenA implements GuiYesNoCallback { private GuiP_SlotList oreslot; private GuiButton delete, top, up, down, bottom; private final TilePump tile; byte dir; public GuiP_List(final byte id, final TilePump tq) { super(null); this.dir = id; this.tile = tq; } @Override public void initGui() { super.initGui(); this.buttonList.add(new GuiButton(-4, this.width / 2 - 160, this.height - 26, 100, 20, StatCollector.translateToLocal("pp.change"))); this.buttonList.add(new GuiButton(-1, this.width / 2 - 50, this.height - 26, 100, 20, StatCollector.translateToLocal("gui.done"))); this.buttonList.add(new GuiButton(-5, this.width / 2 + 60, this.height - 26, 100, 20, StatCollector.translateToLocal("pp.copy"))); this.buttonList.add(new GuiButton(-2, this.width * 2 / 3 + 10, 45, 100, 20, StatCollector .translateToLocal("tof.addnewore") + "(" + StatCollector.translateToLocal("tof.manualinput") + ")")); this.buttonList.add(new GuiButton(-3, this.width * 2 / 3 + 10, 20, 100, 20, StatCollector .translateToLocal("tof.addnewore") + "(" + StatCollector.translateToLocal("tof.fromlist") + ")")); this.buttonList.add(this.delete = new GuiButton(PacketHandler.CtS_REMOVE_MAPPING, this.width * 2 / 3 + 10, 70, 100, 20, StatCollector.translateToLocal("selectServer.delete"))); this.buttonList.add(this.top = new GuiButton(PacketHandler.CtS_TOP_MAPPING, this.width * 2 / 3 + 10, 95, 100, 20, StatCollector.translateToLocal("tof.top"))); this.buttonList.add(this.up = new GuiButton(PacketHandler.CtS_UP_MAPPING, this.width * 2 / 3 + 10, 120, 100, 20, StatCollector.translateToLocal("tof.up"))); this.buttonList.add(this.down = new GuiButton(PacketHandler.CtS_DOWN_MAPPING, this.width * 2 / 3 + 10, 145, 100, 20, StatCollector.translateToLocal("tof.down"))); this.buttonList.add(this.bottom = new GuiButton(PacketHandler.CtS_BOTTOM_MAPPING, this.width * 2 / 3 + 10, 170, 100, 20, StatCollector.translateToLocal("tof.bottom"))); this.oreslot = new GuiP_SlotList(this.mc, this.width * 3 / 5, this.height, 30, this.height - 30, this, this.tile.mapping[this.dir]); } @Override public void actionPerformed(final GuiButton par1) { switch (par1.id) { case -1: showParent(); break; case -2: this.mc.displayGuiScreen(new GuiP_Manual(this, this.dir, this.tile)); break; case -3: this.mc.displayGuiScreen(new GuiP_SelectBlock(this, this.tile, this.dir)); break; case -4: case -5: this.mc.displayGuiScreen(new GuiP_SelectSide(this.tile, this, par1.id == -5)); break; case PacketHandler.CtS_REMOVE_MAPPING: String name = this.tile.mapping[this.dir].get(this.oreslot.currentore); if (FluidRegistry.isFluidRegistered(name)) name = FluidRegistry.getFluid(name).getLocalizedName(FluidRegistry.getFluidStack(name, 0)); this.mc.displayGuiScreen(new GuiYesNo(this, StatCollector .translateToLocal("tof.deletefluidsure"), name, par1.id)); break; default: PacketHandler.sendPacketToServer(this.tile, (byte) par1.id, this.dir, this.tile.mapping[this.dir].get(this.oreslot.currentore)); break; } } @Override public void drawScreen(final int i, final int j, final float k) { drawDefaultBackground(); this.oreslot.drawScreen(i, j, k); drawCenteredString( this.fontRendererObj, StatCollector.translateToLocal("pp.list.setting") + StatCollector.translateToLocal("FD." + ForgeDirection.getOrientation(this.dir).toString()), this.width / 2, 8, 0xFFFFFF); if (this.tile.mapping[this.dir].isEmpty()) { this.delete.enabled = false; this.top.enabled = false; this.up.enabled = false; this.down.enabled = false; this.bottom.enabled = false; } super.drawScreen(i, j, k); } @Override public void confirmClicked(final boolean par1, final int par2) { if (par1) PacketHandler.sendPacketToServer(this.tile, (byte) par2, this.dir, this.oreslot.target.get(this.oreslot.currentore)); else this.mc.displayGuiScreen(this); } }
gpl-3.0
xinyi3/301-assignment1
src/com/example/xinyi3_notes/ItemList.java
3538
package com.example.xinyi3_notes; import java.io.Serializable; import java.util.ArrayList; import java.util.Collection; //the class for actions done inside the arrayList public class ItemList implements Serializable { /** * ItemList serialization ID */ private static final long serialVersionUID = 1885050434788476946L; protected ArrayList<TodoItems> itemList=null; protected transient ArrayList<Listener> listeners=null; //make arrayList of todoItems and new listeners for arraylist update public ItemList(){ itemList=new ArrayList<TodoItems>(); listeners = new ArrayList<Listener>(); } //get listeners private ArrayList<Listener> getListeners(){ if(listeners==null){ listeners = new ArrayList<Listener>(); } return listeners; } //return the itemList public Collection<TodoItems> getItems() { return itemList; } //will notify listeners each time an item is added public void addItem(TodoItems testItem) { itemList.add(testItem); notifyListeners(); } //update listeners update varies depending on the task called private void notifyListeners() { for(Listener listener:getListeners()){ listener.update(); } } //remove an item from itemList and update list public void removeItem(TodoItems testItem) { // TODO Auto-generated method stub itemList.remove(testItem); notifyListeners(); } public int size() { // TODO Auto-generated method stub return itemList.size(); } //iterate eachItem in the list, if item has a checked box, increase the count by 1 public int CheckedSize(){ int a=0; for (TodoItems itemLists:itemList){ if (itemLists.checked == true ){ a++; } } return a; } //iterate eachItem in the list, if item doesn't have a checked box, increase the count by 1 public int UncheckedSize(){ int a=0; for (TodoItems itemLists:itemList){ if (itemLists.checked == false ){ a++; } } return a; } public boolean contains(TodoItems testItem) { // TODO Auto-generated method stub return itemList.contains(testItem); } //add listener public void addListener(Listener l){ getListeners().add(l); } //remove listener public void removeListener(Listener l){ getListeners().remove(l); } //using the boolean value checked to modify the name of the Item and display a checked or unchecked box public void checkItem(TodoItems testItem){ if (testItem.checked==false){ testItem.editName("[x]"+testItem.getOgName()); testItem.setCheck(true); notifyListeners(); }else{ testItem.editName("[]"+testItem.getOgName()); testItem.setCheck(false); notifyListeners(); } } //iterate through list and return a string consisting all items public String getAllItems(){ String a = ""; for (TodoItems itemLists:itemList){ a = a +" " + itemLists.getName() + "\n"; } return a; } //iterate through list and return a string consisting sleceted items based on a boolean value public String getSelectedItems(){ String a=""; for (TodoItems itemLists:itemList){ if (itemLists.getSelect()==true){ a = a +" " + itemLists.getName() + "\n"; } } return a; } // change the boolean value of a item to indicate it is selected public void selectItem(TodoItems testItem){ if (testItem.selected==false){ testItem.setSelect(true); }else{ testItem.setSelect(false); } } //reset the all selected items to unselected public void clear() { for (TodoItems itemLists:itemList){ if (itemLists.getSelect()==true){ itemLists.setSelect(false); } } } }
gpl-3.0
StudioProcess/rvp
src/app/core/actions/dom.service.ts
1379
import { Injectable, Injector, ComponentFactoryResolver, ApplicationRef, EmbeddedViewRef, } from '@angular/core' @Injectable({ providedIn: 'root' }) export class DomService { constructor( private componentFactoryResolver: ComponentFactoryResolver, private appRef: ApplicationRef, private injector: Injector ) { } instantiateComponent(component: any) { // Create a component reference from the component const componentRef = this.componentFactoryResolver .resolveComponentFactory(component) .create(this.injector) // Attach component to the appRef so that it's inside the ng component tree this.appRef.attachView(componentRef.hostView) return componentRef } attachComponent(componentRef: any, attachTo: HTMLElement) { // Get DOM element from component let ret: any = false if (attachTo !== null) { let domElem = (componentRef.hostView as EmbeddedViewRef<any>).rootNodes[0] as HTMLElement // Append DOM element ret = attachTo.appendChild(domElem) } return ret } destroyComponent(componentRef: any) { // remove component from the component tree and from the DOM this.appRef.detachView(componentRef.hostView); return componentRef.destroy() } getInstance(componentRef: any) { return ('instance' in componentRef) ? componentRef.instance : null } }
gpl-3.0
mwveliz/siglas-mppp
plugins/sfPostgresDoctrinePlugin/lib/generator/sfDoctrineBuildModelTask.class.php
10641
<?php /* * This file is part of the symfony package. * (c) Fabien Potencier <fabien.potencier@symfony-project.com> * (c) Jonathan H. Wage <jonwage@gmail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ /** * Create classes for the current model. * * @package symfony * @subpackage doctrine * @author Fabien Potencier <fabien.potencier@symfony-project.com> * @author Jonathan H. Wage <jonwage@gmail.com> * @version SVN: $Id: sfDoctrineBuildModelTask.class.php 24745 2009-12-02 02:14:05Z Kris.Wallsmith $ */ class sfDoctrineBuildModelTask extends sfDoctrineBaseTask { /** * @see sfTask */ protected function configure() { $this->addOptions(array( new sfCommandOption('application', null, sfCommandOption::PARAMETER_OPTIONAL, 'The application name', true), new sfCommandOption('env', null, sfCommandOption::PARAMETER_REQUIRED, 'The environment', 'dev'), )); $this->namespace = 'doctrine'; $this->name = 'build-model'; $this->briefDescription = 'Creates classes for the current model'; $this->detailedDescription = <<<EOF The [doctrine:build-model|INFO] task creates model classes from the schema: [./symfony doctrine:build-model|INFO] The task read the schema information in [config/doctrine/*.yml|COMMENT] from the project and all enabled plugins. The model classes files are created in [lib/model/doctrine|COMMENT]. This task never overrides custom classes in [lib/model/doctrine|COMMENT]. It only replaces files in [lib/model/doctrine/base|COMMENT]. EOF; } /** * @see sfTask */ protected function execute($arguments = array(), $options = array()) { $this->logSection('doctrine', 'generating model classes'); $config = $this->getCliConfig(); $builderOptions = $this->configuration->getPluginConfiguration('sfDoctrinePlugin')->getModelBuilderOptions(); $stubFinder = sfFinder::type('file')->prune('base')->name('*'.$builderOptions['suffix']); $before = $stubFinder->in($config['models_path']); $schema = $this->prepareSchemaFile($config['yaml_schema_path']); $import = new Doctrine_Import_Schema(); $import->setOptions($builderOptions); $import->importSchema($schema, 'yml', $config['models_path']); $listFiles = array(); $listDir = array(); $bI = array( 'package' => isset($properties['symfony']['name']) ? $properties['symfony']['name'] : 'symfony', 'subpackage' => 'model', 'author' => isset($properties['symfony']['author']) ? $properties['symfony']['author'] : 'Your name here', ); $baseRecordFile = sprintf("%s/BaseDoctrineRecord.class.php", $config['models_path']); $baseRecordFileContent = <<<EOF <?php /** * Base doctrine record. * * @package {$bI['package']} * @subpackage {$bI['subpackage']} * @author {$bI['author']} */ ##class## extends sfPostgresDoctrineRecord { } EOF; if (!file_exists($baseRecordFile)) { file_put_contents($baseRecordFile, str_replace('##class##', 'class BaseDoctrineRecord', $baseRecordFileContent)); } $baseTableFile = sprintf("%s/BaseDoctrineTable.class.php", $config['models_path']); $baseTableFileContent = <<<TABLE <?php /** * Base doctrine table. * * @package {$bI['package']} * @subpackage {$bI['subpackage']} * @author {$bI['author']} */ ##class## extends Doctrine_Table { } TABLE; // markup base classes with magic methods foreach (sfYaml::load($schema) as $model => $definition) { $file = sprintf('%s%s/%s/Base%s%s', $config['models_path'], isset($definition['package']) ? '/'.substr($definition['package'], 0, strpos($definition['package'], '.')) : '', $builderOptions['baseClassesDirectory'], $model, $builderOptions['suffix']); $code = file_get_contents($file); // introspect the model without loading the class $matches = array(); if (preg_match_all('/@property (\w+) \$(\w+)/', $code, $matches, PREG_SET_ORDER) || preg_match('/\.Entities/', $definition['package'])) { $properties = array(); foreach ((array) $matches as $match) { $properties[$match[2]] = $match[1]; } if(! empty($matches)) { $typePad = max(array_map('strlen', array_merge(array_values($properties), array($model)))); $namePad = max(array_map('strlen', array_keys(array_map(array('sfInflector', 'camelize'), $properties)))); } $setters = array(); $getters = array(); foreach ($properties as $name => $type) { $camelized = sfInflector::camelize($name); $collection = 'Doctrine_Collection' == $type; $getters[] = sprintf('@method %-'.$typePad.'s %s%-'.($namePad + 2).'s Returns the current record\'s "%s" %s', $type, 'get', $camelized.'()', $name, $collection ? 'collection' : 'value'); $setters[] = sprintf('@method %-'.$typePad.'s %s%-'.($namePad + 2).'s Sets the current record\'s "%s" %s', $model, 'set', $camelized.'()', $name, $collection ? 'collection' : 'value'); } // use the last match as a search string $code = str_replace($match[0], $match[0].PHP_EOL.' * '.PHP_EOL.' * '.implode(PHP_EOL.' * ', array_merge($getters, $setters)), $code); $newfile = sprintf('%s%s%s/%s/Base%s%s', $config['models_path'], isset($definition['package']) && false !== stripos($definition['package'], 'plugin') && 0 !== stripos($definition['package'], 'plugin') ? '/plugins' : '/project', isset($definition['package']) ? '/'.substr($definition['package'], 0, strpos($definition['package'], '.')) : '', $builderOptions['baseClassesDirectory'], $model, $builderOptions['suffix']); $newtablefile = sprintf('%s%s%s/%sTable%s', $config['models_path'], isset($definition['package']) && false !== stripos($definition['package'], 'plugin') && 0 !== stripos($definition['package'], 'plugin') ? '/plugins' : '/project', isset($definition['package']) ? '/'.substr($definition['package'], 0, strpos($definition['package'], '.')) : '', $model, $builderOptions['suffix']); $newdir = sprintf('%s%s%s/%s', $config['models_path'], isset($definition['package']) && false !== stripos($definition['package'], 'plugin') && 0 !== stripos($definition['package'], 'plugin') ? '/plugins' : '/project', isset($definition['package']) ? '/'.substr($definition['package'], 0, strpos($definition['package'], '.')) : '', $builderOptions['baseClassesDirectory']); if (!file_exists($newdir)) { mkdir($newdir, 0777, true); } $listDir[sprintf('%s%s/%s', $config['models_path'], isset($definition['package']) ? '/'.substr($definition['package'], 0, strpos($definition['package'], '.')) : '', $builderOptions['baseClassesDirectory'])] = true; $listDir[sprintf('%s%s', $config['models_path'], isset($definition['package']) ? '/'.substr($definition['package'], 0, strpos($definition['package'], '.')) : '')] = true; if (!file_exists(str_replace(sprintf('%s/Base', $builderOptions['baseClassesDirectory']), '', $newfile))) { $listFiles[sprintf('%s%s/%s%s', $config['models_path'], isset($definition['package']) ? '/'.substr($definition['package'], 0, strpos($definition['package'], '.')) : '', $model, $builderOptions['suffix'])] = str_replace(sprintf('%s/Base', $builderOptions['baseClassesDirectory']), '', $newfile); } else { unlink(sprintf('%s%s/%s%s', $config['models_path'], isset($definition['package']) ? '/'.substr($definition['package'], 0, strpos($definition['package'], '.')) : '', $model, $builderOptions['suffix'])); } if (!file_exists($newtablefile)) { $listFiles[sprintf('%s%s/%sTable%s', $config['models_path'], isset($definition['package']) ? '/'.substr($definition['package'], 0, strpos($definition['package'], '.')) : '', $model, $builderOptions['suffix'])] = $newtablefile; } else { unlink(sprintf('%s%s/%sTable%s', $config['models_path'], isset($definition['package']) ? '/'.substr($definition['package'], 0, strpos($definition['package'], '.')) : '', $model, $builderOptions['suffix'])); } $code = str_replace(" extends sfDoctrineRecord", " extends BaseDoctrineRecord", $code); file_put_contents($newfile, $code); unlink($file); } } $properties = parse_ini_file(sfConfig::get('sf_config_dir').'/properties.ini', true); $tokens = array( '##PACKAGE##' => isset($properties['symfony']['name']) ? $properties['symfony']['name'] : 'symfony', '##SUBPACKAGE##' => 'model', '##NAME##' => isset($properties['symfony']['author']) ? $properties['symfony']['author'] : 'Your name here', ' <##EMAIL##>' => '', "{\n\n}" => "{\n}\n", ); // cleanup new stub classes $after = $stubFinder->in($config['models_path']); $this->getFilesystem()->replaceTokens(array_diff($after, $before), '', '', $tokens); // cleanup base classes $baseFinder = sfFinder::type('file')->name('Base*'.$builderOptions['suffix']); $baseDirFinder = sfFinder::type('dir')->name('base'); $this->getFilesystem()->replaceTokens($baseFinder->in($baseDirFinder->in($config['models_path'])), '', '', $tokens); // cleanup new table classes $tableFinder = sfFinder::type('file')->prune('base')->name('*Table'.$builderOptions['suffix']); foreach (array_diff($tableFinder->in($config['models_path']), $before) as $file) { $contents = file_get_contents($file); if (strpos($file, 'BaseDoctrineTable.class.php') === true) { file_put_contents($file, str_replace('extends BaseDoctrineTable', 'extends Doctrine_Table', sfToolkit::stripComments($contents))); } else { file_put_contents($file, str_replace('extends Doctrine_Table', 'extends BaseDoctrineTable', sfToolkit::stripComments($contents))); } } if (!file_exists($baseTableFile)) { file_put_contents($baseTableFile, str_replace('##class##', 'class BaseDoctrineTable', $baseTableFileContent)); } else { $contents = file_get_contents($baseTableFile); file_put_contents($baseTableFile, str_replace('extends BaseDoctrineTable', 'extends Doctrine_Table', sfToolkit::stripComments($contents))); } foreach($listFiles as $old => $new) { rename($old, $new); } foreach($listDir as $dir => $val) { if (file_exists($dir)) { if (($files = @scandir($dir)) && count($files) <= 2) { rmdir($dir); } } } $this->reloadAutoload(); } }
gpl-3.0
ISRAPIL/FastCorePE
src/pocketmine/block/RedSandstoneSlab.php
2089
<?php namespace pocketmine\block; use pocketmine\item\Item; use pocketmine\Player; class RedSandstoneSlab extends Slab { protected $id = Block::RED_SANDSTONE_SLAB; public function getName(): string { return "Red Sandstone Slab"; } public function place(Item $item, Block $block, Block $target, $face, $fx, $fy, $fz, Player $player = null) { if ($face === 0) { if ($target->getId() === self::RED_SANDSTONE_SLAB and ( $target->getDamage() & 0x08) === 0x08) { $this->getLevel()->setBlock($target, Block::get(Item::DOUBLE_RED_SANDSTONE_SLAB, $this->meta), true); return true; } elseif ($block->getId() === self::RED_SANDSTONE_SLAB) { $this->getLevel()->setBlock($block, Block::get(Item::DOUBLE_RED_SANDSTONE_SLAB, $this->meta), true); return true; } else { $this->meta |= 0x08; } } elseif ($face === 1) { if ($target->getId() === self::RED_SANDSTONE_SLAB and ( $target->getDamage() & 0x08) === 0) { $this->getLevel()->setBlock($target, Block::get(Item::DOUBLE_RED_SANDSTONE_SLAB, $this->meta), true); return true; } elseif ($block->getId() === self::RED_SANDSTONE_SLAB) { $this->getLevel()->setBlock($block, Block::get(Item::DOUBLE_RED_SANDSTONE_SLAB, $this->meta), true); return true; } //TODO: check for collision } else { if ($block->getId() === self::RED_SANDSTONE_SLAB) { $this->getLevel()->setBlock($block, Block::get(Item::DOUBLE_RED_SANDSTONE_SLAB, $this->meta), true); } else { if ($fy > 0.5) { $this->meta |= 0x08; } } } if ($block->getId() === self::RED_SANDSTONE_SLAB and ( $target->getDamage() & 0x07) !== ($this->meta & 0x07)) { return false; } $this->getLevel()->setBlock($block, $this, true, true); return true; } }
gpl-3.0
hackerpals/Python-Tutorials
Kids-Pthon-Workshops/guessing-game/ex2/call-op.py
591
#!/usr/bin/env python3 """ Call Operators in Python """ #Setup our variables num1 = 1 num2 = 2 var1 = 'a' var2 = 'b' ''' + / Additions / Can combine strings or numbes ''' totalNum = num1 + num2 totalVar = var1 + var2 print(totalNum, totalVar ) ''' - / Subtraction ''' totalNum = num1 - num2 ''' * / Multiplication ''' ''' / / Division ''' ''' % / Remainder(Modulo) ''' ''' ** / Power ''' ''' = / Assignment ''' ''' == / Equality ''' ''' != / Not Equal ''' ''' > / Greater than ''' ''' < / Less than ''' ''' &(or and) / and ''' ''' | or / or '''
gpl-3.0
PyPila/apof
src/apof/portal/urls.py
493
from django.conf.urls import include, url from django.contrib.auth import views as auth_views from . import views urlpatterns = [ url(r'', include('social_django.urls', namespace='social')), url(r'^$', views.index, name='home'), url( r'^login/$', auth_views.login, {'redirect_authenticated_user': True}, name='login' ), url( r'^logout/$', auth_views.logout, {'next_page': '/portal'}, name='logout' ), ]
gpl-3.0
svenoaks/QuickLyric
QuickLyric/src/main/java/com/geecko/QuickLyric/utils/UpdateChecker.java
3789
/* * * * * This file is part of QuickLyric * * Created by geecko * * * * QuickLyric 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. * * * * QuickLyric 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 QuickLyric. If not, see <http://www.gnu.org/licenses/>. * */ package com.geecko.QuickLyric.utils; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.net.Uri; import android.os.AsyncTask; import android.support.v7.app.AlertDialog; import com.geecko.QuickLyric.BuildConfig; import com.geecko.QuickLyric.fragment.LyricsViewFragment; public class UpdateChecker { public static boolean isUpdateAvailable(Context context) { if (BuildConfig.DEBUG) return false; PackageInfo pInfo; try { pInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0); } catch (PackageManager.NameNotFoundException e) { e.printStackTrace(); return false; } int versionCode = pInfo.versionCode; int newVersionCode = versionCode; try { String version = Net.getUrlAsString("https://api.quicklyric.be/currentAPK"); version = version.replaceAll("\\D+", ""); newVersionCode = Integer.valueOf(version); } catch (Exception e) { e.printStackTrace(); } return versionCode < newVersionCode; } public static void showDialog(final Context context) { AlertDialog.Builder updateDialog = new AlertDialog.Builder(context); updateDialog.setTitle("Update available") .setMessage("Dear QuickLyric user, a new update is available on F-Droid and Google Play.") .setPositiveButton("Download", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://f-droid.org/repository/browse/?fdid=com.geecko.QuickLyric") ); context.startActivity(browserIntent); } }) .setCancelable(true) .show(); } public static class UpdateCheckTask extends AsyncTask<Void, Void, Boolean> { private final LyricsViewFragment lyricsFragment; public UpdateCheckTask(LyricsViewFragment lyricsViewFragment) { this.lyricsFragment = lyricsViewFragment; } @Override protected Boolean doInBackground(Void... params) { return lyricsFragment.getActivity() != null && UpdateChecker.isUpdateAvailable(lyricsFragment.getActivity().getApplicationContext()); } @Override protected void onPostExecute(Boolean result) { super.onPostExecute(result); if (result && lyricsFragment.getActivity() != null) showDialog(lyricsFragment.getActivity()); else lyricsFragment.updateChecked = true; } } }
gpl-3.0
j0sh/crtmpserver
sources/thelib/src/netio/select/tcpacceptor.cpp
6723
/* * Copyright (c) 2010, * Gavriloaie Eugen-Andrei (shiretu@gmail.com) * * This file is part of crtmpserver. * crtmpserver 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. * * crtmpserver 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 crtmpserver. If not, see <http://www.gnu.org/licenses/>. */ #ifdef NET_SELECT #include "netio/select/tcpacceptor.h" #include "netio/select/iohandlermanager.h" #include "protocols/protocolfactorymanager.h" #include "protocols/tcpprotocol.h" #include "netio/select/tcpcarrier.h" #include "application/baseclientapplication.h" TCPAcceptor::TCPAcceptor(string ipAddress, uint16_t port, Variant parameters, vector<uint64_t>/*&*/ protocolChain) : IOHandler(0, 0, IOHT_ACCEPTOR) { _pApplication = NULL; memset(&_address, 0, sizeof (sockaddr_in)); _address.sin_family = PF_INET; _address.sin_addr.s_addr = inet_addr(STR(ipAddress)); o_assert(_address.sin_addr.s_addr != INADDR_NONE); _address.sin_port = EHTONS(port); //----MARKED-SHORT---- _protocolChain = protocolChain; _parameters = parameters; _enabled = false; _acceptedCount = 0; _droppedCount = 0; _ipAddress = ipAddress; _port = port; } TCPAcceptor::~TCPAcceptor() { CLOSE_SOCKET(_inboundFd); } bool TCPAcceptor::Bind() { _inboundFd = _outboundFd = (int) socket(PF_INET, SOCK_STREAM, 0); if (_inboundFd < 0) { int err = LASTSOCKETERROR; FATAL("Unable to create socket: %d", err); return false; } if (!setFdOptions(_inboundFd, false)) { FATAL("Unable to set socket options"); return false; } if (bind(_inboundFd, (sockaddr *) & _address, sizeof (sockaddr)) != 0) { int err = LASTSOCKETERROR; FATAL("Unable to bind on address: tcp://%s:%hu; Error was: %d", inet_ntoa(((sockaddr_in *) & _address)->sin_addr), ENTOHS(((sockaddr_in *) & _address)->sin_port), err); return false; } if (_port == 0) { socklen_t tempSize = sizeof (sockaddr); if (getsockname(_inboundFd, (sockaddr *) & _address, &tempSize) != 0) { FATAL("Unable to extract the random port"); return false; } _parameters[CONF_PORT] = (uint16_t) ENTOHS(_address.sin_port); } if (listen(_inboundFd, 100) != 0) { FATAL("Unable to put the socket in listening mode"); return false; } _enabled = true; return true; } void TCPAcceptor::SetApplication(BaseClientApplication *pApplication) { o_assert(_pApplication == NULL); _pApplication = pApplication; } bool TCPAcceptor::StartAccept() { return IOHandlerManager::EnableAcceptConnections(this); } bool TCPAcceptor::SignalOutputData() { ASSERT("Operation not supported"); return false; } bool TCPAcceptor::OnEvent(select_event &event) { if (!OnConnectionAvailable(event)) return IsAlive(); else return true; } bool TCPAcceptor::OnConnectionAvailable(select_event &event) { if (_pApplication == NULL) return Accept(); return _pApplication->AcceptTCPConnection(this); } bool TCPAcceptor::Accept() { sockaddr address; memset(&address, 0, sizeof (sockaddr)); socklen_t len = sizeof (sockaddr); int32_t fd; //1. Accept the connection fd = accept(_inboundFd, &address, &len); if (fd < 0) { int err = LASTSOCKETERROR; FATAL("Unable to accept client connection: %d", err); return false; } if (!_enabled) { CLOSE_SOCKET(fd); _droppedCount++; WARN("Acceptor is not enabled. Client dropped: %s:%"PRIu16" -> %s:%"PRIu16, inet_ntoa(((sockaddr_in *) & address)->sin_addr), ENTOHS(((sockaddr_in *) & address)->sin_port), STR(_ipAddress), _port); return true; } INFO("Client connected: %s:%"PRIu16" -> %s:%"PRIu16, inet_ntoa(((sockaddr_in *) & address)->sin_addr), ENTOHS(((sockaddr_in *) & address)->sin_port), STR(_ipAddress), _port); if (!setFdOptions(fd, false)) { FATAL("Unable to set socket options"); CLOSE_SOCKET(fd); return false; } //4. Create the chain BaseProtocol *pProtocol = ProtocolFactoryManager::CreateProtocolChain( _protocolChain, _parameters); if (pProtocol == NULL) { FATAL("Unable to create protocol chain"); CLOSE_SOCKET(fd); return false; } //5. Create the carrier and bind it TCPCarrier *pTCPCarrier = new TCPCarrier(fd); pTCPCarrier->SetProtocol(pProtocol->GetFarEndpoint()); pProtocol->GetFarEndpoint()->SetIOHandler(pTCPCarrier); //6. Register the protocol stack with an application if (_pApplication != NULL) { pProtocol = pProtocol->GetNearEndpoint(); pProtocol->SetApplication(_pApplication); } if (pProtocol->GetNearEndpoint()->GetOutputBuffer() != NULL) pProtocol->GetNearEndpoint()->EnqueueForOutbound(); _acceptedCount++; //7. Done return true; } bool TCPAcceptor::Drop() { sockaddr address; memset(&address, 0, sizeof (sockaddr)); socklen_t len = sizeof (sockaddr); //1. Accept the connection int32_t fd = accept(_inboundFd, &address, &len); if (fd < 0) { int err = LASTSOCKETERROR; WARN("Accept failed. Error code was: %d", err); return false; } //2. Drop it now CLOSE_SOCKET(fd); _droppedCount++; INFO("Client explicitly dropped: %s:%"PRIu16" -> %s:%"PRIu16, inet_ntoa(((sockaddr_in *) & address)->sin_addr), ENTOHS(((sockaddr_in *) & address)->sin_port), STR(_ipAddress), _port); return true; } Variant & TCPAcceptor::GetParameters() { return _parameters; } BaseClientApplication *TCPAcceptor::GetApplication() { return _pApplication; } vector<uint64_t> &TCPAcceptor::GetProtocolChain() { return _protocolChain; } TCPAcceptor::operator string() { return format("A(%d)", _inboundFd); } void TCPAcceptor::GetStats(Variant &info, uint32_t namespaceId) { info = _parameters; info["id"] = (((uint64_t) namespaceId) << 32) | GetId(); info["enabled"] = (bool)_enabled; info["acceptedConnectionsCount"] = _acceptedCount; info["droppedConnectionsCount"] = _droppedCount; if (_pApplication != NULL) { info["appId"] = (((uint64_t) namespaceId) << 32) | _pApplication->GetId(); info["appName"] = _pApplication->GetName(); } else { info["appId"] = (((uint64_t) namespaceId) << 32); info["appName"] = ""; } } bool TCPAcceptor::Enable() { return _enabled; } void TCPAcceptor::Enable(bool enabled) { _enabled = enabled; } bool TCPAcceptor::IsAlive() { //TODO: Implement this. It must return true //if this acceptor is operational NYI; return true; } #endif /* NET_SELECT */
gpl-3.0
Tomucha/coordinator
coordinator-server/src/main/java/cz/clovekvtisni/coordinator/server/web/controller/api/v1/UserApiController.java
7096
package cz.clovekvtisni.coordinator.server.web.controller.api.v1; import cz.clovekvtisni.coordinator.api.request.*; import cz.clovekvtisni.coordinator.api.response.*; import cz.clovekvtisni.coordinator.domain.User; import cz.clovekvtisni.coordinator.domain.UserInEvent; import cz.clovekvtisni.coordinator.exception.ErrorCode; import cz.clovekvtisni.coordinator.exception.MaParseException; import cz.clovekvtisni.coordinator.exception.MaPermissionDeniedException; import cz.clovekvtisni.coordinator.server.domain.UserAuthKey; import cz.clovekvtisni.coordinator.server.domain.UserEntity; import cz.clovekvtisni.coordinator.server.domain.UserInEventEntity; import cz.clovekvtisni.coordinator.server.filter.UserFilter; import cz.clovekvtisni.coordinator.server.security.AuthorizationTool; import cz.clovekvtisni.coordinator.server.service.UserService; import cz.clovekvtisni.coordinator.server.tool.objectify.Filter; import cz.clovekvtisni.coordinator.server.tool.objectify.ResultList; import cz.clovekvtisni.coordinator.server.util.EntityTool; import cz.clovekvtisni.coordinator.server.web.controller.api.AbstractApiController; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import javax.servlet.http.HttpServletRequest; import java.util.List; /** * Created by IntelliJ IDEA. * User: tomas * Date: 10/27/12 * Time: 12:30 AM */ @Controller @RequestMapping("/api/v1/user") public class UserApiController extends AbstractApiController { @Autowired private UserService userService; @RequestMapping(value = "/login", method = RequestMethod.POST) public @ResponseBody ApiResponse login(HttpServletRequest request) { LoginRequestParams params = parseRequestAnonymous(request, LoginRequestParams.class); UserEntity user = userService.loginApi(params.getEmail(), params.getPassword()); if (user == null) { throw MaPermissionDeniedException.wrongCredentials(); } LoginResponseData responseData = new LoginResponseData(user.buildTargetEntity()); UserAuthKey authKey = userService.createAuthKey(user); responseData.setAuthKey(authKey.getAuthKey()); return okResult(responseData); } @RequestMapping(value = "/check-email", method = RequestMethod.POST) public @ResponseBody ApiResponse checkEmail(HttpServletRequest request) { LoginRequestParams params = parseRequestAnonymous(request, LoginRequestParams.class); UserEntity user = userService.findByEmail(params.getEmail()); if (user == null) { return okResult(null); } else { return errorResult(ErrorCode.KEY_EXISTS, null); } } @RequestMapping(value = "/forgotten-password", method = RequestMethod.POST) public @ResponseBody ApiResponse forgottenPassword(HttpServletRequest request) { LoginRequestParams params = parseRequestAnonymous(request, LoginRequestParams.class); if (userService.lostPassword(params.getEmail())) return okResult(null); else return errorResult(ErrorCode.WRONG_CREDENTIALS, null); } @RequestMapping(value = "/register", method = RequestMethod.POST) public @ResponseBody ApiResponse register(HttpServletRequest request) { RegisterRequestParams params = parseRequestAnonymous(request, RegisterRequestParams.class); User newUser = params.getNewUser(); if (newUser == null) throw MaParseException.wrongRequestParams(); final UserEntity newUserEntity = new UserEntity().populateFrom(newUser); // this method is only for new users. For existed users will be method /add-to-event UserEntity loggedUser = getLoggedUser(); if (loggedUser == null) { newUserEntity.setRoleIdList(new String[] {AuthorizationTool.ANONYMOUS}); } else { // it's not new newUserEntity.setId(loggedUser.getId()); } UserInEvent inEvent = params.getUserInEvent(); UserEntity user; if (inEvent != null) { UserInEventEntity inEventEntity = new UserInEventEntity().populateFrom(inEvent); UserInEventEntity regResult = userService.register(newUserEntity, inEventEntity, 0l); user = regResult.getUserEntity(); } else { user = userService.preRegister(newUserEntity, 0l, true); } RegisterResponseData responseData = new RegisterResponseData(user.buildTargetEntity()); if (loggedUser == null) { UserAuthKey authKey = userService.createAuthKey(user); responseData.setAuthKey(authKey.getAuthKey()); } return okResult(responseData); } @RequestMapping(value = "/list", method = RequestMethod.POST) public @ResponseBody ApiResponse filter(HttpServletRequest request) { UserListRequestParams params = parseRequest(request, UserListRequestParams.class); UserFilter filter = new UserFilter(true); filter.setOrganizationIdVal(getLoggedUser().getOrganizationId()); if (params.getModifiedFrom() != null) { filter.setModifiedDateVal(params.getModifiedFrom()); filter.setModifiedDateOp(Filter.Operator.GT); } filter.setOrder("modifiedDate"); ResultList<UserEntity> result = userService.findByFilter(filter, 0, null, 0l); List<User> users = new EntityTool().buildTargetEntities(result.getResult()); return okResult(new UserFilterResponseData(users)); } @RequestMapping(value = "/myself", method = RequestMethod.POST) public @ResponseBody ApiResponse myself(HttpServletRequest request) { parseRequest(request, EmptyRequestParams.class); UserEntity logged = userService.findById(getLoggedUser().getId(), UserService.FLAG_FETCH_EQUIPMENT | UserService.FLAG_FETCH_SKILLS); User u = logged.buildTargetEntity(); return okResult(new UserByIdResponseData(u)); } @RequestMapping(value = "/by-id", method = RequestMethod.POST) public @ResponseBody ApiResponse byId(HttpServletRequest request) { UserByIdRequestParams params = parseRequest(request, UserByIdRequestParams.class); if (params.getById() == null) return okResult(new UserByIdResponseData(new User[0])); List<User> result = new EntityTool().buildTargetEntities(userService.findByIds(0l, params.getById())); return okResult(new UserByIdResponseData(result)); } @RequestMapping(value = "/register-push-token-android", method = RequestMethod.POST) public @ResponseBody ApiResponse registerPushTokenAndroid(HttpServletRequest request) { UserPushTokenRequestParams params = parseRequest(request, UserPushTokenRequestParams.class); userService.registerPushTokenAndroid(params.getToken()); return okResult(null); } }
gpl-3.0
alvsgithub/three-cms
system/application/helpers/strptime_helper.php
5999
<?php /* * This work of Lionel SAURON (http://sauron.lionel.free.fr:80) is licensed under the * Creative Commons Attribution-Noncommercial-Share Alike 2.0 France License. * * To view a copy of this license, visit http://creativecommons.org/licenses/by-nc-sa/2.0/fr/ * or send a letter to Creative Commons, 171 Second Street, Suite 300, San Francisco, California, 94105, USA. */ /** * Parse a time/date generated with strftime(). * * This function is the same as the original one defined by PHP (Linux/Unix only), * but now you can use it on Windows too. * Limitation : Only this format can be parsed %S, %M, %H, %d, %m, %Y * * @author Lionel SAURON * @version 1.0 * @public * * @param $sDate(string) The string to parse (e.g. returned from strftime()). * @param $sFormat(string) The format used in date (e.g. the same as used in strftime()). * @return (array) Returns an array with the <code>$sDate</code> parsed, or <code>false</code> on error. */ if(function_exists("strptime") == false) { function strptime($sDate, $sFormat) { $aResult = array ( 'tm_sec' => 0, 'tm_min' => 0, 'tm_hour' => 0, 'tm_mday' => 1, 'tm_mon' => 0, 'tm_year' => 0, 'tm_wday' => 0, 'tm_yday' => 0, 'unparsed' => $sDate, ); while($sFormat != "") { // ===== Search a %x element, Check the static string before the %x ===== $nIdxFound = strpos($sFormat, '%'); if($nIdxFound === false) { // There is no more format. Check the last static string. $aResult['unparsed'] = ($sFormat == $sDate) ? "" : $sDate; break; } $sFormatBefore = substr($sFormat, 0, $nIdxFound); $sDateBefore = substr($sDate, 0, $nIdxFound); if($sFormatBefore != $sDateBefore) break; // ===== Read the value of the %x found ===== $sFormat = substr($sFormat, $nIdxFound); $sDate = substr($sDate, $nIdxFound); $aResult['unparsed'] = $sDate; $sFormatCurrent = substr($sFormat, 0, 2); $sFormatAfter = substr($sFormat, 2); $nValue = -1; $sDateAfter = ""; switch($sFormatCurrent) { case '%S': // Seconds after the minute (0-59) sscanf($sDate, "%2d%[^\\n]", $nValue, $sDateAfter); if(($nValue < 0) || ($nValue > 59)) return false; $aResult['tm_sec'] = $nValue; break; // ---------- case '%M': // Minutes after the hour (0-59) sscanf($sDate, "%2d%[^\\n]", $nValue, $sDateAfter); if(($nValue < 0) || ($nValue > 59)) return false; $aResult['tm_min'] = $nValue; break; // ---------- case '%H': // Hour since midnight (0-23) sscanf($sDate, "%2d%[^\\n]", $nValue, $sDateAfter); if(($nValue < 0) || ($nValue > 23)) return false; $aResult['tm_hour'] = $nValue; break; // ---------- case '%d': // Day of the month (1-31) sscanf($sDate, "%2d%[^\\n]", $nValue, $sDateAfter); if(($nValue < 1) || ($nValue > 31)) return false; $aResult['tm_mday'] = $nValue; break; // ---------- case '%m': // Months since January (0-11) sscanf($sDate, "%2d%[^\\n]", $nValue, $sDateAfter); if(($nValue < 1) || ($nValue > 12)) return false; $aResult['tm_mon'] = ($nValue - 1); break; // ---------- case '%Y': // Years since 1900 sscanf($sDate, "%4d%[^\\n]", $nValue, $sDateAfter); if($nValue < 1900) return false; $aResult['tm_year'] = ($nValue - 1900); break; // ---------- default: break 2; // Break Switch and while } // END of case format // ===== Next please ===== $sFormat = $sFormatAfter; $sDate = $sDateAfter; $aResult['unparsed'] = $sDate; } // END of while($sFormat != "") // ===== Create the other value of the result array ===== $nParsedDateTimestamp = mktime($aResult['tm_hour'], $aResult['tm_min'], $aResult['tm_sec'], $aResult['tm_mon'] + 1, $aResult['tm_mday'], $aResult['tm_year'] + 1900); // Before PHP 5.1 return -1 when error if(($nParsedDateTimestamp === false) ||($nParsedDateTimestamp === -1)) return false; $aResult['tm_wday'] = (int) strftime("%w", $nParsedDateTimestamp); // Days since Sunday (0-6) $aResult['tm_yday'] = (strftime("%j", $nParsedDateTimestamp) - 1); // Days since January 1 (0-365) return $aResult; } // END of function } // END of if(function_exists("strptime") == false) ?>
gpl-3.0
noodlewiz/xjavab
xjavab-ext/src/main/java/com/noodlewiz/xjavab/ext/render/Pictscreen.java
1218
// // DO NOT MODIFY!!! This file was machine generated. DO NOT MODIFY!!! // // Copyright (c) 2014 Vincent W. Chen. // // This file is part of XJavaB. // // XJavaB is free software: you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // XJavaB 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 Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public License // along with XJavaB. If not, see <http://www.gnu.org/licenses/>. // package com.noodlewiz.xjavab.ext.render; import java.util.List; public class Pictscreen { public final long numDepths; public final long fallback; public final List<Pictdepth> depths; public Pictscreen(final long numDepths, final long fallback, final List<Pictdepth> depths) { this.numDepths = numDepths; this.fallback = fallback; this.depths = depths; } }
gpl-3.0
MartyParty21/AwakenDreamsClient
mcp/src/minecraft/net/minecraft/client/network/NetHandlerPlayClient.java
97852
package net.minecraft.client.network; import com.elementfx.tvp.ad.client.gui.inventory.GuiRucksack; import com.elementfx.tvp.ad.entity.projectile.EntityCustomArrow; import com.elementfx.tvp.ad.entity.projectile.EntityCustomEgg; import com.elementfx.tvp.ad.entity.projectile.EntityThrowingStone; import com.elementfx.tvp.ad.item.ItemRucksack; import com.google.common.collect.Maps; import com.google.common.util.concurrent.FutureCallback; import com.google.common.util.concurrent.Futures; import com.mojang.authlib.GameProfile; import io.netty.buffer.Unpooled; import java.io.File; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Random; import java.util.UUID; import java.util.Map.Entry; import javax.annotation.Nullable; import net.minecraft.block.Block; import net.minecraft.client.ClientBrandRetriever; import net.minecraft.client.Minecraft; import net.minecraft.client.audio.GuardianSound; import net.minecraft.client.audio.ISound; import net.minecraft.client.audio.PositionedSoundRecord; import net.minecraft.client.entity.EntityOtherPlayerMP; import net.minecraft.client.entity.EntityPlayerSP; import net.minecraft.client.gui.GuiCommandBlock; import net.minecraft.client.gui.GuiDisconnected; import net.minecraft.client.gui.GuiDownloadTerrain; import net.minecraft.client.gui.GuiGameOver; import net.minecraft.client.gui.GuiMainMenu; import net.minecraft.client.gui.GuiMerchant; import net.minecraft.client.gui.GuiMultiplayer; import net.minecraft.client.gui.GuiScreen; import net.minecraft.client.gui.GuiScreenBook; import net.minecraft.client.gui.GuiScreenDemo; import net.minecraft.client.gui.GuiScreenRealmsProxy; import net.minecraft.client.gui.GuiWinGame; import net.minecraft.client.gui.GuiYesNo; import net.minecraft.client.gui.GuiYesNoCallback; import net.minecraft.client.gui.IProgressMeter; import net.minecraft.client.gui.inventory.GuiContainerCreative; import net.minecraft.client.multiplayer.PlayerControllerMP; import net.minecraft.client.multiplayer.ServerData; import net.minecraft.client.multiplayer.ServerList; import net.minecraft.client.multiplayer.WorldClient; import net.minecraft.client.particle.ParticleItemPickup; import net.minecraft.client.player.inventory.ContainerLocalMenu; import net.minecraft.client.player.inventory.LocalBlockIntercommunication; import net.minecraft.client.renderer.debug.DebugRendererPathfinding; import net.minecraft.client.resources.I18n; import net.minecraft.client.settings.GameSettings; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityAreaEffectCloud; import net.minecraft.entity.EntityLeashKnot; import net.minecraft.entity.EntityList; import net.minecraft.entity.EntityLiving; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.EntityTracker; import net.minecraft.entity.IMerchant; import net.minecraft.entity.NpcMerchant; import net.minecraft.entity.ai.attributes.AbstractAttributeMap; import net.minecraft.entity.ai.attributes.AttributeModifier; import net.minecraft.entity.ai.attributes.IAttribute; import net.minecraft.entity.ai.attributes.IAttributeInstance; import net.minecraft.entity.ai.attributes.RangedAttribute; import net.minecraft.entity.effect.EntityLightningBolt; import net.minecraft.entity.item.EntityArmorStand; import net.minecraft.entity.item.EntityBoat; import net.minecraft.entity.item.EntityEnderCrystal; import net.minecraft.entity.item.EntityEnderEye; import net.minecraft.entity.item.EntityEnderPearl; import net.minecraft.entity.item.EntityExpBottle; import net.minecraft.entity.item.EntityFallingBlock; import net.minecraft.entity.item.EntityFireworkRocket; import net.minecraft.entity.item.EntityItem; import net.minecraft.entity.item.EntityItemFrame; import net.minecraft.entity.item.EntityMinecart; import net.minecraft.entity.item.EntityPainting; import net.minecraft.entity.item.EntityTNTPrimed; import net.minecraft.entity.item.EntityXPOrb; import net.minecraft.entity.monster.EntityGuardian; import net.minecraft.entity.passive.EntityHorse; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.entity.projectile.EntityArrow; import net.minecraft.entity.projectile.EntityDragonFireball; import net.minecraft.entity.projectile.EntityEgg; import net.minecraft.entity.projectile.EntityFishHook; import net.minecraft.entity.projectile.EntityLargeFireball; import net.minecraft.entity.projectile.EntityPotion; import net.minecraft.entity.projectile.EntityShulkerBullet; import net.minecraft.entity.projectile.EntitySmallFireball; import net.minecraft.entity.projectile.EntitySnowball; import net.minecraft.entity.projectile.EntitySpectralArrow; import net.minecraft.entity.projectile.EntityTippedArrow; import net.minecraft.entity.projectile.EntityWitherSkull; import net.minecraft.init.Items; import net.minecraft.init.SoundEvents; import net.minecraft.inventory.AnimalChest; import net.minecraft.inventory.Container; import net.minecraft.inventory.IInventory; import net.minecraft.inventory.InventoryBasic; import net.minecraft.item.ItemMap; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.network.NetworkManager; import net.minecraft.network.Packet; import net.minecraft.network.PacketBuffer; import net.minecraft.network.PacketThreadUtil; import net.minecraft.network.datasync.EntityDataManager; import net.minecraft.network.play.INetHandlerPlayClient; import net.minecraft.network.play.client.CPacketClientStatus; import net.minecraft.network.play.client.CPacketConfirmTeleport; import net.minecraft.network.play.client.CPacketConfirmTransaction; import net.minecraft.network.play.client.CPacketCustomPayload; import net.minecraft.network.play.client.CPacketKeepAlive; import net.minecraft.network.play.client.CPacketPlayer; import net.minecraft.network.play.client.CPacketResourcePackStatus; import net.minecraft.network.play.client.CPacketVehicleMove; import net.minecraft.network.play.server.SPacketAnimation; import net.minecraft.network.play.server.SPacketBlockAction; import net.minecraft.network.play.server.SPacketBlockBreakAnim; import net.minecraft.network.play.server.SPacketBlockChange; import net.minecraft.network.play.server.SPacketCamera; import net.minecraft.network.play.server.SPacketChangeGameState; import net.minecraft.network.play.server.SPacketChat; import net.minecraft.network.play.server.SPacketChunkData; import net.minecraft.network.play.server.SPacketCloseWindow; import net.minecraft.network.play.server.SPacketCollectItem; import net.minecraft.network.play.server.SPacketCombatEvent; import net.minecraft.network.play.server.SPacketConfirmTransaction; import net.minecraft.network.play.server.SPacketCooldown; import net.minecraft.network.play.server.SPacketCustomPayload; import net.minecraft.network.play.server.SPacketCustomSound; import net.minecraft.network.play.server.SPacketDestroyEntities; import net.minecraft.network.play.server.SPacketDisconnect; import net.minecraft.network.play.server.SPacketDisplayObjective; import net.minecraft.network.play.server.SPacketEffect; import net.minecraft.network.play.server.SPacketEntity; import net.minecraft.network.play.server.SPacketEntityAttach; import net.minecraft.network.play.server.SPacketEntityEffect; import net.minecraft.network.play.server.SPacketEntityEquipment; import net.minecraft.network.play.server.SPacketEntityHeadLook; import net.minecraft.network.play.server.SPacketEntityMetadata; import net.minecraft.network.play.server.SPacketEntityProperties; import net.minecraft.network.play.server.SPacketEntityStatus; import net.minecraft.network.play.server.SPacketEntityTeleport; import net.minecraft.network.play.server.SPacketEntityVelocity; import net.minecraft.network.play.server.SPacketExplosion; import net.minecraft.network.play.server.SPacketHeldItemChange; import net.minecraft.network.play.server.SPacketJoinGame; import net.minecraft.network.play.server.SPacketKeepAlive; import net.minecraft.network.play.server.SPacketMaps; import net.minecraft.network.play.server.SPacketMoveVehicle; import net.minecraft.network.play.server.SPacketMultiBlockChange; import net.minecraft.network.play.server.SPacketOpenWindow; import net.minecraft.network.play.server.SPacketParticles; import net.minecraft.network.play.server.SPacketPlayerAbilities; import net.minecraft.network.play.server.SPacketPlayerListHeaderFooter; import net.minecraft.network.play.server.SPacketPlayerListItem; import net.minecraft.network.play.server.SPacketPlayerPosLook; import net.minecraft.network.play.server.SPacketRemoveEntityEffect; import net.minecraft.network.play.server.SPacketResourcePackSend; import net.minecraft.network.play.server.SPacketRespawn; import net.minecraft.network.play.server.SPacketScoreboardObjective; import net.minecraft.network.play.server.SPacketServerDifficulty; import net.minecraft.network.play.server.SPacketSetExperience; import net.minecraft.network.play.server.SPacketSetPassengers; import net.minecraft.network.play.server.SPacketSetSlot; import net.minecraft.network.play.server.SPacketSignEditorOpen; import net.minecraft.network.play.server.SPacketSoundEffect; import net.minecraft.network.play.server.SPacketSpawnExperienceOrb; import net.minecraft.network.play.server.SPacketSpawnGlobalEntity; import net.minecraft.network.play.server.SPacketSpawnMob; import net.minecraft.network.play.server.SPacketSpawnObject; import net.minecraft.network.play.server.SPacketSpawnPainting; import net.minecraft.network.play.server.SPacketSpawnPlayer; import net.minecraft.network.play.server.SPacketSpawnPosition; import net.minecraft.network.play.server.SPacketStatistics; import net.minecraft.network.play.server.SPacketTabComplete; import net.minecraft.network.play.server.SPacketTeams; import net.minecraft.network.play.server.SPacketTimeUpdate; import net.minecraft.network.play.server.SPacketTitle; import net.minecraft.network.play.server.SPacketUnloadChunk; import net.minecraft.network.play.server.SPacketUpdateBossInfo; import net.minecraft.network.play.server.SPacketUpdateHealth; import net.minecraft.network.play.server.SPacketUpdateScore; import net.minecraft.network.play.server.SPacketUpdateTileEntity; import net.minecraft.network.play.server.SPacketUseBed; import net.minecraft.network.play.server.SPacketWindowItems; import net.minecraft.network.play.server.SPacketWindowProperty; import net.minecraft.network.play.server.SPacketWorldBorder; import net.minecraft.pathfinding.Path; import net.minecraft.potion.Potion; import net.minecraft.potion.PotionEffect; import net.minecraft.realms.DisconnectedRealmsScreen; import net.minecraft.scoreboard.IScoreCriteria; import net.minecraft.scoreboard.Score; import net.minecraft.scoreboard.ScoreObjective; import net.minecraft.scoreboard.ScorePlayerTeam; import net.minecraft.scoreboard.Scoreboard; import net.minecraft.scoreboard.Team; import net.minecraft.stats.Achievement; import net.minecraft.stats.AchievementList; import net.minecraft.stats.StatBase; import net.minecraft.tileentity.TileEntity; import net.minecraft.tileentity.TileEntityBanner; import net.minecraft.tileentity.TileEntityBeacon; import net.minecraft.tileentity.TileEntityCommandBlock; import net.minecraft.tileentity.TileEntityEndGateway; import net.minecraft.tileentity.TileEntityFlowerPot; import net.minecraft.tileentity.TileEntityMobSpawner; import net.minecraft.tileentity.TileEntitySign; import net.minecraft.tileentity.TileEntitySkull; import net.minecraft.tileentity.TileEntityStructure; import net.minecraft.util.EnumFacing; import net.minecraft.util.EnumHand; import net.minecraft.util.EnumParticleTypes; import net.minecraft.util.ITabCompleter; import net.minecraft.util.ResourceLocation; import net.minecraft.util.SoundCategory; import net.minecraft.util.StringUtils; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.MathHelper; import net.minecraft.util.text.ITextComponent; import net.minecraft.util.text.TextComponentTranslation; import net.minecraft.util.text.TextFormatting; import net.minecraft.village.MerchantRecipeList; import net.minecraft.world.Explosion; import net.minecraft.world.GameType; import net.minecraft.world.WorldProviderSurface; import net.minecraft.world.WorldSettings; import net.minecraft.world.chunk.Chunk; import net.minecraft.world.storage.MapData; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; public class NetHandlerPlayClient implements INetHandlerPlayClient { private static final Logger LOGGER = LogManager.getLogger(); /** * The NetworkManager instance used to communicate with the server (used only by handlePlayerPosLook to update * positioning and handleJoinGame to inform the server of the client distribution/mods) */ private final NetworkManager netManager; private final GameProfile profile; /** * Seems to be either null (integrated server) or an instance of either GuiMultiplayer (when connecting to a server) * or GuiScreenReamlsTOS (when connecting to MCO server) */ private final GuiScreen guiScreenServer; /** * Reference to the Minecraft instance, which many handler methods operate on */ private Minecraft gameController; /** * Reference to the current ClientWorld instance, which many handler methods operate on */ private WorldClient clientWorldController; /** * True if the client has finished downloading terrain and may spawn. Set upon receipt of S08PacketPlayerPosLook, * reset upon respawning */ private boolean doneLoadingTerrain; private final Map<UUID, NetworkPlayerInfo> playerInfoMap = Maps.<UUID, NetworkPlayerInfo>newHashMap(); public int currentServerMaxPlayers = 20; private boolean hasStatistics; /** * Just an ordinary random number generator, used to randomize audio pitch of item/orb pickup and randomize both * particlespawn offset and velocity */ private final Random avRandomizer = new Random(); public NetHandlerPlayClient(Minecraft mcIn, GuiScreen p_i46300_2_, NetworkManager networkManagerIn, GameProfile profileIn) { this.gameController = mcIn; this.guiScreenServer = p_i46300_2_; this.netManager = networkManagerIn; this.profile = profileIn; } /** * Clears the WorldClient instance associated with this NetHandlerPlayClient */ public void cleanup() { this.clientWorldController = null; } /** * Registers some server properties (gametype,hardcore-mode,terraintype,difficulty,player limit), creates a new * WorldClient and sets the player initial dimension */ public void handleJoinGame(SPacketJoinGame packetIn) { PacketThreadUtil.checkThreadAndEnqueue(packetIn, this, this.gameController); this.gameController.playerController = new PlayerControllerMP(this.gameController, this); this.clientWorldController = new WorldClient(this, new WorldSettings(0L, packetIn.getGameType(), false, packetIn.isHardcoreMode(), packetIn.getWorldType()), packetIn.getDimension(), packetIn.getDifficulty(), this.gameController.mcProfiler); this.gameController.gameSettings.difficulty = packetIn.getDifficulty(); this.gameController.loadWorld(this.clientWorldController); this.gameController.thePlayer.dimension = packetIn.getDimension(); this.gameController.displayGuiScreen(new GuiDownloadTerrain(this)); this.gameController.thePlayer.setEntityId(packetIn.getPlayerId()); this.currentServerMaxPlayers = packetIn.getMaxPlayers(); this.gameController.thePlayer.setReducedDebug(packetIn.isReducedDebugInfo()); this.gameController.playerController.setGameType(packetIn.getGameType()); this.gameController.gameSettings.sendSettingsToServer(); this.netManager.sendPacket(new CPacketCustomPayload("MC|Brand", (new PacketBuffer(Unpooled.buffer())).writeString(ClientBrandRetriever.getClientModName()))); } /** * Spawns an instance of the objecttype indicated by the packet and sets its position and momentum */ public void handleSpawnObject(SPacketSpawnObject packetIn) { PacketThreadUtil.checkThreadAndEnqueue(packetIn, this, this.gameController); double d0 = packetIn.getX(); double d1 = packetIn.getY(); double d2 = packetIn.getZ(); Entity entity = null; if (packetIn.getType() == 10) { entity = EntityMinecart.create(this.clientWorldController, d0, d1, d2, EntityMinecart.Type.getById(packetIn.getData())); } else if (packetIn.getType() == 90) { Entity entity1 = this.clientWorldController.getEntityByID(packetIn.getData()); if (entity1 instanceof EntityPlayer) { entity = new EntityFishHook(this.clientWorldController, d0, d1, d2, (EntityPlayer)entity1); } packetIn.setData(0); } else if (packetIn.getType() == 60) { entity = new EntityTippedArrow(this.clientWorldController, d0, d1, d2); } else if (packetIn.getType() == 91) { entity = new EntitySpectralArrow(this.clientWorldController, d0, d1, d2); } else if (packetIn.getType() == 61) { entity = new EntitySnowball(this.clientWorldController, d0, d1, d2); } else if (packetIn.getType() == 71) { entity = new EntityItemFrame(this.clientWorldController, new BlockPos(d0, d1, d2), EnumFacing.getHorizontal(packetIn.getData())); packetIn.setData(0); } else if (packetIn.getType() == 77) { entity = new EntityLeashKnot(this.clientWorldController, new BlockPos(MathHelper.floor_double(d0), MathHelper.floor_double(d1), MathHelper.floor_double(d2))); packetIn.setData(0); } else if (packetIn.getType() == 65) { entity = new EntityEnderPearl(this.clientWorldController, d0, d1, d2); } else if (packetIn.getType() == 72) { entity = new EntityEnderEye(this.clientWorldController, d0, d1, d2); } else if (packetIn.getType() == 76) { entity = new EntityFireworkRocket(this.clientWorldController, d0, d1, d2, (ItemStack)null); } else if (packetIn.getType() == 63) { entity = new EntityLargeFireball(this.clientWorldController, d0, d1, d2, (double)packetIn.getSpeedX() / 8000.0D, (double)packetIn.getSpeedY() / 8000.0D, (double)packetIn.getSpeedZ() / 8000.0D); packetIn.setData(0); } else if (packetIn.getType() == 93) { entity = new EntityDragonFireball(this.clientWorldController, d0, d1, d2, (double)packetIn.getSpeedX() / 8000.0D, (double)packetIn.getSpeedY() / 8000.0D, (double)packetIn.getSpeedZ() / 8000.0D); packetIn.setData(0); } else if (packetIn.getType() == 64) { entity = new EntitySmallFireball(this.clientWorldController, d0, d1, d2, (double)packetIn.getSpeedX() / 8000.0D, (double)packetIn.getSpeedY() / 8000.0D, (double)packetIn.getSpeedZ() / 8000.0D); packetIn.setData(0); } else if (packetIn.getType() == 66) { entity = new EntityWitherSkull(this.clientWorldController, d0, d1, d2, (double)packetIn.getSpeedX() / 8000.0D, (double)packetIn.getSpeedY() / 8000.0D, (double)packetIn.getSpeedZ() / 8000.0D); packetIn.setData(0); } else if (packetIn.getType() == 67) { entity = new EntityShulkerBullet(this.clientWorldController, d0, d1, d2, (double)packetIn.getSpeedX() / 8000.0D, (double)packetIn.getSpeedY() / 8000.0D, (double)packetIn.getSpeedZ() / 8000.0D); packetIn.setData(0); } else if (packetIn.getType() == 62) { entity = new EntityEgg(this.clientWorldController, d0, d1, d2); } else if (packetIn.getType() == 73) { entity = new EntityPotion(this.clientWorldController, d0, d1, d2, (ItemStack)null); packetIn.setData(0); } else if (packetIn.getType() == 75) { entity = new EntityExpBottle(this.clientWorldController, d0, d1, d2); packetIn.setData(0); } else if (packetIn.getType() == 1) { entity = new EntityBoat(this.clientWorldController, d0, d1, d2); } else if (packetIn.getType() == 50) { entity = new EntityTNTPrimed(this.clientWorldController, d0, d1, d2, (EntityLivingBase)null); } else if (packetIn.getType() == 78) { entity = new EntityArmorStand(this.clientWorldController, d0, d1, d2); } else if (packetIn.getType() == 51) { entity = new EntityEnderCrystal(this.clientWorldController, d0, d1, d2); } else if (packetIn.getType() == 2) { entity = new EntityItem(this.clientWorldController, d0, d1, d2); } else if (packetIn.getType() == 70) { entity = new EntityFallingBlock(this.clientWorldController, d0, d1, d2, Block.getStateById(packetIn.getData() & 65535)); packetIn.setData(0); } else if (packetIn.getType() == 3) { entity = new EntityAreaEffectCloud(this.clientWorldController, d0, d1, d2); } //Begin Awaken Dreams code else if (packetIn.getType() == 500) { entity = new EntityThrowingStone(this.clientWorldController, d0, d1, d2); } else if (packetIn.getType() == 502) { entity = new EntityCustomEgg(this.clientWorldController, d0, d1, d2); } else if (packetIn.getType() == 503) { entity = new EntityCustomArrow(this.clientWorldController, d0, d1, d2); } //End Awaken Dreams code if (entity != null) { EntityTracker.updateServerPosition(entity, d0, d1, d2); entity.rotationPitch = (float)(packetIn.getPitch() * 360) / 256.0F; entity.rotationYaw = (float)(packetIn.getYaw() * 360) / 256.0F; Entity[] aentity = entity.getParts(); if (aentity != null) { int i = packetIn.getEntityID() - entity.getEntityId(); for (Entity entity2 : aentity) { entity2.setEntityId(entity2.getEntityId() + i); } } entity.setEntityId(packetIn.getEntityID()); entity.setUniqueId(packetIn.getUniqueId()); this.clientWorldController.addEntityToWorld(packetIn.getEntityID(), entity); if (packetIn.getData() > 0) { if (packetIn.getType() == 60 || packetIn.getType() == 91) { Entity entity3 = this.clientWorldController.getEntityByID(packetIn.getData() - 1); if (entity3 instanceof EntityLivingBase && entity instanceof EntityArrow) { ((EntityArrow)entity).shootingEntity = entity3; } } entity.setVelocity((double)packetIn.getSpeedX() / 8000.0D, (double)packetIn.getSpeedY() / 8000.0D, (double)packetIn.getSpeedZ() / 8000.0D); } } } /** * Spawns an experience orb and sets its value (amount of XP) */ public void handleSpawnExperienceOrb(SPacketSpawnExperienceOrb packetIn) { PacketThreadUtil.checkThreadAndEnqueue(packetIn, this, this.gameController); double d0 = packetIn.getX(); double d1 = packetIn.getY(); double d2 = packetIn.getZ(); Entity entity = new EntityXPOrb(this.clientWorldController, d0, d1, d2, packetIn.getXPValue()); EntityTracker.updateServerPosition(entity, d0, d1, d2); entity.rotationYaw = 0.0F; entity.rotationPitch = 0.0F; entity.setEntityId(packetIn.getEntityID()); this.clientWorldController.addEntityToWorld(packetIn.getEntityID(), entity); } /** * Handles globally visible entities. Used in vanilla for lightning bolts */ public void handleSpawnGlobalEntity(SPacketSpawnGlobalEntity packetIn) { PacketThreadUtil.checkThreadAndEnqueue(packetIn, this, this.gameController); double d0 = packetIn.getX(); double d1 = packetIn.getY(); double d2 = packetIn.getZ(); Entity entity = null; if (packetIn.getType() == 1) { entity = new EntityLightningBolt(this.clientWorldController, d0, d1, d2, false); } if (entity != null) { EntityTracker.updateServerPosition(entity, d0, d1, d2); entity.rotationYaw = 0.0F; entity.rotationPitch = 0.0F; entity.setEntityId(packetIn.getEntityId()); this.clientWorldController.addWeatherEffect(entity); } } /** * Handles the spawning of a painting object */ public void handleSpawnPainting(SPacketSpawnPainting packetIn) { PacketThreadUtil.checkThreadAndEnqueue(packetIn, this, this.gameController); EntityPainting entitypainting = new EntityPainting(this.clientWorldController, packetIn.getPosition(), packetIn.getFacing(), packetIn.getTitle()); entitypainting.setUniqueId(packetIn.getUniqueId()); this.clientWorldController.addEntityToWorld(packetIn.getEntityID(), entitypainting); } /** * Sets the velocity of the specified entity to the specified value */ public void handleEntityVelocity(SPacketEntityVelocity packetIn) { PacketThreadUtil.checkThreadAndEnqueue(packetIn, this, this.gameController); Entity entity = this.clientWorldController.getEntityByID(packetIn.getEntityID()); if (entity != null) { entity.setVelocity((double)packetIn.getMotionX() / 8000.0D, (double)packetIn.getMotionY() / 8000.0D, (double)packetIn.getMotionZ() / 8000.0D); } } /** * Invoked when the server registers new proximate objects in your watchlist or when objects in your watchlist have * changed -> Registers any changes locally */ public void handleEntityMetadata(SPacketEntityMetadata packetIn) { PacketThreadUtil.checkThreadAndEnqueue(packetIn, this, this.gameController); Entity entity = this.clientWorldController.getEntityByID(packetIn.getEntityId()); if (entity != null && packetIn.getDataManagerEntries() != null) { entity.getDataManager().setEntryValues(packetIn.getDataManagerEntries()); } } /** * Handles the creation of a nearby player entity, sets the position and held item */ public void handleSpawnPlayer(SPacketSpawnPlayer packetIn) { PacketThreadUtil.checkThreadAndEnqueue(packetIn, this, this.gameController); double d0 = packetIn.getX(); double d1 = packetIn.getY(); double d2 = packetIn.getZ(); float f = (float)(packetIn.getYaw() * 360) / 256.0F; float f1 = (float)(packetIn.getPitch() * 360) / 256.0F; EntityOtherPlayerMP entityotherplayermp = new EntityOtherPlayerMP(this.gameController.theWorld, this.getPlayerInfo(packetIn.getUniqueId()).getGameProfile()); entityotherplayermp.prevPosX = d0; entityotherplayermp.lastTickPosX = d0; entityotherplayermp.prevPosY = d1; entityotherplayermp.lastTickPosY = d1; entityotherplayermp.prevPosZ = d2; entityotherplayermp.lastTickPosZ = d2; EntityTracker.updateServerPosition(entityotherplayermp, d0, d1, d2); entityotherplayermp.setPositionAndRotation(d0, d1, d2, f, f1); this.clientWorldController.addEntityToWorld(packetIn.getEntityID(), entityotherplayermp); List < EntityDataManager.DataEntry<? >> list = packetIn.getDataManagerEntries(); if (list != null) { entityotherplayermp.getDataManager().setEntryValues(list); } } /** * Updates an entity's position and rotation as specified by the packet */ public void handleEntityTeleport(SPacketEntityTeleport packetIn) { PacketThreadUtil.checkThreadAndEnqueue(packetIn, this, this.gameController); Entity entity = this.clientWorldController.getEntityByID(packetIn.getEntityId()); if (entity != null) { double d0 = packetIn.getX(); double d1 = packetIn.getY(); double d2 = packetIn.getZ(); EntityTracker.updateServerPosition(entity, d0, d1, d2); if (!entity.canPassengerSteer()) { float f = (float)(packetIn.getYaw() * 360) / 256.0F; float f1 = (float)(packetIn.getPitch() * 360) / 256.0F; if (Math.abs(entity.posX - d0) < 0.03125D && Math.abs(entity.posY - d1) < 0.015625D && Math.abs(entity.posZ - d2) < 0.03125D) { entity.setPositionAndRotationDirect(entity.posX, entity.posY, entity.posZ, f, f1, 0, true); } else { entity.setPositionAndRotationDirect(d0, d1, d2, f, f1, 3, true); } entity.onGround = packetIn.getOnGround(); } } } /** * Updates which hotbar slot of the player is currently selected */ public void handleHeldItemChange(SPacketHeldItemChange packetIn) { PacketThreadUtil.checkThreadAndEnqueue(packetIn, this, this.gameController); if (InventoryPlayer.isHotbar(packetIn.getHeldItemHotbarIndex())) { this.gameController.thePlayer.inventory.currentItem = packetIn.getHeldItemHotbarIndex(); } } /** * Updates the specified entity's position by the specified relative moment and absolute rotation. Note that * subclassing of the packet allows for the specification of a subset of this data (e.g. only rel. position, abs. * rotation or both). */ public void handleEntityMovement(SPacketEntity packetIn) { PacketThreadUtil.checkThreadAndEnqueue(packetIn, this, this.gameController); Entity entity = packetIn.getEntity(this.clientWorldController); if (entity != null) { entity.serverPosX += (long)packetIn.getX(); entity.serverPosY += (long)packetIn.getY(); entity.serverPosZ += (long)packetIn.getZ(); double d0 = (double)entity.serverPosX / 4096.0D; double d1 = (double)entity.serverPosY / 4096.0D; double d2 = (double)entity.serverPosZ / 4096.0D; if (!entity.canPassengerSteer()) { float f = packetIn.isRotating() ? (float)(packetIn.getYaw() * 360) / 256.0F : entity.rotationYaw; float f1 = packetIn.isRotating() ? (float)(packetIn.getPitch() * 360) / 256.0F : entity.rotationPitch; entity.setPositionAndRotationDirect(d0, d1, d2, f, f1, 3, false); entity.onGround = packetIn.getOnGround(); } } } /** * Updates the direction in which the specified entity is looking, normally this head rotation is independent of the * rotation of the entity itself */ public void handleEntityHeadLook(SPacketEntityHeadLook packetIn) { PacketThreadUtil.checkThreadAndEnqueue(packetIn, this, this.gameController); Entity entity = packetIn.getEntity(this.clientWorldController); if (entity != null) { float f = (float)(packetIn.getYaw() * 360) / 256.0F; entity.setRotationYawHead(f); } } /** * Locally eliminates the entities. Invoked by the server when the items are in fact destroyed, or the player is no * longer registered as required to monitor them. The latter happens when distance between the player and item * increases beyond a certain treshold (typically the viewing distance) */ public void handleDestroyEntities(SPacketDestroyEntities packetIn) { PacketThreadUtil.checkThreadAndEnqueue(packetIn, this, this.gameController); for (int i = 0; i < packetIn.getEntityIDs().length; ++i) { this.clientWorldController.removeEntityFromWorld(packetIn.getEntityIDs()[i]); } } public void handlePlayerPosLook(SPacketPlayerPosLook packetIn) { PacketThreadUtil.checkThreadAndEnqueue(packetIn, this, this.gameController); EntityPlayer entityplayer = this.gameController.thePlayer; double d0 = packetIn.getX(); double d1 = packetIn.getY(); double d2 = packetIn.getZ(); float f = packetIn.getYaw(); float f1 = packetIn.getPitch(); if (packetIn.getFlags().contains(SPacketPlayerPosLook.EnumFlags.X)) { d0 += entityplayer.posX; } else { entityplayer.motionX = 0.0D; } if (packetIn.getFlags().contains(SPacketPlayerPosLook.EnumFlags.Y)) { d1 += entityplayer.posY; } else { entityplayer.motionY = 0.0D; } if (packetIn.getFlags().contains(SPacketPlayerPosLook.EnumFlags.Z)) { d2 += entityplayer.posZ; } else { entityplayer.motionZ = 0.0D; } if (packetIn.getFlags().contains(SPacketPlayerPosLook.EnumFlags.X_ROT)) { f1 += entityplayer.rotationPitch; } if (packetIn.getFlags().contains(SPacketPlayerPosLook.EnumFlags.Y_ROT)) { f += entityplayer.rotationYaw; } entityplayer.setPositionAndRotation(d0, d1, d2, f, f1); this.netManager.sendPacket(new CPacketConfirmTeleport(packetIn.getTeleportId())); this.netManager.sendPacket(new CPacketPlayer.PositionRotation(entityplayer.posX, entityplayer.getEntityBoundingBox().minY, entityplayer.posZ, entityplayer.rotationYaw, entityplayer.rotationPitch, false)); if (!this.doneLoadingTerrain) { this.gameController.thePlayer.prevPosX = this.gameController.thePlayer.posX; this.gameController.thePlayer.prevPosY = this.gameController.thePlayer.posY; this.gameController.thePlayer.prevPosZ = this.gameController.thePlayer.posZ; this.doneLoadingTerrain = true; this.gameController.displayGuiScreen((GuiScreen)null); } } /** * Received from the servers PlayerManager if between 1 and 64 blocks in a chunk are changed. If only one block * requires an update, the server sends S23PacketBlockChange and if 64 or more blocks are changed, the server sends * S21PacketChunkData */ public void handleMultiBlockChange(SPacketMultiBlockChange packetIn) { PacketThreadUtil.checkThreadAndEnqueue(packetIn, this, this.gameController); for (SPacketMultiBlockChange.BlockUpdateData spacketmultiblockchange$blockupdatedata : packetIn.getChangedBlocks()) { this.clientWorldController.invalidateRegionAndSetBlock(spacketmultiblockchange$blockupdatedata.getPos(), spacketmultiblockchange$blockupdatedata.getBlockState()); } } /** * Updates the specified chunk with the supplied data, marks it for re-rendering and lighting recalculation */ public void handleChunkData(SPacketChunkData packetIn) { PacketThreadUtil.checkThreadAndEnqueue(packetIn, this, this.gameController); if (packetIn.doChunkLoad()) { this.clientWorldController.doPreChunk(packetIn.getChunkX(), packetIn.getChunkZ(), true); } this.clientWorldController.invalidateBlockReceiveRegion(packetIn.getChunkX() << 4, 0, packetIn.getChunkZ() << 4, (packetIn.getChunkX() << 4) + 15, 256, (packetIn.getChunkZ() << 4) + 15); Chunk chunk = this.clientWorldController.getChunkFromChunkCoords(packetIn.getChunkX(), packetIn.getChunkZ()); chunk.fillChunk(packetIn.getReadBuffer(), packetIn.getExtractedSize(), packetIn.doChunkLoad()); this.clientWorldController.markBlockRangeForRenderUpdate(packetIn.getChunkX() << 4, 0, packetIn.getChunkZ() << 4, (packetIn.getChunkX() << 4) + 15, 256, (packetIn.getChunkZ() << 4) + 15); if (!packetIn.doChunkLoad() || !(this.clientWorldController.provider instanceof WorldProviderSurface)) { chunk.resetRelightChecks(); } for (NBTTagCompound nbttagcompound : packetIn.func_189554_f()) { BlockPos blockpos = new BlockPos(nbttagcompound.getInteger("x"), nbttagcompound.getInteger("y"), nbttagcompound.getInteger("z")); TileEntity tileentity = this.clientWorldController.getTileEntity(blockpos); if (tileentity != null) { tileentity.readFromNBT(nbttagcompound); } } } public void processChunkUnload(SPacketUnloadChunk packetIn) { PacketThreadUtil.checkThreadAndEnqueue(packetIn, this, this.gameController); this.clientWorldController.doPreChunk(packetIn.getX(), packetIn.getZ(), false); } /** * Updates the block and metadata and generates a blockupdate (and notify the clients) */ public void handleBlockChange(SPacketBlockChange packetIn) { PacketThreadUtil.checkThreadAndEnqueue(packetIn, this, this.gameController); this.clientWorldController.invalidateRegionAndSetBlock(packetIn.getBlockPosition(), packetIn.getBlockState()); } /** * Closes the network channel */ public void handleDisconnect(SPacketDisconnect packetIn) { this.netManager.closeChannel(packetIn.getReason()); } /** * Invoked when disconnecting, the parameter is a ChatComponent describing the reason for termination */ public void onDisconnect(ITextComponent reason) { this.gameController.loadWorld((WorldClient)null); if (this.guiScreenServer != null) { if (this.guiScreenServer instanceof GuiScreenRealmsProxy) { this.gameController.displayGuiScreen((new DisconnectedRealmsScreen(((GuiScreenRealmsProxy)this.guiScreenServer).getProxy(), "disconnect.lost", reason)).getProxy()); } else { this.gameController.displayGuiScreen(new GuiDisconnected(this.guiScreenServer, "disconnect.lost", reason)); } } else { this.gameController.displayGuiScreen(new GuiDisconnected(new GuiMultiplayer(new GuiMainMenu()), "disconnect.lost", reason)); } } public void sendPacket(Packet<?> packetIn) { this.netManager.sendPacket(packetIn); } public void handleCollectItem(SPacketCollectItem packetIn) { PacketThreadUtil.checkThreadAndEnqueue(packetIn, this, this.gameController); Entity entity = this.clientWorldController.getEntityByID(packetIn.getCollectedItemEntityID()); EntityLivingBase entitylivingbase = (EntityLivingBase)this.clientWorldController.getEntityByID(packetIn.getEntityID()); if (entitylivingbase == null) { entitylivingbase = this.gameController.thePlayer; } if (entity != null) { if (entity instanceof EntityXPOrb) { this.clientWorldController.playSound(entity.posX, entity.posY, entity.posZ, SoundEvents.ENTITY_EXPERIENCE_ORB_PICKUP, SoundCategory.PLAYERS, 0.2F, ((this.avRandomizer.nextFloat() - this.avRandomizer.nextFloat()) * 0.7F + 1.0F) * 2.0F, false); } else { this.clientWorldController.playSound(entity.posX, entity.posY, entity.posZ, SoundEvents.ENTITY_ITEM_PICKUP, SoundCategory.PLAYERS, 0.2F, ((this.avRandomizer.nextFloat() - this.avRandomizer.nextFloat()) * 0.7F + 1.0F) * 2.0F, false); } this.gameController.effectRenderer.addEffect(new ParticleItemPickup(this.clientWorldController, entity, entitylivingbase, 0.5F)); this.clientWorldController.removeEntityFromWorld(packetIn.getCollectedItemEntityID()); } } /** * Prints a chatmessage in the chat GUI */ public void handleChat(SPacketChat packetIn) { PacketThreadUtil.checkThreadAndEnqueue(packetIn, this, this.gameController); if (packetIn.getType() == 2) { this.gameController.ingameGUI.setRecordPlaying(packetIn.getChatComponent(), false); } else { this.gameController.ingameGUI.getChatGUI().printChatMessage(packetIn.getChatComponent()); } } /** * Renders a specified animation: Waking up a player, a living entity swinging its currently held item, being hurt * or receiving a critical hit by normal or magical means */ public void handleAnimation(SPacketAnimation packetIn) { PacketThreadUtil.checkThreadAndEnqueue(packetIn, this, this.gameController); Entity entity = this.clientWorldController.getEntityByID(packetIn.getEntityID()); if (entity != null) { if (packetIn.getAnimationType() == 0) { EntityLivingBase entitylivingbase = (EntityLivingBase)entity; entitylivingbase.swingArm(EnumHand.MAIN_HAND); } else if (packetIn.getAnimationType() == 3) { EntityLivingBase entitylivingbase1 = (EntityLivingBase)entity; entitylivingbase1.swingArm(EnumHand.OFF_HAND); } else if (packetIn.getAnimationType() == 1) { entity.performHurtAnimation(); } else if (packetIn.getAnimationType() == 2) { EntityPlayer entityplayer = (EntityPlayer)entity; entityplayer.wakeUpPlayer(false, false, false); } else if (packetIn.getAnimationType() == 4) { this.gameController.effectRenderer.emitParticleAtEntity(entity, EnumParticleTypes.CRIT); } else if (packetIn.getAnimationType() == 5) { this.gameController.effectRenderer.emitParticleAtEntity(entity, EnumParticleTypes.CRIT_MAGIC); } } } /** * Retrieves the player identified by the packet, puts him to sleep if possible (and flags whether all players are * asleep) */ public void handleUseBed(SPacketUseBed packetIn) { PacketThreadUtil.checkThreadAndEnqueue(packetIn, this, this.gameController); packetIn.getPlayer(this.clientWorldController).trySleep(packetIn.getBedPosition()); } /** * Spawns the mob entity at the specified location, with the specified rotation, momentum and type. Updates the * entities Datawatchers with the entity metadata specified in the packet */ public void handleSpawnMob(SPacketSpawnMob packetIn) { PacketThreadUtil.checkThreadAndEnqueue(packetIn, this, this.gameController); double d0 = packetIn.getX(); double d1 = packetIn.getY(); double d2 = packetIn.getZ(); float f = (float)(packetIn.getYaw() * 360) / 256.0F; float f1 = (float)(packetIn.getPitch() * 360) / 256.0F; EntityLivingBase entitylivingbase = (EntityLivingBase)EntityList.createEntityByID(packetIn.getEntityType(), this.gameController.theWorld); EntityTracker.updateServerPosition(entitylivingbase, d0, d1, d2); entitylivingbase.renderYawOffset = (float)(packetIn.getHeadPitch() * 360) / 256.0F; entitylivingbase.rotationYawHead = (float)(packetIn.getHeadPitch() * 360) / 256.0F; Entity[] aentity = entitylivingbase.getParts(); if (aentity != null) { int i = packetIn.getEntityID() - entitylivingbase.getEntityId(); for (Entity entity : aentity) { entity.setEntityId(entity.getEntityId() + i); } } entitylivingbase.setEntityId(packetIn.getEntityID()); entitylivingbase.setUniqueId(packetIn.getUniqueId()); entitylivingbase.setPositionAndRotation(d0, d1, d2, f, f1); entitylivingbase.motionX = (double)((float)packetIn.getVelocityX() / 8000.0F); entitylivingbase.motionY = (double)((float)packetIn.getVelocityY() / 8000.0F); entitylivingbase.motionZ = (double)((float)packetIn.getVelocityZ() / 8000.0F); this.clientWorldController.addEntityToWorld(packetIn.getEntityID(), entitylivingbase); List < EntityDataManager.DataEntry<? >> list = packetIn.getDataManagerEntries(); if (list != null) { entitylivingbase.getDataManager().setEntryValues(list); } } public void handleTimeUpdate(SPacketTimeUpdate packetIn) { PacketThreadUtil.checkThreadAndEnqueue(packetIn, this, this.gameController); this.gameController.theWorld.setTotalWorldTime(packetIn.getTotalWorldTime()); this.gameController.theWorld.setWorldTime(packetIn.getWorldTime()); } public void handleSpawnPosition(SPacketSpawnPosition packetIn) { PacketThreadUtil.checkThreadAndEnqueue(packetIn, this, this.gameController); this.gameController.thePlayer.setSpawnPoint(packetIn.getSpawnPos(), true); this.gameController.theWorld.getWorldInfo().setSpawn(packetIn.getSpawnPos()); } public void handleSetPassengers(SPacketSetPassengers packetIn) { PacketThreadUtil.checkThreadAndEnqueue(packetIn, this, this.gameController); Entity entity = this.clientWorldController.getEntityByID(packetIn.getEntityId()); if (entity == null) { LOGGER.warn("Received passengers for unknown entity"); } else { boolean flag = entity.isRidingOrBeingRiddenBy(this.gameController.thePlayer); entity.removePassengers(); for (int i : packetIn.getPassengerIds()) { Entity entity1 = this.clientWorldController.getEntityByID(i); if (entity1 == null) { LOGGER.warn("Received unknown passenger for {}", new Object[] {entity}); } else { entity1.startRiding(entity, true); if (entity1 == this.gameController.thePlayer && !flag) { this.gameController.ingameGUI.setRecordPlaying(I18n.format("mount.onboard", new Object[] {GameSettings.getKeyDisplayString(this.gameController.gameSettings.keyBindSneak.getKeyCode())}), false); } } } } } public void handleEntityAttach(SPacketEntityAttach packetIn) { PacketThreadUtil.checkThreadAndEnqueue(packetIn, this, this.gameController); Entity entity = this.clientWorldController.getEntityByID(packetIn.getEntityId()); Entity entity1 = this.clientWorldController.getEntityByID(packetIn.getVehicleEntityId()); if (entity instanceof EntityLiving) { if (entity1 != null) { ((EntityLiving)entity).setLeashedToEntity(entity1, false); } else { ((EntityLiving)entity).clearLeashed(false, false); } } } /** * Invokes the entities' handleUpdateHealth method which is implemented in LivingBase (hurt/death), * MinecartMobSpawner (spawn delay), FireworkRocket & MinecartTNT (explosion), IronGolem (throwing,...), Witch * (spawn particles), Zombie (villager transformation), Animal (breeding mode particles), Horse (breeding/smoke * particles), Sheep (...), Tameable (...), Villager (particles for breeding mode, angry and happy), Wolf (...) */ public void handleEntityStatus(SPacketEntityStatus packetIn) { PacketThreadUtil.checkThreadAndEnqueue(packetIn, this, this.gameController); Entity entity = packetIn.getEntity(this.clientWorldController); if (entity != null) { if (packetIn.getOpCode() == 21) { this.gameController.getSoundHandler().playSound(new GuardianSound((EntityGuardian)entity)); } else { entity.handleStatusUpdate(packetIn.getOpCode()); } } } public void handleUpdateHealth(SPacketUpdateHealth packetIn) { PacketThreadUtil.checkThreadAndEnqueue(packetIn, this, this.gameController); this.gameController.thePlayer.setPlayerSPHealth(packetIn.getHealth()); this.gameController.thePlayer.getFoodStats().setFoodLevel(packetIn.getFoodLevel()); this.gameController.thePlayer.getFoodStats().setFoodSaturationLevel(packetIn.getSaturationLevel()); } public void handleSetExperience(SPacketSetExperience packetIn) { PacketThreadUtil.checkThreadAndEnqueue(packetIn, this, this.gameController); this.gameController.thePlayer.setXPStats(packetIn.getExperienceBar(), packetIn.getTotalExperience(), packetIn.getLevel()); } public void handleRespawn(SPacketRespawn packetIn) { PacketThreadUtil.checkThreadAndEnqueue(packetIn, this, this.gameController); if (packetIn.getDimensionID() != this.gameController.thePlayer.dimension) { this.doneLoadingTerrain = false; Scoreboard scoreboard = this.clientWorldController.getScoreboard(); this.clientWorldController = new WorldClient(this, new WorldSettings(0L, packetIn.getGameType(), false, this.gameController.theWorld.getWorldInfo().isHardcoreModeEnabled(), packetIn.getWorldType()), packetIn.getDimensionID(), packetIn.getDifficulty(), this.gameController.mcProfiler); this.clientWorldController.setWorldScoreboard(scoreboard); this.gameController.loadWorld(this.clientWorldController); this.gameController.thePlayer.dimension = packetIn.getDimensionID(); this.gameController.displayGuiScreen(new GuiDownloadTerrain(this)); } this.gameController.setDimensionAndSpawnPlayer(packetIn.getDimensionID()); this.gameController.playerController.setGameType(packetIn.getGameType()); } /** * Initiates a new explosion (sound, particles, drop spawn) for the affected blocks indicated by the packet. */ public void handleExplosion(SPacketExplosion packetIn) { PacketThreadUtil.checkThreadAndEnqueue(packetIn, this, this.gameController); Explosion explosion = new Explosion(this.gameController.theWorld, (Entity)null, packetIn.getX(), packetIn.getY(), packetIn.getZ(), packetIn.getStrength(), packetIn.getAffectedBlockPositions()); explosion.doExplosionB(true); this.gameController.thePlayer.motionX += (double)packetIn.getMotionX(); this.gameController.thePlayer.motionY += (double)packetIn.getMotionY(); this.gameController.thePlayer.motionZ += (double)packetIn.getMotionZ(); } /** * Displays a GUI by ID. In order starting from id 0: Chest, Workbench, Furnace, Dispenser, Enchanting table, * Brewing stand, Villager merchant, Beacon, Anvil, Hopper, Dropper, Horse */ public void handleOpenWindow(SPacketOpenWindow packetIn) { PacketThreadUtil.checkThreadAndEnqueue(packetIn, this, this.gameController); EntityPlayerSP entityplayersp = this.gameController.thePlayer; if ("minecraft:container".equals(packetIn.getGuiId())) { entityplayersp.displayGUIChest(new InventoryBasic(packetIn.getWindowTitle(), packetIn.getSlotCount())); entityplayersp.openContainer.windowId = packetIn.getWindowId(); } else if ("minecraft:villager".equals(packetIn.getGuiId())) { entityplayersp.displayVillagerTradeGui(new NpcMerchant(entityplayersp, packetIn.getWindowTitle())); entityplayersp.openContainer.windowId = packetIn.getWindowId(); } else if ("EntityHorse".equals(packetIn.getGuiId())) { Entity entity = this.clientWorldController.getEntityByID(packetIn.getEntityId()); if (entity instanceof EntityHorse) { entityplayersp.openGuiHorseInventory((EntityHorse)entity, new AnimalChest(packetIn.getWindowTitle(), packetIn.getSlotCount())); entityplayersp.openContainer.windowId = packetIn.getWindowId(); } } else if (!packetIn.hasSlots()) { entityplayersp.displayGui(new LocalBlockIntercommunication(packetIn.getGuiId(), packetIn.getWindowTitle())); entityplayersp.openContainer.windowId = packetIn.getWindowId(); } else { IInventory iinventory = new ContainerLocalMenu(packetIn.getGuiId(), packetIn.getWindowTitle(), packetIn.getSlotCount()); entityplayersp.displayGUIChest(iinventory); entityplayersp.openContainer.windowId = packetIn.getWindowId(); } } /** * Handles pickin up an ItemStack or dropping one in your inventory or an open (non-creative) container */ public void handleSetSlot(SPacketSetSlot packetIn) { PacketThreadUtil.checkThreadAndEnqueue(packetIn, this, this.gameController); EntityPlayer entityplayer = this.gameController.thePlayer; if (packetIn.getWindowId() == -1) { entityplayer.inventory.setItemStack(packetIn.getStack()); } else if (packetIn.getWindowId() == -2) { entityplayer.inventory.setInventorySlotContents(packetIn.getSlot(), packetIn.getStack()); } else { boolean flag = false; if (this.gameController.currentScreen instanceof GuiContainerCreative) { GuiContainerCreative guicontainercreative = (GuiContainerCreative)this.gameController.currentScreen; flag = guicontainercreative.getSelectedTabIndex() != CreativeTabs.INVENTORY.getTabIndex(); } if (packetIn.getWindowId() == 0 && packetIn.getSlot() >= 36 && packetIn.getSlot() < 45) { ItemStack itemstack = entityplayer.inventoryContainer.getSlot(packetIn.getSlot()).getStack(); if (packetIn.getStack() != null && (itemstack == null || itemstack.stackSize < packetIn.getStack().stackSize)) { packetIn.getStack().animationsToGo = 5; } entityplayer.inventoryContainer.putStackInSlot(packetIn.getSlot(), packetIn.getStack()); } else if (packetIn.getWindowId() == entityplayer.openContainer.windowId && (packetIn.getWindowId() != 0 || !flag)) { entityplayer.openContainer.putStackInSlot(packetIn.getSlot(), packetIn.getStack()); } } } /** * Verifies that the server and client are synchronized with respect to the inventory/container opened by the player * and confirms if it is the case. */ public void handleConfirmTransaction(SPacketConfirmTransaction packetIn) { PacketThreadUtil.checkThreadAndEnqueue(packetIn, this, this.gameController); Container container = null; EntityPlayer entityplayer = this.gameController.thePlayer; if (packetIn.getWindowId() == 0) { container = entityplayer.inventoryContainer; } else if (packetIn.getWindowId() == entityplayer.openContainer.windowId) { container = entityplayer.openContainer; } if (container != null && !packetIn.wasAccepted()) { this.sendPacket(new CPacketConfirmTransaction(packetIn.getWindowId(), packetIn.getActionNumber(), true)); } } /** * Handles the placement of a specified ItemStack in a specified container/inventory slot */ public void handleWindowItems(SPacketWindowItems packetIn) { PacketThreadUtil.checkThreadAndEnqueue(packetIn, this, this.gameController); EntityPlayer entityplayer = this.gameController.thePlayer; if (packetIn.getWindowId() == 0) { entityplayer.inventoryContainer.putStacksInSlots(packetIn.getItemStacks()); } else if (packetIn.getWindowId() == entityplayer.openContainer.windowId) { entityplayer.openContainer.putStacksInSlots(packetIn.getItemStacks()); } } /** * Creates a sign in the specified location if it didn't exist and opens the GUI to edit its text */ public void handleSignEditorOpen(SPacketSignEditorOpen packetIn) { PacketThreadUtil.checkThreadAndEnqueue(packetIn, this, this.gameController); TileEntity tileentity = this.clientWorldController.getTileEntity(packetIn.getSignPosition()); if (!(tileentity instanceof TileEntitySign)) { tileentity = new TileEntitySign(); tileentity.setWorldObj(this.clientWorldController); tileentity.setPos(packetIn.getSignPosition()); } this.gameController.thePlayer.openEditSign((TileEntitySign)tileentity); } /** * Updates the NBTTagCompound metadata of instances of the following entitytypes: Mob spawners, command blocks, * beacons, skulls, flowerpot */ public void handleUpdateTileEntity(SPacketUpdateTileEntity packetIn) { PacketThreadUtil.checkThreadAndEnqueue(packetIn, this, this.gameController); if (this.gameController.theWorld.isBlockLoaded(packetIn.getPos())) { TileEntity tileentity = this.gameController.theWorld.getTileEntity(packetIn.getPos()); int i = packetIn.getTileEntityType(); boolean flag = i == 2 && tileentity instanceof TileEntityCommandBlock; if (i == 1 && tileentity instanceof TileEntityMobSpawner || flag || i == 3 && tileentity instanceof TileEntityBeacon || i == 4 && tileentity instanceof TileEntitySkull || i == 5 && tileentity instanceof TileEntityFlowerPot || i == 6 && tileentity instanceof TileEntityBanner || i == 7 && tileentity instanceof TileEntityStructure || i == 8 && tileentity instanceof TileEntityEndGateway || i == 9 && tileentity instanceof TileEntitySign) { tileentity.readFromNBT(packetIn.getNbtCompound()); } if (flag && this.gameController.currentScreen instanceof GuiCommandBlock) { ((GuiCommandBlock)this.gameController.currentScreen).updateGui(); } } } /** * Sets the progressbar of the opened window to the specified value */ public void handleWindowProperty(SPacketWindowProperty packetIn) { PacketThreadUtil.checkThreadAndEnqueue(packetIn, this, this.gameController); EntityPlayer entityplayer = this.gameController.thePlayer; if (entityplayer.openContainer != null && entityplayer.openContainer.windowId == packetIn.getWindowId()) { entityplayer.openContainer.updateProgressBar(packetIn.getProperty(), packetIn.getValue()); } } public void handleEntityEquipment(SPacketEntityEquipment packetIn) { PacketThreadUtil.checkThreadAndEnqueue(packetIn, this, this.gameController); Entity entity = this.clientWorldController.getEntityByID(packetIn.getEntityID()); if (entity != null) { entity.setItemStackToSlot(packetIn.getEquipmentSlot(), packetIn.getItemStack()); } } /** * Resets the ItemStack held in hand and closes the window that is opened */ public void handleCloseWindow(SPacketCloseWindow packetIn) { PacketThreadUtil.checkThreadAndEnqueue(packetIn, this, this.gameController); this.gameController.thePlayer.closeScreenAndDropStack(); } /** * Triggers Block.onBlockEventReceived, which is implemented in BlockPistonBase for extension/retraction, BlockNote * for setting the instrument (including audiovisual feedback) and in BlockContainer to set the number of players * accessing a (Ender)Chest */ public void handleBlockAction(SPacketBlockAction packetIn) { PacketThreadUtil.checkThreadAndEnqueue(packetIn, this, this.gameController); this.gameController.theWorld.addBlockEvent(packetIn.getBlockPosition(), packetIn.getBlockType(), packetIn.getData1(), packetIn.getData2()); } /** * Updates all registered IWorldAccess instances with destroyBlockInWorldPartially */ public void handleBlockBreakAnim(SPacketBlockBreakAnim packetIn) { PacketThreadUtil.checkThreadAndEnqueue(packetIn, this, this.gameController); this.gameController.theWorld.sendBlockBreakProgress(packetIn.getBreakerId(), packetIn.getPosition(), packetIn.getProgress()); } public void handleChangeGameState(SPacketChangeGameState packetIn) { PacketThreadUtil.checkThreadAndEnqueue(packetIn, this, this.gameController); EntityPlayer entityplayer = this.gameController.thePlayer; int i = packetIn.getGameState(); float f = packetIn.getValue(); int j = MathHelper.floor_float(f + 0.5F); if (i >= 0 && i < SPacketChangeGameState.MESSAGE_NAMES.length && SPacketChangeGameState.MESSAGE_NAMES[i] != null) { entityplayer.addChatComponentMessage(new TextComponentTranslation(SPacketChangeGameState.MESSAGE_NAMES[i], new Object[0])); } if (i == 1) { this.clientWorldController.getWorldInfo().setRaining(true); this.clientWorldController.setRainStrength(0.0F); } else if (i == 2) { this.clientWorldController.getWorldInfo().setRaining(false); this.clientWorldController.setRainStrength(1.0F); } else if (i == 3) { this.gameController.playerController.setGameType(GameType.getByID(j)); } else if (i == 4) { if (j == 0) { this.gameController.thePlayer.connection.sendPacket(new CPacketClientStatus(CPacketClientStatus.State.PERFORM_RESPAWN)); this.gameController.displayGuiScreen(new GuiDownloadTerrain(this)); } else if (j == 1) { this.gameController.displayGuiScreen(new GuiWinGame()); } } else if (i == 5) { GameSettings gamesettings = this.gameController.gameSettings; if (f == 0.0F) { this.gameController.displayGuiScreen(new GuiScreenDemo()); } else if (f == 101.0F) { this.gameController.ingameGUI.getChatGUI().printChatMessage(new TextComponentTranslation("demo.help.movement", new Object[] {GameSettings.getKeyDisplayString(gamesettings.keyBindForward.getKeyCode()), GameSettings.getKeyDisplayString(gamesettings.keyBindLeft.getKeyCode()), GameSettings.getKeyDisplayString(gamesettings.keyBindBack.getKeyCode()), GameSettings.getKeyDisplayString(gamesettings.keyBindRight.getKeyCode())})); } else if (f == 102.0F) { this.gameController.ingameGUI.getChatGUI().printChatMessage(new TextComponentTranslation("demo.help.jump", new Object[] {GameSettings.getKeyDisplayString(gamesettings.keyBindJump.getKeyCode())})); } else if (f == 103.0F) { this.gameController.ingameGUI.getChatGUI().printChatMessage(new TextComponentTranslation("demo.help.inventory", new Object[] {GameSettings.getKeyDisplayString(gamesettings.keyBindInventory.getKeyCode())})); } } else if (i == 6) { this.clientWorldController.playSound(entityplayer, entityplayer.posX, entityplayer.posY + (double)entityplayer.getEyeHeight(), entityplayer.posZ, SoundEvents.ENTITY_ARROW_HIT_PLAYER, SoundCategory.PLAYERS, 0.18F, 0.45F); } else if (i == 7) { this.clientWorldController.setRainStrength(f); } else if (i == 8) { this.clientWorldController.setThunderStrength(f); } else if (i == 10) { this.clientWorldController.spawnParticle(EnumParticleTypes.MOB_APPEARANCE, entityplayer.posX, entityplayer.posY, entityplayer.posZ, 0.0D, 0.0D, 0.0D, new int[0]); this.clientWorldController.playSound(entityplayer, entityplayer.posX, entityplayer.posY, entityplayer.posZ, SoundEvents.ENTITY_ELDER_GUARDIAN_CURSE, SoundCategory.HOSTILE, 1.0F, 1.0F); } } /** * Updates the worlds MapStorage with the specified MapData for the specified map-identifier and invokes a * MapItemRenderer for it */ public void handleMaps(SPacketMaps packetIn) { PacketThreadUtil.checkThreadAndEnqueue(packetIn, this, this.gameController); MapData mapdata = ItemMap.loadMapData(packetIn.getMapId(), this.gameController.theWorld); packetIn.setMapdataTo(mapdata); this.gameController.entityRenderer.getMapItemRenderer().updateMapTexture(mapdata); } public void handleEffect(SPacketEffect packetIn) { PacketThreadUtil.checkThreadAndEnqueue(packetIn, this, this.gameController); if (packetIn.isSoundServerwide()) { this.gameController.theWorld.playBroadcastSound(packetIn.getSoundType(), packetIn.getSoundPos(), packetIn.getSoundData()); } else { this.gameController.theWorld.playEvent(packetIn.getSoundType(), packetIn.getSoundPos(), packetIn.getSoundData()); } } /** * Updates the players statistics or achievements */ public void handleStatistics(SPacketStatistics packetIn) { PacketThreadUtil.checkThreadAndEnqueue(packetIn, this, this.gameController); boolean flag = false; for (Entry<StatBase, Integer> entry : packetIn.getStatisticMap().entrySet()) { StatBase statbase = (StatBase)entry.getKey(); int i = ((Integer)entry.getValue()).intValue(); if (statbase.isAchievement() && i > 0) { if (this.hasStatistics && this.gameController.thePlayer.getStatFileWriter().readStat(statbase) == 0) { Achievement achievement = (Achievement)statbase; this.gameController.guiAchievement.displayAchievement(achievement); if (statbase == AchievementList.OPEN_INVENTORY) { this.gameController.gameSettings.showInventoryAchievementHint = false; this.gameController.gameSettings.saveOptions(); } } flag = true; } this.gameController.thePlayer.getStatFileWriter().unlockAchievement(this.gameController.thePlayer, statbase, i); } if (!this.hasStatistics && !flag && this.gameController.gameSettings.showInventoryAchievementHint) { this.gameController.guiAchievement.displayUnformattedAchievement(AchievementList.OPEN_INVENTORY); } this.hasStatistics = true; if (this.gameController.currentScreen instanceof IProgressMeter) { ((IProgressMeter)this.gameController.currentScreen).doneLoading(); } } public void handleEntityEffect(SPacketEntityEffect packetIn) { PacketThreadUtil.checkThreadAndEnqueue(packetIn, this, this.gameController); Entity entity = this.clientWorldController.getEntityByID(packetIn.getEntityId()); if (entity instanceof EntityLivingBase) { Potion potion = Potion.getPotionById(packetIn.getEffectId()); if (potion != null) { PotionEffect potioneffect = new PotionEffect(potion, packetIn.getDuration(), packetIn.getAmplifier(), packetIn.getIsAmbient(), packetIn.doesShowParticles()); potioneffect.setPotionDurationMax(packetIn.isMaxDuration()); ((EntityLivingBase)entity).addPotionEffect(potioneffect); } } } public void handleCombatEvent(SPacketCombatEvent packetIn) { PacketThreadUtil.checkThreadAndEnqueue(packetIn, this, this.gameController); if (packetIn.eventType == SPacketCombatEvent.Event.ENTITY_DIED) { Entity entity = this.clientWorldController.getEntityByID(packetIn.playerId); if (entity == this.gameController.thePlayer) { this.gameController.displayGuiScreen(new GuiGameOver(packetIn.deathMessage)); } } } public void handleServerDifficulty(SPacketServerDifficulty packetIn) { PacketThreadUtil.checkThreadAndEnqueue(packetIn, this, this.gameController); this.gameController.theWorld.getWorldInfo().setDifficulty(packetIn.getDifficulty()); this.gameController.theWorld.getWorldInfo().setDifficultyLocked(packetIn.isDifficultyLocked()); } public void handleCamera(SPacketCamera packetIn) { PacketThreadUtil.checkThreadAndEnqueue(packetIn, this, this.gameController); Entity entity = packetIn.getEntity(this.clientWorldController); if (entity != null) { this.gameController.setRenderViewEntity(entity); } } public void handleWorldBorder(SPacketWorldBorder packetIn) { PacketThreadUtil.checkThreadAndEnqueue(packetIn, this, this.gameController); packetIn.apply(this.clientWorldController.getWorldBorder()); } @SuppressWarnings("incomplete-switch") public void handleTitle(SPacketTitle packetIn) { PacketThreadUtil.checkThreadAndEnqueue(packetIn, this, this.gameController); SPacketTitle.Type spackettitle$type = packetIn.getType(); String s = null; String s1 = null; String s2 = packetIn.getMessage() != null ? packetIn.getMessage().getFormattedText() : ""; switch (spackettitle$type) { case TITLE: s = s2; break; case SUBTITLE: s1 = s2; break; case RESET: this.gameController.ingameGUI.displayTitle("", "", -1, -1, -1); this.gameController.ingameGUI.setDefaultTitlesTimes(); return; } this.gameController.ingameGUI.displayTitle(s, s1, packetIn.getFadeInTime(), packetIn.getDisplayTime(), packetIn.getFadeOutTime()); } public void handlePlayerListHeaderFooter(SPacketPlayerListHeaderFooter packetIn) { this.gameController.ingameGUI.getTabList().setHeader(packetIn.getHeader().getFormattedText().isEmpty() ? null : packetIn.getHeader()); this.gameController.ingameGUI.getTabList().setFooter(packetIn.getFooter().getFormattedText().isEmpty() ? null : packetIn.getFooter()); } public void handleRemoveEntityEffect(SPacketRemoveEntityEffect packetIn) { PacketThreadUtil.checkThreadAndEnqueue(packetIn, this, this.gameController); Entity entity = packetIn.getEntity(this.clientWorldController); if (entity instanceof EntityLivingBase) { ((EntityLivingBase)entity).removeActivePotionEffect(packetIn.getPotion()); } } @SuppressWarnings("incomplete-switch") public void handlePlayerListItem(SPacketPlayerListItem packetIn) { PacketThreadUtil.checkThreadAndEnqueue(packetIn, this, this.gameController); for (SPacketPlayerListItem.AddPlayerData spacketplayerlistitem$addplayerdata : packetIn.getEntries()) { if (packetIn.getAction() == SPacketPlayerListItem.Action.REMOVE_PLAYER) { this.playerInfoMap.remove(spacketplayerlistitem$addplayerdata.getProfile().getId()); } else { NetworkPlayerInfo networkplayerinfo = (NetworkPlayerInfo)this.playerInfoMap.get(spacketplayerlistitem$addplayerdata.getProfile().getId()); if (packetIn.getAction() == SPacketPlayerListItem.Action.ADD_PLAYER) { networkplayerinfo = new NetworkPlayerInfo(spacketplayerlistitem$addplayerdata); this.playerInfoMap.put(networkplayerinfo.getGameProfile().getId(), networkplayerinfo); } if (networkplayerinfo != null) { switch (packetIn.getAction()) { case ADD_PLAYER: networkplayerinfo.setGameType(spacketplayerlistitem$addplayerdata.getGameMode()); networkplayerinfo.setResponseTime(spacketplayerlistitem$addplayerdata.getPing()); break; case UPDATE_GAME_MODE: networkplayerinfo.setGameType(spacketplayerlistitem$addplayerdata.getGameMode()); break; case UPDATE_LATENCY: networkplayerinfo.setResponseTime(spacketplayerlistitem$addplayerdata.getPing()); break; case UPDATE_DISPLAY_NAME: networkplayerinfo.setDisplayName(spacketplayerlistitem$addplayerdata.getDisplayName()); } } } } } public void handleKeepAlive(SPacketKeepAlive packetIn) { this.sendPacket(new CPacketKeepAlive(packetIn.getId())); } public void handlePlayerAbilities(SPacketPlayerAbilities packetIn) { PacketThreadUtil.checkThreadAndEnqueue(packetIn, this, this.gameController); EntityPlayer entityplayer = this.gameController.thePlayer; entityplayer.capabilities.isFlying = packetIn.isFlying(); entityplayer.capabilities.isCreativeMode = packetIn.isCreativeMode(); entityplayer.capabilities.disableDamage = packetIn.isInvulnerable(); entityplayer.capabilities.allowFlying = packetIn.isAllowFlying(); entityplayer.capabilities.setFlySpeed(packetIn.getFlySpeed()); entityplayer.capabilities.setPlayerWalkSpeed(packetIn.getWalkSpeed()); } /** * Displays the available command-completion options the server knows of */ public void handleTabComplete(SPacketTabComplete packetIn) { PacketThreadUtil.checkThreadAndEnqueue(packetIn, this, this.gameController); String[] astring = packetIn.getMatches(); if (this.gameController.currentScreen instanceof ITabCompleter) { ((ITabCompleter)this.gameController.currentScreen).setCompletions(astring); } } public void handleSoundEffect(SPacketSoundEffect packetIn) { PacketThreadUtil.checkThreadAndEnqueue(packetIn, this, this.gameController); this.gameController.theWorld.playSound(this.gameController.thePlayer, packetIn.getX(), packetIn.getY(), packetIn.getZ(), packetIn.getSound(), packetIn.getCategory(), packetIn.getVolume(), packetIn.getPitch()); } public void handleCustomSound(SPacketCustomSound packetIn) { PacketThreadUtil.checkThreadAndEnqueue(packetIn, this, this.gameController); this.gameController.getSoundHandler().playSound(new PositionedSoundRecord(new ResourceLocation(packetIn.getSoundName()), packetIn.getCategory(), packetIn.getVolume(), packetIn.getPitch(), false, 0, ISound.AttenuationType.LINEAR, (float)packetIn.getX(), (float)packetIn.getY(), (float)packetIn.getZ())); } public void handleResourcePack(SPacketResourcePackSend packetIn) { final String s = packetIn.getURL(); final String s1 = packetIn.getHash(); if (this.func_189688_b(s)) { if (s.startsWith("level://")) { String s2 = s.substring("level://".length()); File file1 = new File(this.gameController.mcDataDir, "saves"); File file2 = new File(file1, s2); if (file2.isFile()) { this.netManager.sendPacket(new CPacketResourcePackStatus(CPacketResourcePackStatus.Action.ACCEPTED)); Futures.addCallback(this.gameController.getResourcePackRepository().setResourcePackInstance(file2), this.func_189686_f()); } else { this.netManager.sendPacket(new CPacketResourcePackStatus(CPacketResourcePackStatus.Action.FAILED_DOWNLOAD)); } } else { ServerData serverdata = this.gameController.getCurrentServerData(); if (serverdata != null && serverdata.getResourceMode() == ServerData.ServerResourceMode.ENABLED) { this.netManager.sendPacket(new CPacketResourcePackStatus(CPacketResourcePackStatus.Action.ACCEPTED)); Futures.addCallback(this.gameController.getResourcePackRepository().downloadResourcePack(s, s1), this.func_189686_f()); } else if (serverdata != null && serverdata.getResourceMode() != ServerData.ServerResourceMode.PROMPT) { this.netManager.sendPacket(new CPacketResourcePackStatus(CPacketResourcePackStatus.Action.DECLINED)); } else { this.gameController.addScheduledTask(new Runnable() { public void run() { NetHandlerPlayClient.this.gameController.displayGuiScreen(new GuiYesNo(new GuiYesNoCallback() { public void confirmClicked(boolean result, int id) { NetHandlerPlayClient.this.gameController = Minecraft.getMinecraft(); ServerData serverdata1 = NetHandlerPlayClient.this.gameController.getCurrentServerData(); if (result) { if (serverdata1 != null) { serverdata1.setResourceMode(ServerData.ServerResourceMode.ENABLED); } NetHandlerPlayClient.this.netManager.sendPacket(new CPacketResourcePackStatus(CPacketResourcePackStatus.Action.ACCEPTED)); Futures.addCallback(NetHandlerPlayClient.this.gameController.getResourcePackRepository().downloadResourcePack(s, s1), NetHandlerPlayClient.this.func_189686_f()); } else { if (serverdata1 != null) { serverdata1.setResourceMode(ServerData.ServerResourceMode.DISABLED); } NetHandlerPlayClient.this.netManager.sendPacket(new CPacketResourcePackStatus(CPacketResourcePackStatus.Action.DECLINED)); } ServerList.saveSingleServer(serverdata1); NetHandlerPlayClient.this.gameController.displayGuiScreen((GuiScreen)null); } }, I18n.format("multiplayer.texturePrompt.line1", new Object[0]), I18n.format("multiplayer.texturePrompt.line2", new Object[0]), 0)); } }); } } } } private boolean func_189688_b(String p_189688_1_) { try { URI uri = new URI(p_189688_1_.replace(' ', '+')); String s = uri.getScheme(); boolean flag = "level".equals(s); if (!"http".equals(s) && !"https".equals(s) && !flag) { throw new URISyntaxException(p_189688_1_, "Wrong protocol"); } else if (!flag || !p_189688_1_.contains("..") && p_189688_1_.endsWith("/resources.zip")) { return true; } else { throw new URISyntaxException(p_189688_1_, "Invalid levelstorage resourcepack path"); } } catch (URISyntaxException var5) { this.netManager.sendPacket(new CPacketResourcePackStatus(CPacketResourcePackStatus.Action.FAILED_DOWNLOAD)); return false; } } private FutureCallback<Object> func_189686_f() { return new FutureCallback<Object>() { public void onSuccess(@Nullable Object p_onSuccess_1_) { NetHandlerPlayClient.this.netManager.sendPacket(new CPacketResourcePackStatus(CPacketResourcePackStatus.Action.SUCCESSFULLY_LOADED)); } public void onFailure(Throwable p_onFailure_1_) { NetHandlerPlayClient.this.netManager.sendPacket(new CPacketResourcePackStatus(CPacketResourcePackStatus.Action.FAILED_DOWNLOAD)); } }; } public void handleUpdateEntityNBT(SPacketUpdateBossInfo packetIn) { PacketThreadUtil.checkThreadAndEnqueue(packetIn, this, this.gameController); this.gameController.ingameGUI.getBossOverlay().read(packetIn); } public void handleCooldown(SPacketCooldown packetIn) { PacketThreadUtil.checkThreadAndEnqueue(packetIn, this, this.gameController); if (packetIn.getTicks() == 0) { this.gameController.thePlayer.getCooldownTracker().removeCooldown(packetIn.getItem()); } else { this.gameController.thePlayer.getCooldownTracker().setCooldown(packetIn.getItem(), packetIn.getTicks()); } } public void handleMoveVehicle(SPacketMoveVehicle packetIn) { PacketThreadUtil.checkThreadAndEnqueue(packetIn, this, this.gameController); Entity entity = this.gameController.thePlayer.getLowestRidingEntity(); if (entity != this.gameController.thePlayer && entity.canPassengerSteer()) { entity.setPositionAndRotation(packetIn.getX(), packetIn.getY(), packetIn.getZ(), packetIn.getYaw(), packetIn.getPitch()); this.netManager.sendPacket(new CPacketVehicleMove(entity)); } } /** * Handles packets that have room for a channel specification. Vanilla implemented channels are "MC|TrList" to * acquire a MerchantRecipeList trades for a villager merchant, "MC|Brand" which sets the server brand? on the * player instance and finally "MC|RPack" which the server uses to communicate the identifier of the default server * resourcepack for the client to load. */ public void handleCustomPayload(SPacketCustomPayload packetIn) { PacketThreadUtil.checkThreadAndEnqueue(packetIn, this, this.gameController); if ("MC|TrList".equals(packetIn.getChannelName())) { PacketBuffer packetbuffer = packetIn.getBufferData(); try { int i = packetbuffer.readInt(); GuiScreen guiscreen = this.gameController.currentScreen; if (guiscreen != null && guiscreen instanceof GuiMerchant && i == this.gameController.thePlayer.openContainer.windowId) { IMerchant imerchant = ((GuiMerchant)guiscreen).getMerchant(); MerchantRecipeList merchantrecipelist = MerchantRecipeList.readFromBuf(packetbuffer); imerchant.setRecipes(merchantrecipelist); } } catch (IOException ioexception) { LOGGER.error((String)"Couldn\'t load trade info", (Throwable)ioexception); } finally { packetbuffer.release(); } } else if ("MC|Brand".equals(packetIn.getChannelName())) { this.gameController.thePlayer.setServerBrand(packetIn.getBufferData().readStringFromBuffer(32767)); } else if ("MC|BOpen".equals(packetIn.getChannelName())) { EnumHand enumhand = (EnumHand)packetIn.getBufferData().readEnumValue(EnumHand.class); ItemStack itemstack = enumhand == EnumHand.OFF_HAND ? this.gameController.thePlayer.getHeldItemOffhand() : this.gameController.thePlayer.getHeldItemMainhand(); if (itemstack != null && itemstack.getItem() == Items.WRITTEN_BOOK) { this.gameController.displayGuiScreen(new GuiScreenBook(this.gameController.thePlayer, itemstack, false)); } } else if ("MC|DebugPath".equals(packetIn.getChannelName())) { PacketBuffer packetbuffer1 = packetIn.getBufferData(); int j = packetbuffer1.readInt(); float f = packetbuffer1.readFloat(); Path path = Path.read(packetbuffer1); ((DebugRendererPathfinding)this.gameController.debugRenderer.debugRendererPathfinding).addPath(j, path, f); } else if ("MC|StopSound".equals(packetIn.getChannelName())) { PacketBuffer packetbuffer2 = packetIn.getBufferData(); String s = packetbuffer2.readStringFromBuffer(32767); String s1 = packetbuffer2.readStringFromBuffer(256); this.gameController.getSoundHandler().func_189520_a(s1, SoundCategory.getByName(s)); } // Begin Awaken Dreams code else if ("AD|Rucksack".equals(packetIn.getChannelName())) { EntityPlayerSP entityplayersp = this.gameController.thePlayer; PacketBuffer packetbuffer = packetIn.getBufferData(); try { ItemStack rucksack = packetbuffer.readItemStackFromBuffer(); EnumHand hand = (EnumHand)packetbuffer.readEnumValue(EnumHand.class); entityplayersp.openRucksack(rucksack, hand); } catch (IOException e) { e.printStackTrace(); } int windowId = packetbuffer.readInt(); entityplayersp.openContainer.windowId = windowId; } // End Awaken Dreams code } /** * May create a scoreboard objective, remove an objective from the scoreboard or update an objectives' displayname */ public void handleScoreboardObjective(SPacketScoreboardObjective packetIn) { PacketThreadUtil.checkThreadAndEnqueue(packetIn, this, this.gameController); Scoreboard scoreboard = this.clientWorldController.getScoreboard(); if (packetIn.getAction() == 0) { ScoreObjective scoreobjective = scoreboard.addScoreObjective(packetIn.getObjectiveName(), IScoreCriteria.DUMMY); scoreobjective.setDisplayName(packetIn.getObjectiveValue()); scoreobjective.setRenderType(packetIn.getRenderType()); } else { ScoreObjective scoreobjective1 = scoreboard.getObjective(packetIn.getObjectiveName()); if (packetIn.getAction() == 1) { scoreboard.removeObjective(scoreobjective1); } else if (packetIn.getAction() == 2) { scoreobjective1.setDisplayName(packetIn.getObjectiveValue()); scoreobjective1.setRenderType(packetIn.getRenderType()); } } } /** * Either updates the score with a specified value or removes the score for an objective */ public void handleUpdateScore(SPacketUpdateScore packetIn) { PacketThreadUtil.checkThreadAndEnqueue(packetIn, this, this.gameController); Scoreboard scoreboard = this.clientWorldController.getScoreboard(); ScoreObjective scoreobjective = scoreboard.getObjective(packetIn.getObjectiveName()); if (packetIn.getScoreAction() == SPacketUpdateScore.Action.CHANGE) { Score score = scoreboard.getOrCreateScore(packetIn.getPlayerName(), scoreobjective); score.setScorePoints(packetIn.getScoreValue()); } else if (packetIn.getScoreAction() == SPacketUpdateScore.Action.REMOVE) { if (StringUtils.isNullOrEmpty(packetIn.getObjectiveName())) { scoreboard.removeObjectiveFromEntity(packetIn.getPlayerName(), (ScoreObjective)null); } else if (scoreobjective != null) { scoreboard.removeObjectiveFromEntity(packetIn.getPlayerName(), scoreobjective); } } } /** * Removes or sets the ScoreObjective to be displayed at a particular scoreboard position (list, sidebar, below * name) */ public void handleDisplayObjective(SPacketDisplayObjective packetIn) { PacketThreadUtil.checkThreadAndEnqueue(packetIn, this, this.gameController); Scoreboard scoreboard = this.clientWorldController.getScoreboard(); if (packetIn.getName().isEmpty()) { scoreboard.setObjectiveInDisplaySlot(packetIn.getPosition(), (ScoreObjective)null); } else { ScoreObjective scoreobjective = scoreboard.getObjective(packetIn.getName()); scoreboard.setObjectiveInDisplaySlot(packetIn.getPosition(), scoreobjective); } } /** * Updates a team managed by the scoreboard: Create/Remove the team registration, Register/Remove the player-team- * memberships, Set team displayname/prefix/suffix and/or whether friendly fire is enabled */ public void handleTeams(SPacketTeams packetIn) { PacketThreadUtil.checkThreadAndEnqueue(packetIn, this, this.gameController); Scoreboard scoreboard = this.clientWorldController.getScoreboard(); ScorePlayerTeam scoreplayerteam; if (packetIn.getAction() == 0) { scoreplayerteam = scoreboard.createTeam(packetIn.getName()); } else { scoreplayerteam = scoreboard.getTeam(packetIn.getName()); } if (packetIn.getAction() == 0 || packetIn.getAction() == 2) { scoreplayerteam.setTeamName(packetIn.getDisplayName()); scoreplayerteam.setNamePrefix(packetIn.getPrefix()); scoreplayerteam.setNameSuffix(packetIn.getSuffix()); scoreplayerteam.setChatFormat(TextFormatting.fromColorIndex(packetIn.getColor())); scoreplayerteam.setFriendlyFlags(packetIn.getFriendlyFlags()); Team.EnumVisible team$enumvisible = Team.EnumVisible.getByName(packetIn.getNameTagVisibility()); if (team$enumvisible != null) { scoreplayerteam.setNameTagVisibility(team$enumvisible); } Team.CollisionRule team$collisionrule = Team.CollisionRule.getByName(packetIn.getCollisionRule()); if (team$collisionrule != null) { scoreplayerteam.setCollisionRule(team$collisionrule); } } if (packetIn.getAction() == 0 || packetIn.getAction() == 3) { for (String s : packetIn.getPlayers()) { scoreboard.addPlayerToTeam(s, packetIn.getName()); } } if (packetIn.getAction() == 4) { for (String s1 : packetIn.getPlayers()) { scoreboard.removePlayerFromTeam(s1, scoreplayerteam); } } if (packetIn.getAction() == 1) { scoreboard.removeTeam(scoreplayerteam); } } /** * Spawns a specified number of particles at the specified location with a randomized displacement according to * specified bounds */ public void handleParticles(SPacketParticles packetIn) { PacketThreadUtil.checkThreadAndEnqueue(packetIn, this, this.gameController); if (packetIn.getParticleCount() == 0) { double d0 = (double)(packetIn.getParticleSpeed() * packetIn.getXOffset()); double d2 = (double)(packetIn.getParticleSpeed() * packetIn.getYOffset()); double d4 = (double)(packetIn.getParticleSpeed() * packetIn.getZOffset()); try { this.clientWorldController.spawnParticle(packetIn.getParticleType(), packetIn.isLongDistance(), packetIn.getXCoordinate(), packetIn.getYCoordinate(), packetIn.getZCoordinate(), d0, d2, d4, packetIn.getParticleArgs()); } catch (Throwable var17) { LOGGER.warn("Could not spawn particle effect {}", new Object[] {packetIn.getParticleType()}); } } else { for (int i = 0; i < packetIn.getParticleCount(); ++i) { double d1 = this.avRandomizer.nextGaussian() * (double)packetIn.getXOffset(); double d3 = this.avRandomizer.nextGaussian() * (double)packetIn.getYOffset(); double d5 = this.avRandomizer.nextGaussian() * (double)packetIn.getZOffset(); double d6 = this.avRandomizer.nextGaussian() * (double)packetIn.getParticleSpeed(); double d7 = this.avRandomizer.nextGaussian() * (double)packetIn.getParticleSpeed(); double d8 = this.avRandomizer.nextGaussian() * (double)packetIn.getParticleSpeed(); try { this.clientWorldController.spawnParticle(packetIn.getParticleType(), packetIn.isLongDistance(), packetIn.getXCoordinate() + d1, packetIn.getYCoordinate() + d3, packetIn.getZCoordinate() + d5, d6, d7, d8, packetIn.getParticleArgs()); } catch (Throwable var16) { LOGGER.warn("Could not spawn particle effect {}", new Object[] {packetIn.getParticleType()}); return; } } } } /** * Updates en entity's attributes and their respective modifiers, which are used for speed bonusses (player * sprinting, animals fleeing, baby speed), weapon/tool attackDamage, hostiles followRange randomization, zombie * maxHealth and knockback resistance as well as reinforcement spawning chance. */ public void handleEntityProperties(SPacketEntityProperties packetIn) { PacketThreadUtil.checkThreadAndEnqueue(packetIn, this, this.gameController); Entity entity = this.clientWorldController.getEntityByID(packetIn.getEntityId()); if (entity != null) { if (!(entity instanceof EntityLivingBase)) { throw new IllegalStateException("Server tried to update attributes of a non-living entity (actually: " + entity + ")"); } else { AbstractAttributeMap abstractattributemap = ((EntityLivingBase)entity).getAttributeMap(); for (SPacketEntityProperties.Snapshot spacketentityproperties$snapshot : packetIn.getSnapshots()) { IAttributeInstance iattributeinstance = abstractattributemap.getAttributeInstanceByName(spacketentityproperties$snapshot.getName()); if (iattributeinstance == null) { iattributeinstance = abstractattributemap.registerAttribute(new RangedAttribute((IAttribute)null, spacketentityproperties$snapshot.getName(), 0.0D, 2.2250738585072014E-308D, Double.MAX_VALUE)); } iattributeinstance.setBaseValue(spacketentityproperties$snapshot.getBaseValue()); iattributeinstance.removeAllModifiers(); for (AttributeModifier attributemodifier : spacketentityproperties$snapshot.getModifiers()) { iattributeinstance.applyModifier(attributemodifier); } } } } } /** * Returns this the NetworkManager instance registered with this NetworkHandlerPlayClient */ public NetworkManager getNetworkManager() { return this.netManager; } public Collection<NetworkPlayerInfo> getPlayerInfoMap() { return this.playerInfoMap.values(); } public NetworkPlayerInfo getPlayerInfo(UUID uniqueId) { return (NetworkPlayerInfo)this.playerInfoMap.get(uniqueId); } @Nullable /** * Gets the client's description information about another player on the server. */ public NetworkPlayerInfo getPlayerInfo(String name) { for (NetworkPlayerInfo networkplayerinfo : this.playerInfoMap.values()) { if (networkplayerinfo.getGameProfile().getName().equals(name)) { return networkplayerinfo; } } return null; } public GameProfile getGameProfile() { return this.profile; } }
gpl-3.0
otsaloma/gaupol
aeidon/test/test_file.py
2448
# -*- coding: utf-8 -*- # Copyright (C) 2005 Osmo Salomaa # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import aeidon import codecs class PuppetSubtitleFile(aeidon.SubtitleFile): format = aeidon.formats.SUBVIEWER2 mode = aeidon.modes.TIME class TestSubtitleFile(aeidon.TestCase): def setup_method(self, method): path = self.new_temp_file(PuppetSubtitleFile.format) newline = aeidon.newlines.UNIX self.file = PuppetSubtitleFile(path, "ascii", newline) def test_read__utf_16(self): path = self.new_subrip_file() with open(path, "r") as f: text = f.read() with open(path, "w", encoding="utf_16") as f: f.write(text) file = aeidon.files.new(aeidon.formats.SUBRIP, path, "utf_16") file.read() def test_read__utf_16_be(self): path = self.new_subrip_file() with open(path, "r") as f: text = f.read() with open(path, "w", encoding="utf_16_be") as f: f.write(str(codecs.BOM_UTF16_BE, "utf_16_be")) f.write(text) file = aeidon.files.new(aeidon.formats.SUBRIP, path, "utf_16_be") file.read() def test_read__utf_16_le(self): path = self.new_subrip_file() with open(path, "r") as f: text = f.read() with open(path, "w", encoding="utf_16_le") as f: f.write(str(codecs.BOM_UTF16_LE, "utf_16_le")) f.write(text) file = aeidon.files.new(aeidon.formats.SUBRIP, path, "utf_16_le") file.read() def test_read__utf_8_sig(self): path = self.new_subrip_file() with open(path, "r") as f: text = f.read() with open(path, "w", encoding="utf_8_sig") as f: f.write(text) file = aeidon.files.new(aeidon.formats.SUBRIP, path, "utf_8") file.read()
gpl-3.0
Murerr/GERESA
htdocs/geresa/test/functional/MyModuleFunctionalTest.php
7370
<?php /* <one line to give the program's name and a brief idea of what it does.> * Copyright (C) <year> <name of author> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /** * \file test/functional/MyModuleFunctionalTest.php * \ingroup mymodule * \brief Example Selenium test. * * Put detailed description here. */ namespace test\functional; use PHPUnit_Extensions_Selenium2TestCase_WebDriverException; /** * Class MyModuleFunctionalTest * * Requires chromedriver for Google Chrome * Requires geckodriver for Mozilla Firefox * * @fixme Firefox (Geckodriver/Marionette) support * @todo Opera linux support * @todo Windows support (IE, Google Chrome, Mozilla Firefox, Safari) * @todo OSX support (Safari, Google Chrome, Mozilla Firefox) * * @package test\functional */ class MyModuleFunctionalTest extends \PHPUnit_Extensions_Selenium2TestCase { // TODO: move to a global configuration file? /** @var string Base URL of the webserver under test */ protected static $base_url = 'http://dev.zenfusion.fr'; /** * @var string Dolibarr admin username * @see authenticate */ protected static $dol_admin_user = 'admin'; /** * @var string Dolibarr admin password * @see authenticate */ protected static $dol_admin_pass = 'admin'; /** @var int Dolibarr module ID */ private static $module_id = 500000; // TODO: autodetect? /** @var array Browsers to test with */ public static $browsers = array( array( 'browser' => 'Google Chrome on Linux', 'browserName' => 'chrome', 'sessionStrategy' => 'shared', 'desiredCapabilities' => array() ), // Geckodriver does not keep the session at the moment?! // XPath selectors also don't seem to work // array( // 'browser' => 'Mozilla Firefox on Linux', // 'browserName' => 'firefox', // 'sessionStrategy' => 'shared', // 'desiredCapabilities' => array( // 'marionette' => true // ) // ) ); /** * Helper function to select links by href * * @param $value * @return mixed */ protected function byHref($value) { $anchor = null; $anchors = $this->elements($this->using('tag name')->value('a')); foreach ($anchors as $anchor) { if (strstr($anchor->attribute('href'), $value)) { break; } } return $anchor; } /** * Global test setup */ public static function setUpBeforeClass() { } /** * Unit test setup */ public function setUp() { $this->setSeleniumServerRequestsTimeout(3600); $this->setBrowserUrl(self::$base_url); } /** * Verify pre conditions */ protected function assertPreConditions() { } /** * Handle Dolibarr authentication */ private function authenticate() { try { if ($this->byId('login')) { $login = $this->byId('username'); $login->clear(); $login->value('admin'); $password = $this->byId('password'); $password->clear(); $password->value('admin'); $this->byId('login')->submit(); } } catch (PHPUnit_Extensions_Selenium2TestCase_WebDriverException $e) { // Login does not exist. Assume we are already authenticated } } /** * Test enabling developer mode */ public function testEnableDeveloperMode() { $this->url('/admin/const.php'); $this->authenticate(); $main_features_level_path='//input[@value="MAIN_FEATURES_LEVEL"]/following::input[@type="text"]'; $main_features_level = $this->byXPath($main_features_level_path); $main_features_level->clear(); $main_features_level->value('2'); $this->byName('update')->click(); // Page reloaded, we need a new XPath $main_features_level = $this->byXPath($main_features_level_path); return $this->assertEquals('2', $main_features_level->value(), "MAIN_FEATURES_LEVEL value is 2"); } /** * Test enabling the module * * @depends testEnableDeveloperMode */ public function testModuleEnabled() { $this->url('/admin/modules.php'); $this->authenticate(); $module_status_image_path='//a[contains(@href, "' . self::$module_id . '")]/img'; $module_status_image = $this->byXPath($module_status_image_path); if (strstr($module_status_image->attribute('src'), 'switch_off.png')) { // Enable the module $this->byHref('modMyModule')->click(); } else { // Disable the module $this->byHref('modMyModule')->click(); // Reenable the module $this->byHref('modMyModule')->click(); } // Page reloaded, we need a new Xpath $module_status_image = $this->byXPath($module_status_image_path); return $this->assertContains('switch_on.png', $module_status_image->attribute('src'), "Module enabled"); } /** * Test access to the configuration page * * @depends testModuleEnabled */ public function testConfigurationPage() { $this->url('/custom/mymodule/admin/setup.php'); $this->authenticate(); return $this->assertContains('mymodule/admin/setup.php', $this->url(), 'Configuration page'); } /** * Test access to the about page * * @depends testConfigurationPage */ public function testAboutPage() { $this->url('/custom/mymodule/admin/about.php'); $this->authenticate(); return $this->assertContains('mymodule/admin/about.php', $this->url(), 'About page'); } /** * Test about page is rendering Markdown * * @depends testAboutPage */ public function testAboutPageRendersMarkdownReadme() { $this->url('/custom/mymodule/admin/about.php'); $this->authenticate(); return $this->assertEquals( 'Dolibarr Module Template (aka My Module)', $this->byTag('h1')->text(), "Readme title" ); } /** * Test box is properly declared * * @depends testModuleEnabled */ public function testBoxDeclared() { $this->url('/admin/boxes.php'); $this->authenticate(); return $this->assertContains('mybox', $this->source(), "Box enabled"); } /** * Test trigger is properly enabled * * @depends testModuleEnabled */ public function testTriggerDeclared() { $this->url('/admin/triggers.php'); $this->authenticate(); return $this->assertContains( 'interface_99_modMyModule_MyTrigger.class.php', $this->byTag('body')->text(), "Trigger declared" ); } /** * Test trigger is properly declared * * @depends testTriggerDeclared */ public function testTriggerEnabled() { $this->url('/admin/triggers.php'); $this->authenticate(); return $this->assertContains( 'tick.png', $this ->byXPath('//td[text()="interface_99_modMyModule_MyTrigger.class.php"]/following::img') ->attribute('src'), "Trigger enabled" ); } /** * Verify post conditions */ protected function assertPostConditions() { } /** * Unit test teardown */ public function tearDown() { } /** * Global test teardown */ public static function tearDownAfterClass() { } }
gpl-3.0
ozzi-/Quizzenger
CSQ_SA/controller/controllers/logout.php
35
<?php $sessionModel->logout (); ?>
gpl-3.0
pinky39/grove
source/Grove/CardsLibrary/MeditationPuzzle.cs
1003
namespace Grove.CardsLibrary { using System.Collections.Generic; using AI.TimingRules; using Effects; public class MeditationPuzzle : CardTemplateSource { public override IEnumerable<CardTemplate> GetCards() { yield return Card .Named("Meditation Puzzle") .ManaCost("{3}{W}{W}") .Type("Instant") .Text( "{Convoke}{I}(Your creatures can help cast this spell. Each creature you tap while casting this spell pays for {1} or one mana of that creature's color.){/I}{EOL}You gain 8 life.") .FlavorText("Find your center, and you will find your way.") .SimpleAbilities(Static.Convoke) .Cast(p => { p.Text = "You gain 8 life."; p.Effect = () => new ChangeLife(8, P(e => e.Controller)); p.TimingRule(new Any( new OnEndOfOpponentsTurn(), new AfterYouDeclareBlockers(), new WhenYourLifeCanBecomeZero())); }); } } }
gpl-3.0
lkiesow/lf-portal
plugin/player/simpleengage.py
978
# -*- coding: utf-8 -*- ''' LF-Portal :: Simple Player Plugin ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ This plugin tries the include the Opencast Engage Player using a preset engage server and the episode identifier. This plugin needs the ENGAGE_SERVICE configuration parameter. :copyright: 2013 by Lars Kiesow <lkiesow@uos.de> :license: GPL, see LICENSE for more details. ''' # Set default encoding to UTF-8 import sys reload(sys) sys.setdefaultencoding('utf8') def player( media, config, request ): '''Generate an HTML code for the inclusion of the player into the portal. :param media: Mediapackage media XML structure :param config: Portal configuration :param request: Current request object ''' id = media.getAttribute('id') session = request.cookies.get('JSESSIONID') session = (';jsessionid=%s' % session) if session else '' player = '%sui/watch.html%s?id=%s' % (config['ENGAGE_SERVICE'], session, id) return '<iframe src="%s"></iframe>' % player, {}
gpl-3.0
RedhawkSDR/integration-gnuhawk
components/tagged_file_sink_c/tests/test_tagged_file_sink_c.py
4079
#!/usr/bin/env python # # This file is protected by Copyright. Please refer to the COPYRIGHT file # distributed with this source distribution. # # This file is part of GNUHAWK. # # GNUHAWK is free software: you can redistribute it and/or modify is 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. # # GNUHAWK is distributed in the hope that it will be useful, but WITHOUT ANY # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR # A PARTICULAR PURPOSE. See the GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along with # this program. If not, see http://www.gnu.org/licenses/. # import unittest import ossie.utils.testing import os from omniORB import any class ComponentTests(ossie.utils.testing.ScaComponentTestCase): """Test for all component implementations in tagged_file_sink_c""" def testScaBasicBehavior(self): ####################################################################### # Launch the component with the default execparams execparams = self.getPropertySet(kinds=("execparam",), modes=("readwrite", "writeonly"), includeNil=False) execparams = dict([(x.id, any.from_any(x.value)) for x in execparams]) self.launch(execparams) ####################################################################### # Verify the basic state of the component self.assertNotEqual(self.comp, None) self.assertEqual(self.comp.ref._non_existent(), False) self.assertEqual(self.comp.ref._is_a("IDL:CF/Resource:1.0"), True) ####################################################################### # Validate that query returns all expected parameters # Query of '[]' should return the following set of properties expectedProps = [] expectedProps.extend(self.getPropertySet(kinds=("configure", "execparam"), modes=("readwrite", "readonly"), includeNil=True)) expectedProps.extend(self.getPropertySet(kinds=("allocate",), action="external", includeNil=True)) props = self.comp.query([]) props = dict((x.id, any.from_any(x.value)) for x in props) # Query may return more than expected, but not less for expectedProp in expectedProps: self.assertEquals(props.has_key(expectedProp.id), True) ####################################################################### # Verify that all expected ports are available for port in self.scd.get_componentfeatures().get_ports().get_uses(): port_obj = self.comp.getPort(str(port.get_usesname())) self.assertNotEqual(port_obj, None) self.assertEqual(port_obj._non_existent(), False) self.assertEqual(port_obj._is_a("IDL:CF/Port:1.0"), True) for port in self.scd.get_componentfeatures().get_ports().get_provides(): port_obj = self.comp.getPort(str(port.get_providesname())) self.assertNotEqual(port_obj, None) self.assertEqual(port_obj._non_existent(), False) self.assertEqual(port_obj._is_a(port.get_repid()), True) ####################################################################### # Make sure start and stop can be called without throwing exceptions self.comp.start() self.comp.stop() ####################################################################### # Simulate regular component shutdown self.comp.releaseObject() # TODO Add additional tests here # # See: # ossie.utils.bulkio.bulkio_helpers, # ossie.utils.bluefile.bluefile_helpers # for modules that will assist with testing components with BULKIO ports if __name__ == "__main__": ossie.utils.testing.main("../tagged_file_sink_c.spd.xml") # By default tests all implementations
gpl-3.0
seiyria/landoftherair
src/server/effects/buffs/Invisible.ts
1209
import { SpellEffect } from '../../base/Effect'; import { Character } from '../../../shared/models/character'; import { Skill } from '../../base/Skill'; export class Invisible extends SpellEffect { iconData = { name: 'invisible', color: '#000', tooltipDesc: 'Hidden from the average sight.' }; maxSkillForSkillGain = 20; cast(caster: Character, target: Character, skillRef?: Skill) { this.setPotencyAndGainSkill(caster, skillRef); this.flagUnapply(); this.flagCasterName(caster.name); if(!this.duration) this.duration = 300 * this.potency; this.updateBuffDurationBasedOnTraits(caster); if(caster !== target) { this.casterEffectMessage(caster, { message: `You cast Invisibility on ${target.name}.`, sfx: 'spell-sight-effect' }); } this.aoeAgro(caster, 100); target.applyEffect(this); } effectStart(char: Character) { this.targetEffectMessage(char, { message: 'You can see through yourself!', sfx: 'spell-sight-effect' }); // add some stealth so it triggers transparency on the client this.gainStat(char, 'stealth', 1); } effectEnd(char: Character) { this.effectMessage(char, 'You are once again opaque.'); } }
gpl-3.0
mimi89999/librus-client
app/src/main/java/pl/librus/client/ui/announcements/AnnouncementDetailsFragment.java
2979
package pl.librus.client.ui.announcements; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import java.util.Locale; import pl.librus.client.R; import pl.librus.client.data.Reader; import pl.librus.client.domain.announcement.FullAnnouncement; import pl.librus.client.util.LibrusUtils; /** * A simple {@link Fragment} subclass. * Use the {@link AnnouncementDetailsFragment#newInstance} factory method to * create an instance create this fragment. */ public class AnnouncementDetailsFragment extends Fragment { private static final String ARG_ANNOUNCEMENT = "librus-client:AnnouncementDetailsFragment:announcement"; private FullAnnouncement announcement; public AnnouncementDetailsFragment() { // Required empty public constructor } /** * Use this factory method to create a new instance create * this fragment using the provided parameters. * * @param announcement Announcement to show * @return A new instance create fragment AnnouncementDetailsFragment. */ public static AnnouncementDetailsFragment newInstance(FullAnnouncement announcement) { AnnouncementDetailsFragment fragment = new AnnouncementDetailsFragment(); Bundle args = new Bundle(); args.putSerializable(ARG_ANNOUNCEMENT, announcement); fragment.setArguments(args); return fragment; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (getArguments() != null) { announcement = (FullAnnouncement) getArguments().getSerializable(ARG_ANNOUNCEMENT); } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View root = inflater.inflate(R.layout.fragment_announcement_details, container, false); TextView titleTextView = (TextView) root.findViewById(R.id.fragment_announcement_details_top_panel); TextView contentTextView = (TextView) root.findViewById(R.id.fragment_announcement_details_bottom_panel); TextView authorTextView = (TextView) root.findViewById(R.id.two_line_list_item_title); TextView dateTextView = (TextView) root.findViewById(R.id.two_line_list_item_content); View background = root.findViewById(R.id.fragment_announcement_details); titleTextView.setText(announcement.subject()); contentTextView.setText(announcement.content()); LibrusUtils.setTextViewValue(authorTextView, announcement.addedByName()); dateTextView.setText(announcement.startDate().toString("EEEE, d MMMM yyyy", new Locale("pl"))); background.setTransitionName("announcement_background_" + announcement.id()); new Reader(getContext()).read(announcement); return root; } }
gpl-3.0
OliPro007/FlickBaseball-Cpp
FlickBaseball/Main.cpp
1310
#include "SFML/Graphics.hpp" #include "Game.h" #include <iostream> #include <fstream> void loadLocale(fbb::Config& config); void loadConfig(fbb::Config& config); int main() { setlocale(LC_ALL, ""); sf::Clock* clock = new sf::Clock(); sf::Time beginTime = clock->getElapsedTime(); std::cout << "Creating game instance..." << std::endl; fbb::Config config = {}; loadConfig(config); fbb::Game game(config); std::cout << "Game instance created successfully! Time: " << (clock->getElapsedTime() - beginTime).asMilliseconds() << " milliseconds" << std::endl; delete clock; clock = nullptr; game.gameLoop(); return 0; } void loadConfig(fbb::Config& config) { std::ifstream cfg("cfg.xml"); if(cfg) { //read xml } else { //write xml and load default values from default struct values if(config.locale == "en") //will be empty string for system default loadLocale(config); } } void loadLocale(fbb::Config& config) { std::string locale = setlocale(LC_ALL, NULL); //Get locale string if(locale == "C") locale = "en"; config.locale = locale.substr(0, 2); //Get the language identifier only for(size_t i = 0; i < config.locale.length(); i++) //Put to lowercase because Windows seems to like the long <language>_<region>.<code> format config.locale[i] = tolower(config.locale[i]); }
gpl-3.0
andreydil/Evo
src/Evo.Core/Universe/Mutator.cs
3161
using System; using System.Linq; using System.Runtime.Serialization; using Evo.Core.Basic; using Evo.Core.Units; namespace Evo.Core.Universe { [Serializable] public class Mutator { private readonly World _world; public Mutator(World world) { _world = world; } public Individual GenerateRandom() { var individual = new Individual(_world.GenerateId(), _world); foreach (var geneItem in individual.Genome) { geneItem.Value.Value = _world.Random.Next(geneItem.Value.Min, geneItem.Value.Max); } return individual; } public Individual GenerateAverage() { return new Individual(_world.GenerateId(), _world); } public Individual GenerateChild(Individual father, Individual mother) { var individual = new Individual(_world.GenerateId(), _world, Math.Min(father.MinGeneration, mother.MinGeneration) + 1, Math.Max(father.MaxGeneration, mother.MaxGeneration) + 1); foreach (var geneItem in individual.Genome) { var gene = geneItem.Value; gene.Value = _world.Random.Next(Math.Min(father.Genome[geneItem.Key], mother.Genome[geneItem.Key]), Math.Max(father.Genome[geneItem.Key], mother.Genome[geneItem.Key]) + 1); //somewhere between father and mother if (_world.CheckRng(_world.MutationProbability)) { gene.Value += _world.Random.Next(-_world.MutationMaxDelta, _world.MutationMaxDelta + 1); } } individual.Color.SetRGB(GenerateColorComponent(father.Color.Red, mother.Color.Red), GenerateColorComponent(father.Color.Green, mother.Color.Green), GenerateColorComponent(father.Color.Blue, mother.Color.Blue)); return individual; } public Individual GenerateIndividual(Func<Gene, int> geneFunc, ulong id, World world) { var individual = new Individual(id, world); foreach (var gene in individual.Genome.Select(gi => gi.Value)) { gene.Value = geneFunc(gene); } return individual; } private byte GenerateColorComponent(byte fatherComponent, byte motherComponent) { int component = _world.Random.Next(Math.Min(fatherComponent, motherComponent), Math.Max(fatherComponent, motherComponent) + 1); int mutationMaxDelta = 0xff * _world.MutationMaxDelta / _world.MutationMaxDelta.Max; if (_world.CheckRng(_world.MutationProbability)) { component += _world.Random.Next(-mutationMaxDelta, mutationMaxDelta + 1); } if (component < 0) { return 0; } if (component > 0xff) { return 0xff; } return (byte)component; } } }
gpl-3.0
RoadWorksSoftware/eyecu-qt
src/translations/uk/messagestyles.ts
7462
<?xml version="1.0" ?><!DOCTYPE TS><TS language="uk" sourcelanguage="en" version="2.0"> <context> <name>MessageStyleManager</name> <message> <source>Message Styles Manager</source> <translation>Менеджер стилів повідомлень</translation> </message> <message> <source>Allows to use different styles to display messages</source> <translation>Дозволяє використовувати різні стилі для повідомлень</translation> </message> <message> <source>Messages styles</source> <translation>Стилі повідомлень</translation> </message> <message> <source>Show date separators in message window</source> <translation>Показувати дати у вікні повідомлень</translation> </message> <message> <source>January</source> <translation>Січень</translation> </message> <message> <source>February</source> <translation>Лютий</translation> </message> <message> <source>March</source> <translation>Березень</translation> </message> <message> <source>April</source> <translation>Квітень</translation> </message> <message> <source>May</source> <translation>Травень</translation> </message> <message> <source>June</source> <translation>Червень</translation> </message> <message> <source>July</source> <translation>Липень</translation> </message> <message> <source>August</source> <translation>Серпень</translation> </message> <message> <source>September</source> <translation>Вересень</translation> </message> <message> <source>October</source> <translation>Жовтень</translation> </message> <message> <source>November</source> <translation>Листопад</translation> </message> <message> <source>December</source> <translation>Грудень</translation> </message> <message> <source>Monday</source> <translation>Понеділок</translation> </message> <message> <source>Tuesday</source> <translation>Вівторок</translation> </message> <message> <source>Wednesday</source> <translation>Середа</translation> </message> <message> <source>Thursday</source> <translation>Четвер</translation> </message> <message> <source>Friday</source> <translation>П&apos;ятниця</translation> </message> <message> <source>Saturday</source> <translation>Субота</translation> </message> <message> <source>Sunday</source> <translation>Неділя</translation> </message> <message> <source>%1, %2 dd</source> <translation>%1, %2 dd</translation> </message> <message> <source>Today</source> <translation>Сьогодні</translation> </message> <message> <source>%1, %2 dd, yyyy</source> <translation>%1, %2 dd, yyyy</translation> </message> <message> <source>d MMM yyyy hh:mm</source> <translation>d MMM yyyy hh:mm</translation> </message> <message> <source>d MMM hh:mm</source> <translation>d MMM hh:mm</translation> </message> <message> <source>hh:mm:ss</source> <translation>hh:mm:ss</translation> </message> <message> <source>Use monospaced font for unformatted text</source> <translation>Використовувати моноширокий шрифт для неформатованого тексту</translation> </message> </context> <context> <name>StyleEditOptionsDialog</name> <message> <source>Preview</source> <translation>Показати</translation> </message> <message> <source>Message Style - %1 - %2</source> <translation>Стиль повідомлень - %1 - %2</translation> </message> <message> <source>The message with a error code %1 is received</source> <translation>Отримано повідомлення з помилкою %1</translation> </message> <message> <source>Error description</source> <translation>Опис помилки</translation> </message> <message> <source>Subject: Message subject</source> <translation>Тема: Тема повідомлення</translation> </message> <message> <source>Message body line 1</source> <translation>1 стрічка повідомлення</translation> </message> <message> <source>Message body line 2</source> <translation>2 стрічка повідомлення</translation> </message> <message> <source>Incoming history message</source> <translation>Історія вхідних повідомлень</translation> </message> <message> <source>Incoming history consecutive message</source> <translation>Історія послідовних вхідних повідомлень</translation> </message> <message> <source>Incoming status message</source> <translation>Статус вхідного повідомлення</translation> </message> <message> <source>Outgoing history message</source> <translation>Історія вихідних повідомлень</translation> </message> <message> <source>Outgoing status message</source> <translation>Статус вихідного повідомлення</translation> </message> <message> <source>Conference topic</source> <translation>Тема конференції</translation> </message> <message> <source>Incoming message</source> <translation>Вхідне повідомлення</translation> </message> <message> <source>Incoming event</source> <translation>Віхдна подія</translation> </message> <message> <source>Incoming notification</source> <translation>Вхідне сповіщення</translation> </message> <message> <source>Incoming mention message</source> <translation>Вхідне повідомлення зі згадуванням</translation> </message> <message> <source>Outgoing message</source> <translation>Вихідне повідомлення</translation> </message> <message> <source>Outgoing consecutive message</source> <translation>Вихідне послідовне повідомлення</translation> </message> <message> <source>Contact</source> <translation>Контакт</translation> </message> <message> <source>You</source> <translation>Ви</translation> </message> <message> <source>speaks of himself in the third person</source> <translation>говорить про себе у третій особі</translation> </message> </context> <context> <name>StyleSelectOptionsWidget</name> <message> <source>Chat:</source> <translation>Чат:</translation> </message> <message> <source>Conference:</source> <translation>Конференція:</translation> </message> <message> <source>Message:</source> <translation>Повідомлення:</translation> </message> <message> <source>Headline:</source> <translation>Заголовок:</translation> </message> <message> <source>Error:</source> <translation>Помилка:</translation> </message> <message> <source>Unknown:</source> <translation>Невідомо:</translation> </message> <message> <source>Settings...</source> <translation>Налаштування...</translation> </message> </context> </TS>
gpl-3.0
dakside/shacc
HaccCoreModules/src/dakside/hacc/modules/accounting/accountposting/AccountingController.java
11562
/* * Copyright (C) 2009 Le Tuan Anh * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package dakside.hacc.modules.accounting.accountposting; import dakside.hacc.core.config.Configuration; import dakside.hacc.core.dao.AccountDAO; import org.dakside.dao.DAOException; import dakside.hacc.core.dao.DAOFactory; import dakside.hacc.core.dao.TransactionDAO; import dakside.hacc.core.models.Account; import dakside.hacc.core.models.AccountEntry; import dakside.hacc.core.models.AccountPeriod; import dakside.hacc.core.models.JournalEntry; import dakside.hacc.core.models.Transaction; import dakside.hacc.core.models.TransactionAction; import java.util.ArrayList; import java.util.Date; import java.util.logging.Level; import java.util.logging.Logger; /** * Accounting controller * @author LeTuanAnh <tuananh.ke@gmail.com> */ public class AccountingController { private static final Logger logger = Logger.getLogger(AccountingController.class.getName()); private AccountingView view = null; public AccountingController() { } public AccountingController(AccountingView view) { setView(view); } /** * @return the view */ public AccountingView getView() { return view; } /** * @param view the view to set */ public void setView(AccountingView view) { this.view = view; } public boolean unpost(JournalEntry je) { //only can unpost je of an opening period if (je.getAccountPeriod() != null && je.getAccountPeriod().getStatus() == AccountPeriod.OPENING) { //unpost try { AccountDAO dao = Configuration.getInstance().getDAOFactory().getAccountDAO(); dao.delete(je); return true; } catch (NullPointerException ex) { logger.log(Level.SEVERE, null, ex); } catch (DAOException ex) { logger.log(Level.SEVERE, null, ex); } } return false; } public JournalEntry post(Transaction transaction, AccountPeriod accountPeriod) { //validate transaction if (!isValidForPost(transaction) || accountPeriod == null) { return null; } else { JournalEntry je = new JournalEntry(); Date postTime = new Date(); //create account entries for (TransactionAction action : transaction.getType().getActions()) { //Transaction currency must be same as account base currency if (transaction.getCurrency() != action.getToAccount().getCurrency()) { return null; } AccountEntry entry = new AccountEntry(); //create account entry from action entry.setAction(action.getAction()); entry.setAmount(transaction.getAmount()); entry.setCurrency(transaction.getCurrency()); entry.setToAccount(action.getToAccount()); entry.setType(AccountEntry.TYPE_NORMAL); entry.setAccountPeriod(accountPeriod); entry.setPostDate(postTime); //add to journal entry je.getAccountEntries().add(entry); } je.setAccountPeriod(accountPeriod); //add reference to transactions je.setTransaction(transaction); //posting date is today //TODO should we let user to choose posting date? je.setPostingDate(postTime); //save journal entry to database try { AccountDAO dao = Configuration.getInstance().getDAOFactory().getAccountDAO(); dao.save(je); } catch (NullPointerException ex) { logger.log(Level.SEVERE, null, ex); return null; } catch (DAOException ex) { logger.log(Level.SEVERE, null, ex); return null; } return je; } } private boolean isValidForPost(Transaction transaction) { return transaction != null && transaction.getType() != null; } /** * Get all account periods * @return */ public AccountPeriod[] getAllOpeningPeriods() { try { AccountDAO dao = Configuration.getInstance().getDAOFactory().getAccountDAO(); return dao.getOpeningAccountPeriods(); } catch (NullPointerException ex) { } catch (DAOException ex) { logger.log(Level.SEVERE, null, ex); } return new AccountPeriod[0]; } AccountPeriod findMatchAccountPeriod(Transaction transaction) { try { AccountDAO dao = Configuration.getInstance().getDAOFactory().getAccountDAO(); return dao.getAccountPeriodAt(transaction.getTransactionDate()); } catch (NullPointerException ex) { } catch (DAOException ex) { logger.log(Level.SEVERE, null, ex); } return null; } Transaction[] getUnpostedTransactions() { try { TransactionDAO dao = Configuration.getInstance().getDAOFactory().getTransactionDAO(); return dao.getTransactions(null, Boolean.FALSE, null, null); } catch (NullPointerException ex) { } catch (DAOException ex) { logger.log(Level.SEVERE, "cannot get unposted transcations", ex); } return new Transaction[0]; } JournalEntry[] getAllJournalEntries() { try { AccountDAO dao = Configuration.getInstance().getDAOFactory().getAccountDAO(); return dao.getAllJournalEntries(); } catch (NullPointerException ex) { } catch (DAOException ex) { logger.log(Level.SEVERE, null, ex); } return new JournalEntry[0]; } /** * Auto close all previous account periods */ void autoClosePeriods() { try { AccountDAO dao = Configuration.getInstance().getDAOFactory().getAccountDAO(); //1. get all past account periods AccountPeriod[] periods = dao.getPassedAccountPeriods(); //2. get all available accounts Account[] accounts = dao.getAllAccounts(); //3. for each account period, create close entries for all accounts ArrayList<AccountEntry> entries = new ArrayList<AccountEntry>(); for (AccountPeriod period : periods) { for (Account account : accounts) { // a. get account balance within the account period double balance = dao.getAccountBalance(account, period, false); // b. create an account entry (type=close) and amount = balance AccountEntry closeEntry = new AccountEntry(); closeEntry.setAccountPeriod(period); if (account.getType() == Account.TYPE_CREDIT) { closeEntry.setAction(Account.TYPE_DEBIT); } else { closeEntry.setAction(Account.TYPE_CREDIT); } closeEntry.setAmount(balance); closeEntry.setCurrency(account.getCurrency()); closeEntry.setToAccount(account); closeEntry.setType(AccountEntry.TYPE_CLOSING); closeEntry.setPostDate(period.getToDate()); // c. create an account entry (type=open) in next account period AccountEntry openEntry = new AccountEntry(); //find nextPeriod AccountPeriod nextPeriod = getNextPeriod(dao, period); if (nextPeriod == null) { // if there's no next account period, fire error. throw new RuntimeException("Cannot find next period for " + period.toString()); } openEntry.setAccountPeriod(nextPeriod); openEntry.setPostDate(nextPeriod.getFromDate()); if (account.getType() == Account.TYPE_CREDIT) { openEntry.setAction(Account.TYPE_CREDIT); } else { openEntry.setAction(Account.TYPE_DEBIT); } openEntry.setAmount(balance); openEntry.setCurrency(account.getCurrency()); openEntry.setToAccount(account); openEntry.setType(AccountEntry.TYPE_OPENING); //everything ok, then add the pair entries to list entries.add(openEntry); entries.add(closeEntry); } } //4. If there's no error for closing, write all changes to database. for (AccountEntry entry : entries) { dao.save(entry); } } catch (Exception ex) { Logger.getLogger(AccountingController.class.getName()).log(Level.SEVERE, null, ex); } } private AccountPeriod getNextPeriod(AccountDAO dao, AccountPeriod period) throws DAOException { Date nextPeriodFromDate = (Date) period.getToDate().clone(); nextPeriodFromDate.setTime(nextPeriodFromDate.getTime() + 1); //plus 1 millisecond return dao.getAccountPeriodAt(nextPeriodFromDate); } /** * Get all accounts from database * @return */ public Account[] getAllAccounts() { try { DAOFactory factory = Configuration.getInstance().getDAOFactory(); if (factory != null) { AccountDAO dao = factory.getAccountDAO(); return dao.getAllAccounts(); } } catch (DAOException ex) { Logger.getLogger(AccountingController.class.getName()).log(Level.SEVERE, null, ex); } return new Account[0]; } public AccountEntry[] getAccountEntriesOf(Account acc, AccountPeriod period) { try { DAOFactory factory = Configuration.getInstance().getDAOFactory(); if (factory != null) { AccountDAO dao = factory.getAccountDAO(); return dao.getAccountEntriesOf(acc, period); } } catch (DAOException ex) { Logger.getLogger(AccountingController.class.getName()).log(Level.SEVERE, null, ex); } return new AccountEntry[0]; } public JournalEntry[] getJournalEntriesOf(AccountPeriod period) { try { AccountDAO dao = Configuration.getInstance().getDAOFactory().getAccountDAO(); return dao.getJournalEntriesOf(period); } catch (NullPointerException ex) { } catch (DAOException ex) { Logger.getLogger(AccountingController.class.getName()).log(Level.SEVERE, null, ex); } return new JournalEntry[0]; } }
gpl-3.0
corburn/ISIS
isis/src/qisis/apps/cneteditor/APrioriLongitudeSigmaFilter.cpp
1920
#include "IsisDebug.h" #include "APrioriLongitudeSigmaFilter.h" #include "ControlPoint.h" #include "Longitude.h" namespace Isis { namespace CnetViz { APrioriLongitudeSigmaFilter::APrioriLongitudeSigmaFilter( AbstractFilter::FilterEffectivenessFlag flag, int minimumForSuccess) : AbstractNumberFilter(flag, minimumForSuccess) { } APrioriLongitudeSigmaFilter::APrioriLongitudeSigmaFilter( const APrioriLongitudeSigmaFilter & other) : AbstractNumberFilter(other) { } APrioriLongitudeSigmaFilter::~APrioriLongitudeSigmaFilter() { } bool APrioriLongitudeSigmaFilter::evaluate( const ControlCubeGraphNode * node) const { return evaluateImageFromPointFilter(node); } bool APrioriLongitudeSigmaFilter::evaluate( const ControlPoint * point) const { return AbstractNumberFilter::evaluate( point->GetAprioriSurfacePoint().GetLonSigmaDistance().meters()); } bool APrioriLongitudeSigmaFilter::evaluate( const ControlMeasure * measure) const { return true; } AbstractFilter * APrioriLongitudeSigmaFilter::clone() const { return new APrioriLongitudeSigmaFilter(*this); } QString APrioriLongitudeSigmaFilter::getImageDescription() const { QString description = AbstractFilter::getImageDescription(); if (getMinForSuccess() == 1) description += "point that has an <i>a priori</i> surface point " "longitude sigma which is "; else description += "points that have <i>a priori</i> surface point " "longitude sigmas which are "; description += descriptionSuffix(); return description; } QString APrioriLongitudeSigmaFilter::getPointDescription() const { return "have <i>a priori</i> surface point longitude sigmas which are " + descriptionSuffix(); } } }
gpl-3.0
kostovhg/SoftUni
ProgrammingFundamentals-E-May-17/t12_ArraysAndMethods-E/p10_CountOfNegativeElementsInArray/CountOfNegativeElementsInArray.cs
464
using System; using System.Linq; namespace p10_CountOfNegativeElementsInArray { class CountOfNegativeElementsInArray { static void Main(string[] args) { int n = int.Parse(Console.ReadLine()); int[] arr = new int[n]; for (int i = 0; i < n; i++) { arr[i] = int.Parse(Console.ReadLine()); } Console.WriteLine(arr.Count(i => i < 0)); } } }
gpl-3.0
fppt/mindmapsdb
grakn-dashboard/src/controllers/visualiser.js
12269
import _ from 'underscore'; import Prism from 'prismjs'; import CodeMirror from 'codemirror'; import placeholder from 'codemirror/addon/display/placeholder.js'; import simpleMode from 'codemirror/addon/mode/simple.js'; import Visualiser from '../js/visualiser/Visualiser.js'; import * as HALParser from '../js/HAL/HALParser.js'; import * as API from '../js/HAL/APITerms'; import EngineClient from '../js/EngineClient.js'; import * as PLang from '../js/prismGraql.js'; import simpleGraql from '../js/codemirrorGraql.js'; export default { props: ['useReasoner'], data() { return { errorMessage: undefined, errorPanelClass: undefined, visualiser: {}, engineClient: {}, halParser: {}, analyticsStringResponse: undefined, typeInstances: false, typeKeys: [], doubleClickTime:0, // resources keys used to change label of a node type allNodeProps: [], selectedProps: [], nodeType: undefined, selectedNodeLabel: undefined, // resources attached to the selected node allNodeOntologyProps: {}, allNodeResources: {}, allNodeLinks: {}, numOfResources: 0, numOfLinks: 0, codeMirror: {} } }, created() { visualiser = new Visualiser(); visualiser.setOnDoubleClick(this.doubleClick) .setOnRightClick(this.rightClick) .setOnClick(this.singleClick) .setOnDragEnd(this.dragEnd) .setOnHoldOnNode(this.holdOnNode); engineClient = new EngineClient(); halParser = new HALParser.default(); halParser.setNewResource((id, p, a, l) => visualiser.addNode(id, p, a, l)); halParser.setNewRelationship((f, t, l) => visualiser.addEdge(f, t, l)); halParser.setNodeAlreadyInGraph(id => visualiser.nodeExists(id)); }, attached() { var graph = this.$els.graph; function resizeElements() { // set graph div height var divHeight = window.innerHeight - graph.offsetTop - $('.graph-div').offset().top - 20; $('.graph-div').height(divHeight); //set the height of right panel of same size of graph-div $('.properties-tab').height(divHeight + 7); //fix the height of panel-body so that it is possible to make it overflow:scroll $('.properties-tab .panel-body').height(divHeight - 120); }; visualiser.render(graph); codeMirror = CodeMirror.fromTextArea(this.$els.graqlEditor, { lineNumbers: true, theme: "dracula", mode: "graql", viewportMargin: Infinity, extraKeys: { Enter: this.runQuery, "Shift-Delete": this.clearGraph, "Shift-Backspace": this.clearGraph } }); resizeElements(); window.onresize = resizeElements; $('.properties-tab').hide(); var height = window.innerHeight - graph.offsetTop - $('.graph-div').offset().top + 20; // make the list of resources tab resizable with mouse - jQueryUI $('#list-resources-tab').resizable({ //make it fixed height and only resizable towards west minHeight: height, maxHeight: height, handles: "w" }); }, methods: { /* * User interaction: queries. */ runQuery() { const query = codeMirror.getValue(); // Empty query. if (query == undefined || query.length === 0) return; if (query.trim().startsWith("compute")) engineClient.graqlAnalytics(query, this.analyticsResponse); else engineClient.graqlHAL(query, window.useReasoner, this.graphResponse); this.resetMsg(); }, typeQuery(t, ti) { codeMirror.setValue("match $x " + (t === 'roles' ? 'plays-role' : 'isa') + " " + ti + ";"); this.typeInstances = false; this.runQuery(); }, loadOntology() { let query_isa = "match $x isa " + API.TYPE_TYPE + ";"; let query_sub = "match $x sub " + API.TYPE_TYPE + ";"; engineClient.graqlHAL(query_sub, window.useReasoner, this.graphResponse); engineClient.graqlHAL(query_isa, window.useReasoner, this.graphResponse); }, getMetaTypes() { if (this.typeInstances) this.typeInstances = false; else engineClient.getMetaTypes(x => { if (x != null) { this.typeInstances = x; this.typeKeys = _.keys(x) } }); }, singleClick(param) { let t0 = new Date(); let threshold = 200; //all this fun to be able to distinguish a single click from a double click if (t0 - this.doubleClickTime > threshold) { setTimeout(()=> { if (t0 - this.doubleClickTime > threshold) { this.leftClick(param); } }, threshold); } }, /* * User interaction: visualiser */ leftClick(param) { // As multiselect is disabled, there will only ever be one node. const node = param.nodes[0]; const eventKeys = param.event.srcEvent; const clickType = param.event.type; if (node == undefined || eventKeys.shiftKey || clickType !== "tap") return; //When we will enable clustering, also need to check && !visualiser.expandCluster(node) if (eventKeys.altKey) engineClient.request({ url: visualiser.nodes._data[node].ontology, callback: this.graphResponse }); else { var props = visualiser.getNode(node); this.allNodeOntologyProps = { id: props.uuid, type: props.type, baseType: props.baseType } this.allNodeResources = this.prepareResources(props.properties); this.numOfResources = Object.keys(this.allNodeResources).length; this.numOfLinks = Object.keys(this.allNodeLinks).length; this.selectedNodeLabel = visualiser.getNodeLabel(node); $('#list-resources-tab').addClass('active'); this.openPropertiesTab(); } }, prepareResources(o) { if (o == null) return {}; //Sort object's keys alphabetically and check if the resource contains a URL string return Object.keys(o).sort().reduce( //r is the accumulator variable, i.e. new object with sorted keys //k is the current key (r, k) => { this.checkURLString(o[k]); r[k] = o[k]; return r; }, {}); }, checkURLString(resourceObject) { resourceObject.href = this.validURL(resourceObject.label); }, validURL(str) { var pattern = new RegExp(HALParser.URL_REGEX, "i"); return pattern.test(str); }, dragEnd(param) { // As multiselect is disabled, there will only ever be one node. const node = param.nodes[0]; visualiser.disablePhysicsOnNode(node); }, doubleClick(param) { this.doubleClickTime = new Date(); const node = param.nodes[0]; if (node == undefined || visualiser.expandCluster(node)) return; const eventKeys = param.event.srcEvent; if (visualiser.getNode(node).baseType === API.GENERATED_RELATION_TYPE) visualiser.deleteNode(node); if (eventKeys.shiftKey) visualiser.clearGraph(); engineClient.request({ url: node, callback: this.graphResponse }); }, addResourceNodeWithOwners(id) { engineClient.request({ url: id, callback: this.graphResponse }); }, rightClick(param) { const node = param.nodes[0]; if (node == undefined) return; if (param.event.shiftKey) { param.nodes.map(x => { visualiser.deleteNode(x) }); } }, openPropertiesTab() { $('.properties-tab.active').addClass('animated slideInRight'); $('.properties-tab.active').show(); }, /* * User interaction: visual elements control */ configureNode(p) { if (!(this.nodeType in this.selectedProps)) { this.selectedProps[this.nodeType] = []; } if (this.selectedProps[this.nodeType].includes(p)) this.selectedProps[this.nodeType] = this.selectedProps[this.nodeType].filter(x => x != p); else this.selectedProps[this.nodeType].push(p); visualiser.setDisplayProperties(this.nodeType, this.selectedProps[this.nodeType]); }, closeConfigPanel() { if ($('.properties-tab.active').hasClass('slideInRight')) { $('.properties-tab.active').removeClass('animated slideInRight'); $('.properties-tab.active').fadeOut(300, function() { this.nodeType = undefined; this.allNodeProps = []; this.selectedProps = []; }); $('.properties-tab.active').removeClass('active'); } }, holdOnNode(param) { const node = param.nodes[0]; if (node == undefined) return; this.allNodeProps = visualiser.getAllNodeProperties(node); this.nodeType = visualiser.getNodeType(node); $('#myModal2').modal('show'); }, /* * EngineClient callbacks */ graphResponse(resp, err) { if (resp != null) { if (!halParser.parseResponse(resp)) this.showWarning("Sorry, no results found for your query."); else visualiser.cluster(); } else { this.showError(err); } }, analyticsResponse(resp, err) { if (resp != null) { if (resp.type === "string") { this.analyticsStringResponse = resp.response; } else { halParser.parseResponse(resp.response); } } else { this.showError(err); } }, /* * UX */ suppressEventDefault(e) { e.preventDefault(); }, showError(msg) { this.errorPanelClass = 'panel-c-danger'; this.errorMessage = msg; $('.search-button').removeClass('btn-default').addClass('btn-danger'); }, showWarning(msg) { this.errorPanelClass = 'panel-c-warning'; this.errorMessage = msg; $('.search-button').removeClass('btn-default').addClass('btn-warning'); }, resetMsg() { this.errorMessage = undefined; this.analyticsStringResponse = undefined; $('.search-button') .removeClass('btn-danger') .removeClass('btn-warning') .addClass('btn-default'); }, clearGraph() { // Reset all interface elements to default. codeMirror.setValue(""); this.resetMsg(); this.closeConfigPanel(); // And clear the graph visualiser.clearGraph(); } } }
gpl-3.0
chinapacs/ImageViewer
ImageViewer/Tools/Reporting/View/WinForms/KeyImageClipboardComponentControl.Designer.cs
3434
namespace ClearCanvas.ImageViewer.Tools.Reporting.View.WinForms { partial class KeyImageClipboardComponentControl { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Component Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this._pnlSelectContext = new System.Windows.Forms.Panel(); this._cboCurrentContext = new System.Windows.Forms.ComboBox(); this._pnlMain = new System.Windows.Forms.Panel(); this._pnlSelectContext.SuspendLayout(); this.SuspendLayout(); // // _pnlSelectContext // this._pnlSelectContext.Controls.Add(this._cboCurrentContext); this._pnlSelectContext.Dock = System.Windows.Forms.DockStyle.Top; this._pnlSelectContext.Location = new System.Drawing.Point(0, 0); this._pnlSelectContext.Name = "_pnlSelectContext"; this._pnlSelectContext.Padding = new System.Windows.Forms.Padding(1); this._pnlSelectContext.Size = new System.Drawing.Size(310, 21); this._pnlSelectContext.TabIndex = 0; // // _cboCurrentContext // this._cboCurrentContext.Dock = System.Windows.Forms.DockStyle.Fill; this._cboCurrentContext.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this._cboCurrentContext.FormattingEnabled = true; this._cboCurrentContext.Location = new System.Drawing.Point(1, 1); this._cboCurrentContext.Name = "_cboCurrentContext"; this._cboCurrentContext.Size = new System.Drawing.Size(308, 20); this._cboCurrentContext.TabIndex = 1; // // _pnlMain // this._pnlMain.Dock = System.Windows.Forms.DockStyle.Fill; this._pnlMain.Location = new System.Drawing.Point(0, 21); this._pnlMain.Name = "_pnlMain"; this._pnlMain.Size = new System.Drawing.Size(310, 468); this._pnlMain.TabIndex = 1; // // KeyImageClipboardComponentControl // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.Controls.Add(this._pnlMain); this.Controls.Add(this._pnlSelectContext); this.Name = "KeyImageClipboardComponentControl"; this.Size = new System.Drawing.Size(310, 489); this._pnlSelectContext.ResumeLayout(false); this.ResumeLayout(false); } #endregion private System.Windows.Forms.Panel _pnlSelectContext; private System.Windows.Forms.ComboBox _cboCurrentContext; private System.Windows.Forms.Panel _pnlMain; } }
gpl-3.0
Drakalski/Belote
app/src/test/java/com/belote/belote/ExampleUnitTest.java
411
package com.belote.belote; import org.junit.Test; import static org.junit.Assert.*; /** * Example local unit test, which will execute on the development machine (host). * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ public class ExampleUnitTest { @Test public void addition_isCorrect() throws Exception { assertEquals(4, 2 + 2); } }
gpl-3.0
frits-scholer/pr
pr127/p127bit_v4.cpp
3833
#include <iostream> #include <utility> #include <vector> #include <cmath> #include <algorithm> #include <iterator> #include <numeric> #include <map> using namespace std; #define all(c) begin(c), end(c) #define sp << " " << const double min_cr = 0.637801; const int maxC = 50; const int maxCR = 400; typedef long Uint; typedef pair<int, double> crabc; typedef pair<int, int> radic; struct FenwickTree2D { int n, m; vector<vector<Uint> > a; vector<vector<vector<crabc>> > v; FenwickTree2D(int n, int m) : n(n), m(m), a(n, vector<Uint>(m)), v(n, vector<vector<crabc>>(m)) {} void update(int x, int y, int val, double cr) { v[x][y].push_back(crabc(val, cr)); int y1; while (x < n) { y1 = y; while (y1 < m) { a[x][y1] += val; y1 |= y1 + 1; } x |= x + 1; } } Uint get(int x, int y) { Uint re = 0; int y1; while (x >= 0) { y1 = y; while (y1 >= 0) { re += a[x][y1]; y1 = (y1 & (y1 + 1)) - 1; } x = (x & (x + 1)) - 1; } return re; } Uint get(int x1, int y1, int x2, int y2) { int re = get(x2, y2); re -= get(x1 - 1, y2); re -= get(x2, y1 - 1); re += get(x1 - 1, y1 - 1); return re; } }; inline bool even(int n) {return !(n&1);} inline bool odd(int n) {return n&1;} bool rel_prime(int m, int n) { while (m != 0) { int k = n%m; n=m; m=k; } return n==1; } void fill_radical(vector<int>& rad) { for (unsigned int i=2;i != rad.size();++i) if (rad[i] == 1) { rad[i] = i; for (unsigned int j = i+i; j < rad.size(); j += i) rad[j] *= i; } } istream& operator >> (istream& in, crabc& c) { return in >> c.second >> c.first; } template <typename I> void simple_input(I f, I l) { for (auto i=f;i != l; i++) cin >> *i; } template <typename I> void print(I f, I l) { for (auto i=f;i != l; i++) cout << *i << endl; } void show_event(string s, clock_t& tm) { tm = clock()-tm; cerr << "\t" << s << " " << (double) tm/CLOCKS_PER_SEC << " s "<< endl; } int main() { int T; //clock_t tm=clock(); cin >> T; vector<crabc> L(T); simple_input(all(L)); int Lmax = max_element(all(L))->first; vector<int> rads(Lmax,1); fill_radical(rads); vector<radic> srads(Lmax/2-1); int p{0}; generate(all(srads),[&]{++p;return radic(rads[p],p);}); sort(all(srads)); FenwickTree2D grids(maxC+1, maxCR+1); double sizex = 100000/maxC; double sizey = (1.5-min_cr)/(maxCR); vector<double> lg(Lmax); p=0; generate(begin(lg)+1,end(lg),[&]{++p;return log(p);}); for (int c=4;c<Lmax;++c) { double crl = c*sqrt(c)/rads[c]; int sl = distance(begin(srads), lower_bound(all(srads),radic(crl/(2+even(c))+1, 0))); crl = log(crl); for (auto i=0;i<sl;i++) { if (2*srads[i].second < c) { double rabc = lg[srads[i].first] + lg[rads[c-srads[i].second]]; if (rabc < crl && rel_prime(srads[i].first, rads[c])) { double cr = (rabc+lg[rads[c]])/lg[c]; grids.update(int(c/sizex), int((cr-min_cr)/sizey),c, cr); } } } } for (int i=0;i<T;i++) { if (L[i].second<min_cr) {cout << 0 << endl;continue;} int x=L[i].first/sizex; int y=(L[i].second-min_cr)/sizey; //get sum of all grids Uint S = grids.get(x-1,y-1); for (int k=0;k<=y;k++) for (auto it=begin(grids.v[x][k]);it!=end(grids.v[x][k]);it++) { if (it->first >= L[i].first) break; if (k < y || it->second < L[i].second) S += it->first; } for (int j=0;j<x;j++) for (auto it=begin(grids.v[j][y]);it!=end(grids.v[j][y]);it++) { if (it->second < L[i].second) S += it->first; } cout << S << endl; } //show_event("total time", tm); }
gpl-3.0
james-d-mitchell/semigroupsplusplus
src/cong-pair.cpp
3389
// // libsemigroups - C++ library for semigroups and monoids // Copyright (C) 2019 James D. Mitchell // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. // #include "libsemigroups/cong-pair.hpp" namespace libsemigroups { //////////////////////////////////////////////////////////////////////// // KnuthBendixCongruenceByPairs - constructors - public //////////////////////////////////////////////////////////////////////// KnuthBendixCongruenceByPairs::KnuthBendixCongruenceByPairs( congruence_type type, std::shared_ptr<KnuthBendix> kb) noexcept : CongruenceByPairsHelper_(type, kb, false) { // final param is a dummy set_nr_generators(kb->alphabet().size()); } KnuthBendixCongruenceByPairs::KnuthBendixCongruenceByPairs( congruence_type type, KnuthBendix const& kb) noexcept : KnuthBendixCongruenceByPairs(type, std::make_shared<KnuthBendix>(kb)) {} //////////////////////////////////////////////////////////////////////// // Runner - pure virtual member functions - public //////////////////////////////////////////////////////////////////////// void KnuthBendixCongruenceByPairs::run_impl() { auto stppd = [this]() -> bool { return stopped(); }; state().run_until(stppd); if (!stopped()) { if (!has_parent_froidure_pin()) { set_parent_froidure_pin(state().froidure_pin()); } // TODO(later) should just run_until in the next line, that doesn't // currently work because run_until calls run (i.e. this function), // causing an infinite loop. We really want to call run_until on the // p_type, using its run member function, but that's not currently // possible. CongruenceByPairsHelper_::run_impl(); } report_why_we_stopped(); } bool KnuthBendixCongruenceByPairs::finished_impl() const { return has_parent_froidure_pin() && CongruenceByPairsHelper_::finished_impl(); } //////////////////////////////////////////////////////////////////////// // CongruenceInterface - virtual member functions - public //////////////////////////////////////////////////////////////////////// // Override the method for the class CongruenceByPairs to avoid having to // know the parent semigroup (found as part of // KnuthBendixCongruenceByPairs::run) to add a pair. // TODO(later) this copies KBE(_kb, l) and KBE(_kb, r) twice. void KnuthBendixCongruenceByPairs::add_pair_impl(word_type const& u, word_type const& v) { internal_element_type x = new element_type(state(), u); internal_element_type y = new element_type(state(), v); internal_add_pair(x, y); this->internal_free(x); this->internal_free(y); } } // namespace libsemigroups
gpl-3.0
rhertzog/tryton-account-fr
account.py
2815
# This file is part of Tryton. The COPYRIGHT file at the top level of # this repository contains the full copyright notices and license terms. from sql import Table from trytond.pool import PoolMeta from trytond.transaction import Transaction __all__ = ['TaxTemplate', 'TaxRuleTemplate'] __metaclass__ = PoolMeta class TaxTemplate: __name__ = 'account.tax.template' @classmethod def __register__(cls, module_name): cursor = Transaction().cursor model_data = Table('ir_model_data') # Migration from 3.0: new tax rates if module_name == 'account_fr': for old_id, new_id in ( ('tva_vente_19_6', 'tva_vente_taux_normal'), ('tva_vente_7', 'tva_vente_taux_intermediaire'), ('tva_vente_intracommunautaire_19_6', 'tva_vente_intracommunautaire_taux_normal'), ('tva_vente_intracommunautaire_7', 'tva_vente_intracommunautaire_taux_intermediaire'), ('tva_achat_19_6', 'tva_achat_taux_normal'), ('tva_achat_7', 'tva_achat_taux_intermediaire'), ('tva_achat_intracommunautaire_19_6', 'tva_achat_intracommunautaire_taux_normal'), ): cursor.execute(*model_data.select(model_data.id, where=(model_data.fs_id == new_id) & (model_data.module == module_name))) if cursor.fetchone(): continue cursor.execute(*model_data.update( columns=[model_data.fs_id], values=[new_id], where=(model_data.fs_id == old_id) & (model_data.module == module_name))) super(TaxTemplate, cls).__register__(module_name) class TaxRuleTemplate: __name__ = 'account.tax.rule.template' @classmethod def __register__(cls, module_name): cursor = Transaction().cursor model_data = Table('ir_model_data') if module_name == 'account_fr': for old_id, new_id in ( ('tax_rule_ventes_intracommunautaires_19_6', 'tax_rule_ventes_intracommunautaires_taux_normal'), ('tax_rule_ventes_intracommunautaires_7', 'tax_rule_ventes_intracommunautaires_taux_intermediaire'), ): cursor.execute(*model_data.update( columns=[model_data.fs_id], values=[new_id], where=(model_data.fs_id == old_id) & (model_data.module == module_name))) super(TaxRuleTemplate, cls).__register__(module_name)
gpl-3.0
ivoanjo/phd-jaspexmls
contlib/src/contlib/ContinuationBenchmark1.java
1722
/* * contlib: JVM continuations on top of OpenJDK hotspot with custom patches * Copyright (C) 2015 Ivo Anjo <ivo.anjo@ist.utl.pt> * * This file is part of contlib. * * contlib 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. * * contlib 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 contlib. If not, see <http://www.gnu.org/licenses/>. */ package contlib; public class ContinuationBenchmark1 implements Runnable { private ContinuationBenchmark1() { } private int val = 0; private static final int RUNS = 10; private static final int MAXCOUNT = 1000000; public void run() { Continuation continuation = Continuation.capture(); if (val < MAXCOUNT) { val++; //if (val % 100000 == 0) System.out.println(val); Continuation.resume(continuation); } } public static void main(String[] args) throws InterruptedException { for (int i = 0; i < RUNS; i++) { long clockBefore = System.currentTimeMillis(); Continuation.runWithContinuationSupport(new ContinuationBenchmark1()); long clockAfter = System.currentTimeMillis(); System.out.println("Run #" + i + " took " + (clockAfter-clockBefore) + "ms, avg " + ((float)(clockAfter-clockBefore))/MAXCOUNT + "ms per iteration"); } //while (true) { Thread.sleep(1000); } } }
gpl-3.0
gaoxiangnumber1/Cpp-Primer-5th-Edition-Exercise-Solutions
CH01/1-16.cpp
209
#include <iostream> using std::cin; using std::cout; using std::endl; int main() { int sum = 0; for(int value = 0; cin >> value;) { sum += value; } cout << "The sum is " << sum << endl; return 0; }
gpl-3.0
dfhoughton/sleep_chart
chart.js
3470
function drawChart(data, id,opts) { // pull out some things of general interest // default options if ( opts == null ) { opts = { width: Math.round( data.length / 20 ), } } const {width,goal} = opts; if (goal == null) goal = 7; const c = document.getElementById(id), ctx = c.getContext('2d'); const margin = 40, chartWidth = c.width - 2 * margin, chartHeight = c.height - 2 * margin; var mx, avg = 0; for ( let v of data ) { avg += v; if ( mx == null || mx < v ) { mx = v; } } avg /= data.length; mx = Math.ceil(mx); const vwidth = chartHeight / mx; const hwidth = chartWidth / data.length; // paint canvas white ctx.fillStyle = '#fff'; ctx.fillRect(0,0,c.width, c.height); function drawHorizontalMarker(y, color, label) { ctx.beginPath(); let v = margin + ( mx - y ) * vwidth; ctx.moveTo(margin, v); ctx.fillStyle = ctx.strokeStyle = color; ctx.lineTo(margin + chartWidth, v); ctx.stroke(); ctx.font = "10px Arial"; ctx.textAlign = "right"; ctx.fillText(Math.round(y * 10)/10, margin-6, v); ctx.textAlign = "left"; ctx.fillText(label, c.width - margin + 6, v); } drawHorizontalMarker(avg, 'red', 'avg'); drawHorizontalMarker(goal, 'green', 'goal'); function drawAndLabelAxes() { ctx.beginPath(); ctx.strokeStyle = ctx.fillStyle = 'black'; ctx.font = "10px Arial"; // tics and labels let y = margin; for ( let i = 0; i < mx; i++ ) { ctx.moveTo( margin - 5, y); ctx.lineTo( margin, y); ctx.stroke(); y += vwidth; } // let x = margin + hwidth; // y = margin + chartHeight; // for ( let i = 0; i < data.length; i += 1 ) { // ctx.moveTo( x, y ); // ctx.lineTo( x, y + 5 ); // ctx.stroke(); // x += hwidth; // } // axes themselves ctx.strokeStyle = 'black'; ctx.moveTo(margin, margin); ctx.lineTo(margin, c.height - margin); ctx.stroke(); ctx.lineTo(c.width - margin, c.height - margin); ctx.stroke(); // labels ctx.textAlign = 'center'; ctx.font = "14px Arial"; // x axis ctx.fillText("Days",(c.width - margin)/2, c.height - margin + 26 ); // y axis ctx.rotate(-Math.PI/2); ctx.fillText("Hours",-c.height/2,margin - 15); ctx.rotate(Math.PI/2); // max and min ctx.textAlign = 'right'; ctx.font = '12 px Arial'; ctx.fillText("0", margin - 8, c.height - margin); ctx.fillText(mx, margin - 8, margin + 5); ctx.textAlign = 'center'; ctx.fillText(1, margin, c.height - margin + 16); ctx.fillText(data.length, margin + chartWidth, c.height - margin + 16); } drawAndLabelAxes(); var smoothed = smooth(data, c.width - 2 * margin, { width: width}); // *now* draw dots and whatnot const hstretcher = chartWidth / smoothed.length; ctx.strokeStyle = 'grey'; for ( let i = 0; i < smoothed.length; i++ ) { let s = smoothed[i][0]; x = margin + hstretcher * i, y = margin + chartHeight - s * vwidth; if ( i == 0 ) { ctx.moveTo( x, y ); } else { ctx.lineTo( x, y ); } } ctx.stroke(); // and the actual data points for ( let i = 0; i < smoothed.length; i++) { let r = smoothed[i][1]; if (r != null) { ctx.beginPath(); ctx.strokeStyle = ctx.fillStyle = 'blue'; x = margin + hstretcher * i, y = margin + chartHeight - r * vwidth; ctx.arc(x, y, 2, 0, Math.PI * 2); ctx.stroke(); } } }
gpl-3.0
Cr0s/JavaRA
src/cr0s/javara/render/map/InfantryPathfinder.java
1695
package cr0s.javara.render.map; import org.newdawn.slick.util.pathfinding.AStarHeuristic; import org.newdawn.slick.util.pathfinding.AStarPathFinder; import org.newdawn.slick.util.pathfinding.Mover; import org.newdawn.slick.util.pathfinding.Path; import org.newdawn.slick.util.pathfinding.TileBasedMap; import org.newdawn.slick.util.pathfinding.heuristics.ClosestHeuristic; import org.newdawn.slick.util.pathfinding.heuristics.ClosestSquaredHeuristic; import org.newdawn.slick.util.pathfinding.heuristics.ManhattanHeuristic; import cr0s.javara.entity.MobileEntity; import cr0s.javara.entity.infantry.EntityInfantry; import cr0s.javara.entity.vehicle.EntityVehicle; import cr0s.javara.render.World; /** * A* pathfinding class for vehicles. * @author Cr0s */ public class InfantryPathfinder { private AStarPathFinder pathfinder; private static final int MAX_SEARCH_DISTANCE = 512; public InfantryPathfinder(World world) { this.pathfinder = new AStarPathFinder(world, MAX_SEARCH_DISTANCE, true, new ClosestHeuristic()); } public Path findPathFromTo(EntityInfantry me, int goalX, int goalY) { MobileEntity m = (MobileEntity) me; return this.pathfinder.findPath(me, (int) m.getCellPos().getX(), (int) m.getCellPos().getY(), goalX, goalY); } } class InfantryHeuristic implements AStarHeuristic { public static final float ADJACENT_COST = 1f; public static final float DIAGONAL_COST = (float)Math.sqrt(2); @Override public float getCost(TileBasedMap ctx, Mover mover, int x, int y, int goalX, int goalY) { return Math.max(Math.abs(x - goalX), Math.abs(y - goalY)); } }
gpl-3.0
elefher/AlienVsWolfAndroidGame
src/com/kilobolt/AlienVsWolf/Ring.java
1426
package com.kilobolt.AlienVsWolf; import java.util.ArrayList; import com.kilobolt.framework.Image; import android.graphics.Rect; public class Ring { public int centerX, centerY; private boolean visible = true; public int points; private Background bg = GameScreen.getBg1(); private Robot robot = GameScreen.getRobot(); public Rect r = new Rect(0, 0, 0, 0); private int ringX, ringY, speedX; // Behavioral Methods public void update() { speedX = bg.getSpeedX() * 5; centerX += speedX; r.set(centerX, centerY, centerX /*+ 40*/, centerY /*+ 40*/); if (Rect.intersects(r, Robot.yellowRed)) { checkCollision(); } } public void setPoints(int points){ this.points = points; } public int getPoints(){ return this.points; } private void checkCollision() { if (Rect.intersects(r, Robot.rect) || Rect.intersects(r, Robot.rect2) || Rect.intersects(r, Robot.rect3) || Rect.intersects(r, Robot.rect4)) { visible = false; } } protected void destroy() { this.setCenterX(-200); } public boolean isVisible() { return visible; } public int getCenterX() { return centerX; } public int getCenterY() { return centerY; } public Background getBg() { return bg; } public void setCenterX(int centerX) { this.centerX = centerX; } public void setCenterY(int centerY) { this.centerY = centerY; } public void setBg(Background bg) { this.bg = bg; } }
gpl-3.0
dupengcheng/xxl-job
xxl-job-admin/src/main/java/com/xxl/job/admin/core/util/MailUtil.java
6889
package com.xxl.job.admin.core.util; import org.apache.commons.lang.ArrayUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.mail.javamail.JavaMailSender; import org.springframework.mail.javamail.JavaMailSenderImpl; import org.springframework.mail.javamail.MimeMessageHelper; import javax.mail.internet.MimeMessage; import javax.mail.internet.MimeUtility; import java.io.File; import java.util.Properties; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; /** * 邮件发送.Util * @author xuxueli 2016-3-12 15:06:20 */ public class MailUtil { private static Logger logger = LoggerFactory.getLogger(MailUtil.class); private static String host; private static String port; private static String username; private static String password; private static String sendFrom; private static String sendNick; static{ host = PropertiesUtil.getString("xxl.job.mail.host"); port = PropertiesUtil.getString("xxl.job.mail.port"); username = PropertiesUtil.getString("xxl.job.mail.username"); password = PropertiesUtil.getString("xxl.job.mail.password"); sendFrom = PropertiesUtil.getString("xxl.job.mail.sendFrom"); sendNick = PropertiesUtil.getString("xxl.job.mail.sendNick"); } /** <!-- spring mail sender --> <bean id="javaMailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl" scope="singleton" > <property name="host" value="${mail.host}" /> <!-- SMTP发送邮件的服务器的IP和端口 --> <property name="port" value="${mail.port}" /> <property name="username" value="${mail.username}" /> <!-- 登录SMTP邮件发送服务器的用户名和密码 --> <property name="password" value="${mail.password}" /> <property name="javaMailProperties"> <!-- 获得邮件会话属性,验证登录邮件服务器是否成功 --> <props> <prop key="mail.smtp.auth">true</prop> <prop key="prop">true</prop> <!-- <prop key="mail.smtp.timeout">25000</prop> --> </props> </property> </bean> */ /** * 发送邮件 (完整版)(结合Spring) * * //@param javaMailSender: 发送Bean * //@param sendFrom : 发送人邮箱 * //@param sendNick : 发送人昵称 * @param toAddress : 收件人邮箱 * @param mailSubject : 邮件主题 * @param mailBody : 邮件正文 * @param mailBodyIsHtml: 邮件正文格式,true:HTML格式;false:文本格式 * @param attachments : 附件 */ @SuppressWarnings("null") public static boolean sendMailSpring(String toAddress, String mailSubject, String mailBody, boolean mailBodyIsHtml,File[] attachments) { JavaMailSender javaMailSender = null;//ResourceBundle.getInstance().getJavaMailSender(); try { MimeMessage mimeMessage = javaMailSender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, ArrayUtils.isNotEmpty(attachments), "UTF-8"); // 设置utf-8或GBK编码,否则邮件会有乱码;multipart,true表示文件上传 helper.setFrom(sendFrom, sendNick); helper.setTo(toAddress); // 设置收件人抄送的名片和地址(相当于群发了) //helper.setCc(InternetAddress.parse(MimeUtility.encodeText("邮箱001") + " <@163.com>," + MimeUtility.encodeText("邮箱002") + " <@foxmail.com>")); helper.setSubject(mailSubject); helper.setText(mailBody, mailBodyIsHtml); // 添加附件 if (ArrayUtils.isNotEmpty(attachments)) { for (File file : attachments) { helper.addAttachment(MimeUtility.encodeText(file.getName()), file); } } // 群发 //MimeMessage[] mailMessages = { mimeMessage }; javaMailSender.send(mimeMessage); return true; } catch (Exception e) { logger.info("{}", e); } return false; } /** * 发送邮件 (完整版) (纯JavaMail) * * @param toAddress : 收件人邮箱 * @param mailSubject : 邮件主题 * @param mailBody : 邮件正文 * @param mailBodyIsHtml: 邮件正文格式,true:HTML格式;false:文本格式 * //@param inLineFile : 内嵌文件 * @param attachments : 附件 */ public static boolean sendMail (String toAddress, String mailSubject, String mailBody, boolean mailBodyIsHtml, File[] attachments){ try { // 创建邮件发送类 JavaMailSender (用于发送多元化邮件,包括附件,图片,html 等 ) JavaMailSenderImpl mailSender = new JavaMailSenderImpl(); mailSender.setHost(host); // 设置邮件服务主机 mailSender.setUsername(username); // 发送者邮箱的用户名 mailSender.setPassword(password); // 发送者邮箱的密码 //配置文件,用于实例化java.mail.session Properties pro = new Properties(); pro.put("mail.smtp.auth", "true"); // 登录SMTP服务器,需要获得授权 (网易163邮箱新近注册的邮箱均不能授权,测试 sohu 的邮箱可以获得授权) pro.put("mail.smtp.socketFactory.port", port); pro.put("mail.smtp.socketFactory.fallback", "false"); mailSender.setJavaMailProperties(pro); //创建多元化邮件 (创建 mimeMessage 帮助类,用于封装信息至 mimeMessage) MimeMessage mimeMessage = mailSender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, ArrayUtils.isNotEmpty(attachments), "UTF-8"); helper.setFrom(sendFrom, sendNick); helper.setTo(toAddress); helper.setSubject(mailSubject); helper.setText(mailBody, mailBodyIsHtml); // 添加内嵌文件,第1个参数为cid标识这个文件,第2个参数为资源 //helper.addInline(MimeUtility.encodeText(inLineFile.getName()), inLineFile); // 添加附件 if (ArrayUtils.isNotEmpty(attachments)) { for (File file : attachments) { helper.addAttachment(MimeUtility.encodeText(file.getName()), file); } } mailSender.send(mimeMessage); return true; } catch (Exception e) { logger.error(e.getMessage(), e); } return false; } static int total = 0; public static void main(String[] args) { ExecutorService exec = Executors.newCachedThreadPool(); for (int i = 0; i < 20; i++) { exec.execute(new Thread(new Runnable() { @Override public void run() { while(total < 10){ String mailBody = "<html><head><meta http-equiv=" + "Content-Type" + " content=" + "text/html; charset=gb2312" + "></head><body><h1>新书快递通知</h1>你的新书快递申请已推送新书,请到<a href=''>空间" + "</a>中查看</body></html>"; sendMail("ovono802302@163.com", "测试邮件", mailBody, false, null); System.out.println(total); total++; } } })); } } }
gpl-3.0
Deeg-Kim/Everything-Dojo
include/themedb/mcp_body.php
5389
<?php $data = $themedb->get_mcp_styles(); ?> <h2>Theme Moderator Control Panel</h2> <div id="popup-box"> <h2 id="popup-header"></h2> <span style="color: white;">Confirm your action in the box below.</span> <div id="popup-wrapper"> <div id="popup-inner"> <div id="popup-form"> Are you sure you want to <span id="replace"></span> this theme? <form action="/include/db-handler.php" method="post"> <input type="submit" name="submit" value="Confirm" style="font-size: 15px;" /> <input type="hidden" value="" name="id" id="replace-id" /> <input type="hidden" value="" name="mode" id="replace-form" /> </form> </div> </div> </div> </div> <div class="manage-item" id="manage-1"> <div class="option-title manage-header expanded" id="header-1"> <h4>Unapproved Themes (<?php echo count($data['unapproved']); ?>)</h4> <span class="collapsebutton"></span> </div> <div class="option-wrap"> <table class="manage-table"> <thead style="border-bottom: 1px black solid;"> <tr> <td>Theme</td> <td class="med-col">Author</td> <td class="small-col">Version</td> <td class="small-col">Stage</td> <td class="small-col">Approve</td> </tr> </thead> <tbody> <?php if (count($data['unapproved']) == 0) { ?> <tr> <td><b>No unapproved themes</b></td> <td>-</td> <td>-</td> <td>-</td> <td>-</td> </tr> <?php } else { for ($i = 0; $i < count($data['unapproved']); $i++) { $description = shorten_desc($data['unapproved'][$i]['description']); ?> <tr class="style"> <td onclick="document.location = '<?php echo URL_DATABASE; ?>?mode=view&view=style&id=<?php echo $data['unapproved'][$i]['id']; ?>'"><b><?php echo $data['unapproved'][$i]['name']; ?></b></td> <td onclick="document.location = '<?php echo URL_DATABASE; ?>?mode=view&view=style&id=<?php echo $data['unapproved'][$i]['id']; ?>'"><?php echo $data['unapproved'][$i]['author']; ?></td> <td onclick="document.location = '<?php echo URL_DATABASE; ?>?mode=view&view=style&id=<?php echo $data['unapproved'][$i]['id']; ?>'"><?php echo $data['unapproved'][$i]['version']; ?></td> <td onclick="document.location = '<?php echo URL_DATABASE; ?>?mode=view&view=style&id=<?php echo $data['unapproved'][$i]['id']; ?>'"><?php echo $data['unapproved'][$i]['stage']; ?></td> <td><a href="javascript:;" class="view" onclick="popup_options('approve', <?php echo $data['unapproved'][$i]['id']; ?>);"><img src="../../images/check.png" class="img-edit" /></a> <a href="javascript:;" class="view" onclick="popup_options('reject', <?php echo $data['unapproved'][$i]['id']; ?>);"><img src="../../images/reject.png" class="img-edit" /></a></td> </tr> <?php } } ?> </tbody> </table> </div> </div> <div class="manage-item" id="manage-2"> <div class="option-title manage-header collapsed" id="header-2"> <h4>Validate Requests (<?php echo count($data['validate_request']); ?>)</h4> <span class="collapsebutton"></span> </div> <div class="option-wrap"> <table class="manage-table"> <thead style="border-bottom: 1px black solid;"> <tr> <td>Theme</td> <td class="med-col">Author</td> <td class="small-col">Version</td> <td class="small-col">Stage</td> <td class="small-col">Validate</td> </tr> </thead> <tbody> <?php if (count($data['validate_request']) == 0) { ?> <tr> <td><b>No unapproved themes</b></td> <td>-</td> <td>-</td> <td>-</td> <td>-</td> </tr> <?php } else { for ($i = 0; $i < count($data['validate_request']); $i++) { $description = shorten_desc($data['validate_request'][$i]['validate_request']); ?> <tr class="style"> <td onclick="document.location = '<?php echo URL_DATABASE; ?>?mode=view&view=style&id=<?php echo $data['validate_request'][$i]['id']; ?>'"><b><?php echo $data['validate_request'][$i]['name']; ?></b></td> <td onclick="document.location = '<?php echo URL_DATABASE; ?>?mode=view&view=style&id=<?php echo $data['validate_request'][$i]['id']; ?>'"><?php echo $data['validate_request'][$i]['author']; ?></td> <td onclick="document.location = '<?php echo URL_DATABASE; ?>?mode=view&view=style&id=<?php echo $data['validate_request'][$i]['id']; ?>'"><?php echo $data['validate_request'][$i]['version']; ?></td> <td onclick="document.location = '<?php echo URL_DATABASE; ?>?mode=view&view=style&id=<?php echo $data['validate_request'][$i]['id']; ?>'"><?php echo $data['validate_request'][$i]['stage']; ?></td> <td><a href="javascript:;" class="view" onclick="popup_options('validate', <?php echo $data['validate_request'][$i]['id']; ?>);"><img src="../../images/check.png" class="img-edit" /></a> <a href="javascript:;" class="view" onclick="popup_options('reject', <?php echo $data['validate_request'][$i]['id']; ?>);"><img src="../../images/reject.png" class="img-edit" /></a></td> </tr> <?php } } ?> </tbody> </table> </div> </div>
gpl-3.0
irgsmirx/Utilities
src/main/java/com/ramforth/utilities/triggering/implementation/conditions/generic/ComparerCondition.java
1885
/* * Copyright (C) 2014 Tobias Ramforth * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.ramforth.utilities.triggering.implementation.conditions.generic; import com.ramforth.utilities.triggering.implementation.conditions.AbstractComparerCondition; import java.util.Comparator; //[Description("Bedingung, die erfüllt ist, wenn das Ergebnis der Compare(elementA, elementB)-Methode des übergebenen Comparers mit Wert der übergebenen comparisonValue übereinstimmt.")] //[Category("Common")] //[Serializable] public class ComparerCondition<T> extends AbstractComparerCondition<T> { private Comparator<T> comparer = null; public Comparator<T> getComparer() { return comparer; } public void setComparer(Comparator<T> value) { this.comparer = value; } @Override public boolean isMet() { return ( comparer != null ) && ( comparer.compare(elementA, elementB) == comparisonResult ); } @Override public String toString() { return String.format("{%1s} {%2s} {%3s}", elementA.toString(), comparer.toString(), elementB.toString()); } @Override public String getFormatString() { return "{elementA} {comparer} {elementB}"; } }
gpl-3.0
XapaJIaMnu/gLM
misc_testing/gpu_trie_test_binary_v2.cpp
1805
#include "lm_impl.hh" #include "memory_management.hh" #include "gpu_search_v2.hh" #include <sstream> #include <chrono> #include <ctime> #include <boost/tokenizer.hpp> int main(int argc, char* argv[]) { LM lm(argv[1]); //Initiate gpu search unsigned char * btree_trie_gpu = copyToGPUMemory(lm.trieByteArray.data(), lm.trieByteArray.size()); unsigned int * first_lvl_gpu = copyToGPUMemory(lm.first_lvl.data(), lm.first_lvl.size()); //input ngram std::string response; boost::char_separator<char> sep(" "); while (true) { getline(std::cin, response); if (response == "/end") { break; } std::vector<unsigned int> keys_to_query; boost::tokenizer<boost::char_separator<char> > tokens(response, sep); for (auto word : tokens) { keys_to_query.push_back(std::stoul(word, 0, 10)); } unsigned int num_keys = 1; //How many ngrams are we going to query unsigned int * gpuKeys = copyToGPUMemory(keys_to_query.data(), keys_to_query.size()); float * results; allocateGPUMem(num_keys, &results); searchWrapper(btree_trie_gpu, first_lvl_gpu, gpuKeys, num_keys, results, lm.metadata.btree_node_size, lm.metadata.max_ngram_order); //Copy back to host float * results_cpu = new float[num_keys]; copyToHostMemory(results, results_cpu, num_keys); std::cout << "Query result is: " << results_cpu[0] << std::endl; for (auto key : keys_to_query) { std::cout << lm.decode_map.find(key)->second << " "; } std::cout << std::endl; freeGPUMemory(gpuKeys); freeGPUMemory(results); delete[] results_cpu; } freeGPUMemory(btree_trie_gpu); freeGPUMemory(first_lvl_gpu); }
gpl-3.0
bridystone/baikal
vendor/sabre/dav/lib/DAV/Version.php
349
<?php namespace Sabre\DAV; /** * This class contains the SabreDAV version constants. * * @copyright Copyright (C) fruux GmbH (https://fruux.com/) * @author Evert Pot (http://evertpot.com/) * @license http://sabre.io/license/ Modified BSD License */ class Version { /** * Full version number */ const VERSION = '3.1.1'; }
gpl-3.0
B3Partners/brmo
bgt-loader/src/main/java/nl/b3p/brmo/util/http/HttpResponseWrapper.java
829
/* * Copyright (C) 2021 B3Partners B.V. * * SPDX-License-Identifier: MIT * */ package nl.b3p.brmo.util.http; import java.io.IOException; import java.io.InputStream; /** * A wrapper around a HTTP response to provide access to the response status, headers and body. * * @author Matthijs Laan */ public interface HttpResponseWrapper { /** * @return The response status code. * @throws IOException */ int getStatusCode() throws IOException; /** * @param header The name of the header value to return. Only single header values are expected. * @return */ String getHeader(String header); /** * The input stream for the response body. Closing this stream should release all resources for this request. */ InputStream getResponseBody() throws IOException; }
gpl-3.0
accross/softeng-py
teach/2.strings/variables.py
451
#variables.py - use of variables #andyp - lint=12 floater=3.14 vest="much muppetry" print (lint,floater, vest) lint = lint/5 floater=floater * 3 vest = vest + " in bash" print (lint,floater, vest) smallLint=lint oldFloater=floater lint=lint * 100 floater = int(floater/6) vest = vest + " " + str(smallLint) + str(oldFloater) print (lint,floater, vest) print ("Octal %o" %lint ,"Float %.3f" %floater) print ("Hex %x" %lint, "Octal %o" %lint)
gpl-3.0
neo22s/jaf
core/tests/h_test.php
2512
<?php class h_test extends Test { public function __construct() { } public function autoload_test() { spl_autoload_register('H::autoload'); //locate core file $hook = new Hook(); //locate vendor $seo = new phpSEO(); self::add_note('loaded a core file and a vendor'); //if there's no fail return TRUE; } /* public function load_file_test() { self::add_note('loaded file view.php'); return (H::load_file(CORE_PATH.'/view.php'))?TRUE:FALSE; }*/ public static function clean_request_test() { $_POST['bad'] = '<script>alert(\'asdasd\')</script>'; H::clean_request(); $res = P('bad'); self::add_note('clean bad var:'. $res); return ($res=="alert(\'asdasd\')")?TRUE:FALSE; } public static function nl2br_test() { $res= '---\r\n--here'; self::add_note('nltobr: '. $res); $res = H::nl2br($res); return ($res=='---<br />--here')?TRUE:FALSE; } public function friendly_url_test() { $res = H::friendly_url('helló there!'); self::add_note('helló there!='.$res); return ($res=='hello-there')? TRUE:FALSE; } public static function is_url_test() { self::add_note('http://open-classifieds.com'); return (H::is_URL('http://open-classifieds.com'))?TRUE:FALSE; } public static function is_callable_test() { self::add_note('H::end && P'); return (H::is_callable('H::end') && H::is_callable('P'))?TRUE:FALSE; } public function file_actions_test() { $file=__DIR__.'/file.txt'; self::add_note($file); H::fwrite($file,'some content here'); $res = H::fread($file); if ($res=='some content here') { //since the content is there now we delete and we test the remove resource H::remove_resource($file); return (H::fread($file)==FALSE)?TRUE:FALSE; } return FALSE; } public function get_extension_test() { self::add_note('some_file.txt'); return (H::get_extension('some_file.txt')=='txt')?TRUE:FALSE; } public function email_test() { self::add_note('hrkrvgyp@sharklasers.com'); return H::email('hrkrvgyp@sharklasers.com','jaf@localhost','Subject for JAF unit test '.date('Y-m-d H:i:s'),'Body test'); } }
gpl-3.0
jiongjionger/NeverLag
src/main/java/cn/jiongjionger/neverlag/utils/ChunkInfo.java
1482
package cn.jiongjionger.neverlag.utils; import org.bukkit.Chunk; public class ChunkInfo { private String world; private int chunkx; private int chunkz; public ChunkInfo(Chunk chunk) { this.world = chunk.getWorld().getName(); this.chunkx = chunk.getX(); this.chunkz = chunk.getZ(); } /** * 警告: 此构造器中的 x, z 参数代表着方块坐标, 而并非区块坐标. * * @param x 方块x坐标 * @param z 方块z坐标 */ public ChunkInfo(String world, int x, int z) { this.world = world; this.chunkx = x >> 4; this.chunkz = z >> 4; } @Override public boolean equals(Object orc) { if (this == orc) { return true; } if (orc == null) { return false; } if (getClass() != orc.getClass()) { return false; } ChunkInfo rc = (ChunkInfo) orc; return (this.world.equals(rc.getWorld())) && (this.chunkx == rc.chunkx) && (this.chunkz == rc.chunkz); } public int getChunkx() { return chunkx; } public int getChunkz() { return chunkz; } public String getWorld() { return world; } @Override public int hashCode() { return this.world.hashCode() ^ this.chunkx ^ this.chunkz; } public void setChunkx(int chunkx) { this.chunkx = chunkx; } public void setChunkz(int chunkz) { this.chunkz = chunkz; } public void setWorld(String world) { this.world = world; } @Override public String toString() { return String.format("ChunkInfo [world=%s, chunkx=%d, chunkz=%d]", world, chunkx, chunkz); } }
gpl-3.0
tudelft3d/matahn
matahn/database.py
1604
# This file is part of MATAHN. # MATAHN 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. # MATAHN 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 MATAHN. If not, see <http://www.gnu.org/licenses/>. # Copyright 2014 Ravi Peters, Hugo Ledoux #see http://flask.pocoo.org/docs/patterns/sqlalchemy/ from matahn import app from sqlalchemy import create_engine from sqlalchemy.orm import scoped_session, sessionmaker from sqlalchemy.ext.declarative import declarative_base engine = create_engine(app.config['SQLALCHEMY_DATABASE_URI'], convert_unicode=True) db_session = scoped_session(sessionmaker(autocommit=False, autoflush=False, bind=engine)) Base = declarative_base() Base.query = db_session.query_property() def init_db(): # import all modules here that might define models so that # they will be registered properly on the metadata. Otherwise # you will have to import them first before calling init_db() import matahn.models Base.metadata.create_all(bind=engine) def destroy_db(): import matahn.models Base.metadata.drop_all(bind=engine)
gpl-3.0
idega/is.idega.nest.rafverk
src/java/is/idega/nest/rafverk/bean/UpphafstilkynningRafverktoku.java
716
package is.idega.nest.rafverk.bean; import is.fmr.landskra.Fasteign; import is.idega.nest.rafverk.domain.Rafverktaka; import is.idega.nest.rafverk.domain.Rafverktaki; import is.idega.nest.rafverk.fmr.FMRLookupBean; import java.util.ArrayList; import java.util.List; public class UpphafstilkynningRafverktoku extends BaseBean { //List possibleFasteignir; Rafverktaka rafverktaka; public UpphafstilkynningRafverktoku(){ Rafverktaka verktaka = new Rafverktaka(); //verktaka.setRafverktaki(new Rafverktaki()); setRafverktaka(verktaka); } public Rafverktaka getRafverktaka() { return rafverktaka; } public void setRafverktaka(Rafverktaka verktaka) { this.rafverktaka = verktaka; } }
gpl-3.0
ethereum/solidity
libsolidity/codegen/ir/IRGenerator.cpp
39200
/* This file is part of solidity. solidity 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. solidity 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 solidity. If not, see <http://www.gnu.org/licenses/>. */ // SPDX-License-Identifier: GPL-3.0 /** * @author Alex Beregszaszi * @date 2017 * Component that translates Solidity code into Yul. */ #include <libsolidity/codegen/ir/Common.h> #include <libsolidity/codegen/ir/IRGenerator.h> #include <libsolidity/codegen/ir/IRGeneratorForStatements.h> #include <libsolidity/ast/AST.h> #include <libsolidity/ast/ASTVisitor.h> #include <libsolidity/codegen/ABIFunctions.h> #include <libsolidity/codegen/CompilerUtils.h> #include <libyul/AssemblyStack.h> #include <libyul/Utilities.h> #include <libsolutil/Algorithms.h> #include <libsolutil/CommonData.h> #include <libsolutil/StringUtils.h> #include <libsolutil/Whiskers.h> #include <liblangutil/SourceReferenceFormatter.h> #include <sstream> #include <variant> using namespace std; using namespace solidity; using namespace solidity::frontend; using namespace solidity::langutil; using namespace solidity::util; namespace { void verifyCallGraph( set<CallableDeclaration const*, ASTNode::CompareByID> const& _expectedCallables, set<FunctionDefinition const*> _generatedFunctions ) { for (auto const& expectedCallable: _expectedCallables) if (auto const* expectedFunction = dynamic_cast<FunctionDefinition const*>(expectedCallable)) { solAssert( _generatedFunctions.count(expectedFunction) == 1 || expectedFunction->isConstructor(), "No code generated for function " + expectedFunction->name() + " even though it is not a constructor." ); _generatedFunctions.erase(expectedFunction); } solAssert( _generatedFunctions.size() == 0, "Of the generated functions " + toString(_generatedFunctions.size()) + " are not in the call graph." ); } set<CallableDeclaration const*, ASTNode::CompareByID> collectReachableCallables( CallGraph const& _graph ) { set<CallableDeclaration const*, ASTNode::CompareByID> reachableCallables; for (CallGraph::Node const& reachableNode: _graph.edges | ranges::views::keys) if (holds_alternative<CallableDeclaration const*>(reachableNode)) reachableCallables.emplace(get<CallableDeclaration const*>(reachableNode)); return reachableCallables; } } pair<string, string> IRGenerator::run( ContractDefinition const& _contract, bytes const& _cborMetadata, map<ContractDefinition const*, string_view const> const& _otherYulSources ) { string const ir = yul::reindent(generate(_contract, _cborMetadata, _otherYulSources)); yul::AssemblyStack asmStack( m_evmVersion, yul::AssemblyStack::Language::StrictAssembly, m_optimiserSettings, m_context.debugInfoSelection() ); if (!asmStack.parseAndAnalyze("", ir)) { string errorMessage; for (auto const& error: asmStack.errors()) errorMessage += langutil::SourceReferenceFormatter::formatErrorInformation( *error, asmStack.charStream("") ); solAssert(false, ir + "\n\nInvalid IR generated:\n" + errorMessage + "\n"); } asmStack.optimize(); string warning = "/*=====================================================*\n" " * WARNING *\n" " * Solidity to Yul compilation is still EXPERIMENTAL *\n" " * It can result in LOSS OF FUNDS or worse *\n" " * !USE AT YOUR OWN RISK! *\n" " *=====================================================*/\n\n"; return {warning + ir, warning + asmStack.print(m_context.soliditySourceProvider())}; } string IRGenerator::generate( ContractDefinition const& _contract, bytes const& _cborMetadata, map<ContractDefinition const*, string_view const> const& _otherYulSources ) { auto subObjectSources = [&_otherYulSources](std::set<ContractDefinition const*, ASTNode::CompareByID> const& subObjects) -> string { std::string subObjectsSources; for (ContractDefinition const* subObject: subObjects) subObjectsSources += _otherYulSources.at(subObject); return subObjectsSources; }; auto formatUseSrcMap = [](IRGenerationContext const& _context) -> string { return joinHumanReadable( ranges::views::transform(_context.usedSourceNames(), [_context](string const& _sourceName) { return to_string(_context.sourceIndices().at(_sourceName)) + ":" + escapeAndQuoteString(_sourceName); }), ", " ); }; Whiskers t(R"( /// @use-src <useSrcMapCreation> object "<CreationObject>" { code { <sourceLocationCommentCreation> <memoryInitCreation> <callValueCheck> <?library> <!library> <?constructorHasParams> let <constructorParams> := <copyConstructorArguments>() </constructorHasParams> <constructor>(<constructorParams>) </library> <deploy> <functions> } /// @use-src <useSrcMapDeployed> object "<DeployedObject>" { code { <sourceLocationCommentDeployed> <memoryInitDeployed> <?library> let called_via_delegatecall := iszero(eq(loadimmutable("<library_address>"), address())) </library> <dispatch> <deployedFunctions> } <deployedSubObjects> data "<metadataName>" hex"<cborMetadata>" } <subObjects> } )"); resetContext(_contract, ExecutionContext::Creation); for (VariableDeclaration const* var: ContractType(_contract).immutableVariables()) m_context.registerImmutableVariable(*var); t("CreationObject", IRNames::creationObject(_contract)); t("sourceLocationCommentCreation", dispenseLocationComment(_contract)); t("library", _contract.isLibrary()); FunctionDefinition const* constructor = _contract.constructor(); t("callValueCheck", !constructor || !constructor->isPayable() ? callValueCheck() : ""); vector<string> constructorParams; if (constructor && !constructor->parameters().empty()) { for (size_t i = 0; i < CompilerUtils::sizeOnStack(constructor->parameters()); ++i) constructorParams.emplace_back(m_context.newYulVariable()); t( "copyConstructorArguments", m_utils.copyConstructorArgumentsToMemoryFunction(_contract, IRNames::creationObject(_contract)) ); } t("constructorParams", joinHumanReadable(constructorParams)); t("constructorHasParams", !constructorParams.empty()); t("constructor", IRNames::constructor(_contract)); t("deploy", deployCode(_contract)); generateConstructors(_contract); set<FunctionDefinition const*> creationFunctionList = generateQueuedFunctions(); InternalDispatchMap internalDispatchMap = generateInternalDispatchFunctions(_contract); t("functions", m_context.functionCollector().requestedFunctions()); t("subObjects", subObjectSources(m_context.subObjectsCreated())); // This has to be called only after all other code generation for the creation object is complete. bool creationInvolvesAssembly = m_context.inlineAssemblySeen(); t("memoryInitCreation", memoryInit(!creationInvolvesAssembly)); t("useSrcMapCreation", formatUseSrcMap(m_context)); resetContext(_contract, ExecutionContext::Deployed); // NOTE: Function pointers can be passed from creation code via storage variables. We need to // get all the functions they could point to into the dispatch functions even if they're never // referenced by name in the deployed code. m_context.initializeInternalDispatch(move(internalDispatchMap)); // Do not register immutables to avoid assignment. t("DeployedObject", IRNames::deployedObject(_contract)); t("sourceLocationCommentDeployed", dispenseLocationComment(_contract)); t("library_address", IRNames::libraryAddressImmutable()); t("dispatch", dispatchRoutine(_contract)); set<FunctionDefinition const*> deployedFunctionList = generateQueuedFunctions(); generateInternalDispatchFunctions(_contract); t("deployedFunctions", m_context.functionCollector().requestedFunctions()); t("deployedSubObjects", subObjectSources(m_context.subObjectsCreated())); t("metadataName", yul::Object::metadataName()); t("cborMetadata", toHex(_cborMetadata)); t("useSrcMapDeployed", formatUseSrcMap(m_context)); // This has to be called only after all other code generation for the deployed object is complete. bool deployedInvolvesAssembly = m_context.inlineAssemblySeen(); t("memoryInitDeployed", memoryInit(!deployedInvolvesAssembly)); solAssert(_contract.annotation().creationCallGraph->get() != nullptr, ""); solAssert(_contract.annotation().deployedCallGraph->get() != nullptr, ""); verifyCallGraph(collectReachableCallables(**_contract.annotation().creationCallGraph), move(creationFunctionList)); verifyCallGraph(collectReachableCallables(**_contract.annotation().deployedCallGraph), move(deployedFunctionList)); return t.render(); } string IRGenerator::generate(Block const& _block) { IRGeneratorForStatements generator(m_context, m_utils); generator.generate(_block); return generator.code(); } set<FunctionDefinition const*> IRGenerator::generateQueuedFunctions() { set<FunctionDefinition const*> functions; while (!m_context.functionGenerationQueueEmpty()) { FunctionDefinition const& functionDefinition = *m_context.dequeueFunctionForCodeGeneration(); functions.emplace(&functionDefinition); // NOTE: generateFunction() may modify function generation queue generateFunction(functionDefinition); } return functions; } InternalDispatchMap IRGenerator::generateInternalDispatchFunctions(ContractDefinition const& _contract) { solAssert( m_context.functionGenerationQueueEmpty(), "At this point all the enqueued functions should have been generated. " "Otherwise the dispatch may be incomplete." ); InternalDispatchMap internalDispatchMap = m_context.consumeInternalDispatchMap(); for (YulArity const& arity: internalDispatchMap | ranges::views::keys) { string funName = IRNames::internalDispatch(arity); m_context.functionCollector().createFunction(funName, [&]() { Whiskers templ(R"( <sourceLocationComment> function <functionName>(fun<?+in>, <in></+in>) <?+out>-> <out></+out> { switch fun <#cases> case <funID> { <?+out> <out> :=</+out> <name>(<in>) } </cases> default { <panic>() } } <sourceLocationComment> )"); templ("sourceLocationComment", dispenseLocationComment(_contract)); templ("functionName", funName); templ("panic", m_utils.panicFunction(PanicCode::InvalidInternalFunction)); templ("in", suffixedVariableNameList("in_", 0, arity.in)); templ("out", suffixedVariableNameList("out_", 0, arity.out)); vector<map<string, string>> cases; for (FunctionDefinition const* function: internalDispatchMap.at(arity)) { solAssert(function, ""); solAssert( YulArity::fromType(*TypeProvider::function(*function, FunctionType::Kind::Internal)) == arity, "A single dispatch function can only handle functions of one arity" ); solAssert(!function->isConstructor(), ""); // 0 is reserved for uninitialized function pointers solAssert(function->id() != 0, "Unexpected function ID: 0"); solAssert(m_context.functionCollector().contains(IRNames::function(*function)), ""); cases.emplace_back(map<string, string>{ {"funID", to_string(m_context.internalFunctionID(*function, true))}, {"name", IRNames::function(*function)} }); } templ("cases", move(cases)); return templ.render(); }); } solAssert(m_context.internalDispatchClean(), ""); solAssert( m_context.functionGenerationQueueEmpty(), "Internal dispatch generation must not add new functions to generation queue because they won't be proeessed." ); return internalDispatchMap; } string IRGenerator::generateFunction(FunctionDefinition const& _function) { string functionName = IRNames::function(_function); return m_context.functionCollector().createFunction(functionName, [&]() { m_context.resetLocalVariables(); Whiskers t(R"( <astIDComment><sourceLocationComment> function <functionName>(<params>)<?+retParams> -> <retParams></+retParams> { <retInit> <body> } <contractSourceLocationComment> )"); if (m_context.debugInfoSelection().astID) t("astIDComment", "/// @ast-id " + to_string(_function.id()) + "\n"); else t("astIDComment", ""); t("sourceLocationComment", dispenseLocationComment(_function)); t( "contractSourceLocationComment", dispenseLocationComment(m_context.mostDerivedContract()) ); t("functionName", functionName); vector<string> params; for (auto const& varDecl: _function.parameters()) params += m_context.addLocalVariable(*varDecl).stackSlots(); t("params", joinHumanReadable(params)); vector<string> retParams; string retInit; for (auto const& varDecl: _function.returnParameters()) { retParams += m_context.addLocalVariable(*varDecl).stackSlots(); retInit += generateInitialAssignment(*varDecl); } t("retParams", joinHumanReadable(retParams)); t("retInit", retInit); if (_function.modifiers().empty()) t("body", generate(_function.body())); else { for (size_t i = 0; i < _function.modifiers().size(); ++i) { ModifierInvocation const& modifier = *_function.modifiers().at(i); string next = i + 1 < _function.modifiers().size() ? IRNames::modifierInvocation(*_function.modifiers().at(i + 1)) : IRNames::functionWithModifierInner(_function); generateModifier(modifier, _function, next); } t("body", (retParams.empty() ? string{} : joinHumanReadable(retParams) + " := ") + IRNames::modifierInvocation(*_function.modifiers().at(0)) + "(" + joinHumanReadable(retParams + params) + ")" ); // Now generate the actual inner function. generateFunctionWithModifierInner(_function); } return t.render(); }); } string IRGenerator::generateModifier( ModifierInvocation const& _modifierInvocation, FunctionDefinition const& _function, string const& _nextFunction ) { string functionName = IRNames::modifierInvocation(_modifierInvocation); return m_context.functionCollector().createFunction(functionName, [&]() { m_context.resetLocalVariables(); Whiskers t(R"( <astIDComment><sourceLocationComment> function <functionName>(<params>)<?+retParams> -> <retParams></+retParams> { <assignRetParams> <evalArgs> <body> } <contractSourceLocationComment> )"); t("functionName", functionName); vector<string> retParamsIn; for (auto const& varDecl: _function.returnParameters()) retParamsIn += m_context.addLocalVariable(*varDecl).stackSlots(); vector<string> params = retParamsIn; for (auto const& varDecl: _function.parameters()) params += m_context.addLocalVariable(*varDecl).stackSlots(); t("params", joinHumanReadable(params)); vector<string> retParams; string assignRetParams; for (size_t i = 0; i < retParamsIn.size(); ++i) { retParams.emplace_back(m_context.newYulVariable()); assignRetParams += retParams.at(i) + " := " + retParamsIn.at(i) + "\n"; } t("retParams", joinHumanReadable(retParams)); t("assignRetParams", assignRetParams); ModifierDefinition const* modifier = dynamic_cast<ModifierDefinition const*>( _modifierInvocation.name().annotation().referencedDeclaration ); solAssert(modifier, ""); if (m_context.debugInfoSelection().astID) t("astIDComment", "/// @ast-id " + to_string(modifier->id()) + "\n"); else t("astIDComment", ""); t("sourceLocationComment", dispenseLocationComment(*modifier)); t( "contractSourceLocationComment", dispenseLocationComment(m_context.mostDerivedContract()) ); switch (*_modifierInvocation.name().annotation().requiredLookup) { case VirtualLookup::Virtual: modifier = &modifier->resolveVirtual(m_context.mostDerivedContract()); solAssert(modifier, ""); break; case VirtualLookup::Static: break; case VirtualLookup::Super: solAssert(false, ""); } solAssert( modifier->parameters().empty() == (!_modifierInvocation.arguments() || _modifierInvocation.arguments()->empty()), "" ); IRGeneratorForStatements expressionEvaluator(m_context, m_utils); if (_modifierInvocation.arguments()) for (size_t i = 0; i < _modifierInvocation.arguments()->size(); i++) { IRVariable argument = expressionEvaluator.evaluateExpression( *_modifierInvocation.arguments()->at(i), *modifier->parameters()[i]->annotation().type ); expressionEvaluator.define( m_context.addLocalVariable(*modifier->parameters()[i]), argument ); } t("evalArgs", expressionEvaluator.code()); IRGeneratorForStatements generator(m_context, m_utils, [&]() { string ret = joinHumanReadable(retParams); return (ret.empty() ? "" : ret + " := ") + _nextFunction + "(" + joinHumanReadable(params) + ")\n"; }); generator.generate(modifier->body()); t("body", generator.code()); return t.render(); }); } string IRGenerator::generateFunctionWithModifierInner(FunctionDefinition const& _function) { string functionName = IRNames::functionWithModifierInner(_function); return m_context.functionCollector().createFunction(functionName, [&]() { m_context.resetLocalVariables(); Whiskers t(R"( <sourceLocationComment> function <functionName>(<params>)<?+retParams> -> <retParams></+retParams> { <assignRetParams> <body> } <contractSourceLocationComment> )"); t("sourceLocationComment", dispenseLocationComment(_function)); t( "contractSourceLocationComment", dispenseLocationComment(m_context.mostDerivedContract()) ); t("functionName", functionName); vector<string> retParams; vector<string> retParamsIn; for (auto const& varDecl: _function.returnParameters()) retParams += m_context.addLocalVariable(*varDecl).stackSlots(); string assignRetParams; for (size_t i = 0; i < retParams.size(); ++i) { retParamsIn.emplace_back(m_context.newYulVariable()); assignRetParams += retParams.at(i) + " := " + retParamsIn.at(i) + "\n"; } vector<string> params = retParamsIn; for (auto const& varDecl: _function.parameters()) params += m_context.addLocalVariable(*varDecl).stackSlots(); t("params", joinHumanReadable(params)); t("retParams", joinHumanReadable(retParams)); t("assignRetParams", assignRetParams); t("body", generate(_function.body())); return t.render(); }); } string IRGenerator::generateGetter(VariableDeclaration const& _varDecl) { string functionName = IRNames::function(_varDecl); return m_context.functionCollector().createFunction(functionName, [&]() { Type const* type = _varDecl.annotation().type; solAssert(_varDecl.isStateVariable(), ""); FunctionType accessorType(_varDecl); TypePointers paramTypes = accessorType.parameterTypes(); if (_varDecl.immutable()) { solAssert(paramTypes.empty(), ""); solUnimplementedAssert(type->sizeOnStack() == 1); return Whiskers(R"( <astIDComment><sourceLocationComment> function <functionName>() -> rval { rval := loadimmutable("<id>") } <contractSourceLocationComment> )") ( "astIDComment", m_context.debugInfoSelection().astID ? "/// @ast-id " + to_string(_varDecl.id()) + "\n" : "" ) ("sourceLocationComment", dispenseLocationComment(_varDecl)) ( "contractSourceLocationComment", dispenseLocationComment(m_context.mostDerivedContract()) ) ("functionName", functionName) ("id", to_string(_varDecl.id())) .render(); } else if (_varDecl.isConstant()) { solAssert(paramTypes.empty(), ""); return Whiskers(R"( <astIDComment><sourceLocationComment> function <functionName>() -> <ret> { <ret> := <constantValueFunction>() } <contractSourceLocationComment> )") ( "astIDComment", m_context.debugInfoSelection().astID ? "/// @ast-id " + to_string(_varDecl.id()) + "\n" : "" ) ("sourceLocationComment", dispenseLocationComment(_varDecl)) ( "contractSourceLocationComment", dispenseLocationComment(m_context.mostDerivedContract()) ) ("functionName", functionName) ("constantValueFunction", IRGeneratorForStatements(m_context, m_utils).constantValueFunction(_varDecl)) ("ret", suffixedVariableNameList("ret_", 0, _varDecl.type()->sizeOnStack())) .render(); } string code; auto const& location = m_context.storageLocationOfStateVariable(_varDecl); code += Whiskers(R"( let slot := <slot> let offset := <offset> )") ("slot", location.first.str()) ("offset", to_string(location.second)) .render(); if (!paramTypes.empty()) solAssert( location.second == 0, "If there are parameters, we are dealing with structs or mappings and thus should have offset zero." ); // The code of an accessor is of the form `x[a][b][c]` (it is slightly more complicated // if the final type is a struct). // In each iteration of the loop below, we consume one parameter, perform an // index access, reassign the yul variable `slot` and move @a currentType further "down". // The initial value of @a currentType is only used if we skip the loop completely. Type const* currentType = _varDecl.annotation().type; vector<string> parameters; vector<string> returnVariables; for (size_t i = 0; i < paramTypes.size(); ++i) { MappingType const* mappingType = dynamic_cast<MappingType const*>(currentType); ArrayType const* arrayType = dynamic_cast<ArrayType const*>(currentType); solAssert(mappingType || arrayType, ""); vector<string> keys = IRVariable("key_" + to_string(i), mappingType ? *mappingType->keyType() : *TypeProvider::uint256() ).stackSlots(); parameters += keys; Whiskers templ(R"( <?array> if iszero(lt(<keys>, <length>(slot))) { revert(0, 0) } </array> slot<?array>, offset</array> := <indexAccess>(slot<?+keys>, <keys></+keys>) )"); templ( "indexAccess", mappingType ? m_utils.mappingIndexAccessFunction(*mappingType, *mappingType->keyType()) : m_utils.storageArrayIndexAccessFunction(*arrayType) ) ("array", arrayType != nullptr) ("keys", joinHumanReadable(keys)); if (arrayType) templ("length", m_utils.arrayLengthFunction(*arrayType)); code += templ.render(); currentType = mappingType ? mappingType->valueType() : arrayType->baseType(); } auto returnTypes = accessorType.returnParameterTypes(); solAssert(returnTypes.size() >= 1, ""); if (StructType const* structType = dynamic_cast<StructType const*>(currentType)) { solAssert(location.second == 0, ""); auto const& names = accessorType.returnParameterNames(); for (size_t i = 0; i < names.size(); ++i) { if (returnTypes[i]->category() == Type::Category::Mapping) continue; if ( auto const* arrayType = dynamic_cast<ArrayType const*>(returnTypes[i]); arrayType && !arrayType->isByteArrayOrString() ) continue; pair<u256, unsigned> const& offsets = structType->storageOffsetsOfMember(names[i]); vector<string> retVars = IRVariable("ret_" + to_string(returnVariables.size()), *returnTypes[i]).stackSlots(); returnVariables += retVars; code += Whiskers(R"( <ret> := <readStorage>(add(slot, <slotOffset>)) )") ("ret", joinHumanReadable(retVars)) ("readStorage", m_utils.readFromStorage(*returnTypes[i], offsets.second, true)) ("slotOffset", offsets.first.str()) .render(); } } else { solAssert(returnTypes.size() == 1, ""); auto const* arrayType = dynamic_cast<ArrayType const*>(returnTypes.front()); if (arrayType) solAssert(arrayType->isByteArrayOrString(), ""); vector<string> retVars = IRVariable("ret", *returnTypes.front()).stackSlots(); returnVariables += retVars; code += Whiskers(R"( <ret> := <readStorage>(slot, offset) )") ("ret", joinHumanReadable(retVars)) ("readStorage", m_utils.readFromStorageDynamic(*returnTypes.front(), true)) .render(); } return Whiskers(R"( <astIDComment><sourceLocationComment> function <functionName>(<params>) -> <retVariables> { <code> } <contractSourceLocationComment> )") ("functionName", functionName) ("params", joinHumanReadable(parameters)) ("retVariables", joinHumanReadable(returnVariables)) ("code", std::move(code)) ( "astIDComment", m_context.debugInfoSelection().astID ? "/// @ast-id " + to_string(_varDecl.id()) + "\n" : "" ) ("sourceLocationComment", dispenseLocationComment(_varDecl)) ( "contractSourceLocationComment", dispenseLocationComment(m_context.mostDerivedContract()) ) .render(); }); } string IRGenerator::generateInitialAssignment(VariableDeclaration const& _varDecl) { IRGeneratorForStatements generator(m_context, m_utils); generator.initializeLocalVar(_varDecl); return generator.code(); } pair<string, map<ContractDefinition const*, vector<string>>> IRGenerator::evaluateConstructorArguments( ContractDefinition const& _contract ) { struct InheritanceOrder { bool operator()(ContractDefinition const* _c1, ContractDefinition const* _c2) const { solAssert(contains(linearizedBaseContracts, _c1) && contains(linearizedBaseContracts, _c2), ""); auto it1 = find(linearizedBaseContracts.begin(), linearizedBaseContracts.end(), _c1); auto it2 = find(linearizedBaseContracts.begin(), linearizedBaseContracts.end(), _c2); return it1 < it2; } vector<ContractDefinition const*> const& linearizedBaseContracts; } inheritanceOrder{_contract.annotation().linearizedBaseContracts}; map<ContractDefinition const*, vector<string>> constructorParams; map<ContractDefinition const*, std::vector<ASTPointer<Expression>>const *, InheritanceOrder> baseConstructorArguments(inheritanceOrder); for (ASTPointer<InheritanceSpecifier> const& base: _contract.baseContracts()) if (FunctionDefinition const* baseConstructor = dynamic_cast<ContractDefinition const*>( base->name().annotation().referencedDeclaration )->constructor(); baseConstructor && base->arguments()) solAssert(baseConstructorArguments.emplace( dynamic_cast<ContractDefinition const*>(baseConstructor->scope()), base->arguments() ).second, ""); if (FunctionDefinition const* constructor = _contract.constructor()) for (ASTPointer<ModifierInvocation> const& modifier: constructor->modifiers()) if (auto const* baseContract = dynamic_cast<ContractDefinition const*>( modifier->name().annotation().referencedDeclaration )) if ( FunctionDefinition const* baseConstructor = baseContract->constructor(); baseConstructor && modifier->arguments() ) solAssert(baseConstructorArguments.emplace( dynamic_cast<ContractDefinition const*>(baseConstructor->scope()), modifier->arguments() ).second, ""); IRGeneratorForStatements generator{m_context, m_utils}; for (auto&& [baseContract, arguments]: baseConstructorArguments) { solAssert(baseContract && arguments, ""); if (baseContract->constructor() && !arguments->empty()) { vector<string> params; for (size_t i = 0; i < arguments->size(); ++i) params += generator.evaluateExpression( *(arguments->at(i)), *(baseContract->constructor()->parameters()[i]->type()) ).stackSlots(); constructorParams[baseContract] = std::move(params); } } return {generator.code(), constructorParams}; } string IRGenerator::initStateVariables(ContractDefinition const& _contract) { IRGeneratorForStatements generator{m_context, m_utils}; for (VariableDeclaration const* variable: _contract.stateVariables()) if (!variable->isConstant()) generator.initializeStateVar(*variable); return generator.code(); } void IRGenerator::generateConstructors(ContractDefinition const& _contract) { auto listAllParams = [&](map<ContractDefinition const*, vector<string>> const& baseParams) -> vector<string> { vector<string> params; for (ContractDefinition const* contract: _contract.annotation().linearizedBaseContracts) if (baseParams.count(contract)) params += baseParams.at(contract); return params; }; map<ContractDefinition const*, vector<string>> baseConstructorParams; for (size_t i = 0; i < _contract.annotation().linearizedBaseContracts.size(); ++i) { ContractDefinition const* contract = _contract.annotation().linearizedBaseContracts[i]; baseConstructorParams.erase(contract); m_context.resetLocalVariables(); m_context.functionCollector().createFunction(IRNames::constructor(*contract), [&]() { Whiskers t(R"( <astIDComment><sourceLocationComment> function <functionName>(<params><comma><baseParams>) { <evalBaseArguments> <sourceLocationComment> <?hasNextConstructor> <nextConstructor>(<nextParams>) </hasNextConstructor> <initStateVariables> <userDefinedConstructorBody> } <contractSourceLocationComment> )"); vector<string> params; if (contract->constructor()) for (ASTPointer<VariableDeclaration> const& varDecl: contract->constructor()->parameters()) params += m_context.addLocalVariable(*varDecl).stackSlots(); if (m_context.debugInfoSelection().astID && contract->constructor()) t("astIDComment", "/// @ast-id " + to_string(contract->constructor()->id()) + "\n"); else t("astIDComment", ""); t("sourceLocationComment", dispenseLocationComment( contract->constructor() ? dynamic_cast<ASTNode const&>(*contract->constructor()) : dynamic_cast<ASTNode const&>(*contract) )); t( "contractSourceLocationComment", dispenseLocationComment(m_context.mostDerivedContract()) ); t("params", joinHumanReadable(params)); vector<string> baseParams = listAllParams(baseConstructorParams); t("baseParams", joinHumanReadable(baseParams)); t("comma", !params.empty() && !baseParams.empty() ? ", " : ""); t("functionName", IRNames::constructor(*contract)); pair<string, map<ContractDefinition const*, vector<string>>> evaluatedArgs = evaluateConstructorArguments(*contract); baseConstructorParams.insert(evaluatedArgs.second.begin(), evaluatedArgs.second.end()); t("evalBaseArguments", evaluatedArgs.first); if (i < _contract.annotation().linearizedBaseContracts.size() - 1) { t("hasNextConstructor", true); ContractDefinition const* nextContract = _contract.annotation().linearizedBaseContracts[i + 1]; t("nextConstructor", IRNames::constructor(*nextContract)); t("nextParams", joinHumanReadable(listAllParams(baseConstructorParams))); } else t("hasNextConstructor", false); t("initStateVariables", initStateVariables(*contract)); string body; if (FunctionDefinition const* constructor = contract->constructor()) { vector<ModifierInvocation*> realModifiers; for (auto const& modifierInvocation: constructor->modifiers()) // Filter out the base constructor calls if (dynamic_cast<ModifierDefinition const*>(modifierInvocation->name().annotation().referencedDeclaration)) realModifiers.emplace_back(modifierInvocation.get()); if (realModifiers.empty()) body = generate(constructor->body()); else { for (size_t i = 0; i < realModifiers.size(); ++i) { ModifierInvocation const& modifier = *realModifiers.at(i); string next = i + 1 < realModifiers.size() ? IRNames::modifierInvocation(*realModifiers.at(i + 1)) : IRNames::functionWithModifierInner(*constructor); generateModifier(modifier, *constructor, next); } body = IRNames::modifierInvocation(*realModifiers.at(0)) + "(" + joinHumanReadable(params) + ")"; // Now generate the actual inner function. generateFunctionWithModifierInner(*constructor); } } t("userDefinedConstructorBody", move(body)); return t.render(); }); } } string IRGenerator::deployCode(ContractDefinition const& _contract) { Whiskers t(R"X( let <codeOffset> := <allocateUnbounded>() codecopy(<codeOffset>, dataoffset("<object>"), datasize("<object>")) <#immutables> setimmutable(<codeOffset>, "<immutableName>", <value>) </immutables> return(<codeOffset>, datasize("<object>")) )X"); t("allocateUnbounded", m_utils.allocateUnboundedFunction()); t("codeOffset", m_context.newYulVariable()); t("object", IRNames::deployedObject(_contract)); vector<map<string, string>> immutables; if (_contract.isLibrary()) { solAssert(ContractType(_contract).immutableVariables().empty(), ""); immutables.emplace_back(map<string, string>{ {"immutableName"s, IRNames::libraryAddressImmutable()}, {"value"s, "address()"} }); } else for (VariableDeclaration const* immutable: ContractType(_contract).immutableVariables()) { solUnimplementedAssert(immutable->type()->isValueType()); solUnimplementedAssert(immutable->type()->sizeOnStack() == 1); immutables.emplace_back(map<string, string>{ {"immutableName"s, to_string(immutable->id())}, {"value"s, "mload(" + to_string(m_context.immutableMemoryOffset(*immutable)) + ")"} }); } t("immutables", std::move(immutables)); return t.render(); } string IRGenerator::callValueCheck() { return "if callvalue() { " + m_utils.revertReasonIfDebugFunction("Ether sent to non-payable function") + "() }"; } string IRGenerator::dispatchRoutine(ContractDefinition const& _contract) { Whiskers t(R"X( <?+cases>if iszero(lt(calldatasize(), 4)) { let selector := <shr224>(calldataload(0)) switch selector <#cases> case <functionSelector> { // <functionName> <delegatecallCheck> <callValueCheck> <?+params>let <params> := </+params> <abiDecode>(4, calldatasize()) <?+retParams>let <retParams> := </+retParams> <function>(<params>) let memPos := <allocateUnbounded>() let memEnd := <abiEncode>(memPos <?+retParams>,</+retParams> <retParams>) return(memPos, sub(memEnd, memPos)) } </cases> default {} }</+cases> <?+receiveEther>if iszero(calldatasize()) { <receiveEther> }</+receiveEther> <fallback> )X"); t("shr224", m_utils.shiftRightFunction(224)); vector<map<string, string>> functions; for (auto const& function: _contract.interfaceFunctions()) { functions.emplace_back(); map<string, string>& templ = functions.back(); templ["functionSelector"] = "0x" + function.first.hex(); FunctionTypePointer const& type = function.second; templ["functionName"] = type->externalSignature(); string delegatecallCheck; if (_contract.isLibrary()) { solAssert(!type->isPayable(), ""); if (type->stateMutability() > StateMutability::View) // If the function is not a view function and is called without DELEGATECALL, // we revert. delegatecallCheck = "if iszero(called_via_delegatecall) { " + m_utils.revertReasonIfDebugFunction("Non-view function of library called without DELEGATECALL") + "() }"; } templ["delegatecallCheck"] = delegatecallCheck; templ["callValueCheck"] = (type->isPayable() || _contract.isLibrary()) ? "" : callValueCheck(); unsigned paramVars = make_shared<TupleType>(type->parameterTypes())->sizeOnStack(); unsigned retVars = make_shared<TupleType>(type->returnParameterTypes())->sizeOnStack(); ABIFunctions abiFunctions(m_evmVersion, m_context.revertStrings(), m_context.functionCollector()); templ["abiDecode"] = abiFunctions.tupleDecoder(type->parameterTypes()); templ["params"] = suffixedVariableNameList("param_", 0, paramVars); templ["retParams"] = suffixedVariableNameList("ret_", 0, retVars); if (FunctionDefinition const* funDef = dynamic_cast<FunctionDefinition const*>(&type->declaration())) templ["function"] = m_context.enqueueFunctionForCodeGeneration(*funDef); else if (VariableDeclaration const* varDecl = dynamic_cast<VariableDeclaration const*>(&type->declaration())) templ["function"] = generateGetter(*varDecl); else solAssert(false, "Unexpected declaration for function!"); templ["allocateUnbounded"] = m_utils.allocateUnboundedFunction(); templ["abiEncode"] = abiFunctions.tupleEncoder(type->returnParameterTypes(), type->returnParameterTypes(), _contract.isLibrary()); } t("cases", functions); FunctionDefinition const* etherReceiver = _contract.receiveFunction(); if (etherReceiver) { solAssert(!_contract.isLibrary(), ""); t("receiveEther", m_context.enqueueFunctionForCodeGeneration(*etherReceiver) + "() stop()"); } else t("receiveEther", ""); if (FunctionDefinition const* fallback = _contract.fallbackFunction()) { solAssert(!_contract.isLibrary(), ""); string fallbackCode; if (!fallback->isPayable()) fallbackCode += callValueCheck() + "\n"; if (fallback->parameters().empty()) fallbackCode += m_context.enqueueFunctionForCodeGeneration(*fallback) + "() stop()"; else { solAssert(fallback->parameters().size() == 1 && fallback->returnParameters().size() == 1, ""); fallbackCode += "let retval := " + m_context.enqueueFunctionForCodeGeneration(*fallback) + "(0, calldatasize())\n"; fallbackCode += "return(add(retval, 0x20), mload(retval))\n"; } t("fallback", fallbackCode); } else t("fallback", ( etherReceiver ? m_utils.revertReasonIfDebugFunction("Unknown signature and no fallback defined") : m_utils.revertReasonIfDebugFunction("Contract does not have fallback nor receive functions") ) + "()"); return t.render(); } string IRGenerator::memoryInit(bool _useMemoryGuard) { // This function should be called at the beginning of the EVM call frame // and thus can assume all memory to be zero, including the contents of // the "zero memory area" (the position CompilerUtils::zeroPointer points to). return Whiskers{ _useMemoryGuard ? "mstore(<memPtr>, memoryguard(<freeMemoryStart>))" : "mstore(<memPtr>, <freeMemoryStart>)" } ("memPtr", to_string(CompilerUtils::freeMemoryPointer)) ( "freeMemoryStart", to_string(CompilerUtils::generalPurposeMemoryStart + m_context.reservedMemory()) ).render(); } void IRGenerator::resetContext(ContractDefinition const& _contract, ExecutionContext _context) { solAssert( m_context.functionGenerationQueueEmpty(), "Reset function generation queue while it still had functions." ); solAssert( m_context.functionCollector().requestedFunctions().empty(), "Reset context while it still had functions." ); solAssert( m_context.internalDispatchClean(), "Reset internal dispatch map without consuming it." ); IRGenerationContext newContext( m_evmVersion, _context, m_context.revertStrings(), m_optimiserSettings, m_context.sourceIndices(), m_context.debugInfoSelection(), m_context.soliditySourceProvider() ); newContext.copyFunctionIDsFrom(m_context); m_context = move(newContext); m_context.setMostDerivedContract(_contract); for (auto const& var: ContractType(_contract).stateVariables()) m_context.addStateVariable(*get<0>(var), get<1>(var), get<2>(var)); } string IRGenerator::dispenseLocationComment(ASTNode const& _node) { return ::dispenseLocationComment(_node, m_context); }
gpl-3.0
gagallo7/P4S
SPOJ/Trigraphs/trigraphs4.cpp
2527
/* * ===================================================================================== * * Filename: trigraphs.cpp * * Description: * * Version: 1.0 * Created: 12/09/2014 07:30:28 PM * Reiision: none * Compiler: gcc * * Author: Guilherme Alcarde Gallo (), * Organization: UNICAMP * * ===================================================================================== */ #include <iostream> #include <cstdio> #include <vector> using namespace std; typedef pair < int, int > ii; class graph { public: graph (size_t N) { list = vector < vector < long long int > > (N); } vector < vector < long long int > > list; void add ( int i, long long int weight ) { list [ i ].push_back ( weight ); } /* void print () { for ( auto& a : list ) { for ( auto& b : a ) { cout << b.second << " "; } cout << endl; } } */ }; int main () { int N; int testNumber = 0; cin >> N; while ( N ) { ++testNumber; vector < long long int > A (3); vector < long long int > A2 (3); //cin >> A[0] >> A[1] >> A[2]; scanf ( " %lli %lli %lli", &A[0], &A[1], &A[2] ); A[0] = A[1]; A[2] += A[1]; for ( int i = 1; i < N; ++i ) { for ( int j = 0; j < 3; ++j ) { A2 [j] = A [j]; } for ( int j = 0; j < 3; ++j ) { long long int w; //cin >> w; scanf ( " %lli", &w ); if ( j == 0 ) { w += min ( A2[0], A2[1] ); } else if ( j == 1 ) { const long long int w1 = min ( A2[0], A2[1] ); const long long int w2 = min ( A2[2], A[0] ); w += min ( w1, w2 ); } else { w += min ( A2[2], min ( A[1], A2[1] ) ); } A[j] = w; //cout << w << " "; } //cout << endl; } //cout << testNumber << ". " << A[1] << "\n"; printf ( "%d. %lli\n", testNumber, A[1] ); cin >> N; } return 0; }
gpl-3.0
ricecakesoftware/CommunityMedicalLink
ricecakesoftware.communitymedicallink.hl7/src/org/hl7/v3/KutchinHan.java
1172
package org.hl7.v3; import javax.xml.bind.annotation.XmlEnum; import javax.xml.bind.annotation.XmlEnumValue; import javax.xml.bind.annotation.XmlType; /** * <p>KutchinHanのJavaクラス。 * * <p>次のスキーマ・フラグメントは、このクラス内に含まれる予期されるコンテンツを指定します。 * <p> * <pre> * &lt;simpleType name="KutchinHan"> * &lt;restriction base="{urn:hl7-org:v3}cs"> * &lt;enumeration value="x-HAA"/> * &lt;enumeration value="x-KUC"/> * &lt;/restriction> * &lt;/simpleType> * </pre> * */ @XmlType(name = "KutchinHan") @XmlEnum public enum KutchinHan { @XmlEnumValue("x-HAA") X_HAA("x-HAA"), @XmlEnumValue("x-KUC") X_KUC("x-KUC"); private final String value; KutchinHan(String v) { value = v; } public String value() { return value; } public static KutchinHan fromValue(String v) { for (KutchinHan c: KutchinHan.values()) { if (c.value.equals(v)) { return c; } } throw new IllegalArgumentException(v); } }
gpl-3.0
pezhmanEX/beyond-self-bot
bot/bot.lua
13723
tdcli = dofile('./tg/tdcli.lua') serpent = (loadfile "./libs/serpent.lua")() feedparser = (loadfile "./libs/feedparser.lua")() require('./bot/utils') URL = require "socket.url" http = require "socket.http" https = require "ssl.https" ltn12 = require "ltn12" json = (loadfile "./libs/JSON.lua")() mimetype = (loadfile "./libs/mimetype.lua")() redis = (loadfile "./libs/redis.lua")() JSON = (loadfile "./libs/dkjson.lua")() local lgi = require ('lgi') local notify = lgi.require('Notify') notify.init ("Telegram updates") chats = {} function do_notify (user, msg) local n = notify.Notification.new(user, msg) n:show () end function dl_cb (arg, data) -- vardump(data) end function vardump(value) print(serpent.block(value, {comment=false})) end function load_data(filename) local f = io.open(filename) if not f then return {} end local s = f:read('*all') f:close() local data = JSON.decode(s) return data end function save_data(filename, data) local s = JSON.encode(data) local f = io.open(filename, 'w') f:write(s) f:close() end function match_plugins(msg) for name, plugin in pairs(plugins) do match_plugin(plugin, name, msg) end end function save_self( ) serialize_to_file(_self, './data/self.lua') print ('saved self into ./data/self.lua') end function create_self( ) self = { names = { "solid", "سلید", "سولید", "سعید", "saeed", "saeid" }, answers = { "وات؟ :/", "بلی؟", "بفرما", "بوگوی :|", "جونم؟", "جونز", "ژون؟ :/" }, } serialize_to_file(self, './data/self.lua') print('saved self into ./data/self.lua') end function load_self( ) local f = io.open('./data/self.lua', "r") -- If self.lua doesn't exist if not f then print ("Created new self file: data/self.lua") create_self() else f:close() end local self = loadfile ("./data/self.lua")() for k, v in pairs(self.names) do --print("self names : " ..v) end return self end function save_config( ) serialize_to_file(_config, './data/config.lua') print ('saved config into ./data/config.lua') end function create_config( ) -- A simple config with basic plugins and ourselves as privileged user config = { enabled_plugins = { "self-manager", "groupmanager", "plugins", "self", "tools", "fun" }, sudo_users = {157059515}, admins = {}, disabled_channels = {}, moderation = {data = './data/moderation.json'}, info_text = [[ ]], } serialize_to_file(config, './data/config.lua') print ('saved config into config.lua') end -- Returns the config from config.lua file. -- If file doesn't exist, create it. function load_config( ) local f = io.open('./data/config.lua', "r") -- If config.lua doesn't exist if not f then print ("Created new config file: ./data/config.lua") create_config() else f:close() end local config = loadfile ("./data/config.lua")() for v,user in pairs(config.sudo_users) do print("Allowed user: " ..user) end return config end plugins = {} _config = load_config() _self = load_self() function load_plugins() local config = loadfile ("./data/config.lua")() for k, v in pairs(config.enabled_plugins) do print("Loading Plugins", v) local ok, err = pcall(function() local t = loadfile("plugins/"..v..'.lua')() plugins[v] = t end) if not ok then print('\27[31mError loading plugins '..v..'\27[39m') print(tostring(io.popen("lua plugins/"..v..".lua"):read('*all'))) print('\27[31m'..err..'\27[39m') end end end local function is_channel_disabled( receiver ) if not _config.disabled_channels then return false end if _config.disabled_channels[receiver] == nil then return false end return _config.disabled_channels[receiver] end function msg_valid(msg) if msg.date_ < os.time() - 60 then print('\27[36mNot valid: old msg\27[39m') return false end if is_channel_disabled(msg.chat_id_) then print('\27[36m➣Self Is Off :/\27[39m') return false end return true end function match_pattern(pattern, text, lower_case) if text then local matches = {} if lower_case then matches = { string.match(text:lower(), pattern) } else matches = { string.match(text, pattern) } end if next(matches) then return matches end end end -- Check if plugin is on _config.disabled_plugin_on_chat table local function is_plugin_disabled_on_chat(plugin_name, receiver) local disabled_chats = _config.disabled_plugin_on_chat -- Table exists and chat has disabled plugins if disabled_chats and disabled_chats[receiver] then -- Checks if plugin is disabled on this chat for disabled_plugin,disabled in pairs(disabled_chats[receiver]) do if disabled_plugin == plugin_name and disabled then local warning = '_Plugin_ *'..check_markdown(disabled_plugin)..'* _is disabled on this chat_' print(warning) tdcli.sendMessage(receiver, "", 0, warning, 0, "md") return true end end end return false end function match_plugin(plugin, plugin_name, msg) if plugin.pre_process then --If plugin is for privileged users only local result = plugin.pre_process(msg) if result then print("pre process: ", plugin_name) -- tdcli.sendMessage(msg.chat_id_, "", 0, result, 0, "md") end end for k, pattern in pairs(plugin.patterns) do matches = match_pattern(pattern, msg.text or msg.media.caption) if matches then if is_plugin_disabled_on_chat(plugin_name, msg.chat_id_) then return nil end print("Message matches: ", pattern..' | Plugin: '..plugin_name) if plugin.run then if not warns_user_not_allowed(plugin, msg) then local result = plugin.run(msg, matches) if result then tdcli.sendMessage(msg.chat_id_, msg.id_, 0, result, 0, "md") end end end return end end end _config = load_config() load_plugins() _self = load_self() function var_cb(msg, data) -------------Get Var------------ bot = {} msg.to = {} msg.from = {} msg.media = {} msg.id = msg.id_ msg.to.type = gp_type(data.chat_id_) if data.content_.caption_ then msg.media.caption = data.content_.caption_ end if data.reply_to_message_id_ ~= 0 then msg.reply_id = data.reply_to_message_id_ else msg.reply_id = false end function get_gp(arg, data) if gp_type(msg.chat_id_) == "channel" or gp_type(msg.chat_id_) == "chat" then msg.to.id = msg.chat_id_ msg.to.title = data.title_ else msg.to.id = msg.chat_id_ msg.to.title = false end end tdcli_function ({ ID = "GetChat", chat_id_ = data.chat_id_ }, get_gp, nil) function botifo_cb(arg, data) bot.id = data.id_ our_id = data.id_ if data.username_ then bot.username = data.username_ else bot.username = false end if data.first_name_ then bot.first_name = data.first_name_ end if data.last_name_ then bot.last_name = data.last_name_ else bot.last_name = false end if data.first_name_ and data.last_name_ then bot.print_name = data.first_name_..' '..data.last_name_ else bot.print_name = data.first_name_ end if data.phone_number_ then bot.phone = data.phone_number_ else bot.phone = false end end tdcli_function({ ID = 'GetMe'}, botifo_cb, {chat_id=msg.chat_id_}) function get_user(arg, data) msg.from.id = data.id_ if data.username_ then msg.from.username = data.username_ else msg.from.username = false end if data.first_name_ then msg.from.first_name = data.first_name_ end if data.last_name_ then msg.from.last_name = data.last_name_ else msg.from.last_name = false end if data.first_name_ and data.last_name_ then msg.from.print_name = data.first_name_..' '..data.last_name_ else msg.from.print_name = data.first_name_ end if data.phone_number_ then msg.from.phone = data.phone_number_ else msg.from.phone = false end match_plugins(msg) end tdcli_function ({ ID = "GetUser", user_id_ = data.sender_user_id_ }, get_user, nil) -------------End------------- -- return msg end function whoami() local usr = io.popen("id -un"):read('*a') usr = string.gsub(usr, '^%s+', '') usr = string.gsub(usr, '%s+$', '') usr = string.gsub(usr, '[\n\r]+', ' ') if usr:match("^root$") then tcpath = '/root/.telegram-cli' elseif not usr:match("^root$") then tcpath = '/home/'..usr..'/.telegram-cli' end end function file_cb(msg) if msg.content_.ID == "MessagePhoto" then photo_id = '' local function get_cb(arg, data) photo_id = data.content_.photo_.sizes_[2].photo_.id_ tdcli.downloadFile(photo_id, dl_cb, nil) end tdcli_function ({ ID = "GetMessage", chat_id_ = msg.chat_id_, message_id_ = msg.id_ }, get_cb, nil) elseif msg.content_.ID == "MessageVideo" then video_id = '' local function get_cb(arg, data) video_id = data.content_.video_.video_.id_ tdcli.downloadFile(video_id, dl_cb, nil) end tdcli_function ({ ID = "GetMessage", chat_id_ = msg.chat_id_, message_id_ = msg.id_ }, get_cb, nil) elseif msg.content_.ID == "MessageAnimation" then anim_id, anim_name = '', '' local function get_cb(arg, data) anim_id = data.content_.animation_.animation_.id_ anim_name = data.content_.animation_.file_name_ tdcli.downloadFile(anim_id, dl_cb, nil) end tdcli_function ({ ID = "GetMessage", chat_id_ = msg.chat_id_, message_id_ = msg.id_ }, get_cb, nil) elseif msg.content_.ID == "MessageVoice" then voice_id = '' local function get_cb(arg, data) voice_id = data.content_.voice_.voice_.id_ tdcli.downloadFile(voice_id, dl_cb, nil) end tdcli_function ({ ID = "GetMessage", chat_id_ = msg.chat_id_, message_id_ = msg.id_ }, get_cb, nil) elseif msg.content_.ID == "MessageAudio" then audio_id, audio_name, audio_title = '', '', '' local function get_cb(arg, data) audio_id = data.content_.audio_.audio_.id_ audio_name = data.content_.audio_.file_name_ audio_title = data.content_.audio_.title_ tdcli.downloadFile(audio_id, dl_cb, nil) end tdcli_function ({ ID = "GetMessage", chat_id_ = msg.chat_id_, message_id_ = msg.id_ }, get_cb, nil) elseif msg.content_.ID == "MessageSticker" then sticker_id = '' local function get_cb(arg, data) sticker_id = data.content_.sticker_.sticker_.id_ tdcli.downloadFile(sticker_id, dl_cb, nil) end tdcli_function ({ ID = "GetMessage", chat_id_ = msg.chat_id_, message_id_ = msg.id_ }, get_cb, nil) elseif msg.content_.ID == "MessageDocument" then document_id, document_name = '', '' local function get_cb(arg, data) document_id = data.content_.document_.document_.id_ document_name = data.content_.document_.file_name_ tdcli.downloadFile(document_id, dl_cb, nil) end tdcli_function ({ ID = "GetMessage", chat_id_ = msg.chat_id_, message_id_ = msg.id_ }, get_cb, nil) end end function tdcli_update_callback (data) whoami() -- print(serpent.block(data)) if (data.ID == "UpdateNewMessage") then local msg = data.message_ local d = data.disable_notification_ local chat = chats[msg.chat_id_] local hash = 'msgs:'..msg.sender_user_id_..':'..msg.chat_id_ redis:incr(hash) if redis:get('markread') == 'on' then tdcli.viewMessages(msg.chat_id_, {[0] = msg.id_}, dl_cb, nil) end if ((not d) and chat) then if msg.content_.ID == "MessageText" then do_notify (chat.title_, msg.content_.text_) else do_notify (chat.title_, msg.content_.ID) end end var_cb(msg, msg) file_cb(msg) if msg.content_.ID == "MessageText" then if msg_valid(msg) then msg.text = msg.content_.text_ msg.edited = false msg.pinned = false end elseif msg.content_.ID == "MessagePinMessage" then msg.pinned = true elseif msg.content_.ID == "MessagePhoto" then msg.photo_ = true elseif msg.content_.ID == "MessageVideo" then msg.video_ = true elseif msg.content_.ID == "MessageAnimation" then msg.animation_ = true elseif msg.content_.ID == "MessageVoice" then msg.voice_ = true elseif msg.content_.ID == "MessageAudio" then msg.audio_ = true elseif msg.content_.ID == "MessageForwardedFromUser" then msg.forward_info_ = true elseif msg.content_.ID == "MessageSticker" then msg.sticker_ = true elseif msg.content_.ID == "MessageContact" then msg.contact_ = true elseif msg.content_.ID == "MessageDocument" then msg.document_ = true elseif msg.content_.ID == "MessageLocation" then msg.location_ = true elseif msg.content_.ID == "MessageGame" then msg.game_ = true elseif msg.content_.ID == "MessageChatAddMembers" then if msg_valid(msg) then for i=0,#msg.content_.members_ do msg.adduser = msg.content_.members_[i].id_ end end elseif msg.content_.ID == "MessageChatJoinByLink" then if msg_valid(msg) then msg.joinuser = msg.sender_user_id_ end elseif msg.content_.ID == "MessageChatDeleteMember" then if msg_valid(msg) then msg.deluser = true end end elseif data.ID == "UpdateMessageContent" then cmsg = data local function edited_cb(arg, data) msg = data msg.media = {} if cmsg.new_content_.text_ then msg.text = cmsg.new_content_.text_ end if cmsg.new_content_.caption_ then msg.media.caption = cmsg.new_content_.caption_ end msg.edited = true var_cb(msg, msg) end tdcli_function ({ ID = "GetMessage", chat_id_ = data.chat_id_, message_id_ = data.message_id_ }, edited_cb, nil) elseif data.ID == "UpdateFile" then file_id = data.file_.id_ elseif (data.ID == "UpdateChat") then chat = data.chat_ chats[chat.id_] = chat elseif (data.ID == "UpdateOption" and data.name_ == "my_id") then tdcli_function ({ID="GetChats", offset_order_="9223372036854775807", offset_chat_id_=0, limit_=20}, dl_cb, nil) end end
gpl-3.0
adiwg/mdEditor
app/pods/components/object/md-taxonomy/component.js
745
import Component from '@ember/component'; import { computed } from '@ember/object'; import { inject as service } from '@ember/service'; export default Component.extend({ router: service(), title: computed('model.taxonomicSystem.0.citation.title', function() { let title = this.get('model.taxonomicSystem.0.citation.title'); let index = this.index; return `Collection #${index}` + (title ? `: ${title}`: ''); }), actions: { editCollection(id) { this.set('scrollTo',`collection-${id}`); this.router.transitionTo('record.show.edit.taxonomy.collection.index', id); }, deleteCollection(id) { let taxa = this.get('record.json.metadata.resourceInfo.taxonomy'); taxa.removeAt(id); } } });
gpl-3.0
KostaVlev/SmartStoreNETCore
SmartStoreNETCore/SmartStoreNetCore.Core/Entities/Shipment.cs
1280
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Runtime.Serialization; namespace SmartStoreNetCore.Core.Entities { [DataContract] public class Shipment : BaseEntity { private ICollection<ShipmentItem> shipmentItems; public Shipment() { this.ShipmentItems = new HashSet<ShipmentItem>(); } [DataMember] [Required] public int OrderId { get; set; } [DataMember] [MaxLength(200)] public string TrackingNumber { get; set; } [DataMember] public decimal? TotalWeight { get; set; } [DataMember] public DateTime? ShippedDateUtc { get; set; } [DataMember] public DateTime? DeliveryDateUtc { get; set; } [DataMember] public DateTime CreatedOnUtc { get; set; } [DataMember] [ForeignKey("OrderId")] public virtual Order Order { get; set; } [DataMember] public virtual ICollection<ShipmentItem> ShipmentItems { get { return this.shipmentItems; } protected set { this.shipmentItems = value; } } } }
gpl-3.0
cheinle/NanoLIMS
functions/build_bulk_dna_table.php
11265
<?php //display table function build_bulk_dna_table($stmt,$root){ $path = $_SERVER['DOCUMENT_ROOT'].$root; include($path.'functions/convert_time.php'); //include('convert_header_names.php'); include($path.'functions/text_insert_update.php'); include($path.'functions/dropDown.php'); include($path.'/config/js.php'); echo '<form class="registration" onsubmit="return validate(this)" action="bulk_insert_and_updates/dna_bulk_update.php" method="POST">'; //echo '<div class = \'left\'>'; echo '<div>'; echo '<pre>'; echo '*Notice: Bulk Update will update all samples that have been checkmarked'; echo '</pre>'; echo '<table id = "datatable_bulk" class ="bulk" style="width:90%">'; echo '<button type="button" id="selectAll" class="mini-button" style="float:left;margin-bottom: 0.5%;"><span class="sub"></span> Select All Samples </button>'; echo '<thead>'; echo '<tr>'; echo '<th class="bulk">Sample Name</th>'; echo '<th class="bulk">DNA Conc. (ng/uL)</th>'; echo '</tr>'; echo '</thead>'; echo '<tbody>'; $sort_the_samples = array(); $sample_dna_conc = array(); if ($stmt->execute()){ $stmt->bind_result($sample_name,$dna_conc,$sample_sort); while ($stmt->fetch()){ $sort_the_samples[$sample_sort] = $sample_name; $sample_dna_conc[$sample_name] = $dna_conc; } } ksort($sort_the_samples); foreach ($sort_the_samples as $sorted_name => $sname) { #echo '<tr class = "row_collapse">'; echo '<tr>'; $mod_sample_name = preg_replace("/\//",'-',$sname);//jQuery cannot use slashes $mod_sample_name = preg_replace("/\s+/",'-',$mod_sample_name);//jQuery can also not use spaces ?> <td> <input type="checkbox" class = "checkbox1" id="<?php echo $mod_sample_name;?>_checkbox" name="sample[<?php echo $sname; ?>][checkbox]" value="checked" <?php if (isset($_SESSION['submitted']) && $_SESSION['submitted'] == 'true') { if(isset($_SESSION['sample_array'][$sname]['checkbox']) && htmlspecialchars($_SESSION['sample_array'][$sname]['checkbox']) == 'checked'){ echo "checked"; } }?>/> <?php echo $sname ?><br /> </td> <?php $dna_conc = htmlspecialchars($sample_dna_conc[$sname]);?> <td><input type="text" class = "checkbox1" id="<?php echo $mod_sample_name;?>_dna" name="sample[<?php echo $sname; ?>][dna]" value="<?php if (isset($_SESSION['submitted']) && $_SESSION['submitted'] == 'true') {echo htmlspecialchars($_SESSION['sample_array'][$sname]['dna']);}else{echo $dna_conc;} ?>"></td> <!--mark checkbox if you change a DNA Concentration in the bulk DNA update--> <script type="text/javascript"> $(document).ready(function(){ var sample_name = <?php echo(json_encode($mod_sample_name)); ?>; var sample_name_dna = sample_name+'_dna'; var sample_name_checkbox = sample_name+'_checkbox'; $('#'+sample_name_dna).change(function(){ //on change event if($('#'+sample_name_dna).val.length > 0){ $('#'+sample_name_checkbox).prop('checked',true); }else{ $('#'+sample_name_checkbox).prop('checked',false); } }); }); </script> <?php echo '</tr>'; } $stmt->close(); echo '</tbody>'; echo '</table>'; echo '</div>'; //other fields to update //check if form has been submitted successfully or not $submitted = 'true'; if(isset($_SESSION['submitted']) && $_SESSION['submitted'] == 'false'){ $submitted = 'false'; } ?> </div> <div id = 'bulk'> <table class = 'bulk' id='bulk'> <th class="bulk">DNA Extraction Info:(Required)</th> <tr> <td> <p> <label class="textbox-label">DNA Extraction Date:</label><br> <input type="text" id="datepicker5" name="d_extr_date" placeholder="Enter Date" value="<?php if (isset($_SESSION['submitted']) && $_SESSION['submitted'] == 'true') {echo htmlspecialchars($_SESSION['d_extr_date']);} ?>"/> <script> $('#datepicker5').datepicker({ dateFormat: 'yy-mm-dd' }).val(); </script> </p> </td> </tr> <tr> <td> <p> <!--DNA Extraction Kit dropdown--> <label class="textbox-label">Select DNA Extraction Kit:</label> <br/> <?php //url or $_GET name, table name, field name dropDown('dExtKit', 'dna_extraction', 'd_kit_name','d_kit_name',$submitted,$root); ?> </p> </td> </tr> <!--Volume of DNA--> <tr> <td> <p> <label class="textbox-label">Volume of DNA Elution (ul):</label><br> <input type="text" name="dVol" class="fields" placeholder="Enter A Volume" value="<?php if (isset($_SESSION['submitted']) && $_SESSION['submitted'] == 'true') {echo htmlspecialchars($_SESSION['dVol']);} ?>"> </p> </td> </tr> <!--Instrument used to measure DNA concentration--> <p> <tr> <td> <label class="textbox-label">Instrument/Kit Used to Measure DNA Concentration:</label><br> <?php //url or $_GET name, table name, field name dropDown('dInstru', 'quant_instruments', 'kit_name','kit_name',$submitted,$root); ?> </p> </td> </tr> <!--Volume of DNA to measure DNA conc--> <p> <tr> <td> <label class="textbox-label">Volume of DNA Used for Measure DNA Concentration(ul):</label><br> <input type="text" name="dVol_quant" class="fields" placeholder="Enter A Volume" value="<?php if (isset($_SESSION['submitted']) && $_SESSION['submitted'] == 'true') {echo htmlspecialchars($_SESSION['dVol_quant']);} ?>"> </p> </td> </tr> <!--DNA --> <p> <tr> <td class="textbox-label"> <label class="textbox-label">Location of DNA Extract:(pick freezer and drawer owner)</label><br> <div class="boxed"> <?php //url or $_GET name, table name, field name dropDown('dStore_temp', 'freezer', 'freezer_id','freezer_id',$submitted,$root); ?> <select id="dStore_name" name ="dStore_name" class='fields'> <?php if (isset($_SESSION['submitted']) && $_SESSION['submitted'] == 'true'){ echo '<option value='.$_GET["dStore_name"].' echo "selected";}} ?>'.$_GET["dStore_name"].' </option>'; }else{ echo '<option value="0">-Select-</option>'; }?> </select> </div> </td> </tr> <p> <tr> <td> <!--DNA Extractor Name input--> <label class="textbox-label">Enter Name(s) of Persons Who Extracted DNA:</label> <p class="clone2"> <input type="text" name="dExtrName[]" class='input' placeholder="First Name(s)" value="<?php if (isset($_SESSION['submitted']) && $_SESSION['submitted'] == 'true') {echo htmlspecialchars($_SESSION['dExtrName']);} ?>"/></p> </p> </td> </tr> <p> <tr> <td> <h3 class="checkbox-header">Does Original Sample Still Exist?:</h3><br> <div class="vert-checkboxes"> <label class="checkbox-label"></label="checkbox-label"><input type="checkbox" name="orig_sample_exist" class = "orig_sample_exist" id="orig_sample_exist" value="false" <?php if (isset($_SESSION['submitted']) && $_SESSION['submitted'] == 'true') {if(isset($_SESSION['orig_sample_exist']) && $_SESSION['orig_sample_exist'] == 'true'){echo 'checked';}} ?>/>No</label> <!--<input type="radio" name="orig_sample_exist" class = "orig_sample_exist" id="orig_sample_exist" value="true" <?php if (isset($_SESSION['submitted']) && $_SESSION['submitted'] == 'false') {if(isset($_SESSION['orig_sample_exist']) && $_SESSION['orig_sample_exist'] == 'true'){echo 'checked';}} ?>/>Yes<br />--> </div> </p> </td> </tr> <p> <tr> <td> <h3 class="checkbox-header">Does DNA Extraction Sample Exist?</h3><br> <div class="vert-checkboxes"> <label class="checkbox-label"><input type="radio" name="DNA_sample_exist" value="one" <?php if (isset($_SESSION['submitted']) && $_SESSION['submitted'] == 'true') {if(isset($_SESSION['DNA_sample_exist']) && $_SESSION['DNA_sample_exist'] == 'one'){echo 'checked';}} ?>/>Yes,DNA Sample Exisits</label> <label class="checkbox-label"><input type="radio" name="DNA_sample_exist" value="three" <?php if (isset($_SESSION['submitted']) && $_SESSION['submitted'] == 'true') {if(isset($_SESSION['DNA_sample_exist']) && $_SESSION['DNA_sample_exist'] == 'three'){echo 'checked';}} ?>/>No, DNA Sample Is Used Up</label> </div> </p> </td> </tr> <tr> <td> <button type="submit" name="submit" value="1" class="button"> Update Samples </button> </td> </tr> </table> </form> </div> <?php } ?> <script type="text/javascript"> var name_check = 'true'; function validate(form) { var valid = 'true'; if(check_this_form() == 'false'){ valid = 'false'; } if(valid == 'false'){ alert('ERROR: Some inputs are invalid. Please check fields and ensure at least one sample checkbox is checked'); return false; } else{ return confirm('Sure You Want To Submit?'); } } function check_this_form(){ var index; var valid = 'true'; //check that at least one checkbox is selected var top_table = document.getElementById("datatable_bulk"); var number_of_samples_checked = document.querySelectorAll('input[type="checkbox"]:checked').length; if(number_of_samples_checked < 1){ valid = 'false'; alert("Warning: Please select checkbox for samples to update"); top_table.style.background = "pink"; } else{ top_table.style.background = "white"; } //check that second table is filled in var bottom_table = document.getElementById("bulk"); var input = bottom_table.getElementsByTagName( 'input' ); for ( var z = 0; z < input.length; z++ ) { var input_id = input[z]; var input_value = input_id.value; if(input_value.length < 1){ input_id.style.background = "blue"; }else{ input_id.style.background = "white"; } } var select = bottom_table.getElementsByTagName( 'select' ); for ( var z = 0; z < select.length; z++ ) { var select_id = select[z]; var select_value = select_id.value; if(select_value == 0){ select_id.style.background = "blue"; }else{ select_id.style.background = "white"; } } if( $('input[type=radio]:selected').length == 0 ) { alert('Please select if DNA Extraction Sample Exists.'); bottom_table.style.background = "pink"; }else{ bottom_table.style.background = "white"; } //check that all checked have correct input var bulk_form = document.forms[0]; var i; for (i = 0; i < bulk_form.length; i++) { if (bulk_form[i].checked) { checkbox_name = bulk_form[i].id; var temp = new Array(); temp = checkbox_name.split("_"); var input = document.getElementById(temp[0]+'_dna'); var input_val = input.value; if(input_val == ''){ input.style.background = "blue"; valid = 'false'; } else{ if(isNumeric(input_val) == false){ alert("ERROR: Value must be a number"); input.style.background = "blue"; valid = 'false'; } else{ input.style.background = "white"; } } } } return valid; } function isNumeric(n) { return !isNaN(parseFloat(n)) && isFinite(n); } </script>
gpl-3.0
jaxio/usi2011
src/test/java/usi2011/repository/QuestionRepositoryTest.java
2126
package usi2011.repository; import static org.fest.assertions.Assertions.assertThat; import static usi2011.Main.context; import static usi2011.util.Specifications.FIRST_QUESTION; import static usi2011.util.Specifications.MAX_NUMBER_OF_ANSWERS; import java.io.IOException; import org.junit.BeforeClass; import org.junit.Ignore; import org.junit.Test; import org.springframework.beans.BeansException; import org.springframework.core.io.ClassPathResource; import usi2011.domain.Question; import usi2011.domain.Session; @Ignore public class QuestionRepositoryTest { static QuestionRepository repository = null; @BeforeClass public static void init() throws BeansException, IOException { repository = context.getBean(QuestionRepository.class); } @Test public void reset() { repository.reset(); assertThat(repository.getQuestion(FIRST_QUESTION)).isNull(); assertThat(repository.getQuestion(MAX_NUMBER_OF_ANSWERS)).isNull(); } @Test public void saveSession() { repository.save(session()); // check first question Question firstQuestion = repository.getQuestion(FIRST_QUESTION); assertThat(firstQuestion).isNotNull(); assertThat(firstQuestion.getQuestionId()).isEqualTo(1); // last one Question maxQuestion = repository.getQuestion(MAX_NUMBER_OF_ANSWERS); assertThat(maxQuestion).isNotNull(); assertThat(maxQuestion.getQuestionId()).isEqualTo(MAX_NUMBER_OF_ANSWERS); repository.reset(); assertThat(repository.getQuestion(FIRST_QUESTION)).isNull(); assertThat(repository.getQuestion(MAX_NUMBER_OF_ANSWERS)).isNull(); } @Test(expected = IllegalArgumentException.class) public void outOfBoundariesQuestionsThrowsException() { // out of boundaries assertThat(repository.getQuestion(FIRST_QUESTION - 1)).isNull(); assertThat(repository.getQuestion(MAX_NUMBER_OF_ANSWERS + 1)).isNull(); } private Session session() { return new Session(new ClassPathResource("/session/gamesession-20-questions.xml")); } }
gpl-3.0
wilhelmsen/buoy-validation
libs/satellite.py
19474
# coding: utf-8 import logging import datetime import numpy as np import numpy.ma as ma import netCDF4 import os import datetimehelper import filterhelper import coordinatehelper import math # Define the logger LOG = logging.getLogger(__name__) ZERO_CELCIUS_IN_KELVIN = 273.15 class SatDataException(Exception): pass def get_files_from_datadir(data_dir, date_from_including, date_to_excluding): """ Getting the files from the data dir. It does a walk through the data dir and finds files that - Starts with a date in the specified date range. - Contains the string "-DMI-L4" - Ends with .nc """ LOG.debug("Data dir: '%s'"%data_dir) LOG.debug("Date from: '%s'."%date_from_including) LOG.debug("Date to: '%s'."%date_to_excluding) # Make sure that date_from allways is before date_to. # Be aware of that this must be done in one step. If not a temp variable is needed. date_from_including, date_to_excluding = min(date_from_including, date_to_excluding), max(date_from_including, date_to_excluding) LOG.debug("Dates after min/max:") LOG.debug("Date from (including): '%s'."%date_from_including) LOG.debug("Date to: '%s'."%date_to_excluding) for root, dirs, files in os.walk(data_dir): LOG.debug("Looking for files in '%s'."%(os.path.abspath(root))) # Walk through every files/directories in the data_dir. # Filename example: 20150313000000-DMI-L4_GHRSST-SSTfnd-DMI_OI-NSEABALTIC-v02.0-fv01.0.nc.gz # f.endswith((".nc", ".nc.gz")) for filename in [f for f in files if f.endswith(".nc") and "-DMI-L4" in f and date_from_including <= _get_date_from_filename(f) < date_to_excluding]: abs_filename = os.path.abspath(os.path.join(root, filename)) LOG.debug("Found file '%s'."%(abs_filename)) yield abs_filename def get_available_dates(data_dir): """ Gets the dates that are availabe. That is, it - finds all the relevant files (see get_files_from_datadir) in the data dir, - parses the filenames - returns the date from the filename (not the content of the file). """ date_from = datetime.datetime(1981, 1, 1) date_to = datetime.datetime.now() + datetime.timedelta(days = 1) for filename in get_files_from_datadir(data_dir, date_from, date_to): yield _get_date_from_filename(filename) def _get_date_from_filename(filename): FILENAME_DATE_FORMAT = "%Y%m%d%H%M%S" return datetime.datetime.strptime(os.path.basename(filename).split("-")[0], FILENAME_DATE_FORMAT) class SatelliteDataPoint(object): def __init__(self): # Make the data element ready. self.data = {} def append(self, key, value): """ Appends a key-value-pair to a datapoint. """ self.data[key] = value def filter(self, order=None, ignore_point_if_missing=False): """ Returns a string with the values corresponding to what is given in order. If order is None, all the values are written. Order can be either a list ["lat", "lon"] or a string with one key "lat". """ # If one of the values are missing, and the filter is to ignore the missing values, # None is returned at once. for key, value in self.data.iteritems(): if ignore_point_if_missing and hasattr(variable, "mask"): if variable.mask: return None values = [] # If the datapoint is actually filtered. if order != None: LOG.debug("Order:") LOG.debug(order) if isinstance(order, str): order = [order, ] for key in order: if ":" in key: key, extra_filter_option = key.split(":", 1) if key == "time": if extra_filter_option == "julian": values.append(datetimehelper.date2julian(self.data[key])) elif extra_filter_option != "": values.append(self.data[key].strftime(extra_filter_option)) else: values.append(self.data[key].strftime(datetimehelper.DEFAULT_DATE_FORMAT_MIN)) elif key == "dummy": values.append(extra_filter_option) else: values.append(self.data[key]) # No filtering. All data is written. else: for key in self.data: if key == "time": values.append(self.data[key].strftime(datetimehelper.DEFAULT_DATE_FORMAT_MIN)) else: values.append((self.data[key])) # Return a string with all the values. output = "" for value in values: output += filterhelper.format(value) return output def __str__(self): return self.filter() class Satellite(object): def __init__(self, input_filename): self.input_filename = input_filename self.nc = netCDF4.Dataset(self.input_filename, 'r') def __enter__(self): return self def __exit__(self, type, value, traceback): if self.nc and self.nc != None: self.nc.close() def get_date(self): return _get_date_from_filename(self.input_filename) def has_variables(self, required_variables): """ Makes sure that the variables in the "required_variables" can actually be found in the file. """ LOG.debug("Required variables: %s"%(required_variables)) if isinstance(required_variables, str): required_variables = (required_variables,) variable_names = self.get_variable_names() for required_variable in required_variables: if required_variable not in variable_names: LOG.warning("The file, '%s', must have the variable '%s'."%(self.input_filename, required_variable)) return False return True def get_closest_lat_lon_indexes(self, lat, lon): """ Gets the indexes for the specified lat/lon values. E.g. analysed_sst is a grid. The indexes correspond to (time, lat, lon). Time is only one dimension in the files, so we need the lat / lon indexes. LON +-----+-----+-----+-----+-----+-----+ | x | x | x | x | x | x | +-----+-----+-----+-----+-----+-----+ | x | x | x | x | x | x | LAT +-----+-----+-----+-----+-----+-----+ | x | x | x | x | x | x | +-----+-----+-----+-----+-----+-----+ The lat/lon points are the center values in the grid cell. """ # lat / lon extremes including the edges. lats, lons = self.get_lat_lon_ranges() # Make sure the lat/lon values are within the ranges where there are data. # lat[0] - grid_cell_height/2, lat[1] + grid_cell_height/2 if not lats[0] <= lat <= lats[1]: raise SatDataException("Latitude %s is outside latitude range %s."%(lat, " - ".join([str(l) for l in lats]))) # lon[0] - grid_cell_width/2, lon[1] + grid_cell_width/2 if not lons[0] <= lon <= lons[1]: raise SatDataException("Longitude %s is outside longitude range %s."%(lon, " - ".join([str(l) for l in lons]))) lat_index = self.get_index_of_closest_float_value('lat', lat) lon_index = self.get_index_of_closest_float_value('lon', lon) LOG.debug("Lat index: %i. Lat: %f."%(lat_index, self.nc.variables['lat'][lat_index])) LOG.debug("Lon index: %i. Lon: %f."%(lon_index, self.nc.variables['lon'][lon_index])) return lat_index, lon_index def data(self, lat, lon): """ Getting the values (datapoint) for the specified lat / lon values. It gets the indexes closest to lat/lon and returns a SatelliteDataPoint with the values. """ # Get the closes indexes for the lat lon. LOG.debug("Getting the values from the file.") LOG.debug("Getting the indexes for lat/lon: %f/%f"%(lat, lon)) lat_index, lon_index = self.get_closest_lat_lon_indexes(lat, lon) LOG.debug("The lat/lo indexes for %f/%f were: %i, %i"%(lat, lon, lat_index, lon_index)) data_point = SatelliteDataPoint() # Add the values to the datapoint. for variable_name in self.get_variable_names(): LOG.debug("Adding variable name: %s."%(variable_name)) if variable_name == "lat": variable_value = self.nc.variables[variable_name][lat_index] elif variable_name == "lon": variable_value = self.nc.variables[variable_name][lon_index] elif variable_name == "time": # The time variable is seconds since 1981-01-01. start_date = datetime.datetime(1981, 1, 1) variable_value = (start_date + datetime.timedelta(seconds=int(self.nc.variables['time'][0]))) elif variable_name == "analysed_sst": variable_value = float(self.nc.variables[variable_name][0][lat_index][lon_index]) - ZERO_CELCIUS_IN_KELVIN elif variable_name == "analysed_sst_smooth": variable_value = self.calculate_analysed_sst_smooth(lat, lon) - ZERO_CELCIUS_IN_KELVIN elif variable_name == "dist2ice": variable_value = self.calculate_distance_to_ice(lat, lon) else: variable_value = self.nc.variables[variable_name][0][lat_index][lon_index] # Append the value to the datapoint. data_point.append(variable_name, variable_value) # All values has been inserted. Return the point. return data_point def get_lat_index(self, lat): """ Gets the index of the closest lat value. """ return get_index_of_closest_float_value("lat", lat) def get_lon_index(self, lon): """ Gets the index of the closest lon value. """ return get_index_of_closest_float_value("lon", lon) def get_index_of_closest_float_value(self, variable_name, value): """ Gets the index of the closest float value. """ return int(abs((self.nc.variables[variable_name] - np.float32(value))).argmin()) def calculate_analysed_sst_smooth(self, lat, lon, analysed_sst_smooth_radius_km=25): """ Gets the average analysed_sst within a squared grid (km). LON +-----+-----+-----+-----+-----+-----+ | x | x | x | x | x | x | +-----+-----+-----+-----+-----+-----+ | x | x | x | x | x | x | LAT +-----+-----+-----+-----+-----+-----+ | x | x | x | x | x | x | +-----+-----+-----+-----+-----+-----+ """ # The smooth radius (km) in degrees. # For latitudes. smooth_radius_lat_deg = coordinatehelper.km_2_lats(analysed_sst_smooth_radius_km) # For longitudes. # Assuming that the 1 deg longitude is the same for all points around a specified point. smooth_radius_lon_deg = coordinatehelper.km_2_lons(analysed_sst_smooth_radius_km, lat) # Mask everything outside latitude interval. # Everything inside the interval is True. lat_mask = (self.nc.variables['lat'][:] >= lat-smooth_radius_lat_deg) & (self.nc.variables['lat'][:] <= lat+smooth_radius_lat_deg) # The same for the longitude interval. # True inside interval. lon_mask = (self.nc.variables['lon'][:] > lon-smooth_radius_lon_deg) & (self.nc.variables['lon'][:] < lon+smooth_radius_lon_deg) # Combine the lat mask with the lon mask. # Reshape the two arrays into a matrix with the same dimmensions as the analysed_sst matrix. lat_lon_mask = np.reshape([i&j for i in lat_mask for j in lon_mask], (len(lat_mask), len(lon_mask))) # The values must be from water. That means that bit 1 must be set in the land/sea-mask. # The result is an array with 1s and 0s. It is converted to an array of bools. # Again, if it is sea, the value is True. sea_mask = np.array((self.nc.variables['mask'][0] & 1), dtype=bool) # The resulting mask. Both True values from lat_lon and True values from the land/sea mask. resulting_mask = lat_lon_mask & sea_mask # Get the values data = self.nc.variables['analysed_sst'][0] # Add the original mask. # When the mask is on applied to the variable, True means that the # variable is not to be used. It is "masked". The valid values should # therefore be False. Hence: ~resulting_mask. data.mask = ~resulting_mask | data.mask # Calculate the mean of the valid values. return data.mean() def calculate_distance_to_ice(self, lat, lon, output_ice_point_to_log_info=False): """ Finds the minimum distance to ice. LON +-----+-----+-----+-----+-----+-----+ | x | x | x | x | x | x | +-----+-----+-----+-----+-----+-----+ | x | x | x | x | x | x | LAT +-----+-----+-----+-----+-----+-----+ | x | x | x | x | x | x | +-----+-----+-----+-----+-----+-----+ """ # The maximum allowed distance to ice. If the ice is found further out, # the value should be set to the NO_ICE_DISTANCE_KM MAX_DISTANCE_KM=500 # Kind of a fill value for the distance. The distance is set to 1000 if no # ice is found within MAX_DISTANCE_KM. NO_ICE_DISTANCE_KM=1000.0 # The ice sea fraction must be at least this. MIN_SEA_ICE_FRACTION=0.15 # Create a mask for all the points where the ice is greater than the sea ice fraction. LOG.debug("Icemask where sea ice fraction is > %f "%(MIN_SEA_ICE_FRACTION)) sea_ice_fraction_mask = self.nc.variables['sea_ice_fraction'][0] > MIN_SEA_ICE_FRACTION # Create a mask for all the values that are sea (first bit is set). LOG.debug("The sea mask: Where the first bit in the 'mask' variable (nc file) is set") sea_mask = np.array((self.nc.variables['mask'][0] & 1), dtype=bool) # Combine the two. I.e. a mask where there is sea AND ice. LOG.debug("Combine sea mask and sea ice fraction mask into sea ice mask.") sea_ice_mask = sea_ice_fraction_mask & sea_mask # Creating a matrix with very large values. # This will be used to fill in the values distance values. distances_km = np.empty(sea_ice_mask.shape) distances_km.fill(NO_ICE_DISTANCE_KM) # This is used if we want to output where the ice is found, but is not # really needed elsewhere. if output_ice_point_to_log_info: # For book keeping. min_value = NO_ICE_DISTANCE_KM min_lat = None min_lon = None # Loop through all the points that are both sea and ice, # calculate the distance to our point, # insert the value into the distances matrix. for lat_idx in np.arange(len(self.nc.variables['lat'])): if not sea_ice_mask[lat_idx].any(): # If there are no ice in the sea for the current sea mask row, # go to the next row. continue # There ice values for this sea mask row. # Get the y component to the length to the latitude. latitude = self.nc.variables['lat'][lat_idx] y = coordinatehelper.lats_2_km(np.abs(latitude-lat)) # Run through every point in the row and check if there is # any ice in that point. for lon_idx in np.arange(len(self.nc.variables['lon'])): # Is there ice in the point? if not sea_ice_mask[lat_idx][lon_idx]: # No there were no ice. continue # Yes there were ice. # Get the x component for the length to the ice point. longitude = self.nc.variables['lon'][lon_idx] x = coordinatehelper.lons_2_km(np.abs(longitude - lon), latitude) # Calculate the resulting distance. distances_km[lat_idx][lon_idx] = np.sqrt(x**2 + y**2) # Only for book keeping, when we want to output where the point is. if output_ice_point_to_log_info and distances_km[lat_idx][lon_idx] < min_value: min_value = distances_km[lat_idx][lon_idx] min_lat = latitude min_lon = longitude # The smallest distance to the ice. min_distance_km = distances_km.min() # Only when outputting the distance. if output_ice_point_to_log_info: LOG.info("dist2ice:(%s, %s) -> (%s, %s): %f km: "%(lat, lon, min_lat, min_lon, min_distance_km)) # If the minimum distance is greater than the allowed (500 km), # return a default value. if min_distance_km >= MAX_DISTANCE_KM: LOG.debug("Returning default value: %s"%(NO_ICE_DISTANCE_KM)) return NO_ICE_DISTANCE_KM # Else the minimum distance found is returned. return min_distance_km def get_lat_lon_ranges(self): """ Getting the lat long ranges from a input file, including the extra area on the edges. Opens the file, reads the lat/lon arrays and finds the min/max values. LON +-----+-----+-----+-----+-----+-----+ | x | x | x | x | x | x | +-----+-----+-----+-----+-----+-----+ | x | x | x | x | x | x | LAT +-----+-----+-----+-----+-----+-----+ | x | x | x | x | x | x | +-----+-----+-----+-----+-----+-----+ As the lat/lons are center values in the grid cells, the edges are added to the range. """ # The edge for latitude. lat_edge = self.nc.geospatial_lat_resolution/2.0 # The minimum and maximum values from the file +/- the edges. lat_ranges = [min(self.nc.variables['lat']) - lat_edge, max(self.nc.variables['lat']) + lat_edge] # The edge for longitude. lon_edge = self.nc.geospatial_lon_resolution/2.0 # The minimum and maximum values from the file +/- the edges. lon_ranges = [min(self.nc.variables['lon']) - lon_edge, max(self.nc.variables['lon']) + lon_edge] # The ranges. return lat_ranges, lon_ranges def get_variable_names(self): """ Gets the variable names in the file. That means the variables that can be read from the file. """ LOG.debug("Getting variable names from %s"%self.input_filename) # The variables names from the file. variables = list(self.nc.variables) # Calculated variable names. variables.append("analysed_sst_smooth") variables.append("dist2ice") # Convert the variables to strings. return set([str(var) for var in variables])
gpl-3.0
matusfaro/actiontrigger
actiontriggercommon/include/actiontrigger/controller/services/internal/triggerregex.hpp
1673
/* * ActionTrigger * Copyright (C) 2013 Matus Faro * * This file is part of ActionTrigger. * * ActionTrigger 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. * * ActionTrigger 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 ActionTrigger. If not, see <http://www.gnu.org/licenses/>. */ #ifndef TriggerRegex_HPP_ #define TriggerRegex_HPP_ #include "actiontrigger/controller/services/trigger.hpp" #include "actiontrigger/controller/services/parameterdefinition.hpp" #include <regex.h> namespace actiontrigger { class TriggerRegex: public Trigger { public: TriggerRegex(StatementModel* model); ~TriggerRegex(); static std::string TYPE; std::string getType() const; bool isActive(ExecutionState* state); static const StatementInfo info; const StatementInfo getInfo(); std::vector<ParameterDefinition*>* getParameterDefinitions(); protected: std::string getDefaultParameter(std::string key); bool isEventOnlyTrigger(); private: static Logger* StatementLOG; static std::vector<ParameterDefinition*>* parameterDefinitions; }; } /* namespace actiontrigger */ #endif /* TriggerRegex_HPP_ */
gpl-3.0
Lab21k/standalone-timeline
src/scripts/date-time.js
14999
/** * @fileOverview A collection of date/time utility functions * @name SimileAjax.DateTime */ SimileAjax.DateTime = new Object(); SimileAjax.DateTime.MILLISECOND = 0; SimileAjax.DateTime.SECOND = 1; SimileAjax.DateTime.MINUTE = 2; SimileAjax.DateTime.HOUR = 3; SimileAjax.DateTime.DAY = 4; SimileAjax.DateTime.WEEK = 5; SimileAjax.DateTime.MONTH = 6; SimileAjax.DateTime.YEAR = 7; SimileAjax.DateTime.DECADE = 8; SimileAjax.DateTime.CENTURY = 9; SimileAjax.DateTime.MILLENNIUM = 10; SimileAjax.DateTime.EPOCH = -1; SimileAjax.DateTime.ERA = -2; /** * An array of unit lengths, expressed in milliseconds, of various lengths of * time. The array indices are predefined and stored as properties of the * SimileAjax.DateTime object, e.g. SimileAjax.DateTime.YEAR. * @type Array */ SimileAjax.DateTime.gregorianUnitLengths = []; (function() { var d = SimileAjax.DateTime; var a = d.gregorianUnitLengths; a[d.MILLISECOND] = 1; a[d.SECOND] = 1000; a[d.MINUTE] = a[d.SECOND] * 60; a[d.HOUR] = a[d.MINUTE] * 60; a[d.DAY] = a[d.HOUR] * 24; a[d.WEEK] = a[d.DAY] * 7; a[d.MONTH] = a[d.DAY] * 31; a[d.YEAR] = a[d.DAY] * 365; a[d.DECADE] = a[d.YEAR] * 10; a[d.CENTURY] = a[d.YEAR] * 100; a[d.MILLENNIUM] = a[d.YEAR] * 1000; })(); SimileAjax.DateTime._dateRegexp = new RegExp( "^(-?)([0-9]{4})(" + [ "(-?([0-9]{2})(-?([0-9]{2}))?)", // -month-dayOfMonth "(-?([0-9]{3}))", // -dayOfYear "(-?W([0-9]{2})(-?([1-7]))?)" // -Wweek-dayOfWeek ].join("|") + ")?$" ); SimileAjax.DateTime._timezoneRegexp = new RegExp( "Z|(([-+])([0-9]{2})(:?([0-9]{2}))?)$" ); SimileAjax.DateTime._timeRegexp = new RegExp( "^([0-9]{2})(:?([0-9]{2})(:?([0-9]{2})(\.([0-9]+))?)?)?$" ); /** * Takes a date object and a string containing an ISO 8601 date and sets the * the date using information parsed from the string. Note that this method * does not parse any time information. * * @param {Date} dateObject the date object to modify * @param {String} string an ISO 8601 string to parse * @return {Date} the modified date object */ SimileAjax.DateTime.setIso8601Date = function(dateObject, string) { /* * This function has been adapted from dojo.date, v.0.3.0 * http://dojotoolkit.org/. */ var d = string.match(SimileAjax.DateTime._dateRegexp); if (!d) { throw new Error("Invalid date string: " + string); } var sign = (d[1] == "-") ? -1 : 1; // BC or AD var year = sign * d[2]; var month = d[5]; var date = d[7]; var dayofyear = d[9]; var week = d[11]; var dayofweek = (d[13]) ? d[13] : 1; dateObject.setUTCFullYear(year); if (dayofyear) { dateObject.setUTCMonth(0); dateObject.setUTCDate(Number(dayofyear)); } else if (week) { dateObject.setUTCMonth(0); dateObject.setUTCDate(1); var gd = dateObject.getUTCDay(); var day = (gd) ? gd : 7; var offset = Number(dayofweek) + (7 * Number(week)); if (day <= 4) { dateObject.setUTCDate(offset + 1 - day); } else { dateObject.setUTCDate(offset + 8 - day); } } else { if (month) { dateObject.setUTCDate(1); dateObject.setUTCMonth(month - 1); } if (date) { dateObject.setUTCDate(date); } } return dateObject; }; /** * Takes a date object and a string containing an ISO 8601 time and sets the * the time using information parsed from the string. Note that this method * does not parse any date information. * * @param {Date} dateObject the date object to modify * @param {String} string an ISO 8601 string to parse * @return {Date} the modified date object */ SimileAjax.DateTime.setIso8601Time = function(dateObject, string) { /* * This function has been adapted from dojo.date, v.0.3.0 * http://dojotoolkit.org/. */ var d = string.match(SimileAjax.DateTime._timeRegexp); if (!d) { SimileAjax.Debug.warn("Invalid time string: " + string); return false; } var hours = d[1]; var mins = Number((d[3]) ? d[3] : 0); var secs = (d[5]) ? d[5] : 0; var ms = d[7] ? (Number("0." + d[7]) * 1000) : 0; dateObject.setUTCHours(hours); dateObject.setUTCMinutes(mins); dateObject.setUTCSeconds(secs); dateObject.setUTCMilliseconds(ms); return dateObject; }; /** * The timezone offset in minutes in the user's browser. * @type Number */ SimileAjax.DateTime.timezoneOffset = new Date().getTimezoneOffset(); /** * Takes a date object and a string containing an ISO 8601 date and time and * sets the date object using information parsed from the string. * * @param {Date} dateObject the date object to modify * @param {String} string an ISO 8601 string to parse * @return {Date} the modified date object */ SimileAjax.DateTime.setIso8601 = function(dateObject, string) { /* * This function has been adapted from dojo.date, v.0.3.0 * http://dojotoolkit.org/. */ var offset = null; var comps = (string.indexOf("T") == -1) ? string.split(" ") : string.split("T"); SimileAjax.DateTime.setIso8601Date(dateObject, comps[0]); if (comps.length == 2) { // first strip timezone info from the end var d = comps[1].match(SimileAjax.DateTime._timezoneRegexp); if (d) { if (d[0] == 'Z') { offset = 0; } else { offset = (Number(d[3]) * 60) + Number(d[5]); offset *= ((d[2] == '-') ? 1 : -1); } comps[1] = comps[1].substr(0, comps[1].length - d[0].length); } SimileAjax.DateTime.setIso8601Time(dateObject, comps[1]); } if (offset == null) { offset = dateObject.getTimezoneOffset(); // local time zone if no tz info } dateObject.setTime(dateObject.getTime() + offset * 60000); return dateObject; }; /** * Takes a string containing an ISO 8601 date and returns a newly instantiated * date object with the parsed date and time information from the string. * * @param {String} string an ISO 8601 string to parse * @return {Date} a new date object created from the string */ SimileAjax.DateTime.parseIso8601DateTime = function(string) { try { return SimileAjax.DateTime.setIso8601(new Date(0), string); } catch (e) { return null; } }; /** * Takes a string containing a Gregorian date and time and returns a newly * instantiated date object with the parsed date and time information from the * string. If the param is actually an instance of Date instead of a string, * simply returns the given date instead. * * @param {Object} o an object, to either return or parse as a string * @return {Date} the date object */ SimileAjax.DateTime.parseGregorianDateTime = function(o) { if (o == null) { return null; } else if (o instanceof Date) { return o; } var s = o.toString(); if (s.length > 0 && s.length < 8) { var space = s.indexOf(" "); if (space > 0) { var year = parseInt(s.substr(0, space)); var suffix = s.substr(space + 1); if (suffix.toLowerCase() == "bc") { year = 1 - year; } } else { var year = parseInt(s); } var d = new Date(0); d.setUTCFullYear(year); return d; } try { return new Date(Date.parse(s)); } catch (e) { return null; } }; /** * Rounds date objects down to the nearest interval or multiple of an interval. * This method modifies the given date object, converting it to the given * timezone if specified. * * @param {Date} date the date object to round * @param {Number} intervalUnit a constant, integer index specifying an * interval, e.g. SimileAjax.DateTime.HOUR * @param {Number} timeZone a timezone shift, given in hours * @param {Number} multiple a multiple of the interval to round by * @param {Number} firstDayOfWeek an integer specifying the first day of the * week, 0 corresponds to Sunday, 1 to Monday, etc. */ SimileAjax.DateTime.roundDownToInterval = function(date, intervalUnit, timeZone, multiple, firstDayOfWeek) { var timeShift = timeZone * SimileAjax.DateTime.gregorianUnitLengths[SimileAjax.DateTime.HOUR]; var date2 = new Date(date.getTime() + timeShift); var clearInDay = function(d) { d.setUTCMilliseconds(0); d.setUTCSeconds(0); d.setUTCMinutes(0); d.setUTCHours(0); }; var clearInYear = function(d) { clearInDay(d); d.setUTCDate(1); d.setUTCMonth(0); }; switch (intervalUnit) { case SimileAjax.DateTime.MILLISECOND: var x = date2.getUTCMilliseconds(); date2.setUTCMilliseconds(x - (x % multiple)); break; case SimileAjax.DateTime.SECOND: date2.setUTCMilliseconds(0); var x = date2.getUTCSeconds(); date2.setUTCSeconds(x - (x % multiple)); break; case SimileAjax.DateTime.MINUTE: date2.setUTCMilliseconds(0); date2.setUTCSeconds(0); var x = date2.getUTCMinutes(); date2.setTime(date2.getTime() - (x % multiple) * SimileAjax.DateTime.gregorianUnitLengths[SimileAjax.DateTime.MINUTE]); break; case SimileAjax.DateTime.HOUR: date2.setUTCMilliseconds(0); date2.setUTCSeconds(0); date2.setUTCMinutes(0); var x = date2.getUTCHours(); date2.setUTCHours(x - (x % multiple)); break; case SimileAjax.DateTime.DAY: clearInDay(date2); break; case SimileAjax.DateTime.WEEK: clearInDay(date2); var d = (date2.getUTCDay() + 7 - firstDayOfWeek) % 7; date2.setTime(date2.getTime() - d * SimileAjax.DateTime.gregorianUnitLengths[SimileAjax.DateTime.DAY]); break; case SimileAjax.DateTime.MONTH: clearInDay(date2); date2.setUTCDate(1); var x = date2.getUTCMonth(); date2.setUTCMonth(x - (x % multiple)); break; case SimileAjax.DateTime.YEAR: clearInYear(date2); var x = date2.getUTCFullYear(); date2.setUTCFullYear(x - (x % multiple)); break; case SimileAjax.DateTime.DECADE: clearInYear(date2); date2.setUTCFullYear(Math.floor(date2.getUTCFullYear() / 10) * 10); break; case SimileAjax.DateTime.CENTURY: clearInYear(date2); date2.setUTCFullYear(Math.floor(date2.getUTCFullYear() / 100) * 100); break; case SimileAjax.DateTime.MILLENNIUM: clearInYear(date2); date2.setUTCFullYear(Math.floor(date2.getUTCFullYear() / 1000) * 1000); break; } date.setTime(date2.getTime() - timeShift); }; /** * Rounds date objects up to the nearest interval or multiple of an interval. * This method modifies the given date object, converting it to the given * timezone if specified. * * @param {Date} date the date object to round * @param {Number} intervalUnit a constant, integer index specifying an * interval, e.g. SimileAjax.DateTime.HOUR * @param {Number} timeZone a timezone shift, given in hours * @param {Number} multiple a multiple of the interval to round by * @param {Number} firstDayOfWeek an integer specifying the first day of the * week, 0 corresponds to Sunday, 1 to Monday, etc. * @see SimileAjax.DateTime.roundDownToInterval */ SimileAjax.DateTime.roundUpToInterval = function(date, intervalUnit, timeZone, multiple, firstDayOfWeek) { var originalTime = date.getTime(); SimileAjax.DateTime.roundDownToInterval(date, intervalUnit, timeZone, multiple, firstDayOfWeek); if (date.getTime() < originalTime) { date.setTime(date.getTime() + SimileAjax.DateTime.gregorianUnitLengths[intervalUnit] * multiple); } }; /** * Increments a date object by a specified interval, taking into * consideration the timezone. * * @param {Date} date the date object to increment * @param {Number} intervalUnit a constant, integer index specifying an * interval, e.g. SimileAjax.DateTime.HOUR * @param {Number} timeZone the timezone offset in hours */ SimileAjax.DateTime.incrementByInterval = function(date, intervalUnit, timeZone) { timeZone = (typeof timeZone == 'undefined') ? 0 : timeZone; var timeShift = timeZone * SimileAjax.DateTime.gregorianUnitLengths[SimileAjax.DateTime.HOUR]; var date2 = new Date(date.getTime() + timeShift); switch (intervalUnit) { case SimileAjax.DateTime.MILLISECOND: date2.setTime(date2.getTime() + 1) break; case SimileAjax.DateTime.SECOND: date2.setTime(date2.getTime() + 1000); break; case SimileAjax.DateTime.MINUTE: date2.setTime(date2.getTime() + SimileAjax.DateTime.gregorianUnitLengths[SimileAjax.DateTime.MINUTE]); break; case SimileAjax.DateTime.HOUR: date2.setTime(date2.getTime() + SimileAjax.DateTime.gregorianUnitLengths[SimileAjax.DateTime.HOUR]); break; case SimileAjax.DateTime.DAY: date2.setUTCDate(date2.getUTCDate() + 1); break; case SimileAjax.DateTime.WEEK: date2.setUTCDate(date2.getUTCDate() + 7); break; case SimileAjax.DateTime.MONTH: date2.setUTCMonth(date2.getUTCMonth() + 1); break; case SimileAjax.DateTime.YEAR: date2.setUTCFullYear(date2.getUTCFullYear() + 1); break; case SimileAjax.DateTime.DECADE: date2.setUTCFullYear(date2.getUTCFullYear() + 10); break; case SimileAjax.DateTime.CENTURY: date2.setUTCFullYear(date2.getUTCFullYear() + 100); break; case SimileAjax.DateTime.MILLENNIUM: date2.setUTCFullYear(date2.getUTCFullYear() + 1000); break; } date.setTime(date2.getTime() - timeShift); }; /** * Returns a new date object with the given time offset removed. * * @param {Date} date the starting date * @param {Number} timeZone a timezone specified in an hour offset to remove * @return {Date} a new date object with the offset removed */ SimileAjax.DateTime.removeTimeZoneOffset = function(date, timeZone) { return new Date(date.getTime() + timeZone * SimileAjax.DateTime.gregorianUnitLengths[SimileAjax.DateTime.HOUR]); }; /** * Returns the timezone of the user's browser. * * @return {Number} the timezone in the user's locale in hours */ SimileAjax.DateTime.getTimezone = function() { var d = new Date().getTimezoneOffset(); return d / -60; };
gpl-3.0
Rafiot/GostCrypt-Linux
Platform/Unix/Pipe.cpp
1176
/* Copyright (c) 2008 TrueCrypt Developers Association. All rights reserved. Governed by the TrueCrypt License 3.0 the full text of which is contained in the file License.txt included in TrueCrypt binary and source code distribution packages. */ #include <unistd.h> #include "Pipe.h" #include "Platform/SystemException.h" namespace GostCrypt { Pipe::Pipe () { int fd[2]; throw_sys_if (pipe (fd) == -1); ReadFileDescriptor = fd[0]; WriteFileDescriptor = fd[1]; } Pipe::~Pipe () { try { Close(); } catch (...) { } } void Pipe::Close () { if (ReadFileDescriptor != -1) close (ReadFileDescriptor); if (WriteFileDescriptor != -1) close (WriteFileDescriptor); } int Pipe::GetReadFD () { assert (ReadFileDescriptor != -1); if (WriteFileDescriptor != -1) { close (WriteFileDescriptor); WriteFileDescriptor = -1; } return ReadFileDescriptor; } int Pipe::GetWriteFD () { assert (WriteFileDescriptor != -1); if (ReadFileDescriptor != -1) { close (ReadFileDescriptor); ReadFileDescriptor = -1; } return WriteFileDescriptor; } }
gpl-3.0
rogerz/IEDExplorer
MMS_ASN1_Model/StartUnitControl_Error.cs
1719
// // This file was generated by the BinaryNotes compiler. // See http://bnotes.sourceforge.net // Any modifications to this file will be lost upon recompilation of the source ASN.1. // using System; using org.bn.attributes; using org.bn.attributes.constraints; using org.bn.coders; using org.bn.types; using org.bn; namespace MMS_ASN1_Model { [ASN1PreparedElement] [ASN1Sequence ( Name = "StartUnitControl_Error", IsSet = false )] public class StartUnitControl_Error : IASN1PreparedElement { private Identifier programInvocationName_ ; [ASN1Element ( Name = "programInvocationName", IsOptional = false , HasTag = true, Tag = 0 , HasDefaultValue = false ) ] public Identifier ProgramInvocationName { get { return programInvocationName_; } set { programInvocationName_ = value; } } private ProgramInvocationState programInvocationState_ ; [ASN1Element ( Name = "programInvocationState", IsOptional = false , HasTag = true, Tag = 1 , HasDefaultValue = false ) ] public ProgramInvocationState ProgramInvocationState { get { return programInvocationState_; } set { programInvocationState_ = value; } } public void initWithDefaults() { } private static IASN1PreparedElementData preparedData = CoderFactory.getInstance().newPreparedElementData(typeof(StartUnitControl_Error)); public IASN1PreparedElementData PreparedData { get { return preparedData; } } } }
gpl-3.0
VladimirDeminenko/javascript.ru-nodejs
dropbox/vladimir.deminenko/03_2017-05-16/homework/get-post-server-task/dist/server/app.js
4945
/** * app.ts * Created by Vladimir Deminenko on 01.05.2017 */ "use strict"; exports.__esModule = true; var config = require("config"); var fs = require("fs"); var http = require("http"); var mime = require("mime"); var FILE_SIZE_LIMIT = config.get('fileSizeLimit'); var FILES_ROOT = config.get('filesRoot'); var INDEX_FILE = config.get('indexFile'); var PORT = config.get('port'); var PUBLIC_ROOT = config.get('publicRoot'); var server = http.createServer(function (req, res) { var BAD_FILE_NAME_EXPRESSION = new RegExp(/\/|\.\./); var fileName = req.url.split('/').slice(-1)[0]; if (~req.url.slice(1).search(BAD_FILE_NAME_EXPRESSION)) { res.statusCode = 400; return res.end(getMessage(fileName, req, res)); } var filePath = FILES_ROOT + "/" + fileName; switch (req.method) { case 'GET': { fileName = fileName || INDEX_FILE; if (fileName == INDEX_FILE) { filePath = PUBLIC_ROOT + "/" + INDEX_FILE; } sendFile(req, res, filePath); break; } case 'POST': { var CONTENT_LENGTH = parseInt(req.headers["content-length"]); if (CONTENT_LENGTH > FILE_SIZE_LIMIT) { res.statusCode = 413; return res.end(getMessage(fileName, req, res)); } receiveFile(filePath, req, res); break; } case 'DELETE': { fs.unlink(filePath, function (err) { if (err) { res.statusCode = 404; } else { res.statusCode = 200; } return res.end(getMessage(fileName, req, res)); }); break; } default: { res.statusCode = 400; return res.end(getMessage(fileName, req, res)); } } }); var getMessage = function (aFileName, req, res) { return req.method + " file \"" + aFileName + "\"; status: " + res.statusCode + " " + http.STATUS_CODES[res.statusCode]; }; var receiveFile = function (filePath, req, res) { fs.open(filePath, 'wx', function (err, fd) { var fileName = filePath.split('/').slice(-1); if (err) { if (err.code === 'EEXIST') { res.statusCode = 409; } else { res.statusCode = 500; } return res.end(getMessage(fileName, req, res)); } var WRITE_OPTIONS = { "autoClose": true, "fd": fd, "flags": "wx" }; var wStream = fs.createWriteStream(filePath, WRITE_OPTIONS); var wStreamSize = 0; wStream .on("error", function (err) { if (err.code === 'EEXIST') { res.statusCode = 409; } else { console.error(err); if (!res.headersSent) { res.setHeader('Connection', 'close'); } res.statusCode = 500; } res.end(getMessage(fileName, req, res)); }) .on('close', function () { res.statusCode = 200; res.end(getMessage(fileName, req, res)); }); req .on('data', function (chunk) { wStreamSize += chunk.length; if (wStreamSize > FILE_SIZE_LIMIT) { wStream.close(); fs.unlink(filePath, function (err) { if (!res.headersSent) { res.setHeader('Connection', 'close'); } if (err) { console.error(err); res.statusCode = 500; return res.end(getMessage(fileName, req, res)); } res.statusCode = 413; res.end(getMessage(fileName, req, res)); }); } }) .pipe(wStream); }); }; var sendFile = function (req, res, filePath) { var file = fs.createReadStream(filePath); file .on('error', function (err) { var fileName = filePath.split('/').slice(-1); if (err.code === 'ENOENT') { res.statusCode = 404; } else { res.statusCode = 500; } return res.end(getMessage(fileName, req, res)); }) .on('open', function () { res.setHeader('Content-Type', mime.lookup(filePath)); }) .on('close', function () { res.statusCode = 200; }) .pipe(res) .on('close', function () { file.destroy(); }); }; server.listen(PORT, function () { console.log("\nserver starts on port " + PORT); }); var getDirName = function () { return process.cwd(); }; module.exports = { getDirName: getDirName, getMessage: getMessage, server: server };
gpl-3.0
daedalus4096/VAM
VAM_App/Model/Block/External/BlockSource.cs
1040
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace VAM_App.Model.Block.External { public class BlockSource { public BlockSource(EMinecraftModule module, BlockGameId id) { this.Module = module; this.Id = id; } public EMinecraftModule Module { get; private set; } public BlockGameId Id { get; private set; } public static bool operator ==(BlockSource lhs, BlockSource rhs) { return (lhs.Module == rhs.Module) && (lhs.Id == rhs.Id); } public static bool operator !=(BlockSource lhs, BlockSource rhs) { return !(lhs == rhs); } public override bool Equals(object obj) { return (obj is BlockSource) && (this == (BlockSource)obj); } public override int GetHashCode() { return (this.Module.GetHashCode() * 1000) + this.Id.GetHashCode(); } } }
gpl-3.0
fvelosa/node-primes
routes/utils/primes/sequential.js
411
// Algorithm from http://brianhan.tumblr.com/post/46454945029 module.exports = sequential; function sequential(min, max) { var sieve = [], i, j, primes = []; for (i = 2; i <= max; ++i) { if (!sieve[i]) { // i has not been marked -- it is prime if (i >= min) { primes.push(i); } for (j = i << 1; j <= max; j += i) { sieve[j] = true; } } } return primes; }
gpl-3.0
hpkns/laravel-html
src/HtmlServiceProvider.php
965
<?php namespace Hpkns\Html; use Collective\Html\HtmlServiceProvider as BaseProvider; class HtmlServiceProvider extends BaseProvider { /** * Bootstrap any application services. * * @return void */ public function boot() { $this->publishes([ __DIR__ . '/../config/html.php' => config_path('html.php') ], 'config'); $this->publishes([ __DIR__ . '/../views' => resource_path('views/hpkns/html'), ]); $this->loadViewsFrom(__DIR__ . '/../views', 'html'); } /** * Register the form builder instance. * * @return void */ protected function registerFormBuilder() { $this->app->singleton('form', function ($app) { $form = new FormBuilder($app['html'], $app['url'], $app['view'], $app['session.store']->token(), $app['request']); return $form->setSessionStore($app['session.store']); }); } }
gpl-3.0
RoosterEngine/RoosterEngine
src/gameengine/motion/motions/NoMotion.java
521
package gameengine.motion.motions; import gameengine.entities.Entity; /** * A {@link Motion} that will always return zero as it's velocity * * @author davidrusu */ public class NoMotion implements Motion { public NoMotion() { } @Override public double getVelocityX() { return 0; } @Override public double getVelocityY() { return 0; } @Override public void reset() { } @Override public void update(Entity entity, double elapsedTime) { } }
gpl-3.0
Shebella/HIPPO
clc/modules/wsstack/src/main/java/com/eucalyptus/ws/ServiceDispatchBootstrapper.java
7368
/******************************************************************************* *Copyright (c) 2009 Eucalyptus Systems, Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, only version 3 of the License. * * * This file is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * for more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. * * Please contact Eucalyptus Systems, Inc., 130 Castilian * Dr., Goleta, CA 93101 USA or visit <http://www.eucalyptus.com/licenses/> * if you need additional information or have any questions. * * This file may incorporate work covered under the following copyright and * permission notice: * * Software License Agreement (BSD License) * * Copyright (c) 2008, Regents of the University of California * All rights reserved. * * Redistribution and use of this software in source and binary forms, with * or without modification, are permitted provided that the following * conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. USERS OF * THIS SOFTWARE ACKNOWLEDGE THE POSSIBLE PRESENCE OF OTHER OPEN SOURCE * LICENSED MATERIAL, COPYRIGHTED MATERIAL OR PATENTED MATERIAL IN THIS * SOFTWARE, AND IF ANY SUCH MATERIAL IS DISCOVERED THE PARTY DISCOVERING * IT MAY INFORM DR. RICH WOLSKI AT THE UNIVERSITY OF CALIFORNIA, SANTA * BARBARA WHO WILL THEN ASCERTAIN THE MOST APPROPRIATE REMEDY, WHICH IN * THE REGENTS DISCRETION MAY INCLUDE, WITHOUT LIMITATION, REPLACEMENT * OF THE CODE SO IDENTIFIED, LICENSING OF THE CODE SO IDENTIFIED, OR * WITHDRAWAL OF THE CODE CAPABILITY TO THE EXTENT NEEDED TO COMPLY WITH * ANY SUCH LICENSES OR RIGHTS. *******************************************************************************/ /* * Author: chris grzegorczyk <grze@eucalyptus.com> */ package com.eucalyptus.ws; import java.util.NoSuchElementException; import org.apache.log4j.Logger; import com.eucalyptus.bootstrap.Bootstrap; import com.eucalyptus.bootstrap.Bootstrap.Stage; import com.eucalyptus.bootstrap.BootstrapException; import com.eucalyptus.bootstrap.Bootstrapper; import com.eucalyptus.bootstrap.Provides; import com.eucalyptus.bootstrap.RunDuring; import com.eucalyptus.component.Component; import com.eucalyptus.component.Components; import com.eucalyptus.component.ServiceConfiguration; import com.eucalyptus.component.ServiceRegistrationException; import com.eucalyptus.records.EventRecord; import com.eucalyptus.records.EventType; import com.eucalyptus.util.Exceptions; import com.eucalyptus.ws.client.ServiceDispatcher; @Provides( com.eucalyptus.bootstrap.Component.any ) @RunDuring( Bootstrap.Stage.RemoteServicesInit ) public class ServiceDispatchBootstrapper extends Bootstrapper { private static Logger LOG = Logger.getLogger( ServiceDispatchBootstrapper.class ); @Override public boolean load( Stage current ) throws Exception { /** * TODO: ultimately remove this: it is legacy and enforces a one-to-one * relationship between component impls **/ for ( com.eucalyptus.bootstrap.Component c : com.eucalyptus.bootstrap.Component.values( ) ) { if ( c.hasDispatcher( ) && c.isAlwaysLocal( ) ) { try { Component comp = Components.lookup( c ); } catch ( NoSuchElementException e ) { throw BootstrapException.throwFatal( "Failed to lookup component which is alwaysLocal: " + c.name( ), e ); } } else if( c.hasDispatcher( ) ) { try { Component comp = Components.lookup( c ); } catch ( NoSuchElementException e ) { Exceptions.eat( "Failed to lookup component which may have dispatcher references: " + c.name( ), e ); } } } LOG.trace( "Touching class: " + ServiceDispatcher.class ); boolean failed = false; Component euca = Components.lookup( Components.delegate.eucalyptus ); for ( Component comp : Components.list( ) ) { //EventRecord.here( ServiceVerifyBootstrapper.class, EventType.COMPONENT_INFO, comp.getName( ), comp.isEnabled( ).toString( ) ).info( ); for ( ServiceConfiguration s : comp.list( ) ) { if ( euca.isLocal( ) && euca.getPeer( ).hasDispatcher( ) ) { try { comp.buildService( s ); } catch ( ServiceRegistrationException ex ) { LOG.error( ex, ex ); failed = true; } catch ( Throwable ex ) { BootstrapException.throwFatal( "load(): Building service failed: " + Components.componentToString( ).apply( comp ), ex ); } } } } if ( failed ) { BootstrapException.throwFatal( "Failures occurred while attempting to load component services. See the log files for more information." ); } return true; } @Override public boolean start( ) throws Exception { boolean failed = false; Component euca = Components.lookup( Components.delegate.eucalyptus ); for ( Component comp : Components.list( ) ) { //EventRecord.here( ServiceVerifyBootstrapper.class, EventType.COMPONENT_INFO, comp.getName( ), comp.isEnabled( ).toString( ) ).info( ); for ( ServiceConfiguration s : comp.list( ) ) { if ( euca.isLocal( ) && euca.getPeer( ).hasDispatcher( ) ) { try { comp.startService( s ); } catch ( ServiceRegistrationException ex ) { LOG.error( ex, ex ); failed = true; } catch ( Throwable ex ) { BootstrapException.throwFatal( "start(): Starting service failed: " + Components.componentToString( ).apply( comp ), ex ); } } } } if ( failed ) { BootstrapException.throwFatal( "Failures occurred while attempting to start component services. See the log files for more information." ); } return true; } }
gpl-3.0
anoopvalluthadam/news_parsing
search.py
1700
import http.client as httplib import urllib import json import argparse def get_key(IP, PORT): params = urllib.parse.urlencode({'username': 'admin', 'password': 'iamadmin'}) headers = {"Content-type": "application/x-www-form-urlencoded", "Accept": "text/plain"} conn = httplib.HTTPConnection(IP, PORT) conn.request("POST", "/", params, headers) response = conn.getresponse() key = json.loads(response.read().decode('utf-8'))['key'] return key def get_news_details(keyword, IP, PORT, key): params = urllib.parse.urlencode({'key': key, 'keywords': keyword}) headers = {"Content-type": "application/x-www-form-urlencoded", "Accept": "text/plain"} conn = httplib.HTTPConnection(IP, PORT) conn.request("POST", "/search", params, headers) response = conn.getresponse() return response.read().decode('utf-8') if __name__ == '__main__': parser = argparse.ArgumentParser() parser = argparse.ArgumentParser() parser.add_argument("--search", help="Search words", action="store", dest='keywords', required=True) parser.add_argument("--port", help="Webserver PORT", action="store", dest='PORT', type=int, required=True) parser.add_argument("--ip", help="Webserver IP", action="store", dest='IP', default='localhost') options = parser.parse_args() key = get_key(options.IP, options.PORT) for res in json.loads(get_news_details( options.keywords, options.IP, options.PORT, key)): print(res)
gpl-3.0
theritty/twitterEventDetectionClustering
src/main/java/topologyBuilder/BoltBuilder.java
17437
package topologyBuilder; import cassandraConnector.CassandraDao; import cassandraConnector.CassandraDaoHybrid; import cassandraConnector.CassandraDaoKeyBased; import eventDetectionHybrid.*; import eventDetectionKeybased.EventCompareBoltKeyBased; import eventDetectionKeybased.EventDetectorWithCassandraBoltKeyBased; import eventDetectionKeybased.WordCountBoltKeyBased; import eventDetectionKeybasedWithSleep.EventCompareBoltKeyBasedWithSleep; import eventDetectionKeybasedWithSleep.EventDetectorWithCassandraBoltKeyBasedWithSleep; import eventDetectionKeybasedWithSleep.WordCountBoltKeyBasedWithSleep; import eventDetectionWithClustering.ClusteringBolt; import eventDetectionWithClustering.EventDetectorBoltClustering; import eventDetectionWithClustering.CassandraSpoutClustering; import eventDetectionKeybased.CassandraSpoutKeyBased; import eventDetectionKeybasedWithSleep.CassandraSpoutKeyBasedWithSleep; import org.apache.storm.generated.StormTopology; import org.apache.storm.topology.TopologyBuilder; import org.apache.storm.tuple.Fields; import java.util.Properties; public class BoltBuilder { public static StormTopology prepareBoltsForCassandraSpoutKeyBasedWithSleep(Properties properties) throws Exception { int COUNT_THRESHOLD = Integer.parseInt(properties.getProperty("keybasedsleep.count.threshold")); String FILENUM = properties.getProperty("keybasedsleep.file.number"); double TFIDF_EVENT_RATE = Double.parseDouble(properties.getProperty("keybasedsleep.tfidf.event.rate")); String TWEETS_TABLE = properties.getProperty("keybasedsleep.tweets.table"); String COUNTS_TABLE = properties.getProperty("keybasedsleep.counts.table"); String EVENTS_TABLE = properties.getProperty("keybasedsleep.events.table"); String PROCESSED_TABLE = properties.getProperty("keybasedsleep.processed.table"); String PROCESSTIMES_TABLE = properties.getProperty("keybasedsleep.processtimes.table"); int CAN_TASK_NUM= Integer.parseInt(properties.getProperty("keybasedsleep.can.taskNum")); int USA_TASK_NUM= Integer.parseInt(properties.getProperty("keybasedsleep.usa.taskNum")); int NUM_DETECTORS= Integer.parseInt(properties.getProperty("keybasedsleep.num.detectors.per.country")); System.out.println("Count threshold " + COUNT_THRESHOLD); TopologyHelper.createFolder(Constants.RESULT_FILE_PATH + FILENUM); TopologyHelper.createFolder(Constants.IMAGES_FILE_PATH + FILENUM); TopologyHelper.createFolder(Constants.TIMEBREAKDOWN_FILE_PATH + FILENUM); System.out.println("Preparing Bolts..."); TopologyBuilder builder = new TopologyBuilder(); CassandraDaoKeyBased cassandraDao = new CassandraDaoKeyBased(TWEETS_TABLE, COUNTS_TABLE, EVENTS_TABLE, PROCESSED_TABLE, PROCESSTIMES_TABLE); CassandraSpoutKeyBasedWithSleep cassandraSpout = new CassandraSpoutKeyBasedWithSleep(cassandraDao, Integer.parseInt(properties.getProperty("keybasedsleep.compare.size")), FILENUM,CAN_TASK_NUM+USA_TASK_NUM+NUM_DETECTORS*2+2); WordCountBoltKeyBasedWithSleep countBoltCAN = new WordCountBoltKeyBasedWithSleep(COUNT_THRESHOLD, FILENUM, cassandraDao); WordCountBoltKeyBasedWithSleep countBoltUSA = new WordCountBoltKeyBasedWithSleep(COUNT_THRESHOLD, FILENUM, cassandraDao); EventDetectorWithCassandraBoltKeyBasedWithSleep eventDetectorBolt1 = new EventDetectorWithCassandraBoltKeyBasedWithSleep(cassandraDao, Constants.RESULT_FILE_PATH, FILENUM, TFIDF_EVENT_RATE); EventDetectorWithCassandraBoltKeyBasedWithSleep eventDetectorBolt2 = new EventDetectorWithCassandraBoltKeyBasedWithSleep(cassandraDao, Constants.RESULT_FILE_PATH, FILENUM, TFIDF_EVENT_RATE); EventCompareBoltKeyBasedWithSleep eventCompareBolt = new EventCompareBoltKeyBasedWithSleep(cassandraDao, FILENUM); builder.setSpout(Constants.CASS_SPOUT_ID, cassandraSpout,1); builder.setBolt(Constants.COUNTRY1_COUNT_BOLT_ID, countBoltUSA,USA_TASK_NUM). fieldsGrouping(Constants.CASS_SPOUT_ID, "USA", new Fields("word")); builder.setBolt(Constants.COUNTRY2_COUNT_BOLT_ID, countBoltCAN,CAN_TASK_NUM). fieldsGrouping(Constants.CASS_SPOUT_ID, "CAN", new Fields("word")); builder.setBolt( Constants.COUNTRY1_EVENT_DETECTOR_BOLT, eventDetectorBolt1,NUM_DETECTORS). shuffleGrouping(Constants.COUNTRY1_COUNT_BOLT_ID); builder.setBolt( Constants.COUNTRY2_EVENT_DETECTOR_BOLT, eventDetectorBolt2,NUM_DETECTORS). shuffleGrouping(Constants.COUNTRY2_COUNT_BOLT_ID); builder.setBolt( Constants.EVENT_COMPARE_BOLT, eventCompareBolt,1). globalGrouping(Constants.COUNTRY1_EVENT_DETECTOR_BOLT). globalGrouping(Constants.COUNTRY2_EVENT_DETECTOR_BOLT); return builder.createTopology(); } public static StormTopology prepareBoltsForCassandraSpoutKeyBased(Properties properties) throws Exception { int COUNT_THRESHOLD = Integer.parseInt(properties.getProperty("keybased.count.threshold")); String FILENUM = properties.getProperty("keybased.file.number"); double TFIDF_EVENT_RATE = Double.parseDouble(properties.getProperty("keybased.tfidf.event.rate")); String TWEETS_TABLE = properties.getProperty("keybased.tweets.table"); String COUNTS_TABLE = properties.getProperty("keybased.counts.table"); String EVENTS_TABLE = properties.getProperty("keybased.events.table"); String PROCESSED_TABLE = properties.getProperty("keybased.processed.table"); String PROCESSTIMES_TABLE = properties.getProperty("keybased.processtimes.table"); int CAN_TASK_NUM= Integer.parseInt(properties.getProperty("keybased.can.taskNum")); int USA_TASK_NUM= Integer.parseInt(properties.getProperty("keybased.usa.taskNum")); int NUM_WORKERS= Integer.parseInt(properties.getProperty("keybased.num.workers")); int NUM_DETECTORS= Integer.parseInt(properties.getProperty("keybased.num.detectors.per.country")); int NUM_COUNTRIES= Integer.parseInt(properties.getProperty("keybased.num.countries")); System.out.println("Count threshold " + COUNT_THRESHOLD); TopologyHelper.createFolder(Constants.RESULT_FILE_PATH + FILENUM); TopologyHelper.createFolder(Constants.IMAGES_FILE_PATH + FILENUM); TopologyHelper.createFolder(Constants.TIMEBREAKDOWN_FILE_PATH + FILENUM); System.out.println("Preparing Bolts..."); TopologyBuilder builder = new TopologyBuilder(); CassandraDaoKeyBased cassandraDao = new CassandraDaoKeyBased(TWEETS_TABLE, COUNTS_TABLE, EVENTS_TABLE, PROCESSED_TABLE, PROCESSTIMES_TABLE); CassandraSpoutKeyBased cassandraSpout = new CassandraSpoutKeyBased(cassandraDao, FILENUM, USA_TASK_NUM, CAN_TASK_NUM, NUM_WORKERS, NUM_DETECTORS*NUM_COUNTRIES,CAN_TASK_NUM+USA_TASK_NUM+NUM_DETECTORS*2+2); WordCountBoltKeyBased countBoltUSA = new WordCountBoltKeyBased(COUNT_THRESHOLD, FILENUM, "USA", cassandraDao, NUM_DETECTORS, NUM_WORKERS+CAN_TASK_NUM+USA_TASK_NUM+3); WordCountBoltKeyBased countBoltCAN = new WordCountBoltKeyBased(COUNT_THRESHOLD, FILENUM, "CAN", cassandraDao, NUM_DETECTORS, NUM_WORKERS+CAN_TASK_NUM+USA_TASK_NUM+3+NUM_DETECTORS); EventDetectorWithCassandraBoltKeyBased eventDetectorBoltUSA = new EventDetectorWithCassandraBoltKeyBased(cassandraDao, Constants.RESULT_FILE_PATH, FILENUM, TFIDF_EVENT_RATE, Integer.parseInt(properties.getProperty("keybased.compare.size")), "USA",USA_TASK_NUM); EventDetectorWithCassandraBoltKeyBased eventDetectorBoltCAN = new EventDetectorWithCassandraBoltKeyBased(cassandraDao, Constants.RESULT_FILE_PATH, FILENUM, TFIDF_EVENT_RATE, Integer.parseInt(properties.getProperty("keybased.compare.size")), "CAN",CAN_TASK_NUM); EventCompareBoltKeyBased eventCompareBolt = new EventCompareBoltKeyBased(cassandraDao, FILENUM); builder.setSpout(Constants.CASS_SPOUT_ID, cassandraSpout,1); builder.setBolt(Constants.COUNTRY1_COUNT_BOLT_ID, countBoltUSA,USA_TASK_NUM).directGrouping(Constants.CASS_SPOUT_ID); builder.setBolt(Constants.COUNTRY2_COUNT_BOLT_ID, countBoltCAN,CAN_TASK_NUM).directGrouping(Constants.CASS_SPOUT_ID); builder.setBolt( Constants.COUNTRY1_EVENT_DETECTOR_BOLT, eventDetectorBoltUSA,NUM_DETECTORS).directGrouping(Constants.COUNTRY1_COUNT_BOLT_ID); builder.setBolt( Constants.COUNTRY2_EVENT_DETECTOR_BOLT, eventDetectorBoltCAN,NUM_DETECTORS).directGrouping(Constants.COUNTRY2_COUNT_BOLT_ID); builder.setBolt( Constants.EVENT_COMPARE_BOLT, eventCompareBolt,1). globalGrouping(Constants.COUNTRY1_EVENT_DETECTOR_BOLT). globalGrouping(Constants.COUNTRY2_EVENT_DETECTOR_BOLT); return builder.createTopology(); } public static StormTopology prepareBoltsForCassandraSpoutClustering(Properties properties) throws Exception { int COUNT_THRESHOLD = Integer.parseInt(properties.getProperty("clustering.count.threshold")); String FILENUM = properties.getProperty("clustering.file.number"); String TWEETS_TABLE = properties.getProperty("clustering.tweets.table"); String EVENTS_TABLE = properties.getProperty("clustering.events.table"); String EVENTS_WORDBASED_TABLE = properties.getProperty("clustering.events_wordbased.table"); String CLUSTER_TABLE = properties.getProperty("clustering.clusters.table"); String PROCESSEDTWEET_TABLE = properties.getProperty("clustering.processed_tweets.table"); String PROCESSTIMES_TABLE = properties.getProperty("clustering.processtimes.table"); String TWEETSANDCLUSTER_TABLE = properties.getProperty("clustering.tweetsandcluster.table"); long START_ROUND = Long.parseLong(properties.getProperty("clustering.start.round")); long END_ROUND = Long.parseLong(properties.getProperty("clustering.end.round")); int CAN_TASK_NUM= Integer.parseInt(properties.getProperty("clustering.can.taskNum")); int USA_TASK_NUM= Integer.parseInt(properties.getProperty("clustering.usa.taskNum")); int NUM_WORKERS= Integer.parseInt(properties.getProperty("clustering.num.workers")); System.out.println("Count threshold " + COUNT_THRESHOLD); TopologyHelper.createFolder(Constants.RESULT_FILE_PATH + FILENUM); TopologyHelper.createFolder(Constants.IMAGES_FILE_PATH + FILENUM); TopologyHelper.createFolder(Constants.TIMEBREAKDOWN_FILE_PATH + FILENUM); CassandraDao cassandraDao = new CassandraDao(TWEETS_TABLE, CLUSTER_TABLE, EVENTS_TABLE, EVENTS_WORDBASED_TABLE, PROCESSEDTWEET_TABLE, PROCESSTIMES_TABLE, TWEETSANDCLUSTER_TABLE); TopologyHelper.writeToFile(Constants.RESULT_FILE_PATH + FILENUM + "/" + "sout.txt", "Preparing Bolts..."); TopologyBuilder builder = new TopologyBuilder(); CassandraSpoutClustering cassandraSpoutClustering = new CassandraSpoutClustering(cassandraDao, FILENUM, START_ROUND, END_ROUND, CAN_TASK_NUM, USA_TASK_NUM, NUM_WORKERS,CAN_TASK_NUM+USA_TASK_NUM+3); ClusteringBolt countBoltCAN = new ClusteringBolt( FILENUM, cassandraDao, "CAN"); ClusteringBolt countBoltUSA = new ClusteringBolt( FILENUM, cassandraDao, "USA"); EventDetectorBoltClustering eventDetectorBoltClusteringCAN = new EventDetectorBoltClustering(FILENUM, cassandraDao, "CAN", CAN_TASK_NUM); EventDetectorBoltClustering eventDetectorBoltClusteringUSA = new EventDetectorBoltClustering(FILENUM, cassandraDao, "USA", USA_TASK_NUM); builder.setSpout(Constants.CASS_SPOUT_ID, cassandraSpoutClustering,1); builder.setBolt(Constants.COUNTRY2_CLUSTERING_BOLT_ID, countBoltCAN,CAN_TASK_NUM).directGrouping(Constants.CASS_SPOUT_ID); builder.setBolt(Constants.COUNTRY1_CLUSTERING_BOLT_ID, countBoltUSA,USA_TASK_NUM).directGrouping(Constants.CASS_SPOUT_ID); builder.setBolt(Constants.COUNTRY2_EVENTDETECTOR_BOLT_ID, eventDetectorBoltClusteringCAN,1).shuffleGrouping(Constants.COUNTRY2_CLUSTERING_BOLT_ID); builder.setBolt(Constants.COUNTRY1_EVENTDETECTOR_BOLT_ID, eventDetectorBoltClusteringUSA,1).shuffleGrouping(Constants.COUNTRY1_CLUSTERING_BOLT_ID); System.out.println("Bolts ready"); return builder.createTopology(); } public static StormTopology prepareBoltsForCassandraSpoutHybrid(Properties properties) throws Exception { int COUNT_THRESHOLD = Integer.parseInt(properties.getProperty("hybrid.count.threshold")); String FILENUM = properties.getProperty("hybrid.file.number"); String TWEETS_TABLE = properties.getProperty("hybrid.tweets.table"); String COUNTS_TABLE = properties.getProperty("hybrid.counts.table"); String EVENTS_TABLE = properties.getProperty("hybrid.events.table"); String EVENTS_KEYBASED_TABLE = properties.getProperty("hybrid.eventskeybased.table"); String CLUSTER_TABLE = properties.getProperty("hybrid.clusters.table"); String PROCESSEDTWEET_TABLE = properties.getProperty("hybrid.processed.table"); String PROCESSTIMES_TABLE = properties.getProperty("hybrid.processtimes.table"); String TWEETSANDCLUSTER_TABLE = properties.getProperty("hybrid.tweetsandcluster.table"); double TFIDF_EVENT_RATE = Double.parseDouble(properties.getProperty("hybrid.tfidf.event.rate")); int CAN_TASK_NUM= Integer.parseInt(properties.getProperty("hybrid.can.taskNum")); int USA_TASK_NUM= Integer.parseInt(properties.getProperty("hybrid.usa.taskNum")); int NUM_WORKERS= Integer.parseInt(properties.getProperty("hybrid.num.workers")); int NUM_FINDERS= Integer.parseInt(properties.getProperty("hybrid.num.detectors.per.country")); System.out.println("Count threshold " + COUNT_THRESHOLD); TopologyHelper.createFolder(Constants.RESULT_FILE_PATH + FILENUM); TopologyHelper.createFolder(Constants.IMAGES_FILE_PATH + FILENUM); TopologyHelper.createFolder(Constants.TIMEBREAKDOWN_FILE_PATH + FILENUM); CassandraDaoHybrid cassandraDao = new CassandraDaoHybrid(TWEETS_TABLE, COUNTS_TABLE, EVENTS_TABLE, PROCESSEDTWEET_TABLE, PROCESSTIMES_TABLE, CLUSTER_TABLE, EVENTS_KEYBASED_TABLE, TWEETSANDCLUSTER_TABLE); TopologyHelper.writeToFile(Constants.RESULT_FILE_PATH + FILENUM + "/" + "sout.txt", "Preparing Bolts..."); TopologyBuilder builder = new TopologyBuilder(); CassandraSpoutHybrid cassandraSpoutClustering = new CassandraSpoutHybrid(cassandraDao, FILENUM, USA_TASK_NUM, CAN_TASK_NUM, NUM_WORKERS, NUM_FINDERS, CAN_TASK_NUM+USA_TASK_NUM+4+NUM_FINDERS*2); WordCountBoltHybrid countBoltUSA = new WordCountBoltHybrid(COUNT_THRESHOLD, FILENUM, "USA", cassandraDao, NUM_FINDERS, NUM_WORKERS+CAN_TASK_NUM+USA_TASK_NUM+5); WordCountBoltHybrid countBoltCAN = new WordCountBoltHybrid(COUNT_THRESHOLD, FILENUM, "CAN", cassandraDao, NUM_FINDERS, NUM_WORKERS+CAN_TASK_NUM+USA_TASK_NUM+5+NUM_FINDERS); EventCandidateFinderHybrid eventCandidateFinderHybridUSA = new EventCandidateFinderHybrid(cassandraDao, Constants.RESULT_FILE_PATH,FILENUM, TFIDF_EVENT_RATE, Integer.parseInt(properties.getProperty("hybrid.compare.size")), "USA", USA_TASK_NUM); EventCandidateFinderHybrid eventCandidateFinderHybridCAN = new EventCandidateFinderHybrid(cassandraDao, Constants.RESULT_FILE_PATH,FILENUM, TFIDF_EVENT_RATE, Integer.parseInt(properties.getProperty("hybrid.compare.size")), "CAN", CAN_TASK_NUM); ClusteringBoltHybrid clusteringBoltUSA = new ClusteringBoltHybrid(cassandraDao, Constants.RESULT_FILE_PATH, FILENUM, TFIDF_EVENT_RATE, Integer.parseInt(properties.getProperty("hybrid.compare.size")), "USA",NUM_FINDERS); ClusteringBoltHybrid clusteringBoltCAN = new ClusteringBoltHybrid(cassandraDao, Constants.RESULT_FILE_PATH, FILENUM, TFIDF_EVENT_RATE, Integer.parseInt(properties.getProperty("hybrid.compare.size")), "CAN",NUM_FINDERS); EventDetectorBoltHybrid eventDetectorBolt = new EventDetectorBoltHybrid(FILENUM, cassandraDao); builder.setSpout(Constants.CASS_SPOUT_ID, cassandraSpoutClustering,1); builder.setBolt(Constants.COUNTRY2_COUNT_BOLT_ID, countBoltCAN,CAN_TASK_NUM).directGrouping(Constants.CASS_SPOUT_ID); builder.setBolt(Constants.COUNTRY1_COUNT_BOLT_ID, countBoltUSA,USA_TASK_NUM).directGrouping(Constants.CASS_SPOUT_ID); builder.setBolt( Constants.COUNTRY1_EVENT_FINDER_BOLT, eventCandidateFinderHybridUSA,NUM_FINDERS).directGrouping(Constants.COUNTRY1_COUNT_BOLT_ID); builder.setBolt( Constants.COUNTRY2_EVENT_FINDER_BOLT, eventCandidateFinderHybridCAN,NUM_FINDERS).directGrouping(Constants.COUNTRY2_COUNT_BOLT_ID); builder.setBolt(Constants.COUNTRY2_CLUSTERING_BOLT_ID, clusteringBoltCAN, 1).shuffleGrouping(Constants.COUNTRY2_EVENT_FINDER_BOLT); builder.setBolt(Constants.COUNTRY1_CLUSTERING_BOLT_ID, clusteringBoltUSA, 1).shuffleGrouping(Constants.COUNTRY1_EVENT_FINDER_BOLT); builder.setBolt( Constants.COUNTRY1_EVENT_DETECTOR_BOLT, eventDetectorBolt,1). globalGrouping(Constants.COUNTRY1_CLUSTERING_BOLT_ID). globalGrouping(Constants.COUNTRY2_CLUSTERING_BOLT_ID); System.out.println("Bolts ready"); return builder.createTopology(); } }
gpl-3.0
jfreyss/spirit
src/com/actelion/research/spiritapp/ui/biosample/form/MetadataFormPanel.java
13475
/* * Spirit, a study/biosample management tool for research. * Copyright (C) 2018 Idorsia Pharmaceuticals Ltd., Hegenheimermattweg 91, * CH-4123 Allschwil, Switzerland. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> * * @author Joel Freyss */ package com.actelion.research.spiritapp.ui.biosample.form; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import java.util.ArrayList; import java.util.Collection; import java.util.List; import javax.swing.BorderFactory; import javax.swing.Box; import javax.swing.JComponent; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JSeparator; import com.actelion.research.spiritapp.ui.SpiritFrame; import com.actelion.research.spiritapp.ui.biosample.MetadataComponent; import com.actelion.research.spiritapp.ui.biosample.MetadataComponentFactory; import com.actelion.research.spiritapp.ui.biosample.SampleIdGenerateField; import com.actelion.research.spiritapp.ui.location.ContainerTextField; import com.actelion.research.spiritapp.ui.location.ContainerTypeComboBox; import com.actelion.research.spiritapp.ui.location.LocationPosTextField; import com.actelion.research.spiritapp.ui.study.GroupLabel; import com.actelion.research.spiritcore.business.biosample.BarcodeType; import com.actelion.research.spiritcore.business.biosample.Biosample; import com.actelion.research.spiritcore.business.biosample.Biotype; import com.actelion.research.spiritcore.business.biosample.BiotypeMetadata; import com.actelion.research.spiritcore.services.dao.DAOBiotype; import com.actelion.research.util.ui.FastFont; import com.actelion.research.util.ui.JCustomLabel; import com.actelion.research.util.ui.JCustomTextField; import com.actelion.research.util.ui.JCustomTextField.CustomFieldType; import com.actelion.research.util.ui.JTextComboBox; import com.actelion.research.util.ui.TextChangeListener; /** * Panel used to represent the edition of a biosample as a form. * * @author Joel Freyss * */ public class MetadataFormPanel extends JPanel { private boolean showContainerLocationSample; private final boolean multicolumns; private Biosample biosample; private final GroupLabel groupLabel = new GroupLabel(); private final JCustomTextField elbTextField = new JCustomTextField(CustomFieldType.ALPHANUMERIC, 10); private final SampleIdGenerateField<Biosample> sampleIdTextField = new SampleIdGenerateField<>(); private final ContainerTypeComboBox containerTypeComboBox = new ContainerTypeComboBox(); private final ContainerTextField containerIdTextField = new ContainerTextField(); private final JCustomTextField amountTextField = new JCustomTextField(CustomFieldType.DOUBLE, 5); private final LocationPosTextField locationTextField = new LocationPosTextField(); private JCustomTextField nameTextField = null; private final List<JComponent> components = new ArrayList<>(); private final JCustomTextField commentsTextField = new JCustomTextField(CustomFieldType.ALPHANUMERIC, 18); private boolean editable = true; private TextChangeListener listener = src -> eventTextChanged(); public MetadataFormPanel(boolean showContainerLocationSample, boolean multicolumns) { this(showContainerLocationSample, multicolumns, null); } public MetadataFormPanel(boolean showContainerLocationSample, boolean multicolumns, Biosample biosample) { super(new GridBagLayout()); this.showContainerLocationSample = showContainerLocationSample; this.multicolumns = multicolumns; setOpaque(false); //Add TextChangeListener containerTypeComboBox.addTextChangeListener(e-> { eventTextChanged(); containerIdTextField.setEnabled(containerTypeComboBox.getSelection()!=null && containerTypeComboBox.getSelection().getBarcodeType()!=BarcodeType.NOBARCODE); }); locationTextField.addTextChangeListener(listener); containerIdTextField.addTextChangeListener(listener); amountTextField.addTextChangeListener(listener); commentsTextField.addTextChangeListener(listener); setBiosample(biosample); } public void setEditable(boolean editable) { if(this.editable==editable) return; this.editable = editable; initUI(); } public boolean isEditable() { return editable; } /** * updateView is called by this function */ private void initUI() { boolean refresh = getComponentCount()>0; if(refresh) {removeAll(); components.clear();} if(biosample!=null && biosample.getBiotype()!=null) { final Biotype biotype = biosample.getBiotype(); GridBagConstraints c = new GridBagConstraints(); c.anchor = GridBagConstraints.WEST; c.gridy = 0; c.ipady = -1; c.insets = new Insets(0, 0, 0, 0); int n = 0; containerTypeComboBox.setEnabled(false); //ELB/Study c.gridy = 0; c.gridx = 0; c.gridwidth=2; c.fill=GridBagConstraints.BOTH; add(groupLabel, c); c.gridwidth=1; //Container if(!biotype.isAbstract()) { c.fill=GridBagConstraints.NONE; if(showContainerLocationSample) { if(!biotype.isHideContainer()) { //ContainerType c.gridy = 5; c.gridx = 0; add(new JLabel("ContainerType: "), c); c.gridx = 1; add(containerTypeComboBox, c); if(biotype.getContainerType()!=null) { containerTypeComboBox.setSelection(biotype.getContainerType()); containerTypeComboBox.setEnabled(false); } else { containerTypeComboBox.setEnabled(editable); } //ContainerId if((biotype.getContainerType()==null || biotype.getContainerType().getBarcodeType()==BarcodeType.MATRIX) && !biotype.isHideContainer()) { c.gridy = 6; c.gridx = 0; add(new JLabel("ContainerId: "), c); c.gridx = 1; add(containerIdTextField, c); containerIdTextField.setEnabled(editable && containerTypeComboBox.getSelection()!=null && containerTypeComboBox.getSelection().getBarcodeType()!=BarcodeType.NOBARCODE); } } } //Amount if(biotype.getAmountUnit()!=null) { c.gridy = multicolumns? 5: 7; c.gridx = multicolumns? 3: 0; add(new JLabel(biotype.getAmountUnit().getNameUnit()+": "), c); c.gridx = multicolumns? 4: 1; add(amountTextField, c); amountTextField.setEnabled(editable); } if(showContainerLocationSample) { //Location c.gridy = multicolumns? 6: 8; c.gridx = multicolumns? 3: 0; add(new JLabel("Location: "), c); c.fill=GridBagConstraints.HORIZONTAL; c.gridx = multicolumns? 4: 1; add(locationTextField, c); locationTextField.setEnabled(editable); } } //Separator c.weightx = 1; c.gridy = 9; c.gridwidth = multicolumns?99:2; c.fill = GridBagConstraints.BOTH; c.insets = new Insets(5, 0, 5, 0); ; c.ipady = 2; c.gridx = 0; add(new JSeparator(JSeparator.HORIZONTAL), c); c.weightx = 0; c.gridwidth=1; c.insets = new Insets(0, 0, 0, 0); ; c.ipady = 0; //Spacer for proper alignment c.gridy = 10; c.gridx = 1; add(Box.createHorizontalStrut(240), c); c.gridy = 11; c.fill=GridBagConstraints.NONE; if(showContainerLocationSample) { //SampleId c.gridx = 0; add(new JCustomLabel("SampleId: ", FastFont.BOLD), c); //Name c.gridx = 1; add(sampleIdTextField, c); sampleIdTextField.setEnabled(editable && !biotype.isHideSampleId()); c.gridy++; } int offsetY = 12; int offsetX = 0; c.gridy = offsetY; //Name if(biotype.getSampleNameLabel()!=null) { String text = nameTextField==null?"": nameTextField.getText(); if(biotype.isNameAutocomplete()) { nameTextField = new JTextComboBox() { @Override public Collection<String> getChoices() { return DAOBiotype.getAutoCompletionFieldsForName(biotype, null); } }; } else { nameTextField = new JCustomTextField(); } nameTextField.setText(text); nameTextField.addTextChangeListener(listener); c.gridx = 0; add(new JCustomLabel(biotype.getSampleNameLabel() + ": "), c); //Name c.fill=GridBagConstraints.HORIZONTAL; c.gridx = 1; add(nameTextField, c); c.gridy++; nameTextField.setEnabled(editable); } //Metadata for(BiotypeMetadata bm: biotype.getMetadata()) { //Metadata if(multicolumns && biotype.getMetadata().size()>=2 && (n++)==(biotype.getMetadata().size()+1)/2) { c.gridy = offsetY; c.gridx = offsetX+2; offsetX+=3; add(Box.createHorizontalStrut(15), c); } JComponent comp = MetadataComponentFactory.getComponentFor(bm); if(comp instanceof MetadataComponent) { ((MetadataComponent) comp).addTextChangeListener(listener); } components.add(comp); c.fill=GridBagConstraints.NONE; c.gridx = offsetX; add(new JLabel(bm.getName()+": "), c); c.fill=GridBagConstraints.HORIZONTAL; c.gridx = offsetX+1; add(comp, c); c.gridy++; comp.setEnabled(editable); } //Comments c.fill=GridBagConstraints.NONE; c.gridx = offsetX; add(new JLabel("Comments: "), c); c.fill=GridBagConstraints.HORIZONTAL; c.gridx = offsetX+1; add(commentsTextField, c); c.gridy++; commentsTextField.setEnabled(editable); //Spacer c.weightx = 1; c.weighty = 1; c.gridx = 20; add(Box.createHorizontalGlue(), c); } updateView(); super.validate(); repaint(); } @Override public void setEnabled(boolean enabled) { super.setEnabled(enabled); if(nameTextField!=null) nameTextField.setEnabled(enabled); for (JComponent c : components) { c.setEnabled(enabled); } commentsTextField.setEnabled(enabled); amountTextField.setEnabled(enabled); } /** * This function calls initUI * @param biosample */ public void setBiosample(Biosample biosample) { this.biosample = biosample; initUI(); } public void updateModel() { updateModel(biosample); } /** * Updates Model (can be different of the encapsulated biosample * @param b */ public void updateModel(Biosample b) { if(b==null) return; Biotype biotype = b.getBiotype(); if(biotype==null) return; assert b.getBiotype().equals(biotype); b.setElb(elbTextField.getText()); if(!biotype.isAbstract()) { if(containerTypeComboBox.isVisible() && containerTypeComboBox.isEnabled()) b.setContainerType(containerTypeComboBox.getSelection()); else b.setContainerType(biotype.getContainerType()); if(containerIdTextField.isEnabled()) b.setContainerId(containerIdTextField.getText()); if(amountTextField.isShowing() && biotype.getAmountUnit()!=null) { b.setAmount(amountTextField.getTextDouble()); } try { if(locationTextField.isShowing()) locationTextField.updateBiosample(); } catch(Exception e) { e.printStackTrace(); } } if(!biotype.isHideSampleId()) { b.setSampleId(sampleIdTextField.getText()); } if(biotype.getSampleNameLabel()!=null) { b.setSampleName(nameTextField==null? null: nameTextField.getText()); } int n = 0; for(BiotypeMetadata bm: biotype.getMetadata()) { JComponent c = components.get(n++); if(c instanceof MetadataComponent) { ((MetadataComponent)c).updateModel(b, bm); } } b.setComments(commentsTextField.getText()); if(amountTextField!=null) b.setAmount(amountTextField.getTextDouble()); } /** * Updates View * @param b */ public void updateView() { Biosample b = biosample; if(b==null || b.getBiotype()==null) return; Biotype biotype = b.getBiotype(); if(b.getAttachedStudy()!=null || (b.getParent()!=null && b.getInheritedPhase()!=null && !b.getInheritedPhase().equals(b.getParent().getInheritedPhase()))) { groupLabel.setVisible(true); groupLabel.setBorder(BorderFactory.createLoweredSoftBevelBorder()); groupLabel.setText(b.getInheritedStudy()==null?"": b.getInheritedStudy().getStudyId() + (b.getInheritedGroup()==null?"": " " + b.getInheritedGroupString(SpiritFrame.getUsername()) + " " + b.getInheritedPhaseString()), b.getInheritedGroup()); } else { groupLabel.setVisible(false); groupLabel.setText(""); } elbTextField.setText(b.getElb()); if(!biotype.isAbstract()) { if(containerTypeComboBox.isEnabled()) containerTypeComboBox.setSelection(b.getContainerType()); if(containerIdTextField.isEnabled()) containerIdTextField.setText(b.getContainerId()); if(biotype.getAmountUnit()!=null) { amountTextField.setTextDouble(b.getAmount()); } locationTextField.setBiosample(b); } sampleIdTextField.putCachedSampleId(b, biotype.getPrefix(), b.getId()<=0? null: b.getSampleId()); sampleIdTextField.setText(b.getSampleId()); if(biotype.getSampleNameLabel()!=null) { nameTextField.setText(b.getSampleName()); } int n = 0; for(BiotypeMetadata bm: biotype.getMetadata()) { JComponent c = components.get(n++); if(c instanceof MetadataComponent) { ((MetadataComponent)c).updateView(b, bm); } } commentsTextField.setText(b.getComments()); } public List<JComponent> getMetadataComponents() { return components; } /** * Can be overidden */ public void eventTextChanged() { } }
gpl-3.0
hostviralnetworks/nampy
nampy/core/DictList.py
8664
# This script is developed from DictList.py # in COBRApy, which was distributed # under GNU GENERAL PUBLIC LICENSE Version 3 # Ebrahim, A., Lerman, J. a, Palsson, B. O., & Hyduke, D. R. (2013). # COBRApy: COnstraints-Based Reconstruction and Analysis for Python. # BMC systems biology, 7(1), 74. doi:10.1186/1752-0509-7-74 # Could replace this with collections.OrderedDict # as ebrahim et al. suggest # but there are some nice default methods defined here # like _check from copy import copy, deepcopy import re def get_id(object): """return an id for the object This allows the function to be generalize to non-nampy.core objects, however, this added function call slows things down. """ return object.id class DictList(list): """A combined dict and list that feels like a list, but has the speed benefits of a dict. This may be eventually replaced by collections.OrderedDict. This was written to address the performance issues associated with searching, accessing, or iterating over a list in python that resulted in notable performance decays with COBRA for python. """ def __init__(self, *args, **kwargs): list.__init__(self, *args, **kwargs) self._dict = {} self._object_dict = {} self._generate_index() def _check(self, id): """make sure duplicate id's are not added. This function is called before adding in elements. """ if id in self._dict: raise ValueError, "id %s is already present in list" % str(id) def _generate_index(self): """rebuild the _dict index """ self._dict = {} self._object_dict = {} [(self._dict.update({v.id: k}), self._object_dict.update({v.id: v})) for k, v in enumerate(self)] def get_by_id(self, id): """return the element with a matching id """ return self._object_dict[id] def list_attr(self, attribute): """return a list of the given attribute for every object """ return [getattr(i, attribute) for i in self] def query(self, search_function, attribute="id"): """query the list search_function: this will be used to select which objects to return This can be: - a string, in which case any object.attribute containing the string will be returned - a compiled regular expression - a boolean function which takes one argument and returns True for desired values attribute: the attribute to be searched for (default is 'id'). If this is None, the object itself is used. returns: a list of objects which match the query """ if attribute == None: select_attribute = lambda x : x else: select_attribute = lambda x: getattr(the_object, attribute) # if the search_function is a regular expression match_list = DictList() if isinstance(search_function, str): search_function = re.compile(search_function) if hasattr(search_function, "findall"): for the_object in self: if search_function.findall(select_attribute(the_object)) != []: match_list.append(the_object) else: for the_object in self: if search_function(select_attribute(the_object)): match_list.append(the_object) return match_list # overriding default list functions with new ones def __setitem__(self, i, y): the_id = get_id(y) self._check(the_id) super(DictList, self).__setitem__(i, y) self._dict[the_id] = i self._object_dict[the_id] = y def union(self, iterable): """adds elements with id's not already in the model""" [self.append(i) for i in iterable if get_id(i) not in self._dict] def __add__(self, other, should_deepcopy=True): """ other: an DictList should_deepcopy: Boolean. Allow for shallow copying, however, this can cause problems if one doesn't know that the items are referenceable from different id """ if should_deepcopy: sum = deepcopy(self) # should this be deepcopy or shallow? else: sum = self sum.extend(other) sum._generate_index() return sum def __iadd__(self, other): self.extend(other) return self def index(self, id): """ id: A string or a :class:`~nampy.core.Object` """ # because values are unique, start and stop are not relevant try: the_object = self._dict[id] except: the_object = self._dict[id.id] if self[the_object] is not id: raise Exception("The id for the nampy.object (%s) provided "%repr(id) +\ "is in this dictionary but the_id is not the nampy.object") return the_object def __contains__(self, object): """DictList.__contains__(object) <==> object in DictList object can either be the object to search for itself, or simply the id """ if hasattr(object, "id"): the_id = get_id(object) # allow to check with the object itself in addition to the id else: the_id = object return self._dict.has_key(the_id) def __copy__(self): self._dict.clear() self._object_dict.clear() the_copy = copy(super(DictList, self)) self._generate_index() the_copy._generate_index() return the_copy def __deepcopy__(self, *args, **kwargs): return DictList((deepcopy(i) for i in self)) # these functions are slower because they rebuild the _dict every time # TODO: speed up def extend(self, iterable): # Want something like # [self.append(i) for i in iterable] # But make a new function to avoid # regenerating indices until the end for i in iterable: the_id = get_id(i) self._check(the_id) self._dict[the_id] = len(self) super(DictList, self).append(i) self._object_dict[the_id] = i # This was not in the version from Ebrahim # but this call makes sense here self._generate_index() def append(self, object): the_id = get_id(object) self._check(the_id) self._dict[the_id] = len(self) super(DictList, self).append(object) self._object_dict[the_id] = object # This was not in the version from Ebrahim # but this call could make sense here self._generate_index() def remove_subset(self, subset): the_list = [x for x in self if x not in subset] self[0: len(the_list)] = the_list del self[len(the_list):] self._generate_index() def insert(self, index, object): self._check(get_id(object)) super(DictList, self).insert(index, object) self._generate_index() def pop(self, *args, **kwargs): value = super(DictList, self).pop(*args, **kwargs) self._generate_index() return value def remove(self, *args, **kwargs): super(DictList, self).remove(*args, **kwargs) self._generate_index() def reverse(self, *args, **kwargs): super(DictList, self).reverse(*args, **kwargs) self._generate_index() def sort(self, *args, **kwargs): super(DictList, self).sort(*args, **kwargs) self._generate_index() def __setslice__(self, *args, **kwargs): super(DictList, self).__setslice__(*args, **kwargs) self._generate_index() def __delslice__(self, *args, **kwargs): super(DictList, self).__delslice__(*args, **kwargs) self._generate_index() def __delitem__(self, *args, **kwargs): super(DictList, self).__delitem__(*args, **kwargs) self._generate_index() def __getattr__(self, attr): try: return super(DictList, self).__getattribute__(attr) except: try: func = super(DictList, self).__getattribute__("get_by_id") return func(attr) except: raise AttributeError("DictList has no attribute or entry %s" % \ (attr)) def __dir__(self): attributes = self.__class__.__dict__.keys() attributes.extend(self._dict.keys()) return attributes
gpl-3.0
orivaldosantana/ECT2203LoP
tutorial/codigos/colisao.js
569
var tamMenor = 10; var tamMaior = 50; var x = 0; // os códigos de "setup" só executam uma vez function setup() { createCanvas(640, 480); } // os códigos de "draw" executam constantemente function draw() { background(0); x=x+2; if (dist(width/2, height/2,x, height/2) < (tamMenor + tamMaior)/2) { fill(255,255,0); ellipse(width/2, height/2, tamMaior, tamMaior); fill(255,255,255); } else { ellipse(width/2, height/2, tamMaior, tamMaior); } ellipse(x, height/2, tamMenor, tamMenor); if (x > width) x = 0; }
gpl-3.0
CCAFS/MARLO
marlo-data/src/main/java/org/cgiar/ccafs/marlo/data/manager/impl/ProjectCrpContributionManagerImpl.java
2520
/***************************************************************** * This file is part of Managing Agricultural Research for Learning & * Outcomes Platform (MARLO). * MARLO 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. * MARLO 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 MARLO. If not, see <http://www.gnu.org/licenses/>. *****************************************************************/ package org.cgiar.ccafs.marlo.data.manager.impl; import org.cgiar.ccafs.marlo.data.dao.ProjectCrpContributionDAO; import org.cgiar.ccafs.marlo.data.manager.ProjectCrpContributionManager; import org.cgiar.ccafs.marlo.data.model.ProjectCrpContribution; import java.util.List; import javax.inject.Named; import javax.inject.Inject; /** * @author Christian Garcia */ @Named public class ProjectCrpContributionManagerImpl implements ProjectCrpContributionManager { private ProjectCrpContributionDAO projectCrpContributionDAO; // Managers @Inject public ProjectCrpContributionManagerImpl(ProjectCrpContributionDAO projectCrpContributionDAO) { this.projectCrpContributionDAO = projectCrpContributionDAO; } @Override public void deleteProjectCrpContribution(long projectCrpContributionId) { projectCrpContributionDAO.deleteProjectCrpContribution(projectCrpContributionId); } @Override public boolean existProjectCrpContribution(long projectCrpContributionID) { return projectCrpContributionDAO.existProjectCrpContribution(projectCrpContributionID); } @Override public List<ProjectCrpContribution> findAll() { return projectCrpContributionDAO.findAll(); } @Override public ProjectCrpContribution getProjectCrpContributionById(long projectCrpContributionID) { return projectCrpContributionDAO.find(projectCrpContributionID); } @Override public ProjectCrpContribution saveProjectCrpContribution(ProjectCrpContribution projectCrpContribution) { return projectCrpContributionDAO.save(projectCrpContribution); } }
gpl-3.0
nemesis866/adminCodeando
app/scripts/resources/fileResource.js
1331
/************************************************ Servicio para obtener los archivos ************************************************/ // Recurso para GET (todos) y POST (function (){ 'use strict'; function FileResource ($resource, storageFactory) { var url = storageFactory.urlServer+'/files'; return $resource(url, {}, { 'save': { method:'POST', isArray:false } }); // return $resource(url); } angular .module('app') .service('fileResource', [ '$resource', 'storageFactory', FileResource ]); })(); // Recurso para GET (uno solo) y DELETE (function (){ 'use strict'; function FileExtraResource ($resource, storageFactory) { var url = storageFactory.urlServer+'/files/:id'; return $resource(url, {}, { 'update': { method: 'PUT' } }); } angular .module('app') .service('fileExtraResource', [ '$resource', 'storageFactory', FileExtraResource ]); })(); // Recurso para GET (uno solo) y DELETE extras (function (){ 'use strict'; function FileTemaResource ($resource, storageFactory) { var url = storageFactory.urlServer+'/files/tema/:id'; return $resource(url, {}, { 'update': { method: 'PUT' } }); } angular .module('app') .service('fileTemaResource', [ '$resource', 'storageFactory', FileTemaResource ]); })();
gpl-3.0
twister65/com_jcomments
administrator/models/smiley.php
3852
<?php /** * JComments - Joomla Comment System * * @version 3.0 * @package JComments * @author Sergey M. Litvinov (smart@joomlatune.ru) * @copyright (C) 2006-2013 by Sergey M. Litvinov (http://www.joomlatune.ru) * @license GNU/GPL: http://www.gnu.org/copyleft/gpl.html */ defined('_JEXEC') or die; JTable::addIncludePath(JPATH_COMPONENT . '/tables'); class JCommentsModelSmiley extends JCommentsModelForm { public function getTable($type = 'Smiley', $prefix = 'JCommentsTable', $config = array()) { return JTable::getInstance($type, $prefix, $config); } public function getForm($data = array(), $loadData = true) { $form = $this->loadForm('com_jcomments.smiley', 'smiley', array('control' => 'jform', 'load_data' => $loadData)); if (empty($form)) { return false; } if (!$this->canEditState((object)$data)) { $form->setFieldAttribute('ordering', 'disabled', 'true'); $form->setFieldAttribute('ordering', 'filter', 'unset'); $form->setFieldAttribute('published', 'disabled', 'true'); $form->setFieldAttribute('published', 'filter', 'unset'); } return $form; } protected function loadFormData() { $data = JFactory::getApplication()->getUserState('com_jcomments.edit.smiley.data', array()); if (empty($data)) { $data = $this->getItem(); } return $data; } public function save($data) { $table = $this->getTable(); $pkName = $table->getKeyName(); $pk = (!empty($data[$pkName])) ? $data[$pkName] : (int)$this->getState($this->getName() . '.id'); try { if ($pk > 0) { $table->load($pk); } if (!$table->bind($data)) { $this->setError($table->getError()); return false; } if (!$table->check()) { $this->setError($table->getError()); return false; } if (!$table->store()) { $this->setError($table->getError()); return false; } $this->saveLegacy(); $this->cleanCache('com_jcomments'); } catch (Exception $e) { $this->setError($e->getMessage()); return false; } if (isset($table->$pkName)) { $this->setState($this->getName() . '.id', $table->$pkName); } return true; } public function saveLegacy() { $query = $this->_db->getQuery(true); $query ->select($this->_db->quoteName(array('code', 'image'))) ->from($this->_db->quoteName('#__jcomments_smilies')) ->where($this->_db->quoteName('published') . ' = 1') ->order($this->_db->quoteName('ordering')); $this->_db->setQuery($query); $items = $this->_db->loadObjectList(); if (count($items)) { $values = array(); foreach ($items as $item) { if ($item->code != '' && $item->image != '') { $values[] = $item->code . "\t" . $item->image; } } $values = count($values) ? implode("\n", $values) : ''; $query = $this->_db->getQuery(true); $query ->select(array('COUNT(*)')) ->from($this->_db->quoteName('#__jcomments_settings')) ->where($this->_db->quoteName('component') . ' = ' . $this->_db->quote('')) ->where($this->_db->quoteName('name') . ' = ' . $this->_db->quote('smilies')); $this->_db->setQuery($query); $count = $this->_db->loadResult(); if ($count) { $query = $this->_db->getQuery(true); $query ->update($this->_db->quoteName('#__jcomments_settings')) ->set($this->_db->quoteName('value') . ' = ' . $this->_db->quote($values)) ->where($this->_db->quoteName('name') . ' = ' . $this->_db->quote('smilies')); $this->_db->setQuery($query); $this->_db->execute(); } else { $query = $this->_db->getQuery(true); $query ->insert($this->_db->quoteName('#__jcomments_settings')) ->columns(array($this->_db->quoteName('name'), $this->_db->quoteName('value'))) ->values($this->_db->quote('smilies') . ', ' . $this->_db->quote($values)); $this->_db->setQuery($query); $this->_db->execute(); } } } }
gpl-3.0
anupkdas-nus/global_synapses
pyNN-dispackgaes/standardmodels/synapses.py
15134
# encoding: utf-8 """ Definition of default parameters (and hence, standard parameter names) for standard dynamic synapse models. Classes for specifying short-term plasticity (facilitation/depression): TsodyksMarkramSynapse Classes for defining STDP rules: AdditiveWeightDependence MultiplicativeWeightDependence AdditivePotentiationMultiplicativeDepression GutigWeightDependence SpikePairRule :copyright: Copyright 2006-2016 by the PyNN team, see AUTHORS. :license: CeCILL, see LICENSE for details. """ try: long except NameError: long = int from pyNN import descriptions from pyNN.standardmodels import StandardSynapseType, STDPWeightDependence, STDPTimingDependence from pyNN.parameters import ParameterSpace class StaticSynapse(StandardSynapseType): """ Synaptic connection with fixed weight and delay. """ default_parameters = { 'weight': 0.0, 'delay': None } class ElectricalSynapse(StandardSynapseType): """ A bidirectional electrical synapse (gap junction) with fixed conductance """ default_parameters = { 'weight': 0.0 # the (bidirectional) conductance of the gap junction (uS) } class TsodyksMarkramSynapse(StandardSynapseType): """ Synapse exhibiting facilitation and depression, implemented using the model of Tsodyks, Markram et al.: `Tsodyks, Uziel and Markram (2000)`_ Synchrony Generation in Recurrent Networks with Frequency-Dependent Synapses. Journal of Neuroscience 20:RC50 Note that the time constant of the post-synaptic current is set in the neuron model, not here. Arguments: `U`: use parameter. `tau_rec`: depression time constant (ms). `tau_facil`: facilitation time constant (ms). .. _`Tsodyks, Uziel and Markram (2000)`: http://www.jneurosci.org/content/20/1/RC50.long """ default_parameters = { 'weight': 0.0, 'delay': None, 'U': 0.5, # use parameter 'tau_rec': 100.0, # depression time constant (ms) 'tau_facil': 0.0, # facilitation time constant (ms) } default_initial_values = { 'u': 0.0 } class SimpleStochasticSynapse(StandardSynapseType): """ Each spike is transmitted with a fixed probability `p`. """ default_parameters = { 'weight': 0.0, 'delay': None, 'p': 0.5, } class StochasticTsodyksMarkramSynapse(StandardSynapseType): """ Synapse exhibiting facilitation and depression, implemented using the model of Tsodyks, Markram et al.: `Tsodyks, Uziel and Markram (2000)`_ Synchrony Generation in Recurrent Networks with Frequency-Dependent Synapses. Journal of Neuroscience 20:RC50 in its stochastic version (cf Fuhrmann et al. 2002) Arguments: `U`: use parameter. `tau_rec`: depression time constant (ms). `tau_facil`: facilitation time constant (ms). .. _`Tsodyks, Uziel and Markram (2000)`: http://www.jneurosci.org/content/20/1/RC50.long """ default_parameters = { 'weight': 0.0, 'delay': None, 'U': 0.5, # use parameter 'tau_rec': 100.0, # depression time constant (ms) 'tau_facil': 0.0, # facilitation time constant (ms) } class MultiQuantalSynapse(StandardSynapseType): """ docstring needed """ default_parameters = { 'weight': 0.0, 'delay': None, 'U': 0.5, # maximal fraction of available resources 'n': 1, # total number of release sites 'tau_rec': 800.0, # depression time constant (ms) 'tau_facil': 0.0, # facilitation time constant (ms) } class STDPMechanism(StandardSynapseType): """ A specification for an STDP mechanism, combining a weight-dependence, a timing-dependence, and, optionally, a voltage-dependence of the synaptic change. For point neurons, the synaptic delay `d` can be interpreted either as occurring purely in the pre-synaptic axon + synaptic cleft, in which case the synaptic plasticity mechanism 'sees' the post-synaptic spike immediately and the pre-synaptic spike after a delay `d` (`dendritic_delay_fraction = 0`) or as occurring purely in the post- synaptic dendrite, in which case the pre-synaptic spike is seen immediately, and the post-synaptic spike after a delay `d` (`dendritic_delay_fraction = 1`), or as having both pre- and post- synaptic components (`dendritic_delay_fraction` between 0 and 1). In a future version of the API, we will allow the different components of the synaptic delay to be specified separately in milliseconds. """ def __init__(self, timing_dependence=None, weight_dependence=None, voltage_dependence=None, dendritic_delay_fraction=1.0, weight=0.0, delay=None): """ Create a new specification for an STDP mechanism, by combining a weight-dependence, a timing-dependence, and, optionally, a voltage- dependence. """ if timing_dependence: assert isinstance(timing_dependence, STDPTimingDependence) if weight_dependence: assert isinstance(weight_dependence, STDPWeightDependence) assert isinstance(dendritic_delay_fraction, (int, long, float)) assert 0 <= dendritic_delay_fraction <= 1 self.timing_dependence = timing_dependence self.weight_dependence = weight_dependence self.voltage_dependence = voltage_dependence self.dendritic_delay_fraction = dendritic_delay_fraction self.weight = weight self.delay = delay or self._get_minimum_delay() self._build_translations() def _build_translations(self): self.translations = self.__class__.base_translations # weight and delay for component in (self.timing_dependence, self.weight_dependence, self.voltage_dependence): if component: self.translations.update(component.translations) @property def model(self): return list(self.possible_models)[0] @property def possible_models(self): """ A list of available synaptic plasticity models for the current configuration (weight dependence, timing dependence, ...) in the current simulator. """ td = self.timing_dependence wd = self.weight_dependence pm = td.possible_models.intersection(wd.possible_models) if len(pm) == 0: raise errors.NoModelAvailableError("No available plasticity models") else: # we pass the set of models back to the simulator-specific module for it to deal with return pm def get_parameter_names(self): assert self.voltage_dependence is None # once we have some models with v-dep, need to update the following return ['weight', 'delay', 'dendritic_delay_fraction'] + \ self.timing_dependence.get_parameter_names() + \ self.weight_dependence.get_parameter_names() def has_parameter(self, name): """Does this model have a parameter with the given name?""" return name in self.get_parameter_names() def get_schema(self): """ Returns the model schema: i.e. a mapping of parameter names to allowed parameter types. """ base_schema = {'weight': float, 'delay': float, 'dendritic_delay_fraction': float} for component in (self.timing_dependence, self.weight_dependence, self.voltage_dependence): if component: base_schema.update((name, type(value)) for name, value in component.default_parameters.items()) return base_schema @property def parameter_space(self): timing_parameters = self.timing_dependence.parameter_space weight_parameters = self.weight_dependence.parameter_space parameters = ParameterSpace({'weight': self.weight, 'delay': self.delay, 'dendritic_delay_fraction': self.dendritic_delay_fraction}, self.get_schema()) parameters.update(**timing_parameters) parameters.update(**weight_parameters) return parameters @property def native_parameters(self): """ A dictionary containing the combination of parameters from the different components of the STDP model. """ timing_parameters = self.timing_dependence.native_parameters weight_parameters = self.weight_dependence.native_parameters parameters = self.translate( ParameterSpace({'weight': self.weight, 'delay': self.delay, 'dendritic_delay_fraction': self.dendritic_delay_fraction}, self.get_schema())) parameters.update(**timing_parameters) parameters.update(**weight_parameters) parameters.update(**self.timing_dependence.extra_parameters) parameters.update(**self.weight_dependence.extra_parameters) return parameters def describe(self, template='stdpmechanism_default.txt', engine='default'): """ Returns a human-readable description of the STDP mechanism. The output may be customized by specifying a different template togther with an associated template engine (see ``pyNN.descriptions``). If template is None, then a dictionary containing the template context will be returned. """ context = {'weight_dependence': self.weight_dependence.describe(template=None), 'timing_dependence': self.timing_dependence.describe(template=None), 'voltage_dependence': self.voltage_dependence and self.voltage_dependence.describe(template=None) or None, 'dendritic_delay_fraction': self.dendritic_delay_fraction} return descriptions.render(engine, template, context) class AdditiveWeightDependence(STDPWeightDependence): """ The amplitude of the weight change is independent of the current weight. If the new weight would be less than `w_min` it is set to `w_min`. If it would be greater than `w_max` it is set to `w_max`. Arguments: `w_min`: minimum synaptic weight, in the same units as the weight, i.e. µS or nA. `w_max`: maximum synaptic weight. """ default_parameters = { 'w_min': 0.0, 'w_max': 1.0, } def __init__(self, w_min=0.0, w_max=1.0): parameters = dict(locals()) parameters.pop('self') STDPWeightDependence.__init__(self, **parameters) class MultiplicativeWeightDependence(STDPWeightDependence): """ The amplitude of the weight change depends on the current weight. For depression, Δw ∝ w - w_min For potentiation, Δw ∝ w_max - w Arguments: `w_min`: minimum synaptic weight, in the same units as the weight, i.e. µS or nA. `w_max`: maximum synaptic weight. """ default_parameters = { 'w_min': 0.0, 'w_max': 1.0, } def __init__(self, w_min=0.0, w_max=1.0): parameters = dict(locals()) parameters.pop('self') STDPWeightDependence.__init__(self, **parameters) class AdditivePotentiationMultiplicativeDepression(STDPWeightDependence): """ The amplitude of the weight change depends on the current weight for depression (Δw ∝ w) and is fixed for potentiation. Arguments: `w_min`: minimum synaptic weight, in the same units as the weight, i.e. µS or nA. `w_max`: maximum synaptic weight. """ default_parameters = { 'w_min': 0.0, 'w_max': 1.0, } def __init__(self, w_min=0.0, w_max=1.0): parameters = dict(locals()) parameters.pop('self') STDPWeightDependence.__init__(self, **parameters) class GutigWeightDependence(STDPWeightDependence): """ The amplitude of the weight change depends on (w_max-w)^mu_plus for potentiation and (w-w_min)^mu_minus for depression. Arguments: `w_min`: minimum synaptic weight, in the same units as the weight, i.e. µS or nA. `w_max`: maximum synaptic weight. `mu_plus`: see above `mu_minus`: see above """ default_parameters = { 'w_min': 0.0, 'w_max': 1.0, 'mu_plus': 0.5, 'mu_minus': 0.5 } def __init__(self, w_min=0.0, w_max=1.0, mu_plus=0.5, mu_minus=0.5): """ Create a new specification for the weight-dependence of an STDP rule. """ parameters = dict(locals()) parameters.pop('self') STDPWeightDependence.__init__(self, **parameters) # Not yet implemented for any module #class PfisterSpikeTripletRule(STDPTimingDependence): # raise NotImplementedError class SpikePairRule(STDPTimingDependence): """ The amplitude of the weight change depends only on the relative timing of spike pairs, not triplets, etc. All possible spike pairs are taken into account (cf Song and Abbott). Arguments: `tau_plus`: time constant of the positive part of the STDP curve, in milliseconds. `tau_minus` time constant of the negative part of the STDP curve, in milliseconds. `A_plus`: amplitude of the positive part of the STDP curve. `A_minus`: amplitude of the negative part of the STDP curve. """ default_parameters = { 'tau_plus': 20.0, 'tau_minus': 20.0, 'A_plus': 0.01, 'A_minus': 0.01, } def __init__(self, tau_plus=20.0, tau_minus=20.0, A_plus=0.01, A_minus=0.01): """ Create a new specification for the timing-dependence of an STDP rule. """ parameters = dict(locals()) parameters.pop('self') STDPTimingDependence.__init__(self, **parameters) class Vogels2011Rule(STDPTimingDependence): """ Timing-dependence rule from Vogels TP, Sprekeler H, Zenke F, Clopath C, Gerstner W (2011) Inhibitory plasticity balances excitation and inhibition in sensory pathways and memory networks. Science 334:1569-73 http://dx.doi.org/10.1126/science.1211095 Potentiation depends on the coincidence of pre- and post-synaptic spikes but not on their order. Pre-synaptic spikes in the absence of post- synaptic ones produce depression. Also see http://senselab.med.yale.edu/modeldb/ShowModel.asp?model=143751 """ default_parameters = { 'tau': 20.0, 'eta': 1e-10, 'rho': 3.0 }
gpl-3.0
epam/JDI
Java/Tests/jdi-httpTests/src/main/java/com/epam/jdi/httptests/SimpleService.java
754
package com.epam.jdi.httptests; import com.epam.http.annotations.*; import com.epam.http.requests.M; import static io.restassured.http.ContentType.HTML; import static io.restassured.http.ContentType.JSON; /** * Created by Roman_Iovlev on 9/25/2016. */ @ServiceDomain("http://httpbin.org/") public class SimpleService { @ContentType(JSON) @GET("/get") @Headers({ @Header(name = "Name", value = "Roman"), @Header(name = "Id", value = "Test") }) M<Info> getInfo; @Header(name = "Type", value = "Test") @POST("/post") M postMethod; @PUT("/put") M putMethod; @PATCH("/patch") M patch; @DELETE("/delete") M delete; @GET("/status/%s") M status; @ContentType(HTML) @GET("/html") M getHTMLMethod; }
gpl-3.0
magical-l/http-part
src/main/java/me/magicall/util/net/http/part/HttpMessage.java
994
package me.magicall.util.net.http.part; /** * http消息。http请求和http响应分别是两种不同的http消息。 * * @author Liang Wenjian */ public interface HttpMessage extends HttpPart { /** * 获取头区域。 * * @return */ HttpHeaderArea getHeaderArea(); default StartLine getStartLine(){ return getHeaderArea().getStartLine(); } default HttpHeaders getHeaders(){ return getHeaderArea().getHeaders(); } /** * 获取体。 * * @return */ HttpBody getBody(); @Override default String asString() { final String head = getHeaderArea().asString(); final StringBuilder sb = new StringBuilder(head); if (head.endsWith(CRLF)) { if (!head.endsWith(CRLF + CRLF)) { sb.append(CRLF); } } else { sb.append(CRLF).append(CRLF); } return sb.append(getBody().asString()).toString(); } }
gpl-3.0
ghedlund/phon
components/src/main/java/ca/phon/ui/ipa/DefaultPhoneMapDisplayUI.java
24553
/* * Copyright (C) 2005-2020 Gregory Hedlund & Yvan Rose * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ca.phon.ui.ipa; import java.awt.*; import java.awt.event.*; import java.awt.geom.*; import java.util.*; import java.util.List; import javax.swing.*; import javax.swing.event.*; import org.jdesktop.swingx.painter.effects.*; import ca.phon.ipa.*; import ca.phon.ipa.alignment.*; import ca.phon.syllable.*; import ca.phon.ui.action.*; import ca.phon.util.*; /** * Default UI for the phone map display. This class * handles drawing and all input to the component. */ public class DefaultPhoneMapDisplayUI extends PhoneMapDisplayUI { /* Action IDs */ private static final String FOCUS_PREVIOUS = "_FOCUS_PREV_PHONE_"; private static final String FOCUS_NEXT = "_FOCUS_NEXT_PHONE_"; private static final String MOVE_PHONE_RIGHT = "_MOVE_PHONE_RIGHT_"; private static final String MOVE_PHONE_LEFT = "_MOVE_PHONE_LEFT_"; private static final String TOGGLE_PHONE_COLOUR = "_TOGGLE_PHONE_COLOUR_"; private static final String SELECT_TARGET_SIDE = "_SELECT_TARGET_SIDE_"; private static final String SELECT_ACTUAL_SIDE = "_SELECT_ACTUAL_SIDE_"; /** The display */ private PhoneMapDisplay display; private static final int insetSize = 2; private Insets phoneBoxInsets = new Insets(insetSize, insetSize, insetSize, insetSize); private Dimension phoneBoxSize = new Dimension(18, 20); private static final int groupSpace = 5; private boolean drawPhoneLock = false; private boolean lockTop = false; // bottom locked // variable for controlling mouse drags private boolean isDragging = false; private int dragLeftEdge = -1; private int dragRightEdge = -1; public DefaultPhoneMapDisplayUI(PhoneMapDisplay c) { super(); this.display = c; // installUI(); } @Override public void installUI(JComponent c) { display = (PhoneMapDisplay)c; // setupActions(); installMouseListener(); installKeyListener(); display.addFocusListener(new FocusListener() { @Override public void focusGained(FocusEvent fe) { display.repaint(); } @Override public void focusLost(FocusEvent fe) { display.repaint(); } }); // display.setRequestFocusEnabled(true); } /** Setup actions for component */ private void setupActions() { ActionMap actionMap = display.getActionMap(); InputMap inputMap = display.getInputMap(JComponent.WHEN_FOCUSED); PhonUIAction focusNextAct = new PhonUIAction(this, "focusNextPhone"); actionMap.put(FOCUS_NEXT, focusNextAct); KeyStroke focusNextKs = KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0); inputMap.put(focusNextKs, FOCUS_NEXT); PhonUIAction moveRightAct = new PhonUIAction(this, "movePhoneRight"); actionMap.put(MOVE_PHONE_RIGHT, moveRightAct); KeyStroke moveRightKs = KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, InputEvent.ALT_MASK); inputMap.put(moveRightKs, MOVE_PHONE_RIGHT); PhonUIAction focusPrevAct = new PhonUIAction(this, "focusPrevPhone"); actionMap.put(FOCUS_PREVIOUS, focusPrevAct); KeyStroke focusPrevKs = KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, 0); inputMap.put(focusPrevKs, FOCUS_PREVIOUS); KeyStroke delKs = KeyStroke.getKeyStroke(KeyEvent.VK_BACK_SPACE, 0); inputMap.put(delKs, FOCUS_PREVIOUS); PhonUIAction moveLeftAct = new PhonUIAction(this, "movePhoneLeft"); actionMap.put(MOVE_PHONE_LEFT, moveLeftAct); KeyStroke moveLeftKs = KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, InputEvent.ALT_MASK); inputMap.put(moveLeftKs, MOVE_PHONE_LEFT); PhonUIAction toggleColourAct = new PhonUIAction(this, "togglePhoneColour"); actionMap.put(TOGGLE_PHONE_COLOUR, toggleColourAct); KeyStroke toggleColourKs = KeyStroke.getKeyStroke(KeyEvent.VK_C, InputEvent.ALT_MASK); inputMap.put(toggleColourKs, TOGGLE_PHONE_COLOUR); PhonUIAction selectTargetAct = new PhonUIAction(this, "setLockTop", true); actionMap.put(SELECT_TARGET_SIDE, selectTargetAct); KeyStroke selectTargetKs = KeyStroke.getKeyStroke(KeyEvent.VK_UP, InputEvent.ALT_MASK); inputMap.put(selectTargetKs, SELECT_TARGET_SIDE); PhonUIAction selectActualAct = new PhonUIAction(this, "setLockTop", false); actionMap.put(SELECT_ACTUAL_SIDE, selectActualAct); KeyStroke selectActualKs = KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, InputEvent.ALT_MASK); inputMap.put(selectActualKs, SELECT_ACTUAL_SIDE); } /** Install mouse listener for component */ private void installMouseListener() { MouseInputAdapter mouseListener = new AlignmentMouseHandler(); display.addMouseListener(mouseListener); display.addMouseMotionListener(mouseListener); } private void installKeyListener() { KeyListener keyListener = new ChangeKeyListener(); display.addKeyListener(keyListener); } /** UI Actions */ public void focusNextPhone(PhonActionEvent pae) { int currentFocus = display.getFocusedPosition(); int nextFocus = currentFocus+1; if(nextFocus < display.getNumberOfAlignmentPositions()) { display.setFocusedPosition(nextFocus); } } public void focusPrevPhone(PhonActionEvent pae) { int currentFocus = display.getFocusedPosition(); int prevFocus = currentFocus-1; if(prevFocus >= 0) { display.setFocusedPosition(prevFocus); } } public void movePhoneRight(PhonActionEvent pae) { Tuple<Integer, Integer> alignmentPos = display.positionToGroupPos(display.getFocusedPosition()); display.movePhoneRight(alignmentPos.getObj1(), alignmentPos.getObj2(), lockTop); } public void movePhoneLeft(PhonActionEvent pae) { Tuple<Integer, Integer> alignmentPos = display.positionToGroupPos(display.getFocusedPosition()); display.movePhoneLeft(alignmentPos.getObj1(), alignmentPos.getObj2(), lockTop); } public void togglePhoneColour(PhonActionEvent pae) { display.togglePaintPhoneBackground(); } public void setLockTop(PhonActionEvent pae) { lockTop = (Boolean)pae.getData(); display.repaint(); } private void paintPhone(Graphics2D g2d, IPAElement p, Area pArea, Rectangle pRect) { Font displayFont = display.getFont(); if(display.isPaintPhoneBackground()) { Color grad_top = p.getScType().getColor().brighter(); Color grad_btm = p.getScType().getColor().darker(); GradientPaint gp = new GradientPaint( new Point(pRect.x, pRect.y), grad_top, new Point(pRect.x, pRect.y+pRect.height), grad_btm); Paint oldPaiont = g2d.getPaint(); g2d.setPaint(gp); // g2d.setColor(p.getScType().getColor()); g2d.fill(pArea); g2d.setPaint(oldPaiont); } else { g2d.setColor(display.getBackground()); g2d.fill(pArea); } // draw phone string Rectangle pBox = new Rectangle(pRect.x + phoneBoxInsets.left, pRect.y + phoneBoxInsets.top, phoneBoxSize.width, phoneBoxSize.height); String txt = (new IPATranscriptBuilder()).append(p).toIPATranscript().stripDiacritics().toString(); Font f = displayFont; FontMetrics fm = g2d.getFontMetrics(f); Rectangle2D stringBounds = fm.getStringBounds(txt, g2d); while( (stringBounds.getWidth() > pBox.width) || (stringBounds.getHeight() > pBox.height)) { f = f.deriveFont(f.getSize2D()-0.2f); fm = g2d.getFontMetrics(f); stringBounds = fm.getStringBounds(txt, g2d); } float phoneX = pBox.x + (pBox.width/2.0f) - ((float)stringBounds.getWidth()/2.0f); float phoneY = (float)pBox.y + (float)pBox.height - fm.getDescent(); g2d.setFont(f); g2d.setColor(display.getForeground()); g2d.drawString(txt, phoneX, phoneY); } @Override public void paint(Graphics g, JComponent c) { Graphics2D g2d = (Graphics2D)g; // Enable antialiasing for shapes g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); // Enable antialiasing for text g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); Dimension size = display.getSize(); if(display.isOpaque()) { g2d.setColor(display.getBackground()); g2d.fillRect(0, 0, size.width, size.height); } // setup phone rect int pX = c.getInsets().left + insetSize; int pY = c.getInsets().top + insetSize; int pW = phoneBoxInsets.left + phoneBoxInsets.right + phoneBoxSize.width; int pH = phoneBoxInsets.top + phoneBoxInsets.bottom + phoneBoxSize.height; // FontMetrics fm = g.getFontMetrics(displayFont); Rectangle phoneRect = new Rectangle(pX, pY, pW, pH); double dArcLengthFill = Math.min(phoneRect.width/1.8, phoneRect.height/1.8); double dOffsetFill = dArcLengthFill / 2; g.setColor(Color.black); for(int gIdx = 0; gIdx < display.getNumberOfGroups(); gIdx++) { PhoneMap pm = display.getPhoneMapForGroup(gIdx); if(pm == null) continue; final IPATranscript ipaTarget = pm.getTargetRep(); final IPATranscript ipaActual = pm.getActualRep(); // holders for syllable and phone rects/areas List<Rectangle> targetSyllRects = new ArrayList<Rectangle>(); List<Rectangle> actualSyllRects = new ArrayList<Rectangle>(); // List<Area> targetPhoneAreas = new ArrayList<Area>(); // List<Area> actualPhoneAreas = new ArrayList<Area>(); Area[] targetPhoneAreas = new Area[pm.getAlignmentLength()]; Area[] actualPhoneAreas = new Area[pm.getAlignmentLength()]; // first create a list of target and actual syllables final SyllableVisitor syllVisitor = new SyllableVisitor(); ipaTarget.accept(syllVisitor); final List<IPATranscript> targetSyllables = syllVisitor.getSyllables(); syllVisitor.reset(); ipaActual.accept(syllVisitor); final List<IPATranscript> actualSyllables = syllVisitor.getSyllables(); // iterate through syllables, create syllable rects and // phone areas as needed final AudiblePhoneVisitor audiblePhoneVisitor = new AudiblePhoneVisitor(); Rectangle refRect = new Rectangle(phoneRect); for(IPATranscript targetSyll:targetSyllables) { audiblePhoneVisitor.reset(); targetSyll.accept(audiblePhoneVisitor); final List<IPAElement> targetPhones = audiblePhoneVisitor.getPhones(); Rectangle syllRect = null; for(int pIdx = 0; pIdx < targetPhones.size(); pIdx++) { IPAElement p = targetPhones.get(pIdx); int alignIdx = -1; for(int aIdx = 0; aIdx < pm.getAlignmentLength(); aIdx++) { IPAElement ap = pm.getTopAlignmentElements().get(aIdx); if(ap != null && ap == p) { alignIdx = aIdx; break; } } if(alignIdx >= 0) { int widthOffset = alignIdx * refRect.width; Rectangle pRect = new Rectangle(refRect); pRect.translate(widthOffset, 0); if(syllRect == null) syllRect = new Rectangle(pRect); else syllRect.add(pRect); Area pArea = null; if(pIdx == 0) { if(targetSyll.length() > 1) pArea = createAreaForLeftEdge(pRect); else pArea = createRoundRectArea(pRect); } else if(pIdx == targetSyll.length() -1) { pArea = createAreaForRightEdge(pRect); } else { pArea = createRectArea(pRect); } targetPhoneAreas[alignIdx] = pArea; paintPhone(g2d, p, pArea, pRect); } } if(syllRect != null) targetSyllRects.add(syllRect); } refRect.translate(0, refRect.height); for(IPATranscript actualSyll:actualSyllables) { audiblePhoneVisitor.reset(); actualSyll.accept(audiblePhoneVisitor); final List<IPAElement> actualPhones = audiblePhoneVisitor.getPhones(); Rectangle syllRect = null; for(int pIdx = 0; pIdx < actualPhones.size(); pIdx++) { IPAElement p = actualPhones.get(pIdx); int alignIdx = -1; for(int aIdx = 0; aIdx < pm.getAlignmentLength(); aIdx++) { IPAElement ap = pm.getBottomAlignmentElements().get(aIdx); if(ap != null && ap == p) { alignIdx = aIdx; break; } } if(alignIdx >= 0) { int widthOffset = alignIdx * refRect.width; Rectangle pRect = new Rectangle(refRect); pRect.translate(widthOffset, 0); if(syllRect == null) syllRect = new Rectangle(pRect); else syllRect.add(pRect); Area pArea = null; if(pIdx == 0) { if(actualSyll.length() > 1) pArea = createAreaForLeftEdge(pRect); else pArea = createRoundRectArea(pRect); } else if(pIdx == actualSyll.length()-1) { pArea = createAreaForRightEdge(pRect); } else { pArea = createRectArea(pRect); } actualPhoneAreas[alignIdx] = pArea; paintPhone(g2d, p, pArea, pRect); } } if(syllRect != null) actualSyllRects.add(syllRect); } g2d.setStroke(new BasicStroke(1.5f)); g2d.setColor(Color.darkGray); for(Rectangle syllRect:targetSyllRects) { Color grad_top = new Color(150, 150, 150, 0); Color grad_btm = new Color(150, 150, 150, 100); GradientPaint gp = new GradientPaint( new Point(syllRect.x+(2*insetSize), (syllRect.y+syllRect.height)-3*insetSize), grad_top, new Point(syllRect.x+(2*insetSize), (syllRect.y+syllRect.height)-insetSize), grad_btm); Paint oldPaint = g2d.getPaint(); g2d.setPaint(gp); // g2d.fillRoundRect(sR.x+insetSize, (sR.y+sR.height)-3*insetSize, sR.width-(2*insetSize), 2*insetSize, // (int)dArcLengthFill, (int)dArcLengthFill); g2d.setPaint(oldPaint); RoundRectangle2D.Double syllRect2d = new RoundRectangle2D.Double(syllRect.x, syllRect.y, syllRect.width, syllRect.height, dArcLengthFill, dArcLengthFill); g2d.draw(new Area(syllRect2d)); } for(Rectangle syllRect:actualSyllRects) { Color grad_top = new Color(150, 150, 150, 0); Color grad_btm = new Color(150, 150, 150, 100); GradientPaint gp = new GradientPaint( new Point(syllRect.x+(2*insetSize), (syllRect.y+syllRect.height)-3*insetSize), grad_top, new Point(syllRect.x+(2*insetSize), (syllRect.y+syllRect.height)-insetSize), grad_btm); Paint oldPaint = g2d.getPaint(); g2d.setPaint(gp); // g2d.fillRoundRect(sR.x+insetSize, (sR.y+sR.height)-3*insetSize, sR.width-(2*insetSize), 2*insetSize, // (int)dArcLengthFill, (int)dArcLengthFill); g2d.setPaint(oldPaint); // g2d.setColor(Color.RED); RoundRectangle2D.Double syllRect2d = new RoundRectangle2D.Double(syllRect.x, syllRect.y, syllRect.width, syllRect.height, dArcLengthFill, dArcLengthFill); g2d.draw(new Area(syllRect2d)); } phoneRect.translate( pm.getAlignmentLength() * phoneRect.width + groupSpace, 0); // paint focus if(display.hasFocus()) { Tuple<Integer, Integer> groupLocation = display.positionToGroupPos(display.getFocusedPosition()); if(groupLocation.getObj1() == gIdx) { Area tArea = targetPhoneAreas[groupLocation.getObj2()]; Area aArea = actualPhoneAreas[groupLocation.getObj2()]; // g2d.setColor(Color.YELLOW); // g2d.setStroke(new BasicStroke(1.5f)); GlowPathEffect gpe = new GlowPathEffect(); gpe.setRenderInsideShape(true); if(tArea != null) { if(drawPhoneLock && lockTop) gpe.setBrushColor(Color.cyan); else gpe.setBrushColor(Color.YELLOW); // g2d.draw(tArea); gpe.apply(g2d, tArea, 0, 0); } if(aArea != null) { if(drawPhoneLock && !lockTop) gpe.setBrushColor(Color.CYAN); else gpe.setBrushColor(Color.YELLOW); // g2d.draw(aArea); gpe.apply(g2d, aArea, 0, 0); } } } } } /* Helper methods for phone shapes */ private Area createRectArea(Rectangle phoneRect) { Rectangle2D.Double rect2d = new Rectangle2D.Double(phoneRect.x, phoneRect.y, phoneRect.width, phoneRect.height); return new Area(rect2d); } private Area createRoundRectArea(Rectangle phoneRect) { double dArcLengthFill = Math.min(phoneRect.width/1.8, phoneRect.height/1.8); double dOffsetFill = dArcLengthFill / 2; RoundRectangle2D.Double roundPhoneRect2d = new RoundRectangle2D.Double( phoneRect.x, phoneRect.y, phoneRect.width, phoneRect.height, dArcLengthFill, dArcLengthFill); return new Area(roundPhoneRect2d); } private Area createAreaForLeftEdge(Rectangle phoneRect) { double dArcLengthFill = Math.min(phoneRect.width/1.8, phoneRect.height/1.8); double dOffsetFill = dArcLengthFill / 2; RoundRectangle2D.Double roundPhoneRect2d = new RoundRectangle2D.Double( phoneRect.x, phoneRect.y, phoneRect.width, phoneRect.height, dArcLengthFill, dArcLengthFill); Rectangle2D.Double fillRect = new Rectangle2D.Double( phoneRect.x+phoneRect.width-dOffsetFill, phoneRect.y, dOffsetFill, phoneRect.height); Area retVal = new Area(roundPhoneRect2d); retVal.add(new Area(fillRect)); return retVal; } private Area createAreaForRightEdge(Rectangle phoneRect) { double dArcLengthFill = Math.min(phoneRect.width/1.8, phoneRect.height/1.8); double dOffsetFill = dArcLengthFill / 2; RoundRectangle2D.Double roundPhoneRect2d = new RoundRectangle2D.Double( phoneRect.x, phoneRect.y, phoneRect.width, phoneRect.height, dArcLengthFill, dArcLengthFill); Rectangle2D.Double fillRect = new Rectangle2D.Double( phoneRect.x, phoneRect.y, dOffsetFill, phoneRect.height); Area retVal = new Area(roundPhoneRect2d); retVal.add(new Area(fillRect)); return retVal; } private Area appendAmbisyllabicLeftEdge(Area a, Rectangle phoneRect) { Area retVal = new Area(a); double dArcLengthFill = Math.min(phoneRect.width/1.8, phoneRect.height/1.8); double dOffsetFill = dArcLengthFill / 2; Rectangle2D.Double addRect = new Rectangle2D.Double( phoneRect.x+phoneRect.width, phoneRect.y, phoneRect.width, phoneRect.height); RoundRectangle2D.Double removeRect = new RoundRectangle2D.Double( phoneRect.x+phoneRect.width, phoneRect.y, phoneRect.width*2, phoneRect.height, dArcLengthFill, dArcLengthFill); Area areaToAdd = new Area(addRect); areaToAdd.subtract(new Area(removeRect)); Rectangle2D.Double urFiller = new Rectangle2D.Double( phoneRect.x+phoneRect.width-dOffsetFill, phoneRect.y, dOffsetFill, dOffsetFill); Rectangle2D.Double brFiller = new Rectangle2D.Double( phoneRect.x+phoneRect.width-dOffsetFill, phoneRect.y+phoneRect.height-dOffsetFill, dOffsetFill, dOffsetFill); retVal.add(new Area(urFiller)); retVal.add(new Area(brFiller)); retVal.add(areaToAdd); return retVal; } private Area appendAmbisyllabicRightEdge(Area a, Rectangle phoneRect) { Area retVal = new Area(a); double dArcLengthFill = Math.min(phoneRect.width/1.8, phoneRect.height/1.8); double dOffsetFill = dArcLengthFill / 2; Rectangle2D.Double addRect = new Rectangle2D.Double( phoneRect.x-phoneRect.width, phoneRect.y, phoneRect.width, phoneRect.height); RoundRectangle2D.Double removeRect = new RoundRectangle2D.Double( phoneRect.x-(phoneRect.width*2), phoneRect.y, phoneRect.width*2, phoneRect.height, dArcLengthFill, dArcLengthFill); Area areaToAdd = new Area(addRect); areaToAdd.subtract(new Area(removeRect)); Rectangle2D.Double ulFiller = new Rectangle2D.Double( phoneRect.x, phoneRect.y, dOffsetFill, dOffsetFill); Rectangle2D.Double blFiller = new Rectangle2D.Double( phoneRect.x, phoneRect.y+phoneRect.height-dOffsetFill, dOffsetFill, dOffsetFill); retVal.add(new Area(ulFiller)); retVal.add(new Area(blFiller)); retVal.add(areaToAdd); // phoneArea.add(areaToAdd); return retVal; } public Rectangle phoneRectForPosition(int pos) { Tuple<Integer, Integer> alignmentPos = display.positionToGroupPos(pos); int currentX = display.getInsets().left + insetSize; int widthPerPhone = phoneBoxInsets.right + phoneBoxInsets.left + phoneBoxSize.width; for(int gIdx = 0; gIdx < alignmentPos.getObj1(); gIdx++) { PhoneMap pm = display.getPhoneMapForGroup(gIdx); currentX += pm.getAlignmentLength() * widthPerPhone; currentX += groupSpace; } currentX += alignmentPos.getObj2() * widthPerPhone; return new Rectangle(currentX, 0, widthPerPhone, phoneBoxSize.height + (2 * insetSize)); } public int locationToAlignmentPosition(Point p) { int widthPerPhone = phoneBoxInsets.right + phoneBoxInsets.left + phoneBoxSize.width; int currentX = display.getInsets().left + insetSize; int pIdx = 0; int currentGrp = 0; while(currentX < p.x) { if(pIdx >= display.getNumberOfAlignmentPositions()) { pIdx = 0; break; } Tuple<Integer, Integer> alignmentPos = display.positionToGroupPos(pIdx); if(alignmentPos.getObj1() != currentGrp) { currentX += groupSpace; currentGrp = alignmentPos.getObj1(); } currentX += widthPerPhone; pIdx++; } return pIdx-1; } @Override public Dimension getPreferredSize(JComponent c) { Dimension retVal = new Dimension(0, 0); int widthPerPhone = phoneBoxInsets.right + phoneBoxInsets.left + phoneBoxSize.width; int height = 2 * ( phoneBoxInsets.top + phoneBoxInsets.bottom + phoneBoxSize.height ); retVal.width = widthPerPhone * (display.getNumberOfAlignmentPositions()) + c.getInsets().right + c.getInsets().left; if(display.getNumberOfGroups() > 0) retVal.width += (display.getNumberOfGroups() - 1) * groupSpace + 2 * insetSize; retVal.height = height + c.getInsets().top + c.getInsets().bottom + /*padding*/ 2 * insetSize; return retVal; } /** * Key listener for cmd/ctrl key press/release */ private class ChangeKeyListener implements KeyListener { @Override public void keyTyped(KeyEvent ke) { } @Override public void keyPressed(KeyEvent ke) { if(ke.getKeyCode() == KeyEvent.VK_ALT) { drawPhoneLock = true; display.repaint(); } } @Override public void keyReleased(KeyEvent ke) { if(ke.getKeyCode() == KeyEvent.VK_ALT) { drawPhoneLock = false; display.repaint(); } } } /** * Mouse handler for modifying alignment via drags. */ private class AlignmentMouseHandler extends MouseInputAdapter { @Override public void mouseClicked(MouseEvent me) { } @Override public void mousePressed(MouseEvent me) { // System.out.println(me); display.requestFocusInWindow(); int pIdx = locationToAlignmentPosition(me.getPoint()); if(pIdx >= 0) { drawPhoneLock = true; if(me.getPoint().getY() > (phoneBoxSize.height + (2 * insetSize)) ) { lockTop = false; } else { lockTop = true; } isDragging = true; Rectangle phoneRect = phoneRectForPosition(pIdx); dragLeftEdge = phoneRect.x; dragRightEdge = phoneRect.x + phoneRect.width; display.setFocusedPosition(pIdx); display.setCursor(Cursor.getPredefinedCursor(Cursor.MOVE_CURSOR)); } } @Override public void mouseReleased(MouseEvent me) { if(drawPhoneLock) { drawPhoneLock = false; display.repaint(); display.setCursor(Cursor.getDefaultCursor()); } } @Override public void mouseDragged(MouseEvent me) { if(isDragging) { if(me.getPoint().getX() > dragRightEdge) { final Tuple<Integer, Integer> groupPos = display.positionToGroupPos(display.getFocusedPosition()); display.movePhoneRight( groupPos.getObj1(), groupPos.getObj2(), lockTop); Rectangle newPRect = phoneRectForPosition( display.getFocusedPosition()); dragLeftEdge = newPRect.x; dragRightEdge = newPRect.x + newPRect.width; } if(me.getPoint().getX() < dragLeftEdge) { final Tuple<Integer, Integer> groupPos = display.positionToGroupPos(display.getFocusedPosition()); display.movePhoneLeft( groupPos.getObj1(), groupPos.getObj2(), lockTop); Rectangle newPRect = phoneRectForPosition( display.getFocusedPosition()); dragLeftEdge = newPRect.x; dragRightEdge = newPRect.x + newPRect.width; } } } } }
gpl-3.0