code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
4
991
language
stringclasses
9 values
license
stringclasses
15 values
size
int32
3
1.05M
#pragma once #include <fstream> #include <iomanip> #include <map> #include <sstream> #include <string> #include "jw.hpp" namespace Zee { class Report { public: Report(std::string title, std::string rowTitle) : title_(title), rowTitle_(rowTitle) { rowSize_ = rowTitle_.size(); } void addColumn(std::string colName, std::string texName = "") { columns_.push_back(colName); if (!texName.empty()) columnsTex_.push_back(texName); else columnsTex_.push_back(colName); columnWidth_[colName] = colName.size(); } void addRow(std::string row) { entries_[row] = std::map<std::string, std::string>(); if (row.size() > rowSize_) { rowSize_ = row.size(); } } template <typename T> void addResult(std::string row, std::string column, T result) { if (entries_.find(row) == entries_.end()) { JWLogError << "Trying to add result to non-existing row" << endLog; return; } std::stringstream ss; ss << std::fixed << std::setprecision(1) << result; entries_[row][column] = ss.str(); entriesTex_[row][column] = ss.str(); if (ss.str().size() > columnWidth_[column]) { columnWidth_[column] = ss.str().size(); } } void addResult(std::string row, std::string column, std::string result, std::string texResult) { addResult(row, column, result); entriesTex_[row][column] = texResult; } void print() { JWLogResult << title_ << endLog; unsigned int lineSize = rowSize_ + 4; for (auto col : columnWidth_) { lineSize += col.second + 2; } std::string hline = ""; for (unsigned int i = 0; i < lineSize; ++i) hline.push_back('-'); auto addElement = [](int width, std::stringstream& result, std::string entry) { result << std::left << std::setprecision(1) << std::setw(width) << std::setfill(' ') << entry; }; std::stringstream ss; addElement(rowSize_ + 2, ss, rowTitle_); ss << "| "; for (auto& col : columns_) addElement(columnWidth_[col] + 2, ss, col); JWLogInfo << hline << endLog; JWLogInfo << ss.str() << endLog; JWLogInfo << hline << endLog; for (auto& rowCols : entries_) { std::stringstream rowSs; addElement(rowSize_ + 2, rowSs, rowCols.first); rowSs << "| "; for (auto& col : columns_) { addElement(columnWidth_[col] + 2, rowSs, rowCols.second[col]); } JWLogInfo << rowSs.str() << endLog; } JWLogInfo << hline << endLog; } void saveToCSV(); void readFromCSV(); void saveToTex(std::string filename) { auto replaceTex = [](std::string entry) { std::string texEntry = entry; auto pos = entry.find("+-"); if (pos != std::string::npos) { texEntry = texEntry.substr(0, pos) + "\\pm" + texEntry.substr(pos + 2); } pos = entry.find("%"); if (pos != std::string::npos) { texEntry = texEntry.substr(0, pos) + "\\%" + texEntry.substr(pos + 1); } return texEntry; }; std::ofstream fout(filename); fout << "\\begin{table}" << std::endl; fout << "\\centering" << std::endl; fout << "\\begin{tabular}{|l|"; for (unsigned int i = 0; i < columns_.size(); ++i) { fout << "l"; fout << ((i < (columns_.size() - 1)) ? " " : "|}"); } fout << std::endl << "\\hline" << std::endl; fout << "\\textbf{" << rowTitle_ << "} & "; for (unsigned int i = 0; i < columns_.size(); ++i) { fout << "$" << columnsTex_[i] << "$"; fout << ((i < (columns_.size() - 1)) ? " & " : "\\\\"); } fout << std::endl; fout << "\\hline" << std::endl; for (auto& rowCols : entriesTex_) { fout << "\\verb|" << rowCols.first << "| & "; for (unsigned int i = 0; i < columns_.size(); ++i) { fout << "$" << replaceTex(rowCols.second[columns_[i]]) << "$"; fout << ((i < (columns_.size() - 1)) ? " & " : "\\\\"); } fout << std::endl; } fout << "\\hline" << std::endl; fout << "\\end{tabular}" << std::endl; ; fout << "\\caption{\\ldots}" << std::endl; fout << "\\end{table}" << std::endl; } private: std::string title_; std::string rowTitle_; std::map<std::string, std::map<std::string, std::string>> entries_; std::map<std::string, std::map<std::string, std::string>> entriesTex_; std::vector<std::string> columns_; std::vector<std::string> columnsTex_; std::map<std::string, unsigned int> columnWidth_; unsigned int rowSize_; }; } // namespace Zee
jwbuurlage/Zee
include/util/report.hpp
C++
gpl-3.0
5,111
package ProxyPattern; public class GumballMachineTestDrive { public static void main(String[] args) { int count = 0; if (args .length < 2) { System.out.println("GumballMachine <name> <inventory>"); System.exit(1); } count = Integer.parseInt(args[1]); GumballMachine gumballMachine = new GumballMachine(args[0], count); GumballMonitor monitor = new GumballMonitor(gumballMachine); monitor.report(); } }
ohgood/Head-First-Design-Patterns
ProxyPattern/GumballMachineTestDrive.java
Java
gpl-3.0
425
<?php /** * OpenSKOS * * LICENSE * * This source file is subject to the GPLv3 license that is bundled * with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://www.gnu.org/licenses/gpl-3.0.txt * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to license@zend.com so we can send you a copy immediately. * * @category OpenSKOS * @package OpenSKOS * @copyright Copyright (c) 2011 Pictura Database Publishing. (http://www.pictura-dp.nl) * @author Mark Lindeman * @license http://www.gnu.org/licenses/gpl-3.0.txt GPLv3 */ class OpenSKOS_Solr_Document implements Countable, ArrayAccess, Iterator { protected $fieldnames = array(); protected $data = array(); protected $position = 0; public function __set($fieldname, $value) { //this differs from self::offsetSet: // - if a field has been set before, make this field multiValued $offsetExists = $this->offsetExists($fieldname); $value = !is_array($value) ? array($value) : $value; if (!$offsetExists) { $this->fieldnames[] = $fieldname; $this->data[$fieldname] = $value; } else { if (is_array($this->data[$fieldname])) { $this->data[$fieldname] = array_merge($this->data[$fieldname], $value); } else { $this->data[$fieldname] = array_merge(array($this->data[$fieldname]), $value); } } } public function offsetSet($fieldname, $value) { $newField = false; if (!$this->offsetExists($fieldname)) { $this->fieldnames[] = $fieldname; $newField = true; } if (!is_array($value)) { if (false === $newField) { $this->data[$fieldname][] = $value; } else { $this->data[$fieldname] = array($value); } } else { if (false === $newField) { $this->data[$fieldname] = $this->data[$fieldname] + $value; } else { $this->data[$fieldname] = $value; } } } public function offsetExists($fieldname) { return in_array($fieldname, $this->fieldnames); } public function offsetUnset($fieldname) { if (!$this->offsetExists($fieldname)) { trigger_error('Undefined index: '.$fieldname, E_USER_NOTICE); return; } unset ( $this->data[$fieldname]); $ix = array_search($fieldname, $this->fieldnames); unset($this->fieldnames[$ix]); $fieldnames = array(); foreach ($this->fieldnames as $fieldname) $fieldnames[] = $fieldname; $this->fieldnames = $fieldnames; $this->rewind(); } public function offsetGet($fieldname) { return $this->offsetExists($fieldname) ? $this->data [$fieldname] : null; } public function count() { return count($this->fieldnames); } public function rewind() { $this->position = 0; } public function current() { return $this->data[$this->fieldnames[$this->position]]; } public function key() { return $this->fieldnames[$this->position]; } public function next() { ++$this->position; } public function valid() { return isset($this->data[$this->fieldnames[$this->position]]); } public function toArray() { return $this->data; } /** * @return OpenSKOS_Solr */ protected function solr() { return Zend_Registry::get('OpenSKOS_Solr'); } public function save($commit = null) { $this->solr()->add(new OpenSKOS_Solr_Documents($this), $commit); return $this; } /** * Registers the notation of the document in the database, or generates one if the document does not have notation. * * @return OpenSKOS_Solr */ public function registerOrGenerateNotation() { if ((isset($this->data['class']) && $this->data['class'] == 'Concept') || (isset($this->data['class'][0]) && $this->data['class'][0] == 'Concept')) { $currentNotation = ''; if (isset($this->data['notation']) && isset($this->data['notation'][0])) { $currentNotation = $this->data['notation'][0]; } if (empty($currentNotation)) { $this->fieldnames[] = 'notation'; $this->data['notation'] = array(OpenSKOS_Db_Table_Notations::getNext()); // Adds the notation to the xml. At the end just before </rdf:Description> $closingTag = '</rdf:Description>'; $notationTag = '<skos:notation>' . $this->data['notation'][0] . '</skos:notation>'; $xml = $this->data['xml']; $xml = str_replace($closingTag, $notationTag . $closingTag, $xml); $this->data['xml'] = $xml; } else { if ( ! OpenSKOS_Db_Table_Notations::isRegistered($currentNotation)) { // If we do not have the notation registered - register it. OpenSKOS_Db_Table_Notations::register($currentNotation); } } } return $this; } /** * Generates uri if it can. Alters the document to put it in, also alters the xml to put rdf:about * @param OpenSKOS_Db_Table_Row_Collection $collection From where to get the basic uri. * @throws OpenSKOS_Rdf_Parser_Exception */ public function autoGenerateUri(OpenSKOS_Db_Table_Row_Collection $collection) { if (!((isset($this->data['class']) && $this->data['class'] == 'Concept') || (isset($this->data['class'][0]) && $this->data['class'][0] == 'Concept'))) { throw new OpenSKOS_Rdf_Parser_Exception( 'Auto generate uri is for concepts only. Not working for concept schemas.' ); } if ($collection === null) { throw new OpenSKOS_Rdf_Parser_Exception( 'Auto generate uri is set to true, but collection is not provided.' ); } $baseUri = $collection->getConceptsBaseUri(); if (empty($baseUri)) { throw new OpenSKOS_Rdf_Parser_Exception( 'Auto generate uri is set to true, but collection is not provided.' ); } if (!preg_match('/\/$/', $baseUri) && !preg_match('/=$/', $baseUri)) { $baseUri .= '/'; } $this->registerOrGenerateNotation(); $uri = $baseUri . $this->data['notation'][0]; // Write in the xml. if (strpos($this->data['xml'][0], 'rdf:about') !== false) { throw new OpenSKOS_Rdf_Parser_Exception( 'Can not auto generate uri if rdf about is set.' ); } $this->data['xml'] = str_replace( '<rdf:Description', '<rdf:Description rdf:about="' . $uri . '"', $this->data['xml'] ); $this->uri = $uri; } /** * * @throws OpenSKOS_Rdf_Parser_Exception */ public function updateStatusInGeneratedXml() { if (isset($this->data['status']) && isset($this->data['status'][0])) { $statusTag = '<openskos:status>' . $this->data['status'][0] . '</openskos:status>'; if (strpos($this->data['xml'][0], 'openskos:status') === false) { // Adds the status to the xml. At the end just before </rdf:Description> $closingTag = '</rdf:Description>'; $xml = $this->data['xml']; $xml = str_replace($closingTag, $statusTag . $closingTag, $xml); $this->data['xml'] = $xml; } else { $xml = $this->data['xml']; $xml = preg_replace('/<openskos:status>.*<\/openskos:status>/i', $statusTag, $xml); $this->data['xml'] = $xml; } } } public function __toString() { $doc = new DOMDocument(); $doc->loadXML('<doc/>'); foreach ($this->fieldnames as $fieldname) { foreach ($this->data[$fieldname] as $value) { $node = $doc->documentElement->appendChild($doc->createElement('field')); $htmlSafeValue = htmlspecialchars($value); if ($htmlSafeValue == $value) { $node->appendChild($doc->createTextNode($htmlSafeValue)); } else { $node->appendChild($doc->createCDataSection($value)); } $node->setAttribute('name', $fieldname); } } return $doc->saveXml($doc->documentElement); } }
olhsha/OpenSKOS2tempMeertens
library/OpenSKOS/Solr/Document.php
PHP
gpl-3.0
8,418
// This code is part of the CPCC-NG project. // // Copyright (c) 2009-2016 Clemens Krainer <clemens.krainer@gmail.com> // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software Foundation, // Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. package cpcc.demo.setup.builder; import java.util.Arrays; import java.util.Collections; import java.util.Date; import java.util.List; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.Stream; import org.apache.commons.lang3.tuple.Pair; import cpcc.core.entities.SensorDefinition; import cpcc.core.entities.SensorType; import cpcc.core.entities.SensorVisibility; import cpcc.core.entities.TopicCategory; /** * Sensor Constants implementation. */ public final class SensorConstants { private static final String SENSOR_MSGS_NAV_SAT_FIX = "sensor_msgs/NavSatFix"; private static final String SENSOR_MSGS_IMAGE = "sensor_msgs/Image"; private static final String STD_MSGS_FLOAT32 = "std_msgs/Float32"; private static final Date now = new Date(); private static final SensorDefinition[] SENSOR_DEFINITIONS = { new SensorDefinitionBuilder() .setId(1) .setDescription("Altimeter") .setLastUpdate(now) .setMessageType(STD_MSGS_FLOAT32) .setParameters(null) .setType(SensorType.ALTIMETER) .setVisibility(SensorVisibility.ALL_VV) .setDeleted(false).build(), new SensorDefinitionBuilder() .setId(2) .setDescription("Area of Operations") .setLastUpdate(now) .setMessageType(STD_MSGS_FLOAT32) .setParameters(null) .setType(SensorType.AREA_OF_OPERATIONS) .setVisibility(SensorVisibility.PRIVILEGED_VV) .setDeleted(false).build(), new SensorDefinitionBuilder() .setId(3) .setDescription("Barometer") .setLastUpdate(now) .setMessageType(STD_MSGS_FLOAT32) .setParameters(null) .setType(SensorType.BAROMETER) .setVisibility(SensorVisibility.ALL_VV) .setDeleted(false).build(), new SensorDefinitionBuilder() .setId(4) .setDescription("Battery") .setLastUpdate(now) .setMessageType(STD_MSGS_FLOAT32) .setParameters(null) .setType(SensorType.BATTERY) .setVisibility(SensorVisibility.PRIVILEGED_VV) .setDeleted(false).build(), new SensorDefinitionBuilder() .setId(5) .setDescription("Belly Mounted Camera 640x480") .setLastUpdate(now) .setMessageType(SENSOR_MSGS_IMAGE) .setParameters("width=640 height=480 yaw=0 down=1.571 alignment=''north''") .setType(SensorType.CAMERA) .setVisibility(SensorVisibility.ALL_VV) .setDeleted(false).build(), // new SensorDefinitionBuilder() // .setId(6) // .setDescription("FPV Camera 640x480") // .setLastUpdate(now) // .setMessageType("sensor_msgs/Image") // .setParameters("width=640 height=480 yaw=0 down=0 alignment=''heading''") // .setType(SensorType.CAMERA) // .setVisibility(SensorVisibility.ALL_VV) // .setDeleted(false).build(), new SensorDefinitionBuilder() .setId(7) .setDescription("CO2") .setLastUpdate(now) .setMessageType(STD_MSGS_FLOAT32) .setParameters(null) .setType(SensorType.CO2) .setVisibility(SensorVisibility.ALL_VV) .setDeleted(false).build(), new SensorDefinitionBuilder() .setId(9) .setDescription("GPS") .setLastUpdate(now) .setMessageType(SENSOR_MSGS_NAV_SAT_FIX) .setParameters(null) .setType(SensorType.GPS) .setVisibility(SensorVisibility.ALL_VV) .setDeleted(false).build(), new SensorDefinitionBuilder() .setId(10) .setDescription("Hardware") .setLastUpdate(now) .setMessageType(STD_MSGS_FLOAT32) .setParameters(null) .setType(SensorType.HARDWARE) .setVisibility(SensorVisibility.PRIVILEGED_VV) .setDeleted(false).build(), new SensorDefinitionBuilder() .setId(11) .setDescription("NOx") .setLastUpdate(now) .setMessageType(STD_MSGS_FLOAT32) .setParameters(null) .setType(SensorType.NOX) .setVisibility(SensorVisibility.ALL_VV) .setDeleted(false).build(), new SensorDefinitionBuilder() .setId(12) .setDescription("Thermometer") .setLastUpdate(now) .setMessageType(STD_MSGS_FLOAT32) .setParameters(null) .setType(SensorType.THERMOMETER) .setVisibility(SensorVisibility.ALL_VV) .setDeleted(false).build() }; public static final Map<TopicCategory, SensorType> TOPIC_SENSOR_MAP = Collections.unmodifiableMap(Stream .of(Pair.of(TopicCategory.ALTITUDE_OVER_GROUND, SensorType.ALTIMETER), Pair.of(TopicCategory.CAMERA, SensorType.CAMERA), Pair.of(TopicCategory.CAMERA_INFO, SensorType.CAMERA), Pair.of(TopicCategory.GPS_POSITION_PROVIDER, SensorType.GPS)) .collect(Collectors.toMap(Pair::getLeft, Pair::getRight))); private SensorConstants() { // Intentionally empty. } /** * @param type the required sensor types. * @return all sensor definitions specified in type. */ public static List<SensorDefinition> byType(SensorType... type) { Set<SensorType> types = Stream.of(type).collect(Collectors.toSet()); return Stream.of(SENSOR_DEFINITIONS).filter(x -> types.contains(x.getType())).collect(Collectors.toList()); } /** * @return all sensor definitions. */ public static List<SensorDefinition> all() { return Arrays.asList(SENSOR_DEFINITIONS); } }
cksystemsgroup/cpcc
cpcc-demo/src/main/java/cpcc/demo/setup/builder/SensorConstants.java
Java
gpl-3.0
6,792
<?php namespace App\Console\Commands; use App\App; use Illuminate\Console\Command; use Illuminate\Support\Facades\Artisan; use Imperium\File\File; class Venus extends Command { /** * The name and signature of the console command. * * @var string */ protected $signature = 'app:secure'; /** * The console command description. * * @var string */ protected $description = 'Configure app'; /** * Create a new command instance. * * @return void */ public function __construct() { parent::__construct(); } /** * Execute the console command. * * @return mixed */ public function handle() { $db = database_path('venus'); if (!File::exist($db)) { if (File::create($db)) { File::copy('.env.example', '.env'); Artisan::call('key:generate'); } } return App::cryptEnv(); } }
fumseck/aphrodite
app/Console/Commands/Venus.php
PHP
gpl-3.0
1,016
/* * Decompiled with CFR 0_114. * * Could not load the following classes: * com.stimulsoft.base.drawing.StiBrush * com.stimulsoft.base.drawing.StiColor * com.stimulsoft.base.drawing.StiSolidBrush * com.stimulsoft.base.drawing.enums.StiPenStyle * com.stimulsoft.base.serializing.annotations.StiDefaulValue * com.stimulsoft.base.serializing.annotations.StiSerializable */ package com.stimulsoft.report.chart.view.series.radar; import com.stimulsoft.base.drawing.StiBrush; import com.stimulsoft.base.drawing.StiColor; import com.stimulsoft.base.drawing.StiSolidBrush; import com.stimulsoft.base.drawing.enums.StiPenStyle; import com.stimulsoft.base.serializing.annotations.StiDefaulValue; import com.stimulsoft.base.serializing.annotations.StiSerializable; import com.stimulsoft.report.chart.core.series.StiSeriesCoreXF; import com.stimulsoft.report.chart.core.series.radar.StiRadarAreaSeriesCoreXF; import com.stimulsoft.report.chart.interfaces.series.IStiSeries; import com.stimulsoft.report.chart.interfaces.series.radar.IStiRadarAreaSeries; import com.stimulsoft.report.chart.view.areas.radar.StiRadarAreaArea; import com.stimulsoft.report.chart.view.series.radar.StiRadarSeries; public class StiRadarAreaSeries extends StiRadarSeries implements IStiRadarAreaSeries { private StiColor lineColor = StiColor.Black; private StiPenStyle lineStyle = StiPenStyle.Solid; private boolean lighting = true; private float lineWidth = 2.0f; private StiBrush brush = new StiSolidBrush(StiColor.Gainsboro); @StiSerializable public StiColor getLineColor() { return this.lineColor; } public void setLineColor(StiColor stiColor) { this.lineColor = stiColor; } @StiDefaulValue(value="Solid") @StiSerializable public StiPenStyle getLineStyle() { return this.lineStyle; } public void setLineStyle(StiPenStyle stiPenStyle) { this.lineStyle = stiPenStyle; } @StiDefaulValue(value="true") @StiSerializable public boolean getLighting() { return this.lighting; } public void setLighting(boolean bl) { this.lighting = bl; } @StiDefaulValue(value="2.0") @StiSerializable public float getLineWidth() { return this.lineWidth; } public void setLineWidth(float f) { if (f > 0.0f) { this.lineWidth = f; } } @StiSerializable(shortName="bh") public final StiBrush getBrush() { return this.brush; } public final void setBrush(StiBrush stiBrush) { this.brush = stiBrush; } public Class GetDefaultAreaType() { return StiRadarAreaArea.class; } public StiRadarAreaSeries() { this.setCore(new StiRadarAreaSeriesCoreXF(this)); } }
talek69/curso
stimulsoft/src/com/stimulsoft/report/chart/view/series/radar/StiRadarAreaSeries.java
Java
gpl-3.0
2,787
package com.base.engine.math; public class Vector2f { private float x, y; public Vector2f(float x, float y) { this.x = x; this.y = y; } public Vector2f normalized() { float len = length(); float x_ = x / len; float y_ = y / len; return new Vector2f(x_, y_); } public float length() { return (float)Math.sqrt(x * x + y * y); } public Vector2f add(Vector2f r) { return new Vector2f(x + r.getX(), y + r.getY()); } public Vector2f add(float r) { return new Vector2f(x + r, y + r); } public Vector2f sub(Vector2f r) { return new Vector2f(x - r.getX(), y - r.getY()); } public Vector2f sub(float r) { return new Vector2f(x - r, y - r); } public Vector2f mul(Vector2f r) { return new Vector2f(x * r.getX(), y * r.getY()); } public Vector2f mul(float r) { return new Vector2f(x * r, y * r); } public Vector2f div(Vector2f r) { return new Vector2f(x / r.getX(), y / r.getY()); } public Vector2f div(float r) { return new Vector2f(x / r, y / r); } public Vector2f abs() { return new Vector2f(Math.abs(x), Math.abs(y)); } @Override public String toString() { return "(" + x + ", " + y + ")"; } public float getX() { return this.x; } public void setX(float x) { this.x = x; } public float getY() { return this.y; } public void setY(float y) { this.y = y; } }
mattparizeau/2DGameEngine
ge_common/com/base/engine/math/Vector2f.java
Java
gpl-3.0
1,731
/* * Twidere - Twitter client for Android * * Copyright (C) 2012 Mariotaku Lee <mariotaku.lee@gmail.com> * * 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 org.mariotaku.twidere.util; import java.io.File; import android.annotation.TargetApi; import android.content.Context; import android.os.Build; import android.os.Environment; public final class EnvironmentAccessor { public static File getExternalCacheDir(final Context context) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO) return GetExternalCacheDirAccessorFroyo.getExternalCacheDir(context); final File ext_storage_dir = Environment.getExternalStorageDirectory(); if (ext_storage_dir != null && ext_storage_dir.isDirectory()) { final String ext_cache_path = ext_storage_dir.getAbsolutePath() + "/Android/data/" + context.getPackageName() + "/cache/"; final File ext_cache_dir = new File(ext_cache_path); if (ext_cache_dir.isDirectory() || ext_cache_dir.mkdirs()) return ext_cache_dir; } return null; } @TargetApi(Build.VERSION_CODES.FROYO) private static class GetExternalCacheDirAccessorFroyo { @TargetApi(Build.VERSION_CODES.FROYO) private static File getExternalCacheDir(final Context context) { return context.getExternalCacheDir(); } } }
gen4young/twidere
src/org/mariotaku/twidere/util/EnvironmentAccessor.java
Java
gpl-3.0
1,877
#include "toString.h" vector<string> splitString(string s, char c) { stringstream ss(s); string token; vector<string> res; while (std::getline(ss, token, c)) res.push_back(token); return res; } string toString(string s) { return s; } string toString(bool b) { stringstream ss; ss << b; return ss.str(); } string toString(int i) { stringstream ss; ss << i; return ss.str(); } string toString(size_t i) { stringstream ss; ss << i; return ss.str(); } string toString(unsigned int i) { stringstream ss; ss << i; return ss.str(); } string toString(float f) { stringstream ss; ss << f; return ss.str(); } string toString(double f) { stringstream ss; ss << f; return ss.str(); } string toString(OSG::Vec2f v) { stringstream ss; ss << v[0] << " " << v[1]; return ss.str(); } string toString(OSG::Pnt3f v) { return toString(OSG::Vec3f(v)); } string toString(OSG::Vec3f v) { stringstream ss; ss << v[0] << " " << v[1] << " " << v[2]; return ss.str(); } string toString(OSG::Vec4f v) { stringstream ss; ss << v[0] << " " << v[1] << " " << v[2] << " " << v[3]; return ss.str(); } string toString(OSG::Vec3i v) { stringstream ss; ss << v[0] << " " << v[1] << " " << v[2]; return ss.str(); } bool toBool(string s) { stringstream ss; ss << s; bool b; ss >> b; return b; } int toInt(string s) { stringstream ss; ss << s; int i; ss >> i; return i; } float toFloat(string s) { stringstream ss; ss << s; float i; ss >> i; return i; } OSG::Vec2f toVec2f(string s) { OSG::Vec2f v; stringstream ss(s); ss >> v[0]; ss >> v[1]; return v; } OSG::Vec3f toVec3f(string s) { OSG::Vec3f v; stringstream ss(s); ss >> v[0]; ss >> v[1]; ss >> v[2]; return v; } OSG::Vec4f toVec4f(string s) { OSG::Vec4f v; stringstream ss(s); ss >> v[0]; ss >> v[1]; ss >> v[2]; ss >> v[3]; return v; } OSG::Pnt3f toPnt3f(string s) { OSG::Pnt3f v; stringstream ss(s); ss >> v[0]; ss >> v[1]; ss >> v[2]; return v; } OSG::Vec3i toVec3i(string s) { OSG::Vec3i v; stringstream ss(s); ss >> v[0]; ss >> v[1]; ss >> v[2]; return v; } void toValue(string s, string& s2) { s2 = s; } void toValue(string s, bool& b) { stringstream ss(s); ss >> b; } void toValue(string s, int& i) { stringstream ss(s); ss >> i; } void toValue(string s, float& f) { stringstream ss(s); ss >> f; } void toValue(string s, OSG::Vec2f& v) { stringstream ss(s); ss >> v[0]; ss >> v[1]; } void toValue(string s, OSG::Vec3f& v) { stringstream ss(s); ss >> v[0]; ss >> v[1]; ss >> v[2]; } void toValue(string s, OSG::Vec4f& v) { stringstream ss(s); ss >> v[0]; ss >> v[1]; ss >> v[2]; ss >> v[3]; } void toValue(string s, OSG::Vec3i& v) { stringstream ss(s); ss >> v[0]; ss >> v[1]; ss >> v[2]; }
infobeisel/polyvr
src/core/utils/toString.cpp
C++
gpl-3.0
2,978
<?php class NivelSni extends AppModel { var $name = 'NivelSni'; var $displayField = 'nombre'; var $validate = array( 'nombre' => array( 'minlength' => array( 'rule' => array('minlength', 1), 'message' => 'Valor muy pequeño.', 'allowEmpty' => false ), ), 'descripcion' => array( 'minlength' => array( 'rule' => array('minlength',1), 'message' => 'Ingrese una descripción mas detallada.', 'allowEmpty' => false ), ), ); var $hasMany = array( 'DatosProfesionales' => array( 'className' => 'DatosProfesionales', 'foreignKey' => 'nivel_sni_id', 'dependent' => false, 'conditions' => '', 'fields' => '', 'order' => '', 'limit' => '', 'offset' => '', 'exclusive' => '', 'finderQuery' => '', 'counterQuery' => '' ) ); }
esteban-uo/-Grafo-Red-Social-de-Investigadores
app/models/nivel_sni.php
PHP
gpl-3.0
803
''' Copyright 2015 This file is part of Orbach. Orbach 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. Orbach 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 Orbach. If not, see <http://www.gnu.org/licenses/>. ''' from django.conf.urls import url, include from rest_framework.routers import DefaultRouter from orbach.core import views router = DefaultRouter() router.register(r'galleries', views.GalleryViewSet) router.register(r'image_files', views.ImageFileViewSet) router.register(r'users', views.UserViewSet) urlpatterns = [ url(r'^', include(router.urls)), ]
awood/orbach
orbach/core/urls.py
Python
gpl-3.0
1,005
public class Silver extends Piece { public Silver(int owner) { super(owner); setSymbol("S"); setType("Silver"); } public boolean canMove(Square from, Square to, Board b) { if(promoted) { //Gold movement code if((Math.abs(from.getR() - to.getR()) <= 1 && (Math.abs(from.getC() - to.getC()) <= 1))) { if(owner == 1) { //If Piece is moving backwards check for diagonal if(from.getR() - to.getR() == 1) { if(from.getC() != to.getC()) { return false; } } } else if(owner == 2) { //If Piece is moving backwards check for diagonal if(from.getR() - to.getR() == -1) { if(from.getC() != to.getC()) { return false; } } } if(to.getPiece() != null) { if(from.getPiece().getOwner() == to.getPiece().getOwner()) { return false; } } return true; } return false; } if((Math.abs(from.getR() - to.getR()) <= 1 && (Math.abs(from.getC() - to.getC()) <= 1))) { if(owner == 1) { //If Piece is moving backwards p1 if(from.getR() - to.getR() == 1) { if(from.getC() == to.getC()) { return false; } } } else if(owner == 2) { //If Piece is moving backwards p2 if(from.getR() - to.getR() == -1) { if(from.getC() == to.getC()) { return false; } } } //moving sideways if(from.getR() == to.getR()) { return false; } if(to.getPiece() != null) { if(from.getPiece().getOwner() == to.getPiece().getOwner()) { return false; } } return true; } return false; } }
dma-gh/Shogi-Game
src/Silver.java
Java
gpl-3.0
1,589
/* * This file is part of the OTHERobjects Content Management System. * * Copyright 2007-2009 OTHER works Limited. * * OTHERobjects 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. * * OTHERobjects 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 OTHERobjects. If not, see <http://www.gnu.org/licenses/>. */ package org.otherobjects.cms.tools; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.security.MessageDigest; import javax.annotation.Resource; import org.otherobjects.cms.model.User; import org.otherobjects.cms.model.UserDao; import org.otherobjects.cms.views.Tool; import org.springframework.stereotype.Component; /** * Generates URL to Gravatar images based on user email address. * * <p>For more info on Gravatars see <a href="http://en.gravatar.com/">http://en.gravatar.com/</a>. Details of * the algorithm are available at <a href="http://en.gravatar.com/site/implement/url">http://en.gravatar.com/site/implement/url</a>. * * @author rich */ @Component @Tool public class GravatarTool { private static final String GRAVATAR_SERVER = "http://www.gravatar.com/avatar/"; private static final String GRAVATAR_SECURE_SERVER = "https://secure.gravatar.com/avatar/"; @Resource protected UserDao userDao; /** * Generates url of Gravatar image for provided user. Username must be valid. * * @param username the username for the required user * @param size width in pixels of required image * @return the url to the image */ public String getUrl(String username, int size, boolean ssl) { return getUrl(username, size, null, ssl); } /** * Generates url of Gravatar image for provided user. Username must be valid. * If the user does not have a Gravatar image then the provided placeholder image url * is returned. * * @param username the username for the required user * @param size width in pixels of required image * @param placeholder the url of image to use when no Gravatar is available * @return the url to the image */ public String getUrl(String username, int size, String placeholder, boolean ssl) { User user = (User) userDao.loadUserByUsername(username); return getUrlForEmail(user.getEmail(), size, null, ssl); } /** * Generates url of Gravatar image for provided user. The email address does not * need to be for a user in OTHERobjects. * * If the user does not have a Gravatar image then the provided placeholder image url * is returned (provide a null placeholder to use the default Gravatar one). * * @param email the email address for the required user * @param size width in pixels of required image * @param placeholder the url of image to use when no Gravatar is available * @param ssl whether or not to get an image from a secure Gravatar url * @return the url to the image */ public String getUrlForEmail(String email, int size, String placeholder, boolean ssl) { StringBuffer url = new StringBuffer(ssl ? GRAVATAR_SECURE_SERVER : GRAVATAR_SERVER); // Add image name url.append(md5Hex(email)); url.append(".jpg"); // Add options StringBuffer options = new StringBuffer(); if (size > 0) { options.append("s=" + size); } try { if (placeholder != null) { if (options.length() > 0) { options.append("&"); } options.append("d=" + URLEncoder.encode(placeholder, "UTF-8")); } } catch (UnsupportedEncodingException e) { // Ignore -- UTF-8 must be supported } if (options.length() > 0) { url.append("?" + options.toString()); } return url.toString(); } public String getUrlForEmail(String email, int size, String placeholder) { return getUrlForEmail(email, size, placeholder, false); } private static String hex(byte[] array) { StringBuffer sb = new StringBuffer(); for (int i = 0; i < array.length; ++i) { sb.append(Integer.toHexString((array[i] & 0xFF) | 0x100).substring(1, 3)); } return sb.toString(); } private static String md5Hex(String message) { try { MessageDigest md = MessageDigest.getInstance("MD5"); return hex(md.digest(message.getBytes("CP1252"))); } catch (Exception e) { // Ignore } return null; } }
0x006EA1E5/oo6
src/main/java/org/otherobjects/cms/tools/GravatarTool.java
Java
gpl-3.0
5,206
package com.baobaotao.transaction.nestcall; public class BaseService { }
puliuyinyi/test
src/main/java/com/baobaotao/transaction/nestcall/BaseService.java
Java
gpl-3.0
75
import kivy kivy.require('1.9.1') from kivy.uix.popup import Popup from kivy.uix.label import Label from kivy.uix.gridlayout import GridLayout from kivy.metrics import dp from kivy.app import Builder from kivy.properties import StringProperty, ObjectProperty from kivy.clock import Clock from kivy.metrics import sp from kivy.metrics import dp from iconbutton import IconButton __all__ = ('alertPopup, confirmPopup, okPopup, editor_popup') Builder.load_string(''' <ConfirmPopup>: cols:1 Label: text: root.text GridLayout: cols: 2 size_hint_y: None height: '44sp' spacing: '5sp' IconButton: text: u'\uf00c' on_press: root.dispatch('on_answer', True) IconButton: text: u'\uf00d' color: ColorScheme.get_primary() on_release: root.dispatch('on_answer', False) <OkPopup>: cols:1 Label: text: root.text GridLayout: cols: 2 size_hint_y: None height: '44sp' spacing: '5sp' IconButton: text: u'\uf00c' on_press: root.dispatch('on_answer', True) <EditorPopup>: id: editor_popup cols:1 BoxLayout: id: content GridLayout: id: buttons cols: 2 size_hint_y: None height: '44sp' spacing: '5sp' IconButton: text: u'\uf00c' on_press: root.dispatch('on_answer', True) IconButton: text: u'\uf00d' color: ColorScheme.get_primary() on_release: root.dispatch('on_answer', False) ''') def alertPopup(title, msg): popup = Popup(title = title, content=Label(text = msg), size_hint=(None, None), size=(dp(600), dp(200))) popup.open() def confirmPopup(title, msg, answerCallback): content = ConfirmPopup(text=msg) content.bind(on_answer=answerCallback) popup = Popup(title=title, content=content, size_hint=(None, None), size=(dp(600),dp(200)), auto_dismiss= False) popup.open() return popup class ConfirmPopup(GridLayout): text = StringProperty() def __init__(self,**kwargs): self.register_event_type('on_answer') super(ConfirmPopup,self).__init__(**kwargs) def on_answer(self, *args): pass def editor_popup(title, content, answerCallback): content = EditorPopup(content=content) content.bind(on_answer=answerCallback) popup = Popup(title=title, content=content, size_hint=(0.7, 0.8), auto_dismiss= False, title_size=sp(18)) popup.open() return popup class EditorPopup(GridLayout): content = ObjectProperty(None) def __init__(self,**kwargs): self.register_event_type('on_answer') super(EditorPopup,self).__init__(**kwargs) def on_content(self, instance, value): Clock.schedule_once(lambda dt: self.ids.content.add_widget(value)) def on_answer(self, *args): pass def okPopup(title, msg, answerCallback): content = OkPopup(text=msg) content.bind(on_ok=answerCallback) popup = Popup(title=title, content=content, size_hint=(None, None), size=(dp(600),dp(200)), auto_dismiss= False) popup.open() return popup class OkPopup(GridLayout): text = StringProperty() def __init__(self,**kwargs): self.register_event_type('on_ok') super(OkPopup,self).__init__(**kwargs) def on_ok(self, *args): pass
ddimensia/RaceCapture_App
autosportlabs/racecapture/views/util/alertview.py
Python
gpl-3.0
3,843
class CheckBase(object): """ Base class for checks. """ hooks = [] # pylint: disable=W0105 """Git hooks to which this class applies. A list of strings.""" def execute(self, hook): """ Executes the check. :param hook: The name of the hook being run. :type hook: :class:`str` :returns: ``True`` if the check passed, ``False`` if not. :rtype: :class:`bool` """ pass
lddubeau/glerbl
glerbl/check/__init__.py
Python
gpl-3.0
461
<?php /* Copyright (C) 2003-2006 Rodolphe Quiedeville <rodolphe@quiedeville.org> * Copyright (C) 2004-2011 Laurent Destailleur <eldy@users.sourceforge.net> * Copyright (C) 2005-2009 Regis Houssin <regis.houssin@capnetworks.com> * * 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 htdocs/product/stock/index.php * \ingroup stock * \brief Home page of stock area */ require '../../main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/product/stock/class/entrepot.class.php'; $langs->load("stocks"); // Security check $result=restrictedArea($user,'stock'); /* * View */ $help_url='EN:Module_Stocks_En|FR:Module_Stock|ES:M&oacute;dulo_Stocks'; llxHeader("",$langs->trans("Stocks"),$help_url); print_fiche_titre($langs->trans("StocksArea")); //print '<table border="0" width="100%" class="notopnoleftnoright">'; //print '<tr><td valign="top" width="30%" class="notopnoleft">'; print '<div class="fichecenter"><div class="fichethirdleft">'; /* * Zone recherche entrepot */ print '<form method="post" action="'.DOL_URL_ROOT.'/product/stock/liste.php">'; print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">'; print '<table class="noborder nohover" width="100%">'; print "<tr class=\"liste_titre\">"; print '<td colspan="3">'.$langs->trans("Search").'</td></tr>'; print "<tr ".$bc[false]."><td>"; print $langs->trans("Ref").':</td><td><input class="flat" type="text" size="18" name="sref"></td><td rowspan="2"><input type="submit" value="'.$langs->trans("Search").'" class="button"></td></tr>'; print "<tr ".$bc[false]."><td>".$langs->trans("Other").':</td><td><input type="text" name="sall" class="flat" size="18"></td>'; print "</table></form><br>"; $sql = "SELECT e.label, e.rowid, e.statut"; $sql.= " FROM ".MAIN_DB_PREFIX."entrepot as e"; $sql.= " WHERE e.statut in (0,1)"; $sql.= " AND e.entity = ".$conf->entity; $sql.= $db->order('e.statut','DESC'); $sql.= $db->plimit(15, 0); $result = $db->query($sql); if ($result) { $num = $db->num_rows($result); $i = 0; print '<table class="noborder" width="100%">'; print '<tr class="liste_titre"><td colspan="2">'.$langs->trans("Warehouses").'</td></tr>'; if ($num) { $entrepot=new Entrepot($db); $var=True; while ($i < $num) { $objp = $db->fetch_object($result); $var=!$var; print "<tr $bc[$var]>"; print "<td><a href=\"fiche.php?id=$objp->rowid\">".img_object($langs->trans("ShowStock"),"stock")." ".$objp->label."</a></td>\n"; print '<td align="right">'.$entrepot->LibStatut($objp->statut,5).'</td>'; print "</tr>\n"; $i++; } $db->free($result); } print "</table>"; } else { dol_print_error($db); } //print '</td><td valign="top" width="70%" class="notopnoleftnoright">'; print '</div><div class="fichetwothirdright"><div class="ficheaddleft">'; // Last movements $max=10; $sql = "SELECT p.rowid, p.label as produit,"; $sql.= " e.label as stock, e.rowid as entrepot_id,"; $sql.= " m.value, m.datem"; $sql.= " FROM ".MAIN_DB_PREFIX."entrepot as e"; $sql.= ", ".MAIN_DB_PREFIX."stock_mouvement as m"; $sql.= ", ".MAIN_DB_PREFIX."product as p"; $sql.= " WHERE m.fk_product = p.rowid"; $sql.= " AND m.fk_entrepot = e.rowid"; $sql.= " AND e.entity = ".$conf->entity; if (empty($conf->global->STOCK_SUPPORTS_SERVICES)) $sql.= " AND p.fk_product_type = 0"; $sql.= $db->order("datem","DESC"); $sql.= $db->plimit($max,0); dol_syslog("Index:list stock movements sql=".$sql, LOG_DEBUG); $resql = $db->query($sql); if ($resql) { $num = $db->num_rows($resql); print '<table class="noborder" width="100%">'; print "<tr class=\"liste_titre\">"; print '<td>'.$langs->trans("LastMovements",min($num,$max)).'</td>'; print '<td>'.$langs->trans("Product").'</td>'; print '<td>'.$langs->trans("Warehouse").'</td>'; print '<td align="right"><a href="'.DOL_URL_ROOT.'/product/stock/mouvement.php">'.$langs->trans("FullList").'</a></td>'; print "</tr>\n"; $var=True; $i=0; while ($i < min($num,$max)) { $objp = $db->fetch_object($resql); $var=!$var; print "<tr $bc[$var]>"; print '<td>'.dol_print_date($db->jdate($objp->datem),'dayhour').'</td>'; print "<td><a href=\"../fiche.php?id=$objp->rowid\">"; print img_object($langs->trans("ShowProduct"),"product").' '.$objp->produit; print "</a></td>\n"; print '<td><a href="fiche.php?id='.$objp->entrepot_id.'">'; print img_object($langs->trans("ShowWarehouse"),"stock").' '.$objp->stock; print "</a></td>\n"; print '<td align="right">'; if ($objp->value > 0) print '+'; print $objp->value.'</td>'; print "</tr>\n"; $i++; } $db->free($resql); print "</table>"; } //print '</td></tr></table>'; print '</div></div></div>'; llxFooter(); $db->close(); ?>
jcntux/Dolibarr
htdocs/product/stock/index.php
PHP
gpl-3.0
5,429
<?php require_once ('getConnection.php'); $stmt = $connect -> stmt_init(); $query = "SELECT c_token FROM t_course WHERE c_id = ?"; if (!($stmt -> prepare($query))) { echo "Prepare failed: " . $connect -> errno . $connect -> error; } if (!($stmt -> bind_param("d", $_POST["course"]))) { echo "Bind failed: " . $connect -> errno . $connect -> error; } if (!$stmt -> execute()) { echo "Execute failed: (" . $connect -> errno . ") " . $connect -> error; } if (!($result = $stmt -> get_result())) { echo "Result failed: (" . $connect -> errno . ") " . $connect -> error; } while ($row = $result -> fetch_array(MYSQLI_NUM)) { $course_token = $row[0]; } $stmt -> close(); $stmt = $connect -> stmt_init(); $query = "SELECT p_token FROM t_prof WHERE p_id = ?"; if (!($stmt -> prepare($query))) { echo "Prepare failed: " . $connect -> errno . $connect -> error; } if (!($stmt -> bind_param("d", $_POST['prof']))) { echo "Bind failed: " . $connect -> errno . $connect -> error; } if (!$stmt -> execute()) { echo "Execute failed: (" . $connect -> errno . ") " . $connect -> error; } if (!($result = $stmt -> get_result())) { echo "Result failed: (" . $connect -> errno . ") " . $connect -> error; } while ($row = $result -> fetch_array(MYSQLI_NUM)) { $prof_token = $row[0]; } $stmt -> close(); for ($i = 1; $i <= $_POST['count_tan']; $i++) { do { $stmt = $connect -> stmt_init(); $query = "SELECT t_tan FROM t_tan"; if (!($stmt -> prepare($query))) { echo "Prepare failed: " . $connect -> errno . $connect -> error; } if (!$stmt -> execute()) { echo "Execute failed: (" . $connect -> errno . ") " . $connect -> error; } if (!($result = $stmt -> get_result())) { echo "Result failed: (" . $connect -> errno . ") " . $connect -> error; } while ($row = $result -> fetch_array(MYSQLI_NUM)) { $generated_tans[] = $row[0]; } $stmt -> close(); $tan_pruef = generate($prof_token, $course_token); if (!empty($generated_tans)) { $pruef = in_array($tan_pruef, $generated_tans); } else { $pruef = false; } } while ($pruef); $tan[] = $tan_pruef; } echo "<h1>generated TANs</h1>"; echo "\n"; foreach ($tan as $t) { $stmt = $connect -> stmt_init(); $query = "INSERT into t_tan(t_course, t_prof,t_tan) VALUES(?,?,?)"; if (!($stmt -> prepare($query))) { echo "Prepare failed: " . $connect -> errno . $connect -> error; } if (!($stmt -> bind_param("dds", $_POST['course'], $_POST['prof'], $t))) { echo "Bind failed: " . $connect -> errno . $connect -> error; } if (!$stmt -> execute()) { echo "Execute failed: (" . $connect -> errno . ") " . $connect -> error; } $stmt -> close(); echo '<p>' . $t . '</p>'; echo "\n"; } unset($_POST); echo '<a href="admin_tan.html"><img src="../images/buttons/button_back.jpg" alt="back" id="button" width = 300 height = 150/></a>'; echo "\n"; mysqli_close($connect); function generate($token1, $token2) { $token = rand(100000, 999999); $TAN = $token1 . $token . $token2; return $TAN; }; ?>
Babbafett/evaluate_your_prof
php/generateTAN.php
PHP
gpl-3.0
2,980
/* Copyright (C) 2013 Jason Gowan 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.gowan.plugin; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.ListIterator; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.IJavaProject; import org.eclipse.jdt.core.IPackageFragment; import org.eclipse.jdt.core.IPackageFragmentRoot; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jface.viewers.IStructuredSelection; public class SelectionToICompilationUnitList implements List<ICompilationUnit> { private List<ICompilationUnit> list; public SelectionToICompilationUnitList(IStructuredSelection selection){ List<ICompilationUnit> localList = new ArrayList<ICompilationUnit>(); List<Object> selectionList = selection.toList(); for (Object object : selectionList) { localList.addAll( delegate(object) ); } this.list = localList; } protected List<ICompilationUnit> delegate(Object selected){ List<ICompilationUnit> compilationUnits = new ArrayList<ICompilationUnit>(); if( selected instanceof ICompilationUnit ){ compilationUnits.add((ICompilationUnit)selected); }else if ( selected instanceof IPackageFragment){ compilationUnits.addAll(get((IPackageFragment)selected)); }else if( selected instanceof IPackageFragmentRoot){ compilationUnits.addAll(get((IPackageFragmentRoot)selected)); }else if( selected instanceof IJavaProject){ compilationUnits.addAll(get((IJavaProject)selected)); } return compilationUnits; } protected List<ICompilationUnit> get(IJavaProject selected) { List<ICompilationUnit> result = new ArrayList<ICompilationUnit>(); IPackageFragmentRoot[] packageRoots; try { packageRoots = selected.getAllPackageFragmentRoots(); for(int i=0; i<packageRoots.length; i++){ result.addAll(get(packageRoots[i])); } } catch (JavaModelException e) { e.printStackTrace(); } return result; } protected List<ICompilationUnit> get(IPackageFragment frag){ List<ICompilationUnit> result = new ArrayList<ICompilationUnit>(); try { result = Arrays.asList(frag.getCompilationUnits()); } catch (JavaModelException e) { e.printStackTrace(); } return result; } protected List<ICompilationUnit> get(IPackageFragmentRoot root){ List<ICompilationUnit> result = new ArrayList<ICompilationUnit>(); try { for (IJavaElement frag : Arrays.asList(root.getChildren())) { if( frag instanceof IPackageFragment ){ result.addAll(get((IPackageFragment) frag)); } } } catch (JavaModelException e) { e.printStackTrace(); } return result; } @Override public int size() { return list.size(); } @Override public boolean isEmpty() { return list.isEmpty(); } @Override public boolean contains(Object o) { return list.contains(o); } @Override public Iterator<ICompilationUnit> iterator() { return list.iterator(); } @Override public Object[] toArray() { return list.toArray(); } @Override public <T> T[] toArray(T[] a) { return list.toArray(a); } @Override public boolean add(ICompilationUnit e) { return list.add(e); } @Override public boolean remove(Object o) { return list.remove(o); } @Override public boolean containsAll(Collection<?> c) { return list.contains(c); } @Override public boolean addAll(Collection<? extends ICompilationUnit> c) { return list.addAll(c); } @Override public boolean addAll(int index, Collection<? extends ICompilationUnit> c) { return list.addAll(c); } @Override public boolean removeAll(Collection<?> c) { return list.removeAll(c); } @Override public boolean retainAll(Collection<?> c) { return list.retainAll(c); } @Override public void clear() { list.clear(); } @Override public ICompilationUnit get(int index) { return list.get(index); } @Override public ICompilationUnit set(int index, ICompilationUnit element) { return list.set(index, element); } @Override public void add(int index, ICompilationUnit element) { list.add(index, element); } @Override public ICompilationUnit remove(int index) { return list.remove(index); } @Override public int indexOf(Object o) { return list.indexOf(o); } @Override public int lastIndexOf(Object o) { return list.lastIndexOf(o); } @Override public ListIterator<ICompilationUnit> listIterator() { return list.listIterator(); } @Override public ListIterator<ICompilationUnit> listIterator(int index) { return list.listIterator(index); } @Override public List<ICompilationUnit> subList(int fromIndex, int toIndex) { return list.subList(fromIndex, toIndex); } }
jesg/junit3Tojunit4
src/com/gowan/plugin/SelectionToICompilationUnitList.java
Java
gpl-3.0
5,321
<?php namespace DB; final class mPDO { private $connection = null; private $statement = null; public function __construct($hostname, $username, $password, $database, $port = '3306') { try { $dsn = "mysql:host={$hostname};port={$port};dbname={$database};charset=UTF8"; $options = array( \PDO::ATTR_PERSISTENT => true, \PDO::ATTR_TIMEOUT => 15, \PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION ); $this->connection = new \PDO($dsn, $username, $password, $options); } catch (\PDOException $e) { throw new \Exception('Failed to connect to database. Reason: \'' . $e->getMessage() . '\''); } $this->connection->exec("SET NAMES 'utf8'"); $this->connection->exec("SET CHARACTER SET utf8"); $this->connection->exec("SET CHARACTER_SET_CONNECTION=utf8"); $this->connection->exec("SET SQL_MODE = ''"); $this->rowCount = 0; } public function prepare($sql) { $this->statement = $this->connection->prepare($sql); } public function bindParam($parameter, $variable, $data_type = \PDO::PARAM_STR, $length = 0) { if ($length) { $this->statement->bindParam($parameter, $variable, $data_type, $length); } else { $this->statement->bindParam($parameter, $variable, $data_type); } } public function execute() { try { if ($this->statement && $this->statement->execute()) { $data = array(); while ($row = $this->statement->fetch(\PDO::FETCH_ASSOC)) { $data[] = $row; } $result = new \stdClass(); $result->row = (isset($data[0])) ? $data[0] : array(); $result->rows = $data; $result->num_rows = $this->statement->rowCount(); } } catch (\PDOException $e) { throw new \Exception('Error: ' . $e->getMessage() . ' Error Code : ' . $e->getCode()); } } public function query($sql, $params = array()) { $this->statement = $this->connection->prepare($sql); $result = false; try { if ($this->statement && $this->statement->execute($params)) { $data = array(); $this->rowCount = $this->statement->rowCount(); if ($this->rowCount > 0) { try { $data = $this->statement->fetchAll(\PDO::FETCH_ASSOC); } catch (\Exception $ex) { } } // free up resources $this->statement->closeCursor(); $this->statement = null; $result = new \stdClass(); $result->row = (isset($data[0]) ? $data[0] : array()); $result->rows = $data; $result->num_rows = $this->rowCount; } } catch (\PDOException $e) { throw new \Exception('Error: ' . $e->getMessage() . ' Error Code : ' . $e->getCode() . ' <br />' . $sql); } if ($result) { return $result; } else { $result = new \stdClass(); $result->row = array(); $result->rows = array(); $result->num_rows = 0; return $result; } } public function escape($value) { return str_replace(array( "\\", "\0", "\n", "\r", "\x1a", "'", '"' ), array( "\\\\", "\\0", "\\n", "\\r", "\Z", "\'", '\"' ), $value); } public function countAffected() { if ($this->statement) { return $this->statement->rowCount(); } else { return $this->rowCount; } } public function getLastId() { return $this->connection->lastInsertId(); } public function isConnected() { if ($this->connection) { return true; } else { return false; } } public function __destruct() { $this->connection = null; } }
Copona/copona
system/library/db/mpdo.php
PHP
gpl-3.0
4,141
/** * copyright * Inubit AG * Schoeneberger Ufer 89 * 10785 Berlin * Germany */ package com.inubit.research.textToProcess.textModel; import java.awt.Color; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Shape; import java.awt.geom.Rectangle2D; import net.frapu.code.visualization.ProcessNode; import net.frapu.code.visualization.ProcessUtils; import net.frapu.code.visualization.ProcessUtils.Orientation; /** * @author ff * */ public class WordNode extends ProcessNode { /** * */ public static final Color HIGHLIGHT_COLOR = new Color(255,255,224); private static final int PADDING = 3; //pixels /** * */ public WordNode(String word) { setText(word.replaceAll("\\/", "/")); setBackground(Color.WHITE); } /** * */ public WordNode() { // TODO Auto-generated constructor stub } @Override protected Shape getOutlineShape() { Rectangle2D outline = new Rectangle2D.Float(getPos().x - (getSize().width / 2), getPos().y - (getSize().height / 2), getSize().width, getSize().height); return outline; } @Override protected void paintInternal(Graphics g) { Graphics2D _g = (Graphics2D) g; Shape _s = getOutlineShape(); if(isSelected()) { _g.setColor(WordNode.HIGHLIGHT_COLOR); }else { _g.setColor(getBackground()); _g.setStroke(ProcessUtils.defaultStroke); } _g.fill(_s); _g.setColor(Color.LIGHT_GRAY); _g.draw(_s); _g.setColor(Color.BLACK); if(getText() == null) { ProcessUtils.drawText(_g, getPos().x, getPos().y, getSize().width, "Word", Orientation.CENTER); }else { ProcessUtils.drawText(_g, getPos().x, getPos().y, getSize().width, getText(), Orientation.CENTER); } } @Override public void setSize(int w, int h) { return; } @Override public void setPos(int x, int y) { return; } /** * @return */ public String getWord() { return getText(); } /** * @param stringBounds */ public void setBounds(Rectangle2D b) { super.setSize((int)b.getWidth() + 2* PADDING, (int)b.getHeight() + 2* PADDING); } /** * @param _wx * @param y */ public void setLocation(int x, int y) { super.setPos(x,y); } @Override public String toString() { return "WordNode ("+getText()+")"; } }
FabianFriedrich/Text2Process
src/com/inubit/research/textToProcess/textModel/WordNode.java
Java
gpl-3.0
2,249
<?php /* * $result->groups * $result->auditories * $result->lectors * $result->calendars */ ?> <h1>Додати календар</h1> <div class="uk-margin"> <div class="uk-form"> <?php if(mysqli_num_rows($result->groups) > 0){ echo '<select>'; while($row = mysqli_fetch_assoc($result->groups)) { echo '<option value="'.$row->id.'">'.$row->name.'</option>'; } echo '</select>'; } ?> <?php if(mysqli_num_rows($result->auditories) > 0){ echo '<select>'; while($row = mysqli_fetch_assoc($result->auditories)) { echo '<option value="'.$row->id.'">'.$row->name.'</option>'; } echo '</select>'; } ?> <?php if(mysqli_num_rows($result->lectors) > 0){ echo '<select>'; while($row = mysqli_fetch_assoc($result->lectors)) { echo '<option value="'.$row->id.'">'.$row->name.'</option>'; } echo '</select>'; } ?> </div> </div>
nemishkor/npu-calendars
application/views/calendar_add_view.php
PHP
gpl-3.0
905
<?php /* Scripts and styles options */ /** * Renders the Scripts and styles options section. */ function electric_thop_render_scripts_section(){ echo "<p>" . __('You are not forced to use everything that the theme includes. If you are not going to use a feature (because you don\'t like it or because you prefer a different solution, just uncheck it. You will save some kb to load.','electric') . "</p>" ; echo "<p>" . __('If you use these styles/scripts they will be loaded individually. If you want to boost performance, you can combine them into a single file using a plugin (W3 Total Cache is suggested, but you can use any option or do it manually)','electric') . "</p>" ; } /** * Renders the Icon Fonts checkbox setting field. */ function electric_sfield_use_icon_fonts() { $options = electric_thop_get_options(); ?> <label for="use-icon-fonts" class="description"> <input type="checkbox" name="electric_theme_options[use_icon_fonts]" id="use-icon-fonts" <?php checked('on', $options['use_icon_fonts']); ?> /> <?php _e('Check this if you want to use the icon font.', 'electric'); ?> </label> <p class="description"><?php _e('You can customize the icons uploading the file electric/fonts/fonts/electric.dev.svg to <a href="http://icomoon.io">icomoon.io</a>.', 'electric'); ?></p> <?php } /** * Renders the Google Fonts checkbox setting field. */ function electric_sfield_use_google_fonts() { $options = electric_thop_get_options(); ?> <label for="use-google-fonts" class="description"> <input type="checkbox" name="electric_theme_options[use_google_fonts]" id="use-google-fonts" <?php checked('on', $options['use_google_fonts']); ?> /> <?php _e('Check this if you want to use fonts from Google Web Fonts', 'electric'); ?> </label> <p class="description"><?php _e('Allows you to use fonts from <a href="http://www.google.com/webfonts">Google Web Fonts</a>', 'electric') ?></p> <?php } /** * Renders the Google Fonts Family input setting field. */ function electric_sfield_google_fonts_choice() { $options = electric_thop_get_options(); ?> <input type="text" name="electric_theme_options[google_fonts_choice]" id="google-fonts-choice" value="<?php echo esc_attr($options['google_fonts_choice']); ?>" /> <label class="description" for="google-fonts-choice"><?php _e('Your font family choice', 'electric'); ?></label> <p class="description"><?php _e('If you want to use a different set than the default (Comfortaa + Open Sans):', 'electric') ?></p> <ol class="description"> <li><?php _e('Choose the font(s) you like and click "Use"', 'electric') ?></li> <li><?php _e('Choose the style(s) you want and character set(s) at point 1 and 2', 'electric') ?></li> <li><?php _e('Copy the code at the "Standard" tab at point 3 ', 'electric') ?></li> </ol> <?php } /** * Renders the tooltip checkbox setting field. */ function electric_sfield_use_tooltip_js() { $options = electric_thop_get_options(); ?> <label for="use-tooltip-js" class="description"> <input type="checkbox" name="electric_theme_options[use_tooltip_js]" id="use-tooltip-js" <?php checked('on', $options['use_tooltip_js']); ?> /> <?php _e('Uncheck this if you don\'t want to load the Tooltip script', 'electric'); ?> </label> <p class="description"><?php _e('This script is used to display a tooltip in the menus and in the availability widget. If you don\'t want them, don\'t include the plugin and save some kb', 'electric') ?></p> <p class="description"><?php _e('More info about this tooltip <a href="http://jquerytools.org/demos/tooltip/index.html">here</a>', 'electric') ?></p> <?php }
cmoralesweb/electric-theme
wp-content/themes/electric/inc/theme-options/scripts.php
PHP
gpl-3.0
3,745
odoo.define('point_of_sale.DB', function (require) { "use strict"; var core = require('web.core'); var utils = require('web.utils'); /* The PosDB holds reference to data that is either * - static: does not change between pos reloads * - persistent : must stay between reloads ( orders ) */ var PosDB = core.Class.extend({ name: 'openerp_pos_db', //the prefix of the localstorage data limit: 100, // the maximum number of results returned by a search init: function(options){ options = options || {}; this.name = options.name || this.name; this.limit = options.limit || this.limit; if (options.uuid) { this.name = this.name + '_' + options.uuid; } //cache the data in memory to avoid roundtrips to the localstorage this.cache = {}; this.product_by_id = {}; this.product_by_barcode = {}; this.product_by_category_id = {}; this.product_packaging_by_barcode = {}; this.partner_sorted = []; this.partner_by_id = {}; this.partner_by_barcode = {}; this.partner_search_string = ""; this.partner_write_date = null; this.category_by_id = {}; this.root_category_id = 0; this.category_products = {}; this.category_ancestors = {}; this.category_childs = {}; this.category_parent = {}; this.category_search_string = {}; }, /** * sets an uuid to prevent conflict in locally stored data between multiple PoS Configs. By * using the uuid of the config the local storage from other configs will not get effected nor * loaded in sessions that don't belong to them. * * @param {string} uuid Unique identifier of the PoS Config linked to the current session. */ set_uuid: function(uuid){ this.name = this.name + '_' + uuid; }, /* returns the category object from its id. If you pass a list of id as parameters, you get * a list of category objects. */ get_category_by_id: function(categ_id){ if(categ_id instanceof Array){ var list = []; for(var i = 0, len = categ_id.length; i < len; i++){ var cat = this.category_by_id[categ_id[i]]; if(cat){ list.push(cat); }else{ console.error("get_category_by_id: no category has id:",categ_id[i]); } } return list; }else{ return this.category_by_id[categ_id]; } }, /* returns a list of the category's child categories ids, or an empty list * if a category has no childs */ get_category_childs_ids: function(categ_id){ return this.category_childs[categ_id] || []; }, /* returns a list of all ancestors (parent, grand-parent, etc) categories ids * starting from the root category to the direct parent */ get_category_ancestors_ids: function(categ_id){ return this.category_ancestors[categ_id] || []; }, /* returns the parent category's id of a category, or the root_category_id if no parent. * the root category is parent of itself. */ get_category_parent_id: function(categ_id){ return this.category_parent[categ_id] || this.root_category_id; }, /* adds categories definitions to the database. categories is a list of categories objects as * returned by the openerp server. Categories must be inserted before the products or the * product/ categories association may (will) not work properly */ add_categories: function(categories){ var self = this; if(!this.category_by_id[this.root_category_id]){ this.category_by_id[this.root_category_id] = { id : this.root_category_id, name : 'Root', }; } categories.forEach(function(cat){ self.category_by_id[cat.id] = cat; }); categories.forEach(function(cat){ var parent_id = cat.parent_id[0]; if(!(parent_id && self.category_by_id[parent_id])){ parent_id = self.root_category_id; } self.category_parent[cat.id] = parent_id; if(!self.category_childs[parent_id]){ self.category_childs[parent_id] = []; } self.category_childs[parent_id].push(cat.id); }); function make_ancestors(cat_id, ancestors){ self.category_ancestors[cat_id] = ancestors; ancestors = ancestors.slice(0); ancestors.push(cat_id); var childs = self.category_childs[cat_id] || []; for(var i=0, len = childs.length; i < len; i++){ make_ancestors(childs[i], ancestors); } } make_ancestors(this.root_category_id, []); }, category_contains: function(categ_id, product_id) { var product = this.product_by_id[product_id]; if (product) { var cid = product.pos_categ_id[0]; while (cid && cid !== categ_id){ cid = this.category_parent[cid]; } return !!cid; } return false; }, /* loads a record store from the database. returns default if nothing is found */ load: function(store,deft){ if(this.cache[store] !== undefined){ return this.cache[store]; } var data = localStorage[this.name + '_' + store]; if(data !== undefined && data !== ""){ data = JSON.parse(data); this.cache[store] = data; return data; }else{ return deft; } }, /* saves a record store to the database */ save: function(store,data){ localStorage[this.name + '_' + store] = JSON.stringify(data); this.cache[store] = data; }, _product_search_string: function(product){ var str = product.display_name; if (product.barcode) { str += '|' + product.barcode; } if (product.default_code) { str += '|' + product.default_code; } if (product.description) { str += '|' + product.description; } if (product.description_sale) { str += '|' + product.description_sale; } str = product.id + ':' + str.replace(/:/g,'') + '\n'; return str; }, add_products: function(products){ var stored_categories = this.product_by_category_id; if(!products instanceof Array){ products = [products]; } for(var i = 0, len = products.length; i < len; i++){ var product = products[i]; if (product.id in this.product_by_id) continue; if (product.available_in_pos){ var search_string = utils.unaccent(this._product_search_string(product)); var categ_id = product.pos_categ_id ? product.pos_categ_id[0] : this.root_category_id; product.product_tmpl_id = product.product_tmpl_id[0]; if(!stored_categories[categ_id]){ stored_categories[categ_id] = []; } stored_categories[categ_id].push(product.id); if(this.category_search_string[categ_id] === undefined){ this.category_search_string[categ_id] = ''; } this.category_search_string[categ_id] += search_string; var ancestors = this.get_category_ancestors_ids(categ_id) || []; for(var j = 0, jlen = ancestors.length; j < jlen; j++){ var ancestor = ancestors[j]; if(! stored_categories[ancestor]){ stored_categories[ancestor] = []; } stored_categories[ancestor].push(product.id); if( this.category_search_string[ancestor] === undefined){ this.category_search_string[ancestor] = ''; } this.category_search_string[ancestor] += search_string; } } this.product_by_id[product.id] = product; if(product.barcode){ this.product_by_barcode[product.barcode] = product; } } }, add_packagings: function(product_packagings){ var self = this; _.map(product_packagings, function (product_packaging) { if (_.find(self.product_by_id, {'id': product_packaging.product_id[0]})) { self.product_packaging_by_barcode[product_packaging.barcode] = product_packaging; } }); }, _partner_search_string: function(partner){ var str = partner.name || ''; if(partner.barcode){ str += '|' + partner.barcode; } if(partner.address){ str += '|' + partner.address; } if(partner.phone){ str += '|' + partner.phone.split(' ').join(''); } if(partner.mobile){ str += '|' + partner.mobile.split(' ').join(''); } if(partner.email){ str += '|' + partner.email; } if(partner.vat){ str += '|' + partner.vat; } str = '' + partner.id + ':' + str.replace(':', '').replace(/\n/g, ' ') + '\n'; return str; }, add_partners: function(partners){ var updated_count = 0; var new_write_date = ''; var partner; for(var i = 0, len = partners.length; i < len; i++){ partner = partners[i]; var local_partner_date = (this.partner_write_date || '').replace(/^(\d{4}-\d{2}-\d{2}) ((\d{2}:?){3})$/, '$1T$2Z'); var dist_partner_date = (partner.write_date || '').replace(/^(\d{4}-\d{2}-\d{2}) ((\d{2}:?){3})$/, '$1T$2Z'); if ( this.partner_write_date && this.partner_by_id[partner.id] && new Date(local_partner_date).getTime() + 1000 >= new Date(dist_partner_date).getTime() ) { // FIXME: The write_date is stored with milisec precision in the database // but the dates we get back are only precise to the second. This means when // you read partners modified strictly after time X, you get back partners that were // modified X - 1 sec ago. continue; } else if ( new_write_date < partner.write_date ) { new_write_date = partner.write_date; } if (!this.partner_by_id[partner.id]) { this.partner_sorted.push(partner.id); } this.partner_by_id[partner.id] = partner; updated_count += 1; } this.partner_write_date = new_write_date || this.partner_write_date; if (updated_count) { // If there were updates, we need to completely // rebuild the search string and the barcode indexing this.partner_search_string = ""; this.partner_by_barcode = {}; for (var id in this.partner_by_id) { partner = this.partner_by_id[id]; if(partner.barcode){ this.partner_by_barcode[partner.barcode] = partner; } partner.address = (partner.street ? partner.street + ', ': '') + (partner.zip ? partner.zip + ', ': '') + (partner.city ? partner.city + ', ': '') + (partner.state_id ? partner.state_id[1] + ', ': '') + (partner.country_id ? partner.country_id[1]: ''); this.partner_search_string += this._partner_search_string(partner); } this.partner_search_string = utils.unaccent(this.partner_search_string); } return updated_count; }, get_partner_write_date: function(){ return this.partner_write_date || "1970-01-01 00:00:00"; }, get_partner_by_id: function(id){ return this.partner_by_id[id]; }, get_partner_by_barcode: function(barcode){ return this.partner_by_barcode[barcode]; }, get_partners_sorted: function(max_count){ max_count = max_count ? Math.min(this.partner_sorted.length, max_count) : this.partner_sorted.length; var partners = []; for (var i = 0; i < max_count; i++) { partners.push(this.partner_by_id[this.partner_sorted[i]]); } return partners; }, search_partner: function(query){ try { query = query.replace(/[\[\]\(\)\+\*\?\.\-\!\&\^\$\|\~\_\{\}\:\,\\\/]/g,'.'); query = query.replace(/ /g,'.+'); var re = RegExp("([0-9]+):.*?"+utils.unaccent(query),"gi"); }catch(e){ return []; } var results = []; for(var i = 0; i < this.limit; i++){ var r = re.exec(this.partner_search_string); if(r){ var id = Number(r[1]); results.push(this.get_partner_by_id(id)); }else{ break; } } return results; }, /* removes all the data from the database. TODO : being able to selectively remove data */ clear: function(){ for(var i = 0, len = arguments.length; i < len; i++){ localStorage.removeItem(this.name + '_' + arguments[i]); } }, /* this internal methods returns the count of properties in an object. */ _count_props : function(obj){ var count = 0; for(var prop in obj){ if(obj.hasOwnProperty(prop)){ count++; } } return count; }, get_product_by_id: function(id){ return this.product_by_id[id]; }, get_product_by_barcode: function(barcode){ if(this.product_by_barcode[barcode]){ return this.product_by_barcode[barcode]; } else if (this.product_packaging_by_barcode[barcode]) { return this.product_by_id[this.product_packaging_by_barcode[barcode].product_id[0]]; } return undefined; }, get_product_by_category: function(category_id){ var product_ids = this.product_by_category_id[category_id]; var list = []; if (product_ids) { for (var i = 0, len = Math.min(product_ids.length, this.limit); i < len; i++) { const product = this.product_by_id[product_ids[i]]; if (!(product.active && product.available_in_pos)) continue; list.push(product); } } return list; }, /* returns a list of products with : * - a category that is or is a child of category_id, * - a name, package or barcode containing the query (case insensitive) */ search_product_in_category: function(category_id, query){ try { query = query.replace(/[\[\]\(\)\+\*\?\.\-\!\&\^\$\|\~\_\{\}\:\,\\\/]/g,'.'); query = query.replace(/ /g,'.+'); var re = RegExp("([0-9]+):.*?"+utils.unaccent(query),"gi"); }catch(e){ return []; } var results = []; for(var i = 0; i < this.limit; i++){ var r = re.exec(this.category_search_string[category_id]); if(r){ var id = Number(r[1]); const product = this.get_product_by_id(id); if (!(product.active && product.available_in_pos)) continue; results.push(product); }else{ break; } } return results; }, /* from a product id, and a list of category ids, returns * true if the product belongs to one of the provided category * or one of its child categories. */ is_product_in_category: function(category_ids, product_id) { if (!(category_ids instanceof Array)) { category_ids = [category_ids]; } var cat = this.get_product_by_id(product_id).pos_categ_id[0]; while (cat) { for (var i = 0; i < category_ids.length; i++) { if (cat == category_ids[i]) { // The == is important, ids may be strings return true; } } cat = this.get_category_parent_id(cat); } return false; }, /* paid orders */ add_order: function(order){ var order_id = order.uid; var orders = this.load('orders',[]); // if the order was already stored, we overwrite its data for(var i = 0, len = orders.length; i < len; i++){ if(orders[i].id === order_id){ orders[i].data = order; this.save('orders',orders); return order_id; } } // Only necessary when we store a new, validated order. Orders // that where already stored should already have been removed. this.remove_unpaid_order(order); orders.push({id: order_id, data: order}); this.save('orders',orders); return order_id; }, remove_order: function(order_id){ var orders = this.load('orders',[]); orders = _.filter(orders, function(order){ return order.id !== order_id; }); this.save('orders',orders); }, remove_all_orders: function(){ this.save('orders',[]); }, get_orders: function(){ return this.load('orders',[]); }, get_order: function(order_id){ var orders = this.get_orders(); for(var i = 0, len = orders.length; i < len; i++){ if(orders[i].id === order_id){ return orders[i]; } } return undefined; }, /* working orders */ save_unpaid_order: function(order){ var order_id = order.uid; var orders = this.load('unpaid_orders',[]); var serialized = order.export_as_JSON(); for (var i = 0; i < orders.length; i++) { if (orders[i].id === order_id){ orders[i].data = serialized; this.save('unpaid_orders',orders); return order_id; } } orders.push({id: order_id, data: serialized}); this.save('unpaid_orders',orders); return order_id; }, remove_unpaid_order: function(order){ var orders = this.load('unpaid_orders',[]); orders = _.filter(orders, function(o){ return o.id !== order.uid; }); this.save('unpaid_orders',orders); }, remove_all_unpaid_orders: function(){ this.save('unpaid_orders',[]); }, get_unpaid_orders: function(){ var saved = this.load('unpaid_orders',[]); var orders = []; for (var i = 0; i < saved.length; i++) { orders.push(saved[i].data); } return orders; }, /** * Return the orders with requested ids if they are unpaid. * @param {array<number>} ids order_ids. * @return {array<object>} list of orders. */ get_unpaid_orders_to_sync: function(ids){ var saved = this.load('unpaid_orders',[]); var orders = []; saved.forEach(function(o) { if (ids.includes(o.id)){ orders.push(o); } }); return orders; }, /** * Add a given order to the orders to be removed from the server. * * If an order is removed from a table it also has to be removed from the server to prevent it from reapearing * after syncing. This function will add the server_id of the order to a list of orders still to be removed. * @param {object} order object. */ set_order_to_remove_from_server: function(order){ if (order.server_id !== undefined) { var to_remove = this.load('unpaid_orders_to_remove',[]); to_remove.push(order.server_id); this.save('unpaid_orders_to_remove', to_remove); } }, /** * Get a list of server_ids of orders to be removed. * @return {array<number>} list of server_ids. */ get_ids_to_remove_from_server: function(){ return this.load('unpaid_orders_to_remove',[]); }, /** * Remove server_ids from the list of orders to be removed. * @param {array<number>} ids */ set_ids_removed_from_server: function(ids){ var to_remove = this.load('unpaid_orders_to_remove',[]); to_remove = _.filter(to_remove, function(id){ return !ids.includes(id); }); this.save('unpaid_orders_to_remove', to_remove); }, set_cashier: function(cashier) { // Always update if the user is the same as before this.save('cashier', cashier || null); }, get_cashier: function() { return this.load('cashier'); } }); return PosDB; });
jeremiahyan/odoo
addons/point_of_sale/static/src/js/db.js
JavaScript
gpl-3.0
21,089
/* This file is part of My Nes * * A Nintendo Entertainment System / Family Computer (Nes/Famicom) * Emulator written in C#. * * Copyright © Ala Ibrahim Hadid 2009 - 2014 * * 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/>. */ namespace MyNes.Core { class VRC6PulseSoundChannel { private int dutyForm; private int dutyStep; private bool enabled = true; private bool mode = false; public byte output; private byte volume; private int freqTimer; private int frequency; private int cycles; public void HardReset() { dutyForm = 0; dutyStep = 0xF; enabled = true; mode = false; output = 0; } public void Write0(ref byte data) { mode = (data & 0x80) == 0x80; dutyForm = ((data & 0x70) >> 4); volume = (byte)(data & 0xF); } public void Write1(ref byte data) { frequency = (frequency & 0x0F00) | data; } public void Write2(ref byte data) { frequency = (frequency & 0x00FF) | ((data & 0xF) << 8); enabled = (data & 0x80) == 0x80; } public void ClockSingle() { if (--cycles <= 0) { cycles = (frequency << 1) + 2; if (enabled) { if (mode) output = volume; else { dutyStep--; if (dutyStep < 0) dutyStep = 0xF; if (dutyStep <= dutyForm) output = volume; else output = 0; } } else output = 0; } } /// <summary> /// Save state /// </summary> /// <param name="stream">The stream that should be used to write data</param> public void SaveState(System.IO.BinaryWriter stream) { stream.Write(dutyForm); stream.Write(dutyStep); stream.Write(enabled); stream.Write(mode); stream.Write(output); stream.Write(volume); stream.Write(freqTimer); stream.Write(frequency); stream.Write(cycles); } /// <summary> /// Load state /// </summary> /// <param name="stream">The stream that should be used to read data</param> public void LoadState(System.IO.BinaryReader stream) { dutyForm = stream.ReadInt32(); dutyStep = stream.ReadInt32(); enabled = stream.ReadBoolean(); mode = stream.ReadBoolean(); output = stream.ReadByte(); volume = stream.ReadByte(); freqTimer = stream.ReadInt32(); frequency = stream.ReadInt32(); cycles = stream.ReadInt32(); } } }
MetaFight/Mayonnaise
Core/ExternalSoundChannels/VRC6PulseSoundChannel.cs
C#
gpl-3.0
3,837
/* * Neon, a roguelike engine. * Copyright (C) 2017-2018 - Maarten Driesen * * 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 neon.editor.ui; import java.io.IOException; import java.util.logging.Logger; import com.google.common.eventbus.EventBus; import com.google.common.eventbus.Subscribe; import javafx.fxml.FXMLLoader; import javafx.scene.Scene; import javafx.stage.Stage; import javafx.stage.Window; import neon.common.files.NeonFileSystem; import neon.common.resources.ResourceManager; import neon.editor.LoadEvent; import neon.editor.controllers.CreatureHandler; import neon.editor.controllers.ItemHandler; import neon.editor.controllers.MapHandler; import neon.editor.controllers.MenuHandler; import neon.editor.controllers.TerrainHandler; import neon.editor.resource.CEditor; /** * The {@code UserInterface} takes care of most ui-related editor functionality. * * @author mdriesen * */ public final class UserInterface { private static final Logger logger = Logger.getGlobal(); private final CreatureHandler creatureHandler; private final MapHandler mapHandler; private final MenuHandler menuHandler; private final ItemHandler itemHandler; private final TerrainHandler terrainHandler; private Stage stage; private Scene scene; /** * Initializes the {@code UserInterface}. * * @param files * @param resources * @param bus * @param config */ public UserInterface(NeonFileSystem files, ResourceManager resources, EventBus bus, CEditor config) { // separate handlers for all the different ui elements menuHandler = new MenuHandler(resources, bus, this); bus.register(menuHandler); mapHandler = new MapHandler(resources, bus, config); bus.register(mapHandler); creatureHandler = new CreatureHandler(resources, bus); bus.register(creatureHandler); itemHandler = new ItemHandler(resources, bus); bus.register(itemHandler); terrainHandler = new TerrainHandler(resources, bus); bus.register(terrainHandler); // load the user interface FXMLLoader loader = new FXMLLoader(getClass().getResource("Editor.fxml")); loader.setControllerFactory(this::getController); try { scene = new Scene(loader.load()); scene.getStylesheets().add(getClass().getResource("editor.css").toExternalForm()); } catch (IOException e) { logger.severe("failed to load editor ui: " + e.getMessage()); } } /** * Returns the correct controller for a JavaFX node. * * @param type * @return */ private Object getController(Class<?> type) { if(type.equals(MenuHandler.class)) { return menuHandler; } else if (type.equals(MapHandler.class)) { return mapHandler; } else if (type.equals(CreatureHandler.class)) { return creatureHandler; } else if (type.equals(ItemHandler.class)) { return itemHandler; } else if (type.equals(TerrainHandler.class)) { return terrainHandler; } else { throw new IllegalArgumentException("No controller found for class " + type + "!"); } } /** * * @return the main window of the editor */ public Window getWindow() { return stage; } /** * Shows the main window on screen. * * @param stage */ public void start(Stage stage) { this.stage = stage; stage.setTitle("The Neon Roguelike Editor"); stage.setScene(scene); stage.setWidth(1440); stage.setMinWidth(800); stage.setHeight(720); stage.setMinHeight(600); stage.show(); stage.centerOnScreen(); stage.setOnCloseRequest(event -> System.exit(0)); } /** * Sets the title of the main window. * * @param event */ @Subscribe private void onModuleLoad(LoadEvent event) { stage.setTitle("The Neon Roguelike Editor - " + event.id); } /** * Checks if any resources are still opened and should be saved. This * method should be called when saving a module or exiting the editor. */ public void saveResources() { // check if any maps are still opened mapHandler.saveMaps(); } }
kosmonet/neon
src/neon/editor/ui/UserInterface.java
Java
gpl-3.0
4,700
// This file has been generated by the GUI designer. Do not modify. public partial class WinCryptoSec2Config { private global::Gtk.VBox vbox2; private global::Gtk.Button btnDatabase; private global::Gtk.Button btnFtp; private global::Gtk.Button btnString; private global::Gtk.Button btnXml; private global::Gtk.Button btnCancel; protected virtual void Build () { global::Stetic.Gui.Initialize (this); // Widget WinCryptoSec2Config this.Name = "WinCryptoSec2Config"; this.Title = global::Mono.Unix.Catalog.GetString ("InCrtyptoSec2 Modes"); this.Icon = global::Gdk.Pixbuf.LoadFromResource ("InGtkCryptoSec2.icons.keys_16x16.png"); this.WindowPosition = ((global::Gtk.WindowPosition)(4)); this.Modal = true; // Internal child WinCryptoSec2Config.VBox global::Gtk.VBox w1 = this.VBox; w1.Name = "dialog1_VBox"; w1.BorderWidth = ((uint)(2)); // Container child dialog1_VBox.Gtk.Box+BoxChild this.vbox2 = new global::Gtk.VBox (); this.vbox2.Name = "vbox2"; this.vbox2.Spacing = 10; this.vbox2.BorderWidth = ((uint)(5)); // Container child vbox2.Gtk.Box+BoxChild this.btnDatabase = new global::Gtk.Button (); this.btnDatabase.TooltipMarkup = "InCryptoSec2 module for Database security."; this.btnDatabase.CanFocus = true; this.btnDatabase.Name = "btnDatabase"; this.btnDatabase.UseUnderline = true; this.btnDatabase.Label = global::Mono.Unix.Catalog.GetString ("Database"); global::Gtk.Image w2 = new global::Gtk.Image (); w2.Pixbuf = global::Gdk.Pixbuf.LoadFromResource ("InGtkCryptoSec2.icons.database1_32x32.png"); this.btnDatabase.Image = w2; this.vbox2.Add (this.btnDatabase); global::Gtk.Box.BoxChild w3 = ((global::Gtk.Box.BoxChild)(this.vbox2 [this.btnDatabase])); w3.Position = 0; w3.Expand = false; w3.Fill = false; // Container child vbox2.Gtk.Box+BoxChild this.btnFtp = new global::Gtk.Button (); this.btnFtp.TooltipMarkup = "InCryptoSec2 module for FTP security."; this.btnFtp.CanFocus = true; this.btnFtp.Name = "btnFtp"; this.btnFtp.UseUnderline = true; this.btnFtp.Label = global::Mono.Unix.Catalog.GetString ("FTP"); global::Gtk.Image w4 = new global::Gtk.Image (); w4.Pixbuf = global::Gdk.Pixbuf.LoadFromResource ("InGtkCryptoSec2.icons.server_client_32x32.png"); this.btnFtp.Image = w4; this.vbox2.Add (this.btnFtp); global::Gtk.Box.BoxChild w5 = ((global::Gtk.Box.BoxChild)(this.vbox2 [this.btnFtp])); w5.Position = 1; w5.Expand = false; w5.Fill = false; // Container child vbox2.Gtk.Box+BoxChild this.btnString = new global::Gtk.Button (); this.btnString.TooltipMarkup = "InCryptoSec2 module for String security."; this.btnString.CanFocus = true; this.btnString.Name = "btnString"; this.btnString.UseUnderline = true; this.btnString.Label = global::Mono.Unix.Catalog.GetString ("String"); global::Gtk.Image w6 = new global::Gtk.Image (); w6.Pixbuf = global::Gdk.Pixbuf.LoadFromResource ("InGtkCryptoSec2.icons.text_32x32.png"); this.btnString.Image = w6; this.vbox2.Add (this.btnString); global::Gtk.Box.BoxChild w7 = ((global::Gtk.Box.BoxChild)(this.vbox2 [this.btnString])); w7.Position = 2; w7.Expand = false; w7.Fill = false; // Container child vbox2.Gtk.Box+BoxChild this.btnXml = new global::Gtk.Button (); this.btnXml.TooltipMarkup = "InCryptoSec2 module for XML security."; this.btnXml.CanFocus = true; this.btnXml.Name = "btnXml"; this.btnXml.UseUnderline = true; this.btnXml.Label = global::Mono.Unix.Catalog.GetString ("XML"); global::Gtk.Image w8 = new global::Gtk.Image (); w8.Pixbuf = global::Gdk.Pixbuf.LoadFromResource ("InGtkCryptoSec2.icons.text_tree_32x32.png"); this.btnXml.Image = w8; this.vbox2.Add (this.btnXml); global::Gtk.Box.BoxChild w9 = ((global::Gtk.Box.BoxChild)(this.vbox2 [this.btnXml])); w9.Position = 3; w9.Expand = false; w9.Fill = false; w1.Add (this.vbox2); global::Gtk.Box.BoxChild w10 = ((global::Gtk.Box.BoxChild)(w1 [this.vbox2])); w10.Position = 0; w10.Expand = false; w10.Fill = false; // Internal child WinCryptoSec2Config.ActionArea global::Gtk.HButtonBox w11 = this.ActionArea; w11.Name = "dialog1_Action"; w11.Spacing = 10; w11.BorderWidth = ((uint)(5)); w11.LayoutStyle = ((global::Gtk.ButtonBoxStyle)(4)); // Container child dialog1_Action.Gtk.ButtonBox+ButtonBoxChild this.btnCancel = new global::Gtk.Button (); this.btnCancel.CanDefault = true; this.btnCancel.CanFocus = true; this.btnCancel.Name = "btnCancel"; this.btnCancel.UseStock = true; this.btnCancel.UseUnderline = true; this.btnCancel.Label = "gtk-cancel"; this.AddActionWidget (this.btnCancel, -6); global::Gtk.ButtonBox.ButtonBoxChild w12 = ((global::Gtk.ButtonBox.ButtonBoxChild)(w11 [this.btnCancel])); w12.Expand = false; w12.Fill = false; if ((this.Child != null)) { this.Child.ShowAll (); } this.DefaultWidth = 246; this.DefaultHeight = 276; this.Show (); this.btnDatabase.Clicked += new global::System.EventHandler (this.btnDatabase_OnClick); this.btnFtp.Clicked += new global::System.EventHandler (this.btnFtp_OnClick); this.btnString.Clicked += new global::System.EventHandler (this.btnString_OnClick); this.btnXml.Clicked += new global::System.EventHandler (this.btnXml_OnClick); } }
toncis/InCryptoSec2
InGtkCryptoSec2/gtk-gui/WinCryptoSec2Config.cs
C#
gpl-3.0
5,393
<?php use HebrewParseTrainer\Root; use HebrewParseTrainer\Stem; use HebrewParseTrainer\Tense; ?> @extends('layouts.with_sidebar') @section('sidebar') <form id="hebrewparsetrainer-settings"> <input type="hidden" id="csrf" value="{{ csrf_token() }}"/> <div class="form-group"> <h3>Stems</h3> @foreach (Stem::all() as $stem) <div class="checkbox"> <label><input class="reload-verb" type="checkbox" name="stem" value="{{{ $stem->name }}}" checked="checked"/> {{{ $stem->name }}}</label> </div> @endforeach </div> <div class="form-group"> <h3>Tenses</h3> @foreach (Tense::all() as $tense) <div class="checkbox"> <label><input class="reload-verb" type="checkbox" name="tense" value="{{{ $tense->name }}}" checked="checked"/> {{{ $tense->name }}}</label> </div> @endforeach </div> <div class="form-group"> <h3>Roots</h3> <select name="root" class="reload-verb form-control hebrew ltr" multiple="multiple"> @foreach (Root::orderBy('root_kind_id')->orderBy('root')->get() as $root) @if ($root->verbs()->where('active', 1)->count() > 0) <option value="{{{ $root->root }}}" selected="selected">{{{ $root->root }}} ({{{ $root->kind->name }}})</option> @endif @endforeach </select> </div> <div class="form-group"> <h3>Settings</h3> <div class="checkbox"> <label><input type="checkbox" id="settings-audio" checked="checked"/> Audio</label> </div> </div> </form> @endsection @section('content') <div id="trainer"> <div id="trainer-input-container"> <p class="bg-danger" id="trainer-404">There are no verbs matching the criteria in our database.</p> <p class="lead"><span class="hebrew hebrew-large" id="trainer-verb"></span><span id="trainer-answer"></span></p> </div> <div id="trainer-input-fancy"></div> <div class="text-muted"> <div> <!-- id="trainer-input-help" --> <p>Parse the verb and enter the answer as described below or using the buttons. Press return. If your answer was correct and there are multiple possible parsings, an extra input field will appear. After the first incorrect answer or after entering all possible answers, you can continue to the next verb by pressing return once more.</p> <p> <strong>Stems</strong>: either use the full name or a significant beginning (i.e. <code>Q</code> for Qal and <code>N</code>, <code>Pi</code>, <code>Pu</code>, <code>Hit</code>, <code>Hip</code>, and <code>Hop</code> for the derived stems).<br/> <strong>Tenses</strong>: use the abbreviations <code>pf</code>, <code>ipf</code>, <code>coh</code>, <code>imp</code>, <code>jus</code>, <code>infcs</code>, <code>infabs</code>, <code>ptc</code> and <code>ptcp</code>.<br/> <strong>Person</strong>: <code>1</code>, <code>2</code>, <code>3</code> or none (infinitives and participles).<br/> <strong>Gender</strong>: <code>m</code>, <code>f</code> or none (infinitives).<br/> <strong>Number</strong>: <code>s</code>, <code>p</code> or none (infinitives). </p> <p>Examples: <code>Q pf 3ms</code>, <code>ni ptc fp</code>, <code>pi infabs</code>.</p> <h5>Notes:</h5> <ul> <li>There is no 'common' gender. Instead, enter the masculine and feminine forms separately. The <code>N/A</code> option is for infinitives.</li> <li>The <code>ptcp</code> option is only for the passive participle of the qal. All other participles should be entered with <code>ptc</code> (including participles of the passive stems).</li> </ul> </div> <button type="button" class="btn btn-default btn-xs" id="show-hide-help">Show help</button> </div> </div> <hr/> <div class="row"> <div class="col-md-12"> <div class="panel panel-default"> <div class="panel-heading"> <h3 class="panel-title">About</h3> </div> <div class="panel-body"> <p>&copy; 2015&ndash;{!! date('y') !!} <a href="https://camilstaps.nl">Camil Staps</a>. Licensed under <a href="http://www.gnu.org/licenses/gpl-3.0.en.html">GPL 3.0</a>. Source is on <a href="https://github.com/HebrewTools/ParseTrainer">GitHub</a>.</p> <p>Please report any mistakes to <a href="mailto:info@camilstaps.nl">info@camilstaps.nl</a>.</p> </div> </div> </div> </div> <script type="text/javascript"> var reload_on_load = true; </script> @endsection
camilstaps/HebrewParseTrainer
resources/views/trainer.blade.php
PHP
gpl-3.0
4,228
package net.minecraft.server; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; // CraftBukkit start import org.bukkit.craftbukkit.event.CraftEventFactory; import org.bukkit.event.entity.CreatureSpawnEvent; import org.bukkit.event.entity.SpawnerSpawnEvent; // CraftBukkit end public abstract class MobSpawnerAbstract { public int spawnDelay = 20; private String mobName = "Pig"; private List mobs; private TileEntityMobSpawnerData spawnData; public double c; public double d; private int minSpawnDelay = 200; private int maxSpawnDelay = 800; private int spawnCount = 4; private Entity j; private int maxNearbyEntities = 6; private int requiredPlayerRange = 16; private int spawnRange = 4; public MobSpawnerAbstract() {} public String getMobName() { if (this.i() == null) { if (this.mobName.equals("Minecart")) { this.mobName = "MinecartRideable"; } return this.mobName; } else { return this.i().c; } } public void setMobName(String s) { this.mobName = s; } public boolean f() { return this.a().findNearbyPlayer((double) this.b() + 0.5D, (double) this.c() + 0.5D, (double) this.d() + 0.5D, (double) this.requiredPlayerRange) != null; } public void g() { if (this.f()) { double d0; if (this.a().isStatic) { double d1 = (double) ((float) this.b() + this.a().random.nextFloat()); double d2 = (double) ((float) this.c() + this.a().random.nextFloat()); d0 = (double) ((float) this.d() + this.a().random.nextFloat()); this.a().addParticle("smoke", d1, d2, d0, 0.0D, 0.0D, 0.0D); this.a().addParticle("flame", d1, d2, d0, 0.0D, 0.0D, 0.0D); if (this.spawnDelay > 0) { --this.spawnDelay; } this.d = this.c; this.c = (this.c + (double) (1000.0F / ((float) this.spawnDelay + 200.0F))) % 360.0D; } else { if (this.spawnDelay == -1) { this.j(); } if (this.spawnDelay > 0) { --this.spawnDelay; return; } boolean flag = false; for (int i = 0; i < this.spawnCount; ++i) { Entity entity = EntityTypes.createEntityByName(this.getMobName(), this.a()); if (entity == null) { return; } int j = this.a().a(entity.getClass(), AxisAlignedBB.a((double) this.b(), (double) this.c(), (double) this.d(), (double) (this.b() + 1), (double) (this.c() + 1), (double) (this.d() + 1)).grow((double) (this.spawnRange * 2), 4.0D, (double) (this.spawnRange * 2))).size(); if (j >= this.maxNearbyEntities) { this.j(); return; } d0 = (double) this.b() + (this.a().random.nextDouble() - this.a().random.nextDouble()) * (double) this.spawnRange; double d3 = (double) (this.c() + this.a().random.nextInt(3) - 1); double d4 = (double) this.d() + (this.a().random.nextDouble() - this.a().random.nextDouble()) * (double) this.spawnRange; EntityInsentient entityinsentient = entity instanceof EntityInsentient ? (EntityInsentient) entity : null; entity.setPositionRotation(d0, d3, d4, this.a().random.nextFloat() * 360.0F, 0.0F); if (entityinsentient == null || entityinsentient.canSpawn()) { this.a(entity); this.a().triggerEffect(2004, this.b(), this.c(), this.d(), 0); if (entityinsentient != null) { entityinsentient.s(); } flag = true; } } if (flag) { this.j(); } } } } public Entity a(Entity entity) { if (this.i() != null) { NBTTagCompound nbttagcompound = new NBTTagCompound(); entity.d(nbttagcompound); Iterator iterator = this.i().b.c().iterator(); while (iterator.hasNext()) { String s = (String) iterator.next(); NBTBase nbtbase = this.i().b.get(s); nbttagcompound.set(s, nbtbase.clone()); } entity.f(nbttagcompound); if (entity.world != null) { // CraftBukkit start - call SpawnerSpawnEvent, abort if cancelled SpawnerSpawnEvent event = CraftEventFactory.callSpawnerSpawnEvent(entity, this.b(), this.c(), this.d()); if (!event.isCancelled()) { entity.world.addEntity(entity, CreatureSpawnEvent.SpawnReason.SPAWNER); // CraftBukkit // Spigot Start if ( entity.world.spigotConfig.nerfSpawnerMobs ) { entity.fromMobSpawner = true; } // Spigot End } // CraftBukkit end } NBTTagCompound nbttagcompound1; for (Entity entity1 = entity; nbttagcompound.hasKeyOfType("Riding", 10); nbttagcompound = nbttagcompound1) { nbttagcompound1 = nbttagcompound.getCompound("Riding"); Entity entity2 = EntityTypes.createEntityByName(nbttagcompound1.getString("id"), entity.world); if (entity2 != null) { NBTTagCompound nbttagcompound2 = new NBTTagCompound(); entity2.d(nbttagcompound2); Iterator iterator1 = nbttagcompound1.c().iterator(); while (iterator1.hasNext()) { String s1 = (String) iterator1.next(); NBTBase nbtbase1 = nbttagcompound1.get(s1); nbttagcompound2.set(s1, nbtbase1.clone()); } entity2.f(nbttagcompound2); entity2.setPositionRotation(entity1.locX, entity1.locY, entity1.locZ, entity1.yaw, entity1.pitch); // CraftBukkit start - call SpawnerSpawnEvent, skip if cancelled SpawnerSpawnEvent event = CraftEventFactory.callSpawnerSpawnEvent(entity2, this.b(), this.c(), this.d()); if (event.isCancelled()) { continue; } if (entity.world != null) { entity.world.addEntity(entity2, CreatureSpawnEvent.SpawnReason.SPAWNER); // CraftBukkit } entity1.mount(entity2); } entity1 = entity2; } } else if (entity instanceof EntityLiving && entity.world != null) { ((EntityInsentient) entity).prepare((GroupDataEntity) null); // Spigot start - call SpawnerSpawnEvent, abort if cancelled SpawnerSpawnEvent event = CraftEventFactory.callSpawnerSpawnEvent(entity, this.b(), this.c(), this.d()); if (!event.isCancelled()) { this.a().addEntity(entity, CreatureSpawnEvent.SpawnReason.SPAWNER); // CraftBukkit // Spigot Start if ( entity.world.spigotConfig.nerfSpawnerMobs ) { entity.fromMobSpawner = true; } // Spigot End } // Spigot end } return entity; } private void j() { if (this.maxSpawnDelay <= this.minSpawnDelay) { this.spawnDelay = this.minSpawnDelay; } else { int i = this.maxSpawnDelay - this.minSpawnDelay; this.spawnDelay = this.minSpawnDelay + this.a().random.nextInt(i); } if (this.mobs != null && this.mobs.size() > 0) { this.a((TileEntityMobSpawnerData) WeightedRandom.a(this.a().random, (Collection) this.mobs)); } this.a(1); } public void a(NBTTagCompound nbttagcompound) { this.mobName = nbttagcompound.getString("EntityId"); this.spawnDelay = nbttagcompound.getShort("Delay"); if (nbttagcompound.hasKeyOfType("SpawnPotentials", 9)) { this.mobs = new ArrayList(); NBTTagList nbttaglist = nbttagcompound.getList("SpawnPotentials", 10); for (int i = 0; i < nbttaglist.size(); ++i) { this.mobs.add(new TileEntityMobSpawnerData(this, nbttaglist.get(i))); } } else { this.mobs = null; } if (nbttagcompound.hasKeyOfType("SpawnData", 10)) { this.a(new TileEntityMobSpawnerData(this, nbttagcompound.getCompound("SpawnData"), this.mobName)); } else { this.a((TileEntityMobSpawnerData) null); } if (nbttagcompound.hasKeyOfType("MinSpawnDelay", 99)) { this.minSpawnDelay = nbttagcompound.getShort("MinSpawnDelay"); this.maxSpawnDelay = nbttagcompound.getShort("MaxSpawnDelay"); this.spawnCount = nbttagcompound.getShort("SpawnCount"); } if (nbttagcompound.hasKeyOfType("MaxNearbyEntities", 99)) { this.maxNearbyEntities = nbttagcompound.getShort("MaxNearbyEntities"); this.requiredPlayerRange = nbttagcompound.getShort("RequiredPlayerRange"); } if (nbttagcompound.hasKeyOfType("SpawnRange", 99)) { this.spawnRange = nbttagcompound.getShort("SpawnRange"); } if (this.a() != null && this.a().isStatic) { this.j = null; } } public void b(NBTTagCompound nbttagcompound) { nbttagcompound.setString("EntityId", this.getMobName()); nbttagcompound.setShort("Delay", (short) this.spawnDelay); nbttagcompound.setShort("MinSpawnDelay", (short) this.minSpawnDelay); nbttagcompound.setShort("MaxSpawnDelay", (short) this.maxSpawnDelay); nbttagcompound.setShort("SpawnCount", (short) this.spawnCount); nbttagcompound.setShort("MaxNearbyEntities", (short) this.maxNearbyEntities); nbttagcompound.setShort("RequiredPlayerRange", (short) this.requiredPlayerRange); nbttagcompound.setShort("SpawnRange", (short) this.spawnRange); if (this.i() != null) { nbttagcompound.set("SpawnData", this.i().b.clone()); } if (this.i() != null || this.mobs != null && this.mobs.size() > 0) { NBTTagList nbttaglist = new NBTTagList(); if (this.mobs != null && this.mobs.size() > 0) { Iterator iterator = this.mobs.iterator(); while (iterator.hasNext()) { TileEntityMobSpawnerData tileentitymobspawnerdata = (TileEntityMobSpawnerData) iterator.next(); nbttaglist.add(tileentitymobspawnerdata.a()); } } else { nbttaglist.add(this.i().a()); } nbttagcompound.set("SpawnPotentials", nbttaglist); } } public boolean b(int i) { if (i == 1 && this.a().isStatic) { this.spawnDelay = this.minSpawnDelay; return true; } else { return false; } } public TileEntityMobSpawnerData i() { return this.spawnData; } public void a(TileEntityMobSpawnerData tileentitymobspawnerdata) { this.spawnData = tileentitymobspawnerdata; } public abstract void a(int i); public abstract World a(); public abstract int b(); public abstract int c(); public abstract int d(); }
pvginkel/Tweakkit-Server
src/main/java/net/minecraft/server/MobSpawnerAbstract.java
Java
gpl-3.0
11,945
/*---------------------------------------------------------------------------*\ ========= | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox \\ / O peration | \\ / A nd | Copyright (C) 2016-2021 hyStrath \\/ M anipulation | ------------------------------------------------------------------------------- License This file is part of hyStrath, a derivative work of OpenFOAM. OpenFOAM 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. OpenFOAM 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 OpenFOAM. If not, see <http://www.gnu.org/licenses/>. Class Foam::energyScalingFunction Description SourceFiles energyScalingFunction.C newEnergyScalingFunction.C \*---------------------------------------------------------------------------*/ #ifndef energyScalingFunction_H #define energyScalingFunction_H #include "IOdictionary.H" #include "typeInfo.H" #include "runTimeSelectionTables.H" #include "autoPtr.H" #include "pairPotentialModel.H" #include "reducedUnits.H" // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // namespace Foam { /*---------------------------------------------------------------------------*\ Class energyScalingFunction Declaration \*---------------------------------------------------------------------------*/ class energyScalingFunction { protected: // Protected data word name_; dictionary energyScalingFunctionProperties_; const pairPotentialModel& pairPot_; const reducedUnits& rU_; // Private Member Functions //- Disallow copy construct energyScalingFunction(const energyScalingFunction&); //- Disallow default bitwise assignment void operator=(const energyScalingFunction&); public: //- Runtime type information TypeName("energyScalingFunction"); // Declare run-time constructor selection table declareRunTimeSelectionTable ( autoPtr, energyScalingFunction, dictionary, ( const word& name, const dictionary& energyScalingFunctionProperties, const pairPotentialModel& pairPot, const reducedUnits& rU ), (name, energyScalingFunctionProperties, pairPot, rU) ); // Selectors //- Return a reference to the selected viscosity model static autoPtr<energyScalingFunction> New ( const word& name, const dictionary& energyScalingFunctionProperties, const pairPotentialModel& pairPot, const reducedUnits& rU ); // Constructors //- Construct from components energyScalingFunction ( const word& name, const dictionary& energyScalingFunctionProperties, const pairPotentialModel& pairPot, const reducedUnits& rU ); // Destructor virtual ~energyScalingFunction() {} // Member Functions virtual void scaleEnergy(scalar& e, const scalar r) const = 0; const dictionary& energyScalingFunctionProperties() const { return energyScalingFunctionProperties_; } //- Read energyScalingFunction dictionary virtual bool read ( const dictionary& energyScalingFunctionProperties ) = 0; }; // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // } // End namespace Foam // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // #endif // ************************************************************************* //
vincentcasseau/hyStrath
src/lagrangian/molecularDynamics/polyCloud/potentials/energyScalingFunction/basic/energyScalingFunction.H
C++
gpl-3.0
4,236
#!/usr/bin/python3 ### rev: 5.0 ### author: <zhq> ### features: ### errors included ### up to 63 bases (2 to 64) ### caps recognition and same output format (deprecated) ### for the function parameters, `cur` represents the current (input) base, `res` represents the result (output) base, and `num` represents the current (input) number. def scale(cur, res, num): # int, int, str -> str # Default Settings num = str(num) iscaps = False positive = True # Input if cur == res: return num if num == "0": return "0" assert cur in range(2, 65) and res in range(2, 65), "Base not defined." if num[0] == "-": positive = False num = num[1:] result = 0 unit = 1 if cur != 10: for i in num[::-1]: value = ord(i) if value in range(48, 58): value -= 48 elif value in range(65, 92): value -= 55 elif value in range(97, 123): value -= 61 elif value == 64: value = 62 elif value == 95: value = 63 assert value <= cur, "Digit larger than original base. v:%d(%s) b:%d\nCall: scale(%d, %d, %s)" % (value, i, cur, cur, res, num) result += value * unit unit *= cur result = str(result) # Output if res != 10: num = int(result or num) result = "" while num > 0: num, value = divmod(num, res) if value < 10: digit = value + 48 elif value < 36: digit = value + 55 elif value < 62: digit = value + 61 elif value == 62: digit = 64 elif value == 63: digit = 95 result = chr(digit) + result if not positive: result = "-" + result return result
Irides-Chromium/cipher
scale_strict.py
Python
gpl-3.0
1,750
<?php /** * OpenEyes * * (C) Moorfields Eye Hospital NHS Foundation Trust, 2008-2011 * (C) OpenEyes Foundation, 2011-2012 * This file is part of OpenEyes. * OpenEyes 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. * OpenEyes 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 OpenEyes in a file titled COPYING. If not, see <http://www.gnu.org/licenses/>. * * @package OpenEyes * @link http://www.openeyes.org.uk * @author OpenEyes <info@openeyes.org.uk> * @copyright Copyright (c) 2008-2011, Moorfields Eye Hospital NHS Foundation Trust * @copyright Copyright (c) 2011-2012, OpenEyes Foundation * @license http://www.gnu.org/licenses/gpl-3.0.html The GNU General Public License V3.0 */ /** * This is the model class for table "family_history". * * The followings are the available columns in table 'family_history': * @property integer $id * @property string $name */ class FamilyHistory extends BaseActiveRecordVersioned { /** * Returns the static model of the specified AR class. * @return FamilyHistory the static model class */ public static function model($className=__CLASS__) { return parent::model($className); } /** * @return string the associated database table name */ public function tableName() { return 'family_history'; } /** * @return array validation rules for model attributes. */ public function rules() { // NOTE: you should only define rules for those attributes that // will receive user inputs. return array( array('patient_id, relative_id, side_id, condition_id, comments','safe'), array('patient_id, relative_id, side_id, condition_id','required'), // The following rule is used by search(). // Please remove those attributes that should not be searched. array('id, name', 'safe', 'on'=>'search'), ); } /** * @return array relational rules. */ public function relations() { // NOTE: you may need to adjust the relation name and the related // class name for the relations automatically generated below. return array( 'relative' => array(self::BELONGS_TO, 'FamilyHistoryRelative', 'relative_id'), 'side' => array(self::BELONGS_TO, 'FamilyHistorySide', 'side_id'), 'condition' => array(self::BELONGS_TO, 'FamilyHistoryCondition', 'condition_id'), ); } /** * @return array customized attribute labels (name=>label) */ public function attributeLabels() { return array( 'id' => 'ID', 'name' => 'Name', ); } /** * Retrieves a list of models based on the current search/filter conditions. * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions. */ public function search() { // Warning: Please modify the following code to remove attributes that // should not be searched. $criteria=new CDbCriteria; $criteria->compare('id',$this->id,true); $criteria->compare('name',$this->name,true); return new CActiveDataProvider(get_class($this), array( 'criteria'=>$criteria, )); } }
openeyeswales/OpenEyes
protected/models/FamilyHistory.php
PHP
gpl-3.0
3,430
using UnityEngine; using System; using System.Collections; using System.Collections.Generic; // manager for the gondola spawning public class GondolaManager : MonoBehaviour { private static int N = 50; private static int DELAY = 4; private static float OFFSET = -1.8f; // the offet between the rope center and a gondola center private int count = 0; // the count of ropes in the scene private DateTime curr; // the current time for second counting use public GameObject rope; // the rope object public GameObject gondola;// the gondola object public GameObject currentRope; // the last rope spawned public Transform firstRope; // the first rope in the scene private static GondolaManager instance; // the instance of the GondolaManager public static GondolaManager Instance { get { // an instance getter if (instance == null) { instance = GameObject.FindObjectOfType<GondolaManager> (); } return instance; } } void Start () { curr = DateTime.Now; // the time now // initialization of ropes and gondolas for (int i = 0; i < N; i++) { count++; SpawnRope (); if (count % 3 == 0) { SpawnGondola (currentRope.transform); } } SpawnGondola (firstRope); } void FixedUpdate () { DateTime now = DateTime.Now; if ((now - curr).TotalSeconds >= DELAY) { // if the interval has passed SpawnGondola (firstRope); // spawn fondola in the first rope for (int i = 0; i < N / 10; i++) { // spawn N/10 ropes SpawnRope (); count++; } curr = now; } } // spawns a rope object in the scene private void SpawnRope() { GameObject tmp = Instantiate (rope); tmp.transform.position = currentRope.transform.GetChild (0).position; // creates the link between the current and new rope currentRope.GetComponent<Rope> ().next = tmp.transform; currentRope = tmp; currentRope.GetComponent<Rope> ().next = firstRope.transform; } private void SpawnGondola(Transform parent) { GameObject gon = Instantiate (gondola); // new location of the gondole minus the offset between its senter and location of the parent gon.transform.localPosition = new Vector3 (0,OFFSET,0) + parent.position; } }
sarasolano/ZooBreak
Assets/Scripts/GondolaManager.cs
C#
gpl-3.0
2,177
module BaseControllerHelper end
seekshiva/courses
app/helpers/base_controller_helper.rb
Ruby
gpl-3.0
32
import { Component } from '@angular/core'; import { NavController, ToastController } from 'ionic-angular'; import { Http } from '@angular/http'; import { ActionSheetController } from 'ionic-angular'; import { NotifikasiPage } from '../notifikasi/notifikasi'; import { ArtikelBacaPage } from '../artikel-baca/artikel-baca'; import { TulisArtikelPage } from '../tulis-artikel/tulis-artikel'; import { TulisDiskusiPage } from '../tulis-diskusi/tulis-diskusi'; import '../../providers/user-data'; /* Generated class for the Cari page. See http://ionicframework.com/docs/v2/components/#navigation for more info on Ionic pages and navigation. */ @Component({ selector: 'page-cari', templateUrl: 'cari.html' }) export class CariPage { public searchQuery = ""; public posts; public limit = 0; public httpErr = false; constructor(public navCtrl: NavController, public actionSheetCtrl: ActionSheetController, public http: Http, public toastCtrl: ToastController) { this.getData(); } ionViewDidLoad() { console.log('Hello CariPage Page'); } notif() { this.navCtrl.push(NotifikasiPage); } getData() { this.limit = 0; this.http.get('http://cybex.ipb.ac.id/api/search.php?search='+this.searchQuery+'&limit='+this.limit).subscribe(res => { this.posts = res.json(); console.log('dapet data'); this.httpErr = false; }, err => {this.showAlert(err.status)}); } getItems(searchbar){ this.getData(); } doInfinite(infiniteScroll) { console.log('Begin async operation'); setTimeout(() => { this.limit = this.limit+5; this.http.get('http://cybex.ipb.ac.id/api/search.php?search='+this.searchQuery+'&limit='+this.limit).subscribe(res => { this.posts = this.posts.concat(res.json()); }); console.log('Async operation has ended'); infiniteScroll.complete(); }, 2000); } baca(idArtikel){ this.navCtrl.push(ArtikelBacaPage, idArtikel); } presentActionSheet() { let actionSheet = this.actionSheetCtrl.create({ title: 'Pilihan', buttons: [ { text: 'Tulis Artikel', role: 'tulisArtikel', handler: () => { console.log('Tulis Artikel clicked'); this.navCtrl.push(TulisArtikelPage); } },{ text: 'Tanya/Diskusi', role: 'tulisDiskusi', handler: () => { console.log('Tulis Diskusi clicked'); this.navCtrl.push(TulisDiskusiPage); } },{ text: 'Batal', role: 'cancel', handler: () => { console.log('Cancel clicked'); } } ] }); actionSheet.present(); } showAlert(status){ if(status == 0){ let toast = this.toastCtrl.create({ message: 'Tidak ada koneksi. Cek kembali sambungan Internet perangkat Anda.', position: 'bottom', showCloseButton: true, closeButtonText: 'X' }); toast.present(); }else{ let toast = this.toastCtrl.create({ message: 'Tidak dapat menyambungkan ke server. Mohon muat kembali halaman ini.', position: 'bottom', showCloseButton: true, closeButtonText: 'X' }); toast.present(); } this.httpErr = true; } }
Rajamuda/cybex-mobile-ipb
src/pages/cari/cari.ts
TypeScript
gpl-3.0
3,304
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'events.ui' # # Created by: PyQt4 UI code generator 4.11.4 # # WARNING! All changes made in this file will be lost! from PyQt4 import QtCore, QtGui from collections import * from functools import * import os, glob import pandas as pd try: _fromUtf8 = QtCore.QString.fromUtf8 except AttributeError: def _fromUtf8(s): return s try: _encoding = QtGui.QApplication.UnicodeUTF8 def _translate(context, text, disambig): return QtGui.QApplication.translate(context, text, disambig, _encoding) except AttributeError: def _translate(context, text, disambig): return QtGui.QApplication.translate(context, text, disambig) class Ui_SamplesDialog(QtGui.QDialog): def __init__(self, parent=None, datafolder=None): """ Constructor """ QtGui.QDialog.__init__(self, parent) # self.filelist = filelist self.datafolder = datafolder # labels font self.font_labels = QtGui.QFont("Arial", 12, QtGui.QFont.Bold) self.font_edits = QtGui.QFont("Arial", 12) self.font_buttons = QtGui.QFont("Arial", 10, QtGui.QFont.Bold) self.setupUi(self) self.exec_() def setupUi(self, Dialog): Dialog.setObjectName(_fromUtf8("Dialog")) Dialog.resize(1000, 400) self.gridLayout = QtGui.QGridLayout(Dialog) self.gridLayout.setObjectName(_fromUtf8("gridLayout")) # list of Events self.prepare_form(Dialog) self.retranslateUi(Dialog) QtCore.QMetaObject.connectSlotsByName(Dialog) def load_data(self): print(self.datafolder) self.samplefile = glob.glob(os.path.join(self.datafolder, "*_SAMPLES.csv"))[0] if os.path.isfile(self.samplefile): self.samplesdf = pd.read_csv(self.samplefile, encoding='ISO-8859-1') else: print("File not found: ", self.samplefile) self.samplesdf = None self.combodefaults = {'cuvette': ['600', '2000', '4000']} def prepare_form(self, Dialog): # load or reload data self.load_data() # form dicts edit_list = ['date', 'time', 'samplename', 'filename', 'smoothing', 'cal32', 'cal44', 'cons32', 'cons44', 'zero44', 'zero45', 'zero46', 'zero47', 'zero49'] combo_list = ['user', 'membrane', 'cuvette'] self.labels = defaultdict(defaultdict) self.edits = defaultdict(defaultdict) self.radios = defaultdict(defaultdict) self.combobox = defaultdict(defaultdict) self.labs = defaultdict(defaultdict) self.labs = {"time": "Time", "date": "Date", "samplename": "Sample Name", "filename": "File Name", "smoothing": "Smoothing", "cuvette": "Cuvette", "user": "User", "membrane": "Membrane", "cal44": "Calibration 44", "cal32": "Calibration 32", "cons32": "Consumption 32", "cons44": "Consumption 44", "zero32": "Zero 32", "zero44": "Zero 44", "zero45": "Zero 45", "zero46": "Zero 46", "zero47": "Zero 47", "zero49": "Zero 49"} self.buttons = OrderedDict(sorted({'Apply': defaultdict(object), 'Delete': defaultdict(object)}.items())) xpos, ypos = 1, 0 for row in self.samplesdf.iterrows(): row_index = row[0] r = row[1] self.radios[row_index] = QtGui.QRadioButton(Dialog) self.radios[row_index].setObjectName(_fromUtf8("_".join(["radio", str(row_index)]))) self.gridLayout.addWidget(self.radios[row_index], ypos+1, 0, 1, 1) for k in ['samplename', 'date', 'time', 'cuvette']: # create labels if ypos == 0: self.labels[k] = QtGui.QLabel(Dialog) self.labels[k].setObjectName(_fromUtf8("_".join(["label", k]))) self.labels[k].setText(str(self.labs[k])) self.labels[k].setAlignment(QtCore.Qt.AlignCenter | QtCore.Qt.AlignVCenter) self.labels[k].setFont(self.font_labels) self.gridLayout.addWidget(self.labels[k], 0, xpos, 1, 1) if k in edit_list: self.edits[k][row_index] = QtGui.QLineEdit(Dialog) self.edits[k][row_index].setObjectName(_fromUtf8("_".join(["edit", k, str(row_index)]))) self.edits[k][row_index].setText(str(r[k])) self.edits[k][row_index].setFont(self.font_edits) if k in ['time', 'date']: self.edits[k][row_index].setFixedWidth(80) self.gridLayout.addWidget(self.edits[k][row_index], ypos+1, xpos, 1, 1) elif k in combo_list: self.combobox[k][row_index] = QtGui.QComboBox(Dialog) self.combobox[k][row_index].setObjectName(_fromUtf8("_".join(["combo", k, str(row_index)]))) self.combobox[k][row_index].addItems(self.combodefaults[k]) self.combobox[k][row_index].setCurrentIndex(self.combobox[k][row_index].findText(str(r[k]), QtCore.Qt.MatchFixedString)) self.combobox[k][row_index].setFont(self.font_edits) self.gridLayout.addWidget(self.combobox[k][row_index], ypos+1, xpos, 1, 1) xpos += 1 # create buttons for k in self.buttons.keys(): # if ypos > 0: self.buttons[k][row_index] = QtGui.QPushButton(Dialog) self.buttons[k][row_index].setObjectName(_fromUtf8("_".join(["event", k, "button", str(row_index)]))) self.buttons[k][row_index].setText(_translate("Dialog", k + str(row_index), None)) self.buttons[k][row_index].setFont(self.font_buttons) if k == 'Apply': self.buttons[k][row_index].clicked.connect(partial(self.ask_apply_changes, [row_index, Dialog])) self.buttons[k][row_index].setStyleSheet("background-color: #ffeedd") elif k == 'Delete': self.buttons[k][row_index].clicked.connect(partial(self.ask_delete_confirm1, [row_index, Dialog])) self.buttons[k][row_index].setStyleSheet("background-color: #ffcddd") self.gridLayout.addWidget(self.buttons[k][row_index], ypos+1, xpos, 1, 1) xpos += 1 # increments ypos += 1 xpos = 1 Dialog.resize(1000, 70 + (30 * ypos)) # self.add_row(Dialog) def ask_delete_confirm1(self, args): sid = args[0] Dialog = args[1] # check if radio button is checked. if self.radios[sid].isChecked(): msg = "Are you sure you want to delete the following sample : \n\n" details = "" for c in self.samplesdf.columns: details += str(c) + ": " + str(self.samplesdf.at[sid, c]) + "\n" reply = QtGui.QMessageBox.warning(self, 'Confirmation #1', msg + details, QtGui.QMessageBox.Yes, QtGui.QMessageBox.No) if reply == QtGui.QMessageBox.Yes: msg2 = "Are you sure REALLY REALLY sure you want to delete the following sample ? \n\n" + \ "This is the last confirmation message. After confirming, the files will be PERMANENTLY deleted and the data WILL be lost ! \n\n" msgbox = QtGui.QMessageBox.critical(self, 'Confirmation #2', msg2 + details, QtGui.QMessageBox.Yes | QtGui.QMessageBox.No, QtGui.QMessageBox.No) reply2 = msgbox if reply2 == QtGui.QMessageBox.Yes: # deletion confirmed self.delete_confirmed(sid) self.update_form( Dialog) else: QtGui.QMessageBox.question(self, 'Error', 'Please select the sample you want to delete on the left', QtGui.QMessageBox.Ok) def delete_confirmed(self, sid): # sample file filename = self.samplesdf.loc[sid, 'filename'] # delete row in samplesdf self.samplesdf = self.samplesdf.drop(self.samplesdf.index[sid]) self.samplesdf.to_csv(self.samplefile, index=False, encoding='ISO-8859-1') # delete file in rawdata if os.path.isfile(os.path.join(self.datafolder, "rawdata", filename)): os.remove(os.path.join(self.datafolder, "rawdata", filename)) # print(" delete: ", os.path.join(self.datafolder, "rawdata", filename)) # delete file in data if os.path.isfile(os.path.join(self.datafolder, filename)): os.remove(os.path.join(self.datafolder, filename)) # print(" delete: ", os.path.join(self.datafolder, filename)) def ask_apply_changes(self, args): sid = args[0] Dialog = args[1] newdata=defaultdict(str) for k in self.edits.keys(): newdata[k] = self.edits[k][sid].text() for k in self.combobox.keys(): newdata[k] = self.combobox[k][sid].currentText() details = "" for k in newdata: details += str(self.samplesdf.at[sid, k]) + '\t --> \t' + str(newdata[k]) + "\n" msg = "Are you sure you want to apply the changes to sample " + str(self.samplesdf.at[sid, 'samplename']) + " ?\n\n" reply = QtGui.QMessageBox.question(self, 'Modify a sample', msg + details, QtGui.QMessageBox.Yes, QtGui.QMessageBox.No) if reply == QtGui.QMessageBox.Yes: self.apply_changes_confirmed(sid, newdata) self.update_form(Dialog) else: print('cancel modification') def apply_changes_confirmed(self, sid, newdata): # rename files newdata['filename'] = str(newdata['date']) + "_" + str(newdata['samplename']) + ".csv" os.rename(os.path.join(self.datafolder, str(self.samplesdf.at[sid, 'filename'])), os.path.join(self.datafolder, str(newdata['filename']))) os.rename(os.path.join(self.datafolder, "rawdata", str(self.samplesdf.at[sid, 'filename'])), os.path.join(self.datafolder, "rawdata", str(newdata['filename']))) for k in newdata.keys(): self.samplesdf.at[sid, k] = newdata[k] self.samplesdf.to_csv(self.samplefile, index=False, encoding='ISO-8859-1') def update_form(self, Dialog): # empty variables self.edits = None self.combobox = None self.buttons = None self.radios = None self.labs = None self.labels = None # empty layout for i in reversed(range(self.gridLayout.count())): self.gridLayout.itemAt(i).widget().setParent(None) self.prepare_form(Dialog) def retranslateUi(self, Dialog): Dialog.setWindowTitle(_translate("Dialog", "Samples Manager", None)) # self.label.setText(_translate("Dialog", "File", None))
vince8290/dana
ui_files/samples.py
Python
gpl-3.0
11,728
/* * Copyright (c) 2011 Sveriges Television AB <info@casparcg.com> * * This file is part of CasparCG (www.casparcg.com). * * CasparCG 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. * * CasparCG 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 CasparCG. If not, see <http://www.gnu.org/licenses/>. * * Author: Helge Norberg, helge.norberg@svt.se */ #include "../../StdAfx.h" #include "synchronizing_consumer.h" #include <common/log/log.h> #include <common/diagnostics/graph.h> #include <common/concurrency/future_util.h> #include <core/video_format.h> #include <boost/range/adaptor/transformed.hpp> #include <boost/range/algorithm/min_element.hpp> #include <boost/range/algorithm/max_element.hpp> #include <boost/range/algorithm/for_each.hpp> #include <boost/range/algorithm/count_if.hpp> #include <boost/range/numeric.hpp> #include <boost/algorithm/string/join.hpp> #include <boost/thread/future.hpp> #include <functional> #include <vector> #include <queue> #include <utility> #include <tbb/atomic.h> namespace caspar { namespace core { using namespace boost::adaptors; class delegating_frame_consumer : public frame_consumer { safe_ptr<frame_consumer> consumer_; public: delegating_frame_consumer(const safe_ptr<frame_consumer>& consumer) : consumer_(consumer) { } frame_consumer& get_delegate() { return *consumer_; } const frame_consumer& get_delegate() const { return *consumer_; } virtual void initialize( const video_format_desc& format_desc, int channel_index) override { get_delegate().initialize(format_desc, channel_index); } virtual int64_t presentation_frame_age_millis() const { return get_delegate().presentation_frame_age_millis(); } virtual boost::unique_future<bool> send( const safe_ptr<read_frame>& frame) override { return get_delegate().send(frame); } virtual std::wstring print() const override { return get_delegate().print(); } virtual boost::property_tree::wptree info() const override { return get_delegate().info(); } virtual bool has_synchronization_clock() const override { return get_delegate().has_synchronization_clock(); } virtual size_t buffer_depth() const override { return get_delegate().buffer_depth(); } virtual int index() const override { return get_delegate().index(); } }; const std::vector<int>& diag_colors() { static std::vector<int> colors = boost::assign::list_of<int> (diagnostics::color(0.0f, 0.6f, 0.9f)) (diagnostics::color(0.6f, 0.3f, 0.3f)) (diagnostics::color(0.3f, 0.6f, 0.3f)) (diagnostics::color(0.4f, 0.3f, 0.8f)) (diagnostics::color(0.9f, 0.9f, 0.5f)) (diagnostics::color(0.2f, 0.9f, 0.9f)); return colors; } class buffering_consumer_adapter : public delegating_frame_consumer { std::queue<safe_ptr<read_frame>> buffer_; tbb::atomic<size_t> buffered_; tbb::atomic<int64_t> duplicate_next_; public: buffering_consumer_adapter(const safe_ptr<frame_consumer>& consumer) : delegating_frame_consumer(consumer) { buffered_ = 0; duplicate_next_ = 0; } boost::unique_future<bool> consume_one() { if (!buffer_.empty()) { buffer_.pop(); --buffered_; } return get_delegate().send(buffer_.front()); } virtual boost::unique_future<bool> send( const safe_ptr<read_frame>& frame) override { if (duplicate_next_) { --duplicate_next_; } else if (!buffer_.empty()) { buffer_.pop(); --buffered_; } buffer_.push(frame); ++buffered_; return get_delegate().send(buffer_.front()); } void duplicate_next(int64_t to_duplicate) { duplicate_next_ += to_duplicate; } size_t num_buffered() const { return buffered_ - 1; } virtual std::wstring print() const override { return L"buffering[" + get_delegate().print() + L"]"; } virtual boost::property_tree::wptree info() const override { boost::property_tree::wptree info; info.add(L"type", L"buffering-consumer-adapter"); info.add_child(L"consumer", get_delegate().info()); info.add(L"buffered-frames", num_buffered()); return info; } }; static const uint64_t MAX_BUFFERED_OUT_OF_MEMORY_GUARD = 5; struct synchronizing_consumer::implementation { private: std::vector<safe_ptr<buffering_consumer_adapter>> consumers_; size_t buffer_depth_; bool has_synchronization_clock_; std::vector<boost::unique_future<bool>> results_; boost::promise<bool> promise_; video_format_desc format_desc_; safe_ptr<diagnostics::graph> graph_; int64_t grace_period_; tbb::atomic<int64_t> current_diff_; public: implementation(const std::vector<safe_ptr<frame_consumer>>& consumers) : grace_period_(0) { BOOST_FOREACH(auto& consumer, consumers) consumers_.push_back(make_safe<buffering_consumer_adapter>(consumer)); current_diff_ = 0; auto buffer_depths = consumers | transformed(std::mem_fn(&frame_consumer::buffer_depth)); std::vector<size_t> depths(buffer_depths.begin(), buffer_depths.end()); buffer_depth_ = *boost::max_element(depths); has_synchronization_clock_ = boost::count_if(consumers, std::mem_fn(&frame_consumer::has_synchronization_clock)) > 0; diagnostics::register_graph(graph_); } boost::unique_future<bool> send(const safe_ptr<read_frame>& frame) { results_.clear(); BOOST_FOREACH(auto& consumer, consumers_) results_.push_back(consumer->send(frame)); promise_ = boost::promise<bool>(); promise_.set_wait_callback(std::function<void(boost::promise<bool>&)>([this](boost::promise<bool>& promise) { BOOST_FOREACH(auto& result, results_) { result.get(); } auto frame_ages = consumers_ | transformed(std::mem_fn(&frame_consumer::presentation_frame_age_millis)); std::vector<int64_t> ages(frame_ages.begin(), frame_ages.end()); auto max_age_iter = boost::max_element(ages); auto min_age_iter = boost::min_element(ages); int64_t min_age = *min_age_iter; if (min_age == 0) { // One of the consumers have yet no measurement, wait until next // frame until we make any assumptions. promise.set_value(true); return; } int64_t max_age = *max_age_iter; int64_t age_diff = max_age - min_age; current_diff_ = age_diff; for (unsigned i = 0; i < ages.size(); ++i) graph_->set_value( narrow(consumers_[i]->print()), static_cast<double>(ages[i]) / *max_age_iter); bool grace_period_over = grace_period_ == 1; if (grace_period_) --grace_period_; if (grace_period_ == 0) { int64_t frame_duration = static_cast<int64_t>(1000 / format_desc_.fps); if (age_diff >= frame_duration) { CASPAR_LOG(info) << print() << L" Consumers not in sync. min: " << min_age << L" max: " << max_age; auto index = min_age_iter - ages.begin(); auto to_duplicate = age_diff / frame_duration; auto& consumer = *consumers_.at(index); auto currently_buffered = consumer.num_buffered(); if (currently_buffered + to_duplicate > MAX_BUFFERED_OUT_OF_MEMORY_GUARD) { CASPAR_LOG(info) << print() << L" Protecting from out of memory. Duplicating less frames than calculated"; to_duplicate = MAX_BUFFERED_OUT_OF_MEMORY_GUARD - currently_buffered; } consumer.duplicate_next(to_duplicate); grace_period_ = 10 + to_duplicate + buffer_depth_; } else if (grace_period_over) { CASPAR_LOG(info) << print() << L" Consumers resynced. min: " << min_age << L" max: " << max_age; } } blocking_consume_unnecessarily_buffered(); promise.set_value(true); })); return promise_.get_future(); } void blocking_consume_unnecessarily_buffered() { auto buffered = consumers_ | transformed(std::mem_fn(&buffering_consumer_adapter::num_buffered)); std::vector<size_t> num_buffered(buffered.begin(), buffered.end()); auto min_buffered = *boost::min_element(num_buffered); if (min_buffered) CASPAR_LOG(info) << print() << L" " << min_buffered << L" frames unnecessarily buffered. Consuming and letting channel pause during that time."; while (min_buffered) { std::vector<boost::unique_future<bool>> results; BOOST_FOREACH(auto& consumer, consumers_) results.push_back(consumer->consume_one()); BOOST_FOREACH(auto& result, results) result.get(); --min_buffered; } } void initialize(const video_format_desc& format_desc, int channel_index) { for (size_t i = 0; i < consumers_.size(); ++i) { auto& consumer = consumers_.at(i); consumer->initialize(format_desc, channel_index); graph_->set_color( narrow(consumer->print()), diag_colors().at(i % diag_colors().size())); } graph_->set_text(print()); format_desc_ = format_desc; } int64_t presentation_frame_age_millis() const { int64_t result = 0; BOOST_FOREACH(auto& consumer, consumers_) result = std::max(result, consumer->presentation_frame_age_millis()); return result; } std::wstring print() const { return L"synchronized[" + boost::algorithm::join(consumers_ | transformed(std::mem_fn(&frame_consumer::print)), L"|") + L"]"; } boost::property_tree::wptree info() const { boost::property_tree::wptree info; info.add(L"type", L"synchronized-consumer"); BOOST_FOREACH(auto& consumer, consumers_) info.add_child(L"consumer", consumer->info()); info.add(L"age-diff", current_diff_); return info; } bool has_synchronization_clock() const { return has_synchronization_clock_; } size_t buffer_depth() const { return buffer_depth_; } int index() const { return boost::accumulate(consumers_ | transformed(std::mem_fn(&frame_consumer::index)), 10000); } }; synchronizing_consumer::synchronizing_consumer(const std::vector<safe_ptr<frame_consumer>>& consumers) : impl_(new implementation(consumers)) { } boost::unique_future<bool> synchronizing_consumer::send(const safe_ptr<read_frame>& frame) { return impl_->send(frame); } void synchronizing_consumer::initialize(const video_format_desc& format_desc, int channel_index) { impl_->initialize(format_desc, channel_index); } int64_t synchronizing_consumer::presentation_frame_age_millis() const { return impl_->presentation_frame_age_millis(); } std::wstring synchronizing_consumer::print() const { return impl_->print(); } boost::property_tree::wptree synchronizing_consumer::info() const { return impl_->info(); } bool synchronizing_consumer::has_synchronization_clock() const { return impl_->has_synchronization_clock(); } size_t synchronizing_consumer::buffer_depth() const { return impl_->buffer_depth(); } int synchronizing_consumer::index() const { return impl_->index(); } }}
gfto/Server
core/consumer/synchronizing/synchronizing_consumer.cpp
C++
gpl-3.0
11,040
package nest.util; import android.text.TextUtils; import java.util.regex.Matcher; import java.util.regex.Pattern; import timber.log.Timber; public class TraceTree extends Timber.HollowTree { private final DebugTree debugTree; public TraceTree(boolean useTraces) { debugTree = new DebugTree(useTraces); } @Override public void v(String message, Object... args) { debugTree.v(message, args); } @Override public void v(Throwable t, String message, Object... args) { debugTree.v(t, message, args); } @Override public void d(String message, Object... args) { debugTree.d(message, args); } @Override public void d(Throwable t, String message, Object... args) { debugTree.d(t, message, args); } @Override public void i(String message, Object... args) { debugTree.i(message, args); } @Override public void i(Throwable t, String message, Object... args) { debugTree.i(t, message, args); } @Override public void w(String message, Object... args) { debugTree.w(message, args); } @Override public void w(Throwable t, String message, Object... args) { debugTree.w(t, message, args); } @Override public void e(String message, Object... args) { debugTree.e(message, args); } @Override public void e(Throwable t, String message, Object... args) { debugTree.e(t, message, args); } private static class DebugTree extends Timber.DebugTree { private static final Pattern ANONYMOUS_CLASS = Pattern.compile("\\$\\d+$"); private static final int STACK_POSITION = 6; private final boolean useTraces; private StackTraceElement lastTrace; private DebugTree(boolean useTraces) { this.useTraces = useTraces; } @Override protected String createTag() { String tag; if (!useTraces) { tag = nextTag(); if (tag != null) { return tag; } } StackTraceElement[] stackTrace = new Throwable().getStackTrace(); if (stackTrace.length < STACK_POSITION) { return "---"; } if (useTraces) { lastTrace = stackTrace[STACK_POSITION]; } tag = stackTrace[STACK_POSITION].getClassName(); Matcher m = ANONYMOUS_CLASS.matcher(tag); if (m.find()) { tag = m.replaceAll(""); } return tag.substring(tag.lastIndexOf('.') + 1); } @Override protected void logMessage(int priority, String tag, String message) { if (lastTrace != null) { message = (TextUtils.isEmpty(message) ? "" : message +" ") + "at "+ lastTrace; lastTrace = null; } super.logMessage(priority, tag, message); } } }
withoutuniverse/nest_tt
appko_tt/app/src/main/java/nest/util/TraceTree.java
Java
gpl-3.0
3,022
/* * Copyright (C) 2012 Carl Green * * 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 info.carlwithak.mpxg2.sysex.effects.algorithms; import info.carlwithak.mpxg2.model.effects.algorithms.DetuneStereo; /** * Class to parse parameter data for Detune (S) effect. * * @author Carl Green */ public class DetuneStereoParser { public static DetuneStereo parse(byte[] effectParameters) { DetuneStereo detuneStereo = new DetuneStereo(); int mix = effectParameters[0] + effectParameters[1] * 16; detuneStereo.mix.setValue(mix); int level = effectParameters[2] + effectParameters[3] * 16; detuneStereo.level.setValue(level); int tune = effectParameters[4] + effectParameters[5] * 16; detuneStereo.tune.setValue(tune); int optimize = effectParameters[6] + effectParameters[7] * 16; detuneStereo.optimize.setValue(optimize); int preDelay = effectParameters[8] + effectParameters[9] * 16; detuneStereo.preDelay.setValue(preDelay); return detuneStereo; } }
carlgreen/Lexicon-MPX-G2-Editor
mpxg2-sysex/src/main/java/info/carlwithak/mpxg2/sysex/effects/algorithms/DetuneStereoParser.java
Java
gpl-3.0
1,687
/*---------------------------------------------------------------------------*\ ========= | \\ / F ield | foam-extend: Open Source CFD \\ / O peration | Version: 3.2 \\ / A nd | Web: http://www.foam-extend.org \\/ M anipulation | For copyright notice see file Copyright ------------------------------------------------------------------------------- License This file is part of foam-extend. foam-extend 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. foam-extend 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 foam-extend. If not, see <http://www.gnu.org/licenses/>. \*---------------------------------------------------------------------------*/ #include "faceTriangulation.H" #include "plane.H" // * * * * * * * * * * * * * * Static Data Members * * * * * * * * * * * * * // const Foam::scalar Foam::faceTriangulation::edgeRelTol = 1E-6; // Edge to the right of face vertex i Foam::label Foam::faceTriangulation::right(const label, label i) { return i; } // Edge to the left of face vertex i Foam::label Foam::faceTriangulation::left(const label size, label i) { return i ? i-1 : size-1; } // Calculate (normalized) edge vectors. // edges[i] gives edge between point i+1 and i. Foam::tmp<Foam::vectorField> Foam::faceTriangulation::calcEdges ( const face& f, const pointField& points ) { tmp<vectorField> tedges(new vectorField(f.size())); vectorField& edges = tedges(); forAll(f, i) { point thisPt = points[f[i]]; point nextPt = points[f[f.fcIndex(i)]]; vector vec(nextPt - thisPt); vec /= mag(vec) + VSMALL; edges[i] = vec; } return tedges; } // Calculates half angle components of angle from e0 to e1 void Foam::faceTriangulation::calcHalfAngle ( const vector& normal, const vector& e0, const vector& e1, scalar& cosHalfAngle, scalar& sinHalfAngle ) { // truncate cos to +-1 to prevent negative numbers scalar cos = max(-1, min(1, e0 & e1)); scalar sin = (e0 ^ e1) & normal; if (sin < -ROOTVSMALL) { // 3rd or 4th quadrant cosHalfAngle = - Foam::sqrt(0.5*(1 + cos)); sinHalfAngle = Foam::sqrt(0.5*(1 - cos)); } else { // 1st or 2nd quadrant cosHalfAngle = Foam::sqrt(0.5*(1 + cos)); sinHalfAngle = Foam::sqrt(0.5*(1 - cos)); } } // Calculate intersection point between edge p1-p2 and ray (in 2D). // Return true and intersection point if intersection between p1 and p2. Foam::pointHit Foam::faceTriangulation::rayEdgeIntersect ( const vector& normal, const point& rayOrigin, const vector& rayDir, const point& p1, const point& p2, scalar& posOnEdge ) { // Start off from miss pointHit result(p1); // Construct plane normal to rayDir and intersect const vector y = normal ^ rayDir; posOnEdge = plane(rayOrigin, y).normalIntersect(p1, (p2-p1)); // Check intersection to left of p1 or right of p2 if ((posOnEdge < 0) || (posOnEdge > 1)) { // Miss } else { // Check intersection behind rayOrigin point intersectPt = p1 + posOnEdge * (p2 - p1); if (((intersectPt - rayOrigin) & rayDir) < 0) { // Miss } else { // Hit result.setHit(); result.setPoint(intersectPt); result.setDistance(mag(intersectPt - rayOrigin)); } } return result; } // Return true if triangle given its three points (anticlockwise ordered) // contains point bool Foam::faceTriangulation::triangleContainsPoint ( const vector& n, const point& p0, const point& p1, const point& p2, const point& pt ) { scalar area01Pt = triPointRef(p0, p1, pt).normal() & n; scalar area12Pt = triPointRef(p1, p2, pt).normal() & n; scalar area20Pt = triPointRef(p2, p0, pt).normal() & n; if ((area01Pt > 0) && (area12Pt > 0) && (area20Pt > 0)) { return true; } else if ((area01Pt < 0) && (area12Pt < 0) && (area20Pt < 0)) { FatalErrorIn("triangleContainsPoint") << abort(FatalError); return false; } else { return false; } } // Starting from startIndex find diagonal. Return in index1, index2. // Index1 always startIndex except when convex polygon void Foam::faceTriangulation::findDiagonal ( const pointField& points, const face& f, const vectorField& edges, const vector& normal, const label startIndex, label& index1, label& index2 ) { const point& startPt = points[f[startIndex]]; // Calculate angle at startIndex const vector& rightE = edges[right(f.size(), startIndex)]; const vector leftE = -edges[left(f.size(), startIndex)]; // Construct ray which bisects angle scalar cosHalfAngle = GREAT; scalar sinHalfAngle = GREAT; calcHalfAngle(normal, rightE, leftE, cosHalfAngle, sinHalfAngle); vector rayDir ( cosHalfAngle*rightE + sinHalfAngle*(normal ^ rightE) ); // rayDir should be normalized already but is not due to rounding errors // so normalize. rayDir /= mag(rayDir) + VSMALL; // // Check all edges (apart from rightE and leftE) for nearest intersection // label faceVertI = f.fcIndex(startIndex); pointHit minInter(false, vector::zero, GREAT, true); label minIndex = -1; scalar minPosOnEdge = GREAT; for (label i = 0; i < f.size() - 2; i++) { scalar posOnEdge; pointHit inter = rayEdgeIntersect ( normal, startPt, rayDir, points[f[faceVertI]], points[f[f.fcIndex(faceVertI)]], posOnEdge ); if (inter.hit() && inter.distance() < minInter.distance()) { minInter = inter; minIndex = faceVertI; minPosOnEdge = posOnEdge; } faceVertI = f.fcIndex(faceVertI); } if (minIndex == -1) { //WarningIn("faceTriangulation::findDiagonal") // << "Could not find intersection starting from " << f[startIndex] // << " for face " << f << endl; index1 = -1; index2 = -1; return; } const label leftIndex = minIndex; const label rightIndex = f.fcIndex(minIndex); // Now ray intersects edge from leftIndex to rightIndex. // Check for intersection being one of the edge points. Make sure never // to return two consecutive points. if (mag(minPosOnEdge) < edgeRelTol && f.fcIndex(startIndex) != leftIndex) { index1 = startIndex; index2 = leftIndex; return; } if ( mag(minPosOnEdge - 1) < edgeRelTol && f.fcIndex(rightIndex) != startIndex ) { index1 = startIndex; index2 = rightIndex; return; } // Select visible vertex that minimizes // angle to bisection. Visibility checking by checking if inside triangle // formed by startIndex, leftIndex, rightIndex const point& leftPt = points[f[leftIndex]]; const point& rightPt = points[f[rightIndex]]; minIndex = -1; scalar maxCos = -GREAT; // all vertices except for startIndex and ones to left and right of it. faceVertI = f.fcIndex(f.fcIndex(startIndex)); for (label i = 0; i < f.size() - 3; i++) { const point& pt = points[f[faceVertI]]; if ( (faceVertI == leftIndex) || (faceVertI == rightIndex) || (triangleContainsPoint(normal, startPt, leftPt, rightPt, pt)) ) { // pt inside triangle (so perhaps visible) // Select based on minimal angle (so guaranteed visible). vector edgePt0 = pt - startPt; edgePt0 /= mag(edgePt0); scalar cos = rayDir & edgePt0; if (cos > maxCos) { maxCos = cos; minIndex = faceVertI; } } faceVertI = f.fcIndex(faceVertI); } if (minIndex == -1) { // no vertex found. Return startIndex and one of the intersected edge // endpoints. index1 = startIndex; if (f.fcIndex(startIndex) != leftIndex) { index2 = leftIndex; } else { index2 = rightIndex; } return; } index1 = startIndex; index2 = minIndex; } // Find label of vertex to start splitting from. Is: // 1] flattest concave angle // 2] flattest convex angle if no concave angles. Foam::label Foam::faceTriangulation::findStart ( const face& f, const vectorField& edges, const vector& normal ) { const label size = f.size(); scalar minCos = GREAT; label minIndex = -1; forAll(f, fp) { const vector& rightEdge = edges[right(size, fp)]; const vector leftEdge = -edges[left(size, fp)]; if (((rightEdge ^ leftEdge) & normal) < ROOTVSMALL) { scalar cos = rightEdge & leftEdge; if (cos < minCos) { minCos = cos; minIndex = fp; } } } if (minIndex == -1) { // No concave angle found. Get flattest convex angle minCos = GREAT; forAll(f, fp) { const vector& rightEdge = edges[right(size, fp)]; const vector leftEdge = -edges[left(size, fp)]; scalar cos = rightEdge & leftEdge; if (cos < minCos) { minCos = cos; minIndex = fp; } } } return minIndex; } // * * * * * * * * * * * * * Private Member Functions * * * * * * * * * * * // // Split face f into triangles. Handles all simple (convex & concave) // polygons. bool Foam::faceTriangulation::split ( const bool fallBack, const pointField& points, const face& f, const vector& normal, label& triI ) { const label size = f.size(); if (size <= 2) { WarningIn ( "split(const bool, const pointField&, const face&" ", const vector&, label&)" ) << "Illegal face:" << f << " with points " << UIndirectList<point>(points, f)() << endl; return false; } else if (size == 3) { // Triangle. Just copy. triFace& tri = operator[](triI++); tri[0] = f[0]; tri[1] = f[1]; tri[2] = f[2]; return true; } else { // General case. Start splitting for -flattest concave angle // -or flattest convex angle if no concave angles. tmp<vectorField> tedges(calcEdges(f, points)); const vectorField& edges = tedges(); label startIndex = findStart(f, edges, normal); // Find diagonal to split face across label index1 = -1; label index2 = -1; for (label iter = 0; iter < f.size(); iter++) { findDiagonal ( points, f, edges, normal, startIndex, index1, index2 ); if (index1 != -1 && index2 != -1) { // Found correct diagonal break; } // Try splitting from next startingIndex. startIndex = f.fcIndex(startIndex); } if (index1 == -1 || index2 == -1) { if (fallBack) { // Do naive triangulation. Find smallest angle to start // triangulating from. label maxIndex = -1; scalar maxCos = -GREAT; forAll(f, fp) { const vector& rightEdge = edges[right(size, fp)]; const vector leftEdge = -edges[left(size, fp)]; scalar cos = rightEdge & leftEdge; if (cos > maxCos) { maxCos = cos; maxIndex = fp; } } WarningIn ( "split(const bool, const pointField&, const face&" ", const vector&, label&)" ) << "Cannot find valid diagonal on face " << f << " with points " << UIndirectList<point>(points, f)() << nl << "Returning naive triangulation starting from " << f[maxIndex] << " which might not be correct for a" << " concave or warped face" << endl; label fp = f.fcIndex(maxIndex); for (label i = 0; i < size-2; i++) { label nextFp = f.fcIndex(fp); triFace& tri = operator[](triI++); tri[0] = f[maxIndex]; tri[1] = f[fp]; tri[2] = f[nextFp]; fp = nextFp; } return true; } else { WarningIn ( "split(const bool, const pointField&, const face&" ", const vector&, label&)" ) << "Cannot find valid diagonal on face " << f << " with points " << UIndirectList<point>(points, f)() << nl << "Returning empty triFaceList" << endl; return false; } } // Split into two subshapes. // face1: index1 to index2 // face2: index2 to index1 // Get sizes of the two subshapes label diff = 0; if (index2 > index1) { diff = index2 - index1; } else { // folded round diff = index2 + size - index1; } label nPoints1 = diff + 1; label nPoints2 = size - diff + 1; if (nPoints1 == size || nPoints2 == size) { FatalErrorIn ( "split(const bool, const pointField&, const face&" ", const vector&, label&)" ) << "Illegal split of face:" << f << " with points " << UIndirectList<point>(points, f)() << " at indices " << index1 << " and " << index2 << abort(FatalError); } // Collect face1 points face face1(nPoints1); label faceVertI = index1; for (int i = 0; i < nPoints1; i++) { face1[i] = f[faceVertI]; faceVertI = f.fcIndex(faceVertI); } // Collect face2 points face face2(nPoints2); faceVertI = index2; for (int i = 0; i < nPoints2; i++) { face2[i] = f[faceVertI]; faceVertI = f.fcIndex(faceVertI); } // Decompose the split faces //Pout<< "Split face:" << f << " into " << face1 << " and " << face2 // << endl; //string oldPrefix(Pout.prefix()); //Pout.prefix() = " " + oldPrefix; bool splitOk = split(fallBack, points, face1, normal, triI) && split(fallBack, points, face2, normal, triI); //Pout.prefix() = oldPrefix; return splitOk; } } // * * * * * * * * * * * * * * * * Constructors * * * * * * * * * * * * * * // // Null constructor Foam::faceTriangulation::faceTriangulation() : triFaceList() {} // Construct from components Foam::faceTriangulation::faceTriangulation ( const pointField& points, const face& f, const bool fallBack ) : triFaceList(f.size()-2) { vector avgNormal = f.normal(points); avgNormal /= mag(avgNormal) + VSMALL; label triI = 0; bool valid = split(fallBack, points, f, avgNormal, triI); if (!valid) { setSize(0); } } // Construct from components Foam::faceTriangulation::faceTriangulation ( const pointField& points, const face& f, const vector& n, const bool fallBack ) : triFaceList(f.size()-2) { label triI = 0; bool valid = split(fallBack, points, f, n, triI); if (!valid) { setSize(0); } } // Construct from Istream Foam::faceTriangulation::faceTriangulation(Istream& is) : triFaceList(is) {} // ************************************************************************* //
Unofficial-Extend-Project-Mirror/foam-extend-foam-extend-3.2
src/meshTools/triSurface/faceTriangulation/faceTriangulation.C
C++
gpl-3.0
17,132
<?php /* Smarty version Smarty-3.1.19, created on 2016-03-17 14:44:03 compiled from "/Users/Evergreen/Documents/workspace/licpresta/admin/themes/default/template/controllers/shop/helpers/list/list_action_delete.tpl" */ ?> <?php /*%%SmartyHeaderCode:154545909656eab4a3d7e136-98563971%%*/if(!defined('SMARTY_DIR')) exit('no direct access allowed'); $_valid = $_smarty_tpl->decodeProperties(array ( 'file_dependency' => array ( 'cbf2ed399b76a836e7562130658957cc92238d15' => array ( 0 => '/Users/Evergreen/Documents/workspace/licpresta/admin/themes/default/template/controllers/shop/helpers/list/list_action_delete.tpl', 1 => 1452095428, 2 => 'file', ), ), 'nocache_hash' => '154545909656eab4a3d7e136-98563971', 'function' => array ( ), 'variables' => array ( 'href' => 0, 'action' => 0, 'id_shop' => 0, 'shops_having_dependencies' => 0, 'confirm' => 0, ), 'has_nocache_code' => false, 'version' => 'Smarty-3.1.19', 'unifunc' => 'content_56eab4a3e7ff77_59198683', ),false); /*/%%SmartyHeaderCode%%*/?> <?php if ($_valid && !is_callable('content_56eab4a3e7ff77_59198683')) {function content_56eab4a3e7ff77_59198683($_smarty_tpl) {?> <a href="<?php echo htmlspecialchars($_smarty_tpl->tpl_vars['href']->value, ENT_QUOTES, 'UTF-8', true);?> " class="delete" title="<?php echo htmlspecialchars($_smarty_tpl->tpl_vars['action']->value, ENT_QUOTES, 'UTF-8', true);?> " <?php if (in_array($_smarty_tpl->tpl_vars['id_shop']->value,$_smarty_tpl->tpl_vars['shops_having_dependencies']->value)) {?> onclick="jAlert('<?php echo smartyTranslate(array('s'=>'You cannot delete this shop\'s (customer and/or order dependency)','js'=>1),$_smarty_tpl);?> '); return false;" <?php } elseif (isset($_smarty_tpl->tpl_vars['confirm']->value)) {?> onclick="if (confirm('<?php echo $_smarty_tpl->tpl_vars['confirm']->value;?> ')){return true;}else{event.stopPropagation(); event.preventDefault();};" <?php }?>> <i class="icon-trash"></i> <?php echo htmlspecialchars($_smarty_tpl->tpl_vars['action']->value, ENT_QUOTES, 'UTF-8', true);?> </a><?php }} ?>
ToxEn/LicPresta
cache/smarty/compile/cb/f2/ed/cbf2ed399b76a836e7562130658957cc92238d15.file.list_action_delete.tpl.php
PHP
gpl-3.0
2,123
<?php namespace UJM\ExoBundle\Installation; use Claroline\InstallationBundle\Additional\AdditionalInstaller as BaseInstaller; use UJM\ExoBundle\Installation\Updater\Updater060000; use UJM\ExoBundle\Installation\Updater\Updater060001; use UJM\ExoBundle\Installation\Updater\Updater060200; use UJM\ExoBundle\Installation\Updater\Updater070000; use UJM\ExoBundle\Installation\Updater\Updater090000; use UJM\ExoBundle\Installation\Updater\Updater090002; class AdditionalInstaller extends BaseInstaller { public function preUpdate($currentVersion, $targetVersion) { if (version_compare($currentVersion, '6.0.0', '<=')) { $updater = new Updater060000($this->container->get('doctrine.dbal.default_connection')); $updater->setLogger($this->logger); $updater->preUpdate(); } if (version_compare($currentVersion, '6.0.0', '=')) { $updater = new Updater060001($this->container->get('doctrine.dbal.default_connection')); $updater->setLogger($this->logger); $updater->preUpdate(); } if (version_compare($currentVersion, '6.2.0', '<')) { $updater = new Updater060200($this->container->get('doctrine.dbal.default_connection')); $updater->setLogger($this->logger); $updater->preUpdate(); } if (version_compare($currentVersion, '7.0.0', '<=')) { $updater = new Updater070000($this->container->get('doctrine.dbal.default_connection')); $updater->setLogger($this->logger); $updater->preUpdate(); } } public function postUpdate($currentVersion, $targetVersion) { if (version_compare($currentVersion, '6.0.0', '<=')) { $updater = new Updater060000($this->container->get('doctrine.dbal.default_connection')); $updater->setLogger($this->logger); $updater->postUpdate(); } if (version_compare($currentVersion, '6.2.0', '<')) { $updater = new Updater060200($this->container->get('doctrine.dbal.default_connection')); $updater->setLogger($this->logger); $updater->postUpdate(); } if (version_compare($currentVersion, '9.0.0', '<')) { $updater = new Updater090000( $this->container->get('doctrine.dbal.default_connection'), $this->container->get('claroline.persistence.object_manager'), $this->container->get('ujm_exo.serializer.exercise'), $this->container->get('ujm_exo.serializer.step'), $this->container->get('ujm_exo.serializer.item') ); $updater->setLogger($this->logger); $updater->postUpdate(); } if (version_compare($currentVersion, '9.0.2', '<')) { $updater = new Updater090002( $this->container->get('doctrine.dbal.default_connection') ); $updater->setLogger($this->logger); $updater->postUpdate(); } } }
remytms/Distribution
plugin/exo/Installation/AdditionalInstaller.php
PHP
gpl-3.0
3,059
/* * Copyright 2014 Erik Wilson <erikwilson@magnorum.com> * * 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 org.tritania.stables; import org.bukkit.Material; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.ShapedRecipe; import org.bukkit.Bukkit; import org.tritania.stables.Stables; import org.tritania.stables.util.Message; import org.tritania.stables.util.Log; public class RaceSystem { public Stables ht; public RaceSystem(Stables ht) { this.ht = ht; } }
tritania/Stables
src/main/java/org/tritania/stables/RaceSystem.java
Java
gpl-3.0
1,118
// This is a generated file. Not intended for manual editing. package org.modula.parsing.definition.psi.impl; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.lang.ASTNode; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiElementVisitor; import com.intellij.psi.util.PsiTreeUtil; import static org.modula.parsing.definition.psi.ModulaTypes.*; import com.intellij.extapi.psi.ASTWrapperPsiElement; import org.modula.parsing.definition.psi.*; public class DefinitionFormalParametersImpl extends ASTWrapperPsiElement implements DefinitionFormalParameters { public DefinitionFormalParametersImpl(ASTNode node) { super(node); } public void accept(@NotNull PsiElementVisitor visitor) { if (visitor instanceof DefinitionVisitor) ((DefinitionVisitor)visitor).visitFormalParameters(this); else super.accept(visitor); } @Override @NotNull public List<DefinitionFPSection> getFPSectionList() { return PsiTreeUtil.getChildrenOfTypeAsList(this, DefinitionFPSection.class); } @Override @Nullable public DefinitionQualident getQualident() { return findChildByClass(DefinitionQualident.class); } }
miracelwhipp/idea-modula-support
ims-plugin/gen/org/modula/parsing/definition/psi/impl/DefinitionFormalParametersImpl.java
Java
gpl-3.0
1,213
class MeetingQuery < Query self.queried_class = Meeting self.available_columns = [ QueryColumn.new(:subject, :sortable => "#{Meeting.table_name}.subject",:groupable => true), QueryColumn.new(:location_online, :sortable => "#{Meeting.table_name}.location_online",:groupable => true, caption: 'location'), QueryColumn.new(:date, :sortable => "#{Meeting.table_name}.date",:groupable => true), QueryColumn.new(:end_date, :sortable => "#{Meeting.table_name}.end_date",:groupable => true), QueryColumn.new(:start_time, :sortable => "#{Meeting.table_name}.start_time",:groupable => true), QueryColumn.new(:status, :sortable => "#{Meeting.table_name}.status",:groupable => true), ] def initialize(attributes=nil, *args) super attributes self.filters ||= {} add_filter('subject', '*') unless filters.present? end def initialize_available_filters add_available_filter "subject", :type => :string, :order => 0 add_available_filter "date", :type => :string, :order => 1 add_available_filter "end_date", :type => :string, :order => 1 add_available_filter "start_time", :type => :string, :order => 2 add_available_filter "location_online", :type => :string, :order => 3 add_available_filter "status", :type => :string, :order => 4 # add_custom_fields_filters(MeetingCustomField.where(:is_filter => true)) end def available_columns return @available_columns if @available_columns @available_columns = self.class.available_columns.dup # @available_columns += CustomField.where(:type => 'MeetingCustomField').all.map {|cf| QueryCustomFieldColumn.new(cf) } @available_columns end def default_columns_names @default_columns_names ||= [:subject, :date, :end_date, :start_time, :location_online, :status] end def results_scope(options={}) order_option = [group_by_sort_order, options[:order]].flatten.reject(&:blank?) Meeting.visible. where(statement).where(project_id: options[:project_id]). order(order_option). joins(joins_for_order_statement(order_option.join(','))) end def meetings end end
MicroHealthLLC/redmine_meeting
app/models/meeting_query.rb
Ruby
gpl-3.0
2,145
/* This file is part of the OdinMS Maple Story Server Copyright (C) 2008 Patrick Huy <patrick.huy@frz.cc> Matthias Butz <matze@odinms.de> Jan Christian Meyer <vimes@odinms.de> This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License version 3 as published by the Free Software Foundation. You may not use, modify or distribute this program under any other version of the GNU Affero General Public License. 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 Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ /** -- Odin JavaScript -------------------------------------------------------------------------------- Konpei - Showa Town(801000000) -- By --------------------------------------------------------------------------------------------- Information -- Version Info ----------------------------------------------------------------------------------- 1.1 - Fixed by Moogra 1.0 - First Version by Information --------------------------------------------------------------------------------------------------- **/ function start() { cm.sendSimple ("What do you want from me?\r #L0##bGather up some information on the hideout.#l\r\n#L1#Take me to the hideout#l\r\n#L2#Nothing#l#k"); } function action(mode, type, selection) { if (mode < 1) { cm.dispose(); } else { status++; if (status == 1) { if (selection == 0) { cm.sendNext("I can take you to the hideout, but the place is infested with thugs looking for trouble. You'll need to be both incredibly strong and brave to enter the premise. At the hideaway, you'll find the Boss that controls all the other bosses around this area. It's easy to get to the hideout, but the room on the top floor of the place can only be entered ONCE a day. The Boss's Room is not a place to mess around. I suggest you don't stay there for too long; you'll need to swiftly take care of the business once inside. The boss himself is a difficult foe, but you'll run into some incredibly powerful enemies on you way to meeting the boss! It ain't going to be easy."); cm.dispose(); } else if (selection == 1) cm.sendNext("Oh, the brave one. I've been awaiting your arrival. If these\r\nthugs are left unchecked, there's no telling what going to\r\nhappen in this neighborhood. Before that happens, I hope\r\nyou take care of all them and beat the boss, who resides\r\non the 5th floor. You'll need to be on alert at all times, since\r\nthe boss is too tough for even wisemen to handle.\r\nLooking at your eyes, however, I can see that eye of the\r\ntiger, the eyes that tell me you can do this. Let's go!"); else { cm.sendOk("I'm a busy person! Leave me alone if that's all you need!"); cm.dispose(); } } else { cm.warp(801040000); cm.dispose(); } } }
NovaStory/AeroStory
scripts/npc/world0/9120015.js
JavaScript
gpl-3.0
3,358
/* * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * Copyright (c) 2015, Joyent, Inc. */ var test = require('./test-namer')('vm-to-zones'); var util = require('util'); var bunyan = require('bunyan'); var utils = require('../../lib/utils'); var buildZonesFromVm = require('../../lib/vm-to-zones'); var log = bunyan.createLogger({name: 'cns'}); test('basic single container', function (t) { var config = { forward_zones: { 'foo': {} }, reverse_zones: {} }; var vm = { uuid: 'abc123', services: [], listInstance: true, listServices: true, owner: { uuid: 'def432' }, nics: [ { ip: '1.2.3.4', zones: ['foo'] } ] }; var zones = buildZonesFromVm(vm, config, log); t.deepEqual(Object.keys(zones), ['foo', '3.2.1.in-addr.arpa']); t.deepEqual(Object.keys(zones['foo']), ['abc123.inst.def432']); t.deepEqual(Object.keys(zones['3.2.1.in-addr.arpa']), ['4']); var fwd = zones['foo']['abc123.inst.def432']; t.deepEqual(fwd, [ {constructor: 'A', args: ['1.2.3.4']}, {constructor: 'TXT', args: ['abc123']} ]); var rev = zones['3.2.1.in-addr.arpa']['4']; t.deepEqual(rev, [ {constructor: 'PTR', args: ['abc123.inst.def432.foo']} ]); t.end(); }); test('cloudapi instance', function (t) { var config = { forward_zones: { 'foo': {} }, reverse_zones: {} }; var vm = { uuid: 'abc123', services: [ { name: 'cloudapi', ports: [] } ], listInstance: true, listServices: true, owner: { uuid: 'def432', login: 'admin' }, nics: [ { ip: '1.2.3.4', zones: ['foo'] } ] }; var zones = buildZonesFromVm(vm, config, log); t.deepEqual(Object.keys(zones), ['foo', '3.2.1.in-addr.arpa']); t.deepEqual(Object.keys(zones['foo']), [ 'abc123.inst.def432', 'cloudapi.svc.def432', 'cloudapi']); t.deepEqual(Object.keys(zones['3.2.1.in-addr.arpa']), ['4']); var fwd = zones['foo']['cloudapi']; t.deepEqual(fwd, [ {constructor: 'A', args: ['1.2.3.4'], src: 'abc123'}, {constructor: 'TXT', args: ['abc123'], src: 'abc123'} ]); var rev = zones['3.2.1.in-addr.arpa']['4']; t.deepEqual(rev, [ {constructor: 'PTR', args: ['abc123.inst.def432.foo']} ]); t.end(); }); test('with use_alias', function (t) { var config = { use_alias: true, forward_zones: { 'foo': {} }, reverse_zones: {} }; var vm = { uuid: 'abc123', alias: 'test', services: [], listInstance: true, listServices: true, owner: { uuid: 'def432' }, nics: [ { ip: '1.2.3.4', zones: ['foo'] } ] }; var zones = buildZonesFromVm(vm, config, log); t.deepEqual(Object.keys(zones), ['foo', '3.2.1.in-addr.arpa']); t.deepEqual(Object.keys(zones['foo']), ['abc123.inst.def432', 'test.inst.def432']); t.deepEqual(Object.keys(zones['3.2.1.in-addr.arpa']), ['4']); var fwd = zones['foo']['test.inst.def432']; t.deepEqual(fwd, [ {constructor: 'A', args: ['1.2.3.4']}, {constructor: 'TXT', args: ['abc123']} ]); var rev = zones['3.2.1.in-addr.arpa']['4']; t.deepEqual(rev, [ {constructor: 'PTR', args: ['test.inst.def432.foo']} ]); t.end(); }); test('with use_login', function (t) { var config = { use_login: true, forward_zones: { 'foo': {} }, reverse_zones: {} }; var vm = { uuid: 'abc123', alias: 'test', services: [], listInstance: true, listServices: true, owner: { uuid: 'def432', login: 'bar' }, nics: [ { ip: '1.2.3.4', zones: ['foo'] } ] }; var zones = buildZonesFromVm(vm, config, log); t.deepEqual(Object.keys(zones), ['foo', '3.2.1.in-addr.arpa']); t.deepEqual(Object.keys(zones['foo']), ['abc123.inst.def432', 'abc123.inst.bar']); t.deepEqual(Object.keys(zones['3.2.1.in-addr.arpa']), ['4']); var fwd = zones['foo']['abc123.inst.bar']; t.deepEqual(fwd, [ {constructor: 'A', args: ['1.2.3.4']}, {constructor: 'TXT', args: ['abc123']} ]); var rev = zones['3.2.1.in-addr.arpa']['4']; t.deepEqual(rev, [ {constructor: 'PTR', args: ['abc123.inst.bar.foo']} ]); t.end(); }); test('with use_alias and use_login', function (t) { var config = { use_alias: true, use_login: true, forward_zones: { 'foo': {} }, reverse_zones: {} }; var vm = { uuid: 'abc123', alias: 'test', services: [], listInstance: true, listServices: true, owner: { uuid: 'def432', login: 'bar' }, nics: [ { ip: '1.2.3.4', zones: ['foo'] } ] }; var zones = buildZonesFromVm(vm, config, log); t.deepEqual(Object.keys(zones), ['foo', '3.2.1.in-addr.arpa']); t.deepEqual(Object.keys(zones['foo']), ['abc123.inst.def432', 'abc123.inst.bar', 'test.inst.def432', 'test.inst.bar']); t.deepEqual(Object.keys(zones['3.2.1.in-addr.arpa']), ['4']); var fwd = zones['foo']['test.inst.bar']; t.deepEqual(fwd, [ {constructor: 'A', args: ['1.2.3.4']}, {constructor: 'TXT', args: ['abc123']} ]); var rev = zones['3.2.1.in-addr.arpa']['4']; t.deepEqual(rev, [ {constructor: 'PTR', args: ['test.inst.bar.foo']} ]); t.end(); }); test('using a PTR name', function (t) { var config = { use_alias: true, use_login: true, forward_zones: { 'foo': {} }, reverse_zones: {} }; var vm = { uuid: 'abc123', alias: 'test', services: [], ptrname: 'test.something.com', listInstance: true, listServices: true, owner: { uuid: 'def432', login: 'bar' }, nics: [ { ip: '1.2.3.4', zones: ['foo'] } ] }; var zones = buildZonesFromVm(vm, config, log); t.deepEqual(Object.keys(zones), ['foo', '3.2.1.in-addr.arpa']); var rev = zones['3.2.1.in-addr.arpa']['4']; t.deepEqual(rev, [ {constructor: 'PTR', args: ['test.something.com']} ]); t.end(); }); test('multi-zone', function (t) { var config = { use_alias: true, use_login: true, forward_zones: { 'foo': {}, 'bar': {} }, reverse_zones: {} }; var vm = { uuid: 'abc123', alias: 'test', services: [], listInstance: true, listServices: true, owner: { uuid: 'def432', login: 'bar' }, nics: [ { ip: '1.2.3.4', zones: ['foo'] }, { ip: '3.2.1.4', zones: ['bar'] } ] }; var zones = buildZonesFromVm(vm, config, log); t.deepEqual(Object.keys(zones).sort(), ['1.2.3.in-addr.arpa', '3.2.1.in-addr.arpa', 'bar', 'foo']); t.deepEqual(Object.keys(zones['foo']).sort(), ['abc123.inst.bar', 'abc123.inst.def432', 'test.inst.bar', 'test.inst.def432']); t.deepEqual(Object.keys(zones['bar']).sort(), Object.keys(zones['foo']).sort()); t.deepEqual(Object.keys(zones['3.2.1.in-addr.arpa']), ['4']); t.deepEqual(Object.keys(zones['1.2.3.in-addr.arpa']), ['4']); var fwd = zones['foo']['test.inst.bar']; t.deepEqual(fwd, [ {constructor: 'A', args: ['1.2.3.4']}, {constructor: 'TXT', args: ['abc123']} ]); var rev = zones['3.2.1.in-addr.arpa']['4']; t.deepEqual(rev, [ {constructor: 'PTR', args: ['test.inst.bar.foo']} ]); var rev2 = zones['1.2.3.in-addr.arpa']['4']; t.deepEqual(rev2, [ {constructor: 'PTR', args: ['test.inst.bar.bar']} ]); t.end(); }); test('multi-zone, single PTRs', function (t) { var config = { use_alias: true, use_login: true, forward_zones: { 'foo': {}, 'bar': {}, 'baz': {} }, reverse_zones: {} }; var vm = { uuid: 'abc123', alias: 'test', services: [], listInstance: true, listServices: true, owner: { uuid: 'def432', login: 'bar' }, nics: [ { ip: '1.2.3.4', zones: ['foo', 'bar'] }, { ip: '3.2.1.4', zones: ['baz'] } ] }; var zones = buildZonesFromVm(vm, config, log); t.deepEqual(Object.keys(zones).sort(), ['1.2.3.in-addr.arpa', '3.2.1.in-addr.arpa', 'bar', 'baz', 'foo']); t.deepEqual(Object.keys(zones['foo']).sort(), ['abc123.inst.bar', 'abc123.inst.def432', 'test.inst.bar', 'test.inst.def432']); t.deepEqual(Object.keys(zones['bar']).sort(), Object.keys(zones['foo']).sort()); t.deepEqual(Object.keys(zones['3.2.1.in-addr.arpa']), ['4']); t.deepEqual(Object.keys(zones['1.2.3.in-addr.arpa']), ['4']); var fwd = zones['foo']['test.inst.bar']; t.deepEqual(fwd, [ {constructor: 'A', args: ['1.2.3.4']}, {constructor: 'TXT', args: ['abc123']} ]); var rev = zones['3.2.1.in-addr.arpa']['4']; t.deepEqual(rev, [ {constructor: 'PTR', args: ['test.inst.bar.foo']} ]); var rev2 = zones['1.2.3.in-addr.arpa']['4']; t.deepEqual(rev2, [ {constructor: 'PTR', args: ['test.inst.bar.baz']} ]); t.end(); }); test('multi-zone, shortest zone priority PTR', function (t) { var config = { use_alias: true, use_login: true, forward_zones: { 'foobarbaz': {}, 'foobar': {}, 'baz': {} }, reverse_zones: {} }; var vm = { uuid: 'abc123', alias: 'test', services: [], listInstance: true, listServices: true, owner: { uuid: 'def432', login: 'bar' }, nics: [ { ip: '1.2.3.4', zones: ['foobar', 'foobarbaz', 'baz'] } ] }; var zones = buildZonesFromVm(vm, config, log); var rev = zones['3.2.1.in-addr.arpa']['4']; t.deepEqual(rev, [ {constructor: 'PTR', args: ['test.inst.bar.baz']} ]); t.end(); }); test('service with srvs', function (t) { var config = { use_alias: true, forward_zones: { 'foo': {} }, reverse_zones: {} }; var vm = { uuid: 'abc123', alias: 'test', services: [ { name: 'svc1', ports: [1234, 1235] } ], listInstance: true, listServices: true, owner: { uuid: 'def432' }, nics: [ { ip: '1.2.3.4', zones: ['foo'] } ] }; var zones = buildZonesFromVm(vm, config, log); t.deepEqual(Object.keys(zones), ['foo', '3.2.1.in-addr.arpa']); t.deepEqual(Object.keys(zones['foo']), ['abc123.inst.def432', 'test.inst.def432', 'svc1.svc.def432']); var fwd = zones['foo']['test.inst.def432']; t.deepEqual(fwd, [ {constructor: 'A', args: ['1.2.3.4']}, {constructor: 'TXT', args: ['abc123']} ]); var svc = zones['foo']['svc1.svc.def432']; t.deepEqual(svc, [ {constructor: 'A', args: ['1.2.3.4'], src: 'abc123'}, {constructor: 'TXT', args: ['abc123'], src: 'abc123'}, {constructor: 'SRV', args: ['test.inst.def432.foo', 1234], src: 'abc123'}, {constructor: 'SRV', args: ['test.inst.def432.foo', 1235], src: 'abc123'} ]); t.end(); });
eait-itig/triton-cns
test/unit/vm-to-zones.test.js
JavaScript
mpl-2.0
10,814
from cProfile import Profile from optparse import make_option from django.conf import settings from django.core.management.base import (BaseCommand, CommandError) from treeherder.etl.buildapi import (Builds4hJobsProcess, PendingJobsProcess, RunningJobsProcess) from treeherder.etl.pushlog import HgPushlogProcess from treeherder.model.derived import RefDataManager class Command(BaseCommand): """Management command to ingest data from a single push.""" help = "Ingests a single push into treeherder" args = '<project> <changeset>' option_list = BaseCommand.option_list + ( make_option('--profile-file', action='store', dest='profile_file', default=None, help='Profile command and write result to profile file'), make_option('--filter-job-group', action='store', dest='filter_job_group', default=None, help="Only process jobs in specified group symbol " "(e.g. 'T')") ) def _handle(self, *args, **options): if len(args) != 2: raise CommandError("Need to specify (only) branch and changeset") (project, changeset) = args # get reference to repo rdm = RefDataManager() repos = filter(lambda x: x['name'] == project, rdm.get_all_repository_info()) if not repos: raise CommandError("No project found named '%s'" % project) repo = repos[0] # make sure all tasks are run synchronously / immediately settings.CELERY_ALWAYS_EAGER = True # get hg pushlog pushlog_url = '%s/json-pushes/?full=1&version=2' % repo['url'] # ingest this particular revision for this project process = HgPushlogProcess() # Use the actual push SHA, in case the changeset specified was a tag # or branch name (eg tip). HgPushlogProcess returns the full SHA, but # job ingestion expects the short version, so we truncate it. push_sha = process.run(pushlog_url, project, changeset=changeset)[0:12] Builds4hJobsProcess().run(filter_to_project=project, filter_to_revision=push_sha, filter_to_job_group=options['filter_job_group']) PendingJobsProcess().run(filter_to_project=project, filter_to_revision=push_sha, filter_to_job_group=options['filter_job_group']) RunningJobsProcess().run(filter_to_project=project, filter_to_revision=push_sha, filter_to_job_group=options['filter_job_group']) def handle(self, *args, **options): if options['profile_file']: profiler = Profile() profiler.runcall(self._handle, *args, **options) profiler.dump_stats(options['profile_file']) else: self._handle(*args, **options)
adusca/treeherder
treeherder/etl/management/commands/ingest_push.py
Python
mpl-2.0
3,195
<?php return function ($bh) { $bh->match('progressbar', function($ctx, $json) { $val = $json->val ?: 0; $ctx ->js([ 'val' => $val ]) ->content([ 'elem' => 'bar', 'attrs' => [ 'style' => 'width:' . $val . '%' ] ]); }); };
kompolom/bem-components-php
common.blocks/progressbar/progressbar.bh.php
PHP
mpl-2.0
314
// Copyright (c) 2016, 2018, 2021, Oracle and/or its affiliates. All rights reserved. // This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license. // Code generated. DO NOT EDIT. // Management Agent API // // API for Management Agent Cloud Service // package managementagent // EditModesEnum Enum with underlying type: string type EditModesEnum string // Set of constants representing the allowable values for EditModesEnum const ( EditModesReadOnly EditModesEnum = "READ_ONLY" EditModesWritable EditModesEnum = "WRITABLE" EditModesExtensible EditModesEnum = "EXTENSIBLE" ) var mappingEditModes = map[string]EditModesEnum{ "READ_ONLY": EditModesReadOnly, "WRITABLE": EditModesWritable, "EXTENSIBLE": EditModesExtensible, } // GetEditModesEnumValues Enumerates the set of values for EditModesEnum func GetEditModesEnumValues() []EditModesEnum { values := make([]EditModesEnum, 0) for _, v := range mappingEditModes { values = append(values, v) } return values }
oracle/terraform-provider-baremetal
vendor/github.com/oracle/oci-go-sdk/v46/managementagent/edit_modes.go
GO
mpl-2.0
1,173
package de.maxgb.vertretungsplan.manager; import android.content.Context; import android.os.AsyncTask; import de.maxgb.android.util.Logger; import de.maxgb.vertretungsplan.util.Constants; import de.maxgb.vertretungsplan.util.Stunde; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; public class StundenplanManager { public static final int BEGINN_NACHMITTAG = 8; public static final int ANZAHL_SAMSTAG = 4; public static final int ANZAHL_NACHMITTAG = 2; private static StundenplanManager instance; public static synchronized StundenplanManager getInstance(Context context) { if (instance == null) { instance = new StundenplanManager(context); } return instance; } private final String TAG = "StundenplanManager"; private int lastResult = 0; private ArrayList<Stunde[]> woche; private Context context; // Listener------------- private ArrayList<OnUpdateListener> listener = new ArrayList<OnUpdateListener>(); private StundenplanManager(Context context) { this.context = context; auswerten(); } public void asyncAuswerten() { AuswertenTask task = new AuswertenTask(); task.execute(); } public void auswerten() { lastResult = dateiAuswerten(); if (lastResult == -1) { } else { woche = null; } } public void auswertenWithNotify() { auswerten(); notifyListener(); } public ArrayList<Stunde[]> getClonedStundenplan() { if (woche == null) return null; ArrayList<Stunde[]> clone; try { clone = new ArrayList<Stunde[]>(woche.size()); for (Stunde[] item : woche) { Stunde[] clone2 = new Stunde[item.length]; for (int i = 0; i < item.length; i++) { clone2[i] = item[i].clone(); } clone.add(clone2); } return clone; } catch (NullPointerException e) { Logger.e(TAG, "Failed to clone stundenplan", e); return null; } } public String getLastResult() { switch (lastResult) { case -1: return "Erfolgreich ausgewertet"; case 1: return "Datei existiert nicht"; case 2: return "Kann Datei nicht lesen"; case 3: return "Zugriffsfehler"; case 4: return "Parsingfehler"; default: return "Noch nicht ausgewertet"; } } public ArrayList<Stunde[]> getStundenplan() { return woche; } public void notifyListener() { for (int i = 0; i < listener.size(); i++) { if (listener.get(i) != null) { listener.get(i).onStundenplanUpdate(); } } } public void registerOnUpdateListener(OnUpdateListener listener) { this.listener.add(listener); } public void unregisterOnUpdateListener(OnUpdateListener listener) { this.listener.remove(listener); } private Stunde[] convertJSONArrayToStundenArray(JSONArray tag) throws JSONException { Stunde[] result = new Stunde[BEGINN_NACHMITTAG - 1 + ANZAHL_NACHMITTAG]; for (int i = 0; i < BEGINN_NACHMITTAG - 1 + ANZAHL_NACHMITTAG; i++) { JSONArray stunde = tag.getJSONArray(i); if (i >= BEGINN_NACHMITTAG - 1) { result[i] = new Stunde(stunde.getString(0), stunde.getString(1), i + 1, stunde.getString(2)); } else { result[i] = new Stunde(stunde.getString(0), stunde.getString(1), i + 1); } } return result; } /** * Wertet die Stundenplandatei aus * * @return Fehlercode -1 bei Erfolg,1 Datei existiert nicht, 2 Datei kann nicht gelesen werden,3 Fehler beim Lesen,4 Fehler * beim Parsen * */ private int dateiAuswerten() { File loadoutFile = new File(context.getFilesDir(), Constants.SP_FILE_NAME); ArrayList<Stunde[]> w = new ArrayList<Stunde[]>(); if (!loadoutFile.exists()) { Logger.w(TAG, "Stundenplan file doesn´t exist"); return 1; } if (!loadoutFile.canRead()) { Logger.w(TAG, "Can´t read Stundenplan file"); return 2; } try { BufferedReader br = new BufferedReader(new FileReader(loadoutFile)); String line = br.readLine(); br.close(); JSONObject stundenplan = new JSONObject(line); JSONArray mo = stundenplan.getJSONArray("mo"); JSONArray di = stundenplan.getJSONArray("di"); JSONArray mi = stundenplan.getJSONArray("mi"); JSONArray d = stundenplan.getJSONArray("do"); JSONArray fr = stundenplan.getJSONArray("fr"); JSONObject sa = stundenplan.getJSONObject("sa"); // Samstag Stunde[] samstag = new Stunde[9]; JSONArray eins = sa.getJSONArray("0"); JSONArray zwei = sa.getJSONArray("1"); JSONArray drei = sa.getJSONArray("2"); JSONArray vier = sa.getJSONArray("3"); JSONArray acht = sa.getJSONArray("7"); JSONArray neun = sa.getJSONArray("8"); samstag[0] = new Stunde(eins.getString(0), eins.getString(1), 1); samstag[1] = new Stunde(zwei.getString(0), zwei.getString(1), 2); samstag[2] = new Stunde(drei.getString(0), drei.getString(1), 3); samstag[3] = new Stunde(vier.getString(0), vier.getString(1), 4); samstag[4] = new Stunde("", "", 5); samstag[5] = new Stunde("", "", 6); samstag[6] = new Stunde("", "", 7); samstag[7] = new Stunde(acht.getString(0), acht.getString(1), 8, acht.getString(2)); samstag[8] = new Stunde(neun.getString(0), neun.getString(1), 9, neun.getString(2)); w.add(convertJSONArrayToStundenArray(mo)); w.add(convertJSONArrayToStundenArray(di)); w.add(convertJSONArrayToStundenArray(mi)); w.add(convertJSONArrayToStundenArray(d)); w.add(convertJSONArrayToStundenArray(fr)); w.add(samstag); /* * for(int i=0;i<w.size();i++){ for(int j=0;j<w.get(i).length;j++){ System.out.println(w.get(i)[j].toString()); } } */ } catch (IOException e) { Logger.e(TAG, "Fehler beim Lesen der Datei", e); return 3; } catch (JSONException e) { Logger.e(TAG, "Fehler beim Parsen der Datei", e); return 4; } woche = w; return -1; } public interface OnUpdateListener { void onStundenplanUpdate(); } // ------------------------ private class AuswertenTask extends AsyncTask<Void, Void, Void> { @Override protected Void doInBackground(Void... params) { auswerten(); return null; } @Override protected void onPostExecute(Void v) { notifyListener(); } } }
maxanier/Vertretungsplan
app/src/main/java/de/maxgb/vertretungsplan/manager/StundenplanManager.java
Java
mpl-2.0
6,174
import tape from 'tape' import Common, { Chain, Hardfork } from '@ethereumjs/common' import { FeeMarketEIP1559Transaction } from '@ethereumjs/tx' import { Block } from '@ethereumjs/block' import { PeerPool } from '../../lib/net/peerpool' import { TxPool } from '../../lib/sync/txpool' import { Config } from '../../lib/config' tape('[TxPool]', async (t) => { const common = new Common({ chain: Chain.Mainnet, hardfork: Hardfork.London }) const config = new Config({ transports: [] }) const A = { address: Buffer.from('0b90087d864e82a284dca15923f3776de6bb016f', 'hex'), privateKey: Buffer.from( '64bf9cc30328b0e42387b3c82c614e6386259136235e20c1357bd11cdee86993', 'hex' ), } const B = { address: Buffer.from('6f62d8382bf2587361db73ceca28be91b2acb6df', 'hex'), privateKey: Buffer.from( '2a6e9ad5a6a8e4f17149b8bc7128bf090566a11dbd63c30e5a0ee9f161309cd6', 'hex' ), } const createTx = (from = A, to = B, nonce = 0, value = 1) => { const txData = { nonce, maxFeePerGas: 1000000000, maxInclusionFeePerGas: 100000000, gasLimit: 100000, to: to.address, value, } const tx = FeeMarketEIP1559Transaction.fromTxData(txData, { common }) const signedTx = tx.sign(from.privateKey) return signedTx } const txA01 = createTx() // A -> B, nonce: 0, value: 1 const txA02 = createTx(A, B, 0, 2) // A -> B, nonce: 0, value: 2 (different hash) const txB01 = createTx(B, A) // B -> A, nonce: 0, value: 1 const txB02 = createTx(B, A, 1, 5) // B -> A, nonce: 1, value: 5 t.test('should initialize correctly', (t) => { const config = new Config({ transports: [] }) const pool = new TxPool({ config }) t.equal(pool.pool.size, 0, 'pool empty') t.notOk((pool as any).opened, 'pool not opened yet') pool.open() t.ok((pool as any).opened, 'pool opened') pool.start() t.ok((pool as any).running, 'pool running') pool.stop() t.notOk((pool as any).running, 'pool not running anymore') pool.close() t.notOk((pool as any).opened, 'pool not opened anymore') t.end() }) t.test('should open/close', async (t) => { t.plan(3) const config = new Config({ transports: [] }) const pool = new TxPool({ config }) pool.open() pool.start() t.ok((pool as any).opened, 'pool opened') t.equals(pool.open(), false, 'already opened') pool.stop() pool.close() t.notOk((pool as any).opened, 'closed') }) t.test('announcedTxHashes() -> add single tx / knownByPeer / getByHash()', async (t) => { // Safeguard that send() method from peer2 gets called t.plan(12) const pool = new TxPool({ config }) pool.open() pool.start() const peer: any = { id: '1', eth: { getPooledTransactions: () => { return [null, [txA01]] }, send: () => { t.fail('should not send to announcing peer') }, }, } let sentToPeer2 = 0 const peer2: any = { id: '2', eth: { send: () => { sentToPeer2++ t.equal(sentToPeer2, 1, 'should send once to non-announcing peer') }, }, } const peerPool = new PeerPool({ config }) peerPool.add(peer) peerPool.add(peer2) await pool.handleAnnouncedTxHashes([txA01.hash()], peer, peerPool) t.equal(pool.pool.size, 1, 'pool size 1') t.equal((pool as any).pending.length, 0, 'cleared pending txs') t.equal((pool as any).handled.size, 1, 'added to handled txs') t.equal((pool as any).knownByPeer.size, 2, 'known tx hashes size 2 (entries for both peers)') t.equal((pool as any).knownByPeer.get(peer.id).length, 1, 'one tx added for peer 1') t.equal( (pool as any).knownByPeer.get(peer.id)[0].hash, txA01.hash().toString('hex'), 'new known tx hashes entry for announcing peer' ) const txs = pool.getByHash([txA01.hash()]) t.equal(txs.length, 1, 'should get correct number of txs by hash') t.equal( txs[0].serialize().toString('hex'), txA01.serialize().toString('hex'), 'should get correct tx by hash' ) pool.pool.clear() await pool.handleAnnouncedTxHashes([txA01.hash()], peer, peerPool) t.equal(pool.pool.size, 0, 'should not add a once handled tx') t.equal( (pool as any).knownByPeer.get(peer.id).length, 1, 'should add tx only once to known tx hashes' ) t.equal((pool as any).knownByPeer.size, 2, 'known tx hashes size 2 (entries for both peers)') pool.stop() pool.close() }) t.test('announcedTxHashes() -> TX_RETRIEVAL_LIMIT', async (t) => { const pool = new TxPool({ config }) const TX_RETRIEVAL_LIMIT: number = (pool as any).TX_RETRIEVAL_LIMIT pool.open() pool.start() const peer = { eth: { getPooledTransactions: (res: any) => { t.equal(res['hashes'].length, TX_RETRIEVAL_LIMIT, 'should limit to TX_RETRIEVAL_LIMIT') return [null, []] }, }, } const peerPool = new PeerPool({ config }) const hashes = [] for (let i = 1; i <= TX_RETRIEVAL_LIMIT + 1; i++) { // One more than TX_RETRIEVAL_LIMIT hashes.push(Buffer.from(i.toString().padStart(64, '0'), 'hex')) // '0000000000000000000000000000000000000000000000000000000000000001',... } await pool.handleAnnouncedTxHashes(hashes, peer as any, peerPool) pool.stop() pool.close() }) t.test('announcedTxHashes() -> add two txs (different sender)', async (t) => { const pool = new TxPool({ config }) pool.open() pool.start() const peer: any = { eth: { getPooledTransactions: () => { return [null, [txA01, txB01]] }, }, } const peerPool = new PeerPool({ config }) await pool.handleAnnouncedTxHashes([txA01.hash(), txB01.hash()], peer, peerPool) t.equal(pool.pool.size, 2, 'pool size 2') pool.stop() pool.close() }) t.test('announcedTxHashes() -> add two txs (same sender and nonce)', async (t) => { const config = new Config({ transports: [] }) const pool = new TxPool({ config }) pool.open() pool.start() const peer: any = { eth: { getPooledTransactions: () => { return [null, [txA01, txA02]] }, }, } const peerPool = new PeerPool({ config }) await pool.handleAnnouncedTxHashes([txA01.hash(), txA02.hash()], peer, peerPool) t.equal(pool.pool.size, 1, 'pool size 1') const address = A.address.toString('hex') const poolContent = pool.pool.get(address)! t.equal(poolContent.length, 1, 'only one tx') t.deepEqual(poolContent[0].tx.hash(), txA02.hash(), 'only later-added tx') pool.stop() pool.close() }) t.test('announcedTxs()', async (t) => { const config = new Config({ transports: [] }) const pool = new TxPool({ config }) pool.open() pool.start() const peer: any = { eth: { send: () => {}, }, } const peerPool = new PeerPool({ config }) await pool.handleAnnouncedTxs([txA01], peer, peerPool) t.equal(pool.pool.size, 1, 'pool size 1') const address = A.address.toString('hex') const poolContent = pool.pool.get(address)! t.equal(poolContent.length, 1, 'one tx') t.deepEqual(poolContent[0].tx.hash(), txA01.hash(), 'correct tx') pool.stop() pool.close() }) t.test('newBlocks() -> should remove included txs', async (t) => { const config = new Config({ transports: [] }) const pool = new TxPool({ config }) pool.open() pool.start() let peer: any = { eth: { getPooledTransactions: () => { return [null, [txA01]] }, }, } const peerPool = new PeerPool({ config }) await pool.handleAnnouncedTxHashes([txA01.hash()], peer, peerPool) t.equal(pool.pool.size, 1, 'pool size 1') // Craft block with tx not in pool let block = Block.fromBlockData({ transactions: [txA02] }, { common }) pool.removeNewBlockTxs([block]) t.equal(pool.pool.size, 1, 'pool size 1') // Craft block with tx in pool block = Block.fromBlockData({ transactions: [txA01] }, { common }) pool.removeNewBlockTxs([block]) t.equal(pool.pool.size, 0, 'pool should be empty') peer = { eth: { getPooledTransactions: () => { return [null, [txB01, txB02]] }, }, } await pool.handleAnnouncedTxHashes([txB01.hash(), txB02.hash()], peer, peerPool) t.equal(pool.pool.size, 1, 'pool size 1') const address = B.address.toString('hex') let poolContent = pool.pool.get(address)! t.equal(poolContent.length, 2, 'two txs') // Craft block with tx not in pool block = Block.fromBlockData({ transactions: [txA02] }, { common }) pool.removeNewBlockTxs([block]) t.equal(pool.pool.size, 1, 'pool size 1') poolContent = pool.pool.get(address)! t.equal(poolContent.length, 2, 'two txs') // Craft block with tx in pool block = Block.fromBlockData({ transactions: [txB01] }, { common }) pool.removeNewBlockTxs([block]) poolContent = pool.pool.get(address)! t.equal(poolContent.length, 1, 'only one tx') // Craft block with tx in pool block = Block.fromBlockData({ transactions: [txB02] }, { common }) pool.removeNewBlockTxs([block]) t.equal(pool.pool.size, 0, 'pool size 0') pool.stop() pool.close() }) t.test('cleanup()', async (t) => { const pool = new TxPool({ config }) pool.open() pool.start() const peer: any = { eth: { getPooledTransactions: () => { return [null, [txA01, txB01]] }, }, send: () => {}, } const peerPool = new PeerPool({ config }) peerPool.add(peer) await pool.handleAnnouncedTxHashes([txA01.hash(), txB01.hash()], peer, peerPool) t.equal(pool.pool.size, 2, 'pool size 2') t.equal((pool as any).handled.size, 2, 'handled size 2') t.equal((pool as any).knownByPeer.size, 1, 'known by peer size 1') t.equal((pool as any).knownByPeer.get(peer.id).length, 2, '2 known txs') pool.cleanup() t.equal( pool.pool.size, 2, 'should not remove txs from pool (POOLED_STORAGE_TIME_LIMIT within range)' ) t.equal( (pool as any).knownByPeer.size, 1, 'should not remove txs from known by peer map (POOLED_STORAGE_TIME_LIMIT within range)' ) t.equal( (pool as any).handled.size, 2, 'should not remove txs from handled (HANDLED_CLEANUP_TIME_LIMIT within range)' ) const address = txB01.getSenderAddress().toString().slice(2) const poolObj = pool.pool.get(address)![0] poolObj.added = Date.now() - pool.POOLED_STORAGE_TIME_LIMIT * 60 - 1 pool.pool.set(address, [poolObj]) const knownByPeerObj1 = (pool as any).knownByPeer.get(peer.id)[0] const knownByPeerObj2 = (pool as any).knownByPeer.get(peer.id)[1] knownByPeerObj1.added = Date.now() - pool.POOLED_STORAGE_TIME_LIMIT * 60 - 1 ;(pool as any).knownByPeer.set(peer.id, [knownByPeerObj1, knownByPeerObj2]) const hash = txB01.hash().toString('hex') const handledObj = (pool as any).handled.get(hash) handledObj.added = Date.now() - pool.HANDLED_CLEANUP_TIME_LIMIT * 60 - 1 ;(pool as any).handled.set(hash, handledObj) pool.cleanup() t.equal( pool.pool.size, 1, 'should remove txs from pool (POOLED_STORAGE_TIME_LIMIT before range)' ) t.equal( (pool as any).knownByPeer.get(peer.id).length, 1, 'should remove one tx from known by peer map (POOLED_STORAGE_TIME_LIMIT before range)' ) t.equal( (pool as any).handled.size, 1, 'should remove txs from handled (HANDLED_CLEANUP_TIME_LIMIT before range)' ) pool.stop() pool.close() }) })
ethereumjs/ethereumjs-vm
packages/client/test/sync/txpool.spec.ts
TypeScript
mpl-2.0
11,829
package minejava.reg.util.concurrent; public interface RunnableFuture<V> extends Runnable, Future<V>{ @Override void run(); }
cFerg/MineJava
src/main/java/minejava/reg/util/concurrent/RunnableFuture.java
Java
mpl-2.0
135
package testtravis; import static org.junit.Assert.*; import org.junit.Test; public class Operar_unit { @Test public void testSumar() { System.out.println("Sumar dos numeros"); int numero1 = 6; int numero2 = 6; Operaciones instance = new Operaciones(); int expResult = 12; int result = instance.sumar(numero1, numero2); assertEquals(expResult, result); } @Test public void testRestar() { System.out.println("Restar dos numeros"); int numero1 = 4; int numero2 = 2; Operaciones instance = new Operaciones(); int expResult = 2; int result = instance.restar(numero1, numero2); assertEquals(expResult, result); } @Test public void testMultiplicar() { System.out.println("Multiplicar dos numeros"); int numero1 = 3; int numero2 =3; Operaciones instance = new Operaciones(); int expResult = 9; int result = instance.multiplicar(numero1, numero2); assertEquals(expResult, result); } @Test public void testDividir() { System.out.println("Dividir Dos numeros"); int numero1 = 6; int numero2 = 3; Operaciones instance = new Operaciones(); int expResult = 2; int result = instance.dividir(numero1, numero2); assertEquals(expResult, result); } }
nricaurte/prueba_degit
src/testtravis/Operar_unit.java
Java
mpl-2.0
1,428
require 'test_helper' class CFRGCurvesTest < Minitest::Test def test_curve25519_eddsa_ed25519 vectors = [ [ # TEST 1 hexstr2bin( "9d61b19deffd5a60ba844af492ec2cc4"\ "4449c5697b326919703bac031cae7f60"), # SECRET KEY hexstr2bin( "d75a980182b10ab7d54bfed3c964073a"\ "0ee172f3daa62325af021a68f707511a"), # PUBLIC KEY "", # MESSAGE hexstr2bin( "e5564300c360ac729086e2cc806e828a"\ "84877f1eb8e5d974d873e06522490155"\ "5fb8821590a33bacc61e39701cf9b46b"\ "d25bf5f0595bbe24655141438e7a100b") # SIGNATURE ], [ # TEST 2 hexstr2bin( "4ccd089b28ff96da9db6c346ec114e0f"\ "5b8a319f35aba624da8cf6ed4fb8a6fb"), # SECRET KEY hexstr2bin( "3d4017c3e843895a92b70aa74d1b7ebc"\ "9c982ccf2ec4968cc0cd55f12af4660c"), # PUBLIC KEY hexstr2bin("72"), # MESSAGE hexstr2bin( "92a009a9f0d4cab8720e820b5f642540"\ "a2b27b5416503f8fb3762223ebdb69da"\ "085ac1e43e15996e458f3613d0f11d8c"\ "387b2eaeb4302aeeb00d291612bb0c00") # SIGNATURE ], [ # TEST 3 hexstr2bin( "c5aa8df43f9f837bedb7442f31dcb7b1"\ "66d38535076f094b85ce3a2e0b4458f7"), # SECRET KEY hexstr2bin( "fc51cd8e6218a1a38da47ed00230f058"\ "0816ed13ba3303ac5deb911548908025"), # PUBLIC KEY hexstr2bin("af82"), # MESSAGE hexstr2bin( "6291d657deec24024827e69c3abe01a3"\ "0ce548a284743a445e3680d7db5ac3ac"\ "18ff9b538d16f290ae67f760984dc659"\ "4a7c15e9716ed28dc027beceea1ec40a") # SIGNATURE ], [ # TEST 1024 hexstr2bin( "f5e5767cf153319517630f226876b86c"\ "8160cc583bc013744c6bf255f5cc0ee5"), # SECRET KEY hexstr2bin( "278117fc144c72340f67d0f2316e8386"\ "ceffbf2b2428c9c51fef7c597f1d426e"), # PUBLIC KEY hexstr2bin( "08b8b2b733424243760fe426a4b54908"\ "632110a66c2f6591eabd3345e3e4eb98"\ "fa6e264bf09efe12ee50f8f54e9f77b1"\ "e355f6c50544e23fb1433ddf73be84d8"\ "79de7c0046dc4996d9e773f4bc9efe57"\ "38829adb26c81b37c93a1b270b20329d"\ "658675fc6ea534e0810a4432826bf58c"\ "941efb65d57a338bbd2e26640f89ffbc"\ "1a858efcb8550ee3a5e1998bd177e93a"\ "7363c344fe6b199ee5d02e82d522c4fe"\ "ba15452f80288a821a579116ec6dad2b"\ "3b310da903401aa62100ab5d1a36553e"\ "06203b33890cc9b832f79ef80560ccb9"\ "a39ce767967ed628c6ad573cb116dbef"\ "efd75499da96bd68a8a97b928a8bbc10"\ "3b6621fcde2beca1231d206be6cd9ec7"\ "aff6f6c94fcd7204ed3455c68c83f4a4"\ "1da4af2b74ef5c53f1d8ac70bdcb7ed1"\ "85ce81bd84359d44254d95629e9855a9"\ "4a7c1958d1f8ada5d0532ed8a5aa3fb2"\ "d17ba70eb6248e594e1a2297acbbb39d"\ "502f1a8c6eb6f1ce22b3de1a1f40cc24"\ "554119a831a9aad6079cad88425de6bd"\ "e1a9187ebb6092cf67bf2b13fd65f270"\ "88d78b7e883c8759d2c4f5c65adb7553"\ "878ad575f9fad878e80a0c9ba63bcbcc"\ "2732e69485bbc9c90bfbd62481d9089b"\ "eccf80cfe2df16a2cf65bd92dd597b07"\ "07e0917af48bbb75fed413d238f5555a"\ "7a569d80c3414a8d0859dc65a46128ba"\ "b27af87a71314f318c782b23ebfe808b"\ "82b0ce26401d2e22f04d83d1255dc51a"\ "ddd3b75a2b1ae0784504df543af8969b"\ "e3ea7082ff7fc9888c144da2af58429e"\ "c96031dbcad3dad9af0dcbaaaf268cb8"\ "fcffead94f3c7ca495e056a9b47acdb7"\ "51fb73e666c6c655ade8297297d07ad1"\ "ba5e43f1bca32301651339e22904cc8c"\ "42f58c30c04aafdb038dda0847dd988d"\ "cda6f3bfd15c4b4c4525004aa06eeff8"\ "ca61783aacec57fb3d1f92b0fe2fd1a8"\ "5f6724517b65e614ad6808d6f6ee34df"\ "f7310fdc82aebfd904b01e1dc54b2927"\ "094b2db68d6f903b68401adebf5a7e08"\ "d78ff4ef5d63653a65040cf9bfd4aca7"\ "984a74d37145986780fc0b16ac451649"\ "de6188a7dbdf191f64b5fc5e2ab47b57"\ "f7f7276cd419c17a3ca8e1b939ae49e4"\ "88acba6b965610b5480109c8b17b80e1"\ "b7b750dfc7598d5d5011fd2dcc5600a3"\ "2ef5b52a1ecc820e308aa342721aac09"\ "43bf6686b64b2579376504ccc493d97e"\ "6aed3fb0f9cd71a43dd497f01f17c0e2"\ "cb3797aa2a2f256656168e6c496afc5f"\ "b93246f6b1116398a346f1a641f3b041"\ "e989f7914f90cc2c7fff357876e506b5"\ "0d334ba77c225bc307ba537152f3f161"\ "0e4eafe595f6d9d90d11faa933a15ef1"\ "369546868a7f3a45a96768d40fd9d034"\ "12c091c6315cf4fde7cb68606937380d"\ "b2eaaa707b4c4185c32eddcdd306705e"\ "4dc1ffc872eeee475a64dfac86aba41c"\ "0618983f8741c5ef68d3a101e8a3b8ca"\ "c60c905c15fc910840b94c00a0b9d0"), # MESSAGE hexstr2bin( "0aab4c900501b3e24d7cdf4663326a3a"\ "87df5e4843b2cbdb67cbf6e460fec350"\ "aa5371b1508f9f4528ecea23c436d94b"\ "5e8fcd4f681e30a6ac00a9704a188a03") # SIGNATURE ], [ # TEST SHA(abc) hexstr2bin( "833fe62409237b9d62ec77587520911e"\ "9a759cec1d19755b7da901b96dca3d42"), # SECRET KEY hexstr2bin( "ec172b93ad5e563bf4932c70e1245034"\ "c35467ef2efd4d64ebf819683467e2bf"), # PUBLIC KEY hexstr2bin( "ddaf35a193617abacc417349ae204131"\ "12e6fa4e89a97ea20a9eeee64b55d39a"\ "2192992a274fc1a836ba3c23a3feebbd"\ "454d4423643ce80e2a9ac94fa54ca49f"), # MESSAGE hexstr2bin( "dc2a4459e7369633a52b1bf277839a00"\ "201009a3efbf3ecb69bea2186c26b589"\ "09351fc9ac90b3ecfdfbc7c66431e030"\ "3dca179c138ac17ad9bef1177331a704") # SIGNATURE ] ] vectors.each do |(secret, pk, m, sig)| _pk, sk = JOSE::JWA::Ed25519.keypair(secret) assert_equal pk, _pk _sig = JOSE::JWA::Ed25519.sign(m, sk) assert_equal sig, _sig assert JOSE::JWA::Ed25519.verify(sig, m, pk) if JOSE::JWA::Curve25519_RbNaCl.__supported__? _pk, sk = JOSE::JWA::Ed25519_RbNaCl.keypair(secret) assert_equal pk, _pk _sig = JOSE::JWA::Ed25519_RbNaCl.sign(m, sk) assert_equal sig, _sig assert JOSE::JWA::Ed25519_RbNaCl.verify(sig, m, pk) end end end def test_curve25519_eddsa_ed25519ph vectors = [ [ # TEST abc hexstr2bin( "833fe62409237b9d62ec77587520911e"\ "9a759cec1d19755b7da901b96dca3d42"), # SECRET KEY hexstr2bin( "ec172b93ad5e563bf4932c70e1245034"\ "c35467ef2efd4d64ebf819683467e2bf"), # PUBLIC KEY hexstr2bin("616263"), # MESSAGE hexstr2bin( "dc2a4459e7369633a52b1bf277839a00"\ "201009a3efbf3ecb69bea2186c26b589"\ "09351fc9ac90b3ecfdfbc7c66431e030"\ "3dca179c138ac17ad9bef1177331a704") # SIGNATURE ] ] vectors.each do |(secret, pk, m, sig)| if JOSE::JWA::Curve25519_RbNaCl.__supported__? _pk, sk = JOSE::JWA::Ed25519_RbNaCl.keypair(secret) assert_equal pk, _pk _sig = JOSE::JWA::Ed25519_RbNaCl.sign_ph(m, sk) assert_equal sig, _sig assert JOSE::JWA::Ed25519_RbNaCl.verify_ph(sig, m, pk) end end end def test_curve25519_rfc7748_curve25519 vectors = [ [ 31029842492115040904895560451863089656472772604678260265531221036453811406496, # Input scalar 34426434033919594451155107781188821651316167215306631574996226621102155684838, # Input u-coordinate hexstr2lint("c3da55379de9c6908e94ea4df28d084f32eccf03491c71f754b4075577a28552") # Output u-coordinate ], [ 35156891815674817266734212754503633747128614016119564763269015315466259359304, # Input scalar 8883857351183929894090759386610649319417338800022198945255395922347792736741, # Input u-coordinate hexstr2lint("95cbde9476e8907d7aade45cb4b873f88b595a68799fa152e6f8f7647aac7957") # Output u-coordinate ] ] vectors.each do |(input_scalar, input_u_coordinate, output_u_coordinate)| input_scalar = JOSE::JWA::X25519.coerce_scalar_fe!(input_scalar) input_u_coordinate = JOSE::JWA::X25519.coerce_coordinate_fe!(input_u_coordinate) output_u_coordinate = JOSE::JWA::X25519.coerce_coordinate_fe!(output_u_coordinate) assert_equal output_u_coordinate, JOSE::JWA::X25519.curve25519(input_scalar, input_u_coordinate) if JOSE::JWA::Curve25519_RbNaCl.__supported__? assert_equal output_u_coordinate.to_bytes(256), JOSE::JWA::X25519_RbNaCl.curve25519(input_scalar, input_u_coordinate) end end end def test_curve25519_rfc7748_x25519 vectors = [ [ hexstr2bin("77076d0a7318a57d3c16c17251b26645df4c2f87ebc0992ab177fba51db92c2a"), # Alice's private key, f hexstr2bin("8520f0098930a754748b7ddcb43ef75a0dbf3a0d26381af4eba4a98eaa9b4e6a"), # Alice's public key, X25519(f, 9) hexstr2bin("5dab087e624a8a4b79e17f8b83800ee66f3bb1292618b6fd1c2f8b27ff88e0eb"), # Bob's private key, g hexstr2bin("de9edb7d7b7dc1b4d35b61c2ece435373f8343c85b78674dadfc7e146f882b4f"), # Bob's public key, X25519(g, 9) hexstr2bin("4a5d9d5ba4ce2de1728e3bf480350f25e07e21c947d19e3376f09b3c1e161742") # Their shared secret, K ] ] vectors.each do |(alice_sk, alice_pk, bob_sk, bob_pk, k)| assert_equal k, JOSE::JWA::X25519.shared_secret(alice_pk, bob_sk) assert_equal k, JOSE::JWA::X25519.shared_secret(bob_pk, alice_sk) if JOSE::JWA::Curve25519_RbNaCl.__supported__? assert_equal k, JOSE::JWA::X25519_RbNaCl.shared_secret(alice_pk, bob_sk) assert_equal k, JOSE::JWA::X25519_RbNaCl.shared_secret(bob_pk, alice_sk) end end end def test_curve448_eddsa_ed448 vectors = [ [ # Blank hexstr2bin( "6c82a562cb808d10d632be89c8513ebf"\ "6c929f34ddfa8c9f63c9960ef6e348a3"\ "528c8a3fcc2f044e39a3fc5b94492f8f"\ "032e7549a20098f95b"), # SECRET KEY hexstr2bin( "5fd7449b59b461fd2ce787ec616ad46a"\ "1da1342485a70e1f8a0ea75d80e96778"\ "edf124769b46c7061bd6783df1e50f6c"\ "d1fa1abeafe8256180"), # PUBLIC KEY "", # MESSAGE hexstr2bin( "533a37f6bbe457251f023c0d88f976ae"\ "2dfb504a843e34d2074fd823d41a591f"\ "2b233f034f628281f2fd7a22ddd47d78"\ "28c59bd0a21bfd3980ff0d2028d4b18a"\ "9df63e006c5d1c2d345b925d8dc00b41"\ "04852db99ac5c7cdda8530a113a0f4db"\ "b61149f05a7363268c71d95808ff2e65"\ "2600") # SIGNATURE ], [ # 1 octet hexstr2bin( "c4eab05d357007c632f3dbb48489924d"\ "552b08fe0c353a0d4a1f00acda2c463a"\ "fbea67c5e8d2877c5e3bc397a659949e"\ "f8021e954e0a12274e"), # SECRET KEY hexstr2bin( "43ba28f430cdff456ae531545f7ecd0a"\ "c834a55d9358c0372bfa0c6c6798c086"\ "6aea01eb00742802b8438ea4cb82169c"\ "235160627b4c3a9480"), # PUBLIC KEY hexstr2bin("03"), # MESSAGE hexstr2bin( "26b8f91727bd62897af15e41eb43c377"\ "efb9c610d48f2335cb0bd0087810f435"\ "2541b143c4b981b7e18f62de8ccdf633"\ "fc1bf037ab7cd779805e0dbcc0aae1cb"\ "cee1afb2e027df36bc04dcecbf154336"\ "c19f0af7e0a6472905e799f1953d2a0f"\ "f3348ab21aa4adafd1d234441cf807c0"\ "3a00") # SIGNATURE ], [ # 1 octet (with context) hexstr2bin( "c4eab05d357007c632f3dbb48489924d"\ "552b08fe0c353a0d4a1f00acda2c463a"\ "fbea67c5e8d2877c5e3bc397a659949e"\ "f8021e954e0a12274e"), # SECRET KEY hexstr2bin( "43ba28f430cdff456ae531545f7ecd0a"\ "c834a55d9358c0372bfa0c6c6798c086"\ "6aea01eb00742802b8438ea4cb82169c"\ "235160627b4c3a9480"), # PUBLIC KEY hexstr2bin("03"), # MESSAGE hexstr2bin("666f6f"), # CONTEXT hexstr2bin( "d4f8f6131770dd46f40867d6fd5d5055"\ "de43541f8c5e35abbcd001b32a89f7d2"\ "151f7647f11d8ca2ae279fb842d60721"\ "7fce6e042f6815ea000c85741de5c8da"\ "1144a6a1aba7f96de42505d7a7298524"\ "fda538fccbbb754f578c1cad10d54d0d"\ "5428407e85dcbc98a49155c13764e66c"\ "3c00") # SIGNATURE ], [ # 11 octets hexstr2bin( "cd23d24f714274e744343237b93290f5"\ "11f6425f98e64459ff203e8985083ffd"\ "f60500553abc0e05cd02184bdb89c4cc"\ "d67e187951267eb328"), # SECRET KEY hexstr2bin( "dcea9e78f35a1bf3499a831b10b86c90"\ "aac01cd84b67a0109b55a36e9328b1e3"\ "65fce161d71ce7131a543ea4cb5f7e9f"\ "1d8b00696447001400"), # PUBLIC KEY hexstr2bin("0c3e544074ec63b0265e0c"), # MESSAGE hexstr2bin( "1f0a8888ce25e8d458a21130879b840a"\ "9089d999aaba039eaf3e3afa090a09d3"\ "89dba82c4ff2ae8ac5cdfb7c55e94d5d"\ "961a29fe0109941e00b8dbdeea6d3b05"\ "1068df7254c0cdc129cbe62db2dc957d"\ "bb47b51fd3f213fb8698f064774250a5"\ "028961c9bf8ffd973fe5d5c206492b14"\ "0e00") # SIGNATURE ], [ # 12 octets hexstr2bin( "258cdd4ada32ed9c9ff54e63756ae582"\ "fb8fab2ac721f2c8e676a72768513d93"\ "9f63dddb55609133f29adf86ec9929dc"\ "cb52c1c5fd2ff7e21b"), # SECRET KEY hexstr2bin( "3ba16da0c6f2cc1f30187740756f5e79"\ "8d6bc5fc015d7c63cc9510ee3fd44adc"\ "24d8e968b6e46e6f94d19b945361726b"\ "d75e149ef09817f580"), # PUBLIC KEY hexstr2bin("64a65f3cdedcdd66811e2915"), # MESSAGE hexstr2bin( "7eeeab7c4e50fb799b418ee5e3197ff6"\ "bf15d43a14c34389b59dd1a7b1b85b4a"\ "e90438aca634bea45e3a2695f1270f07"\ "fdcdf7c62b8efeaf00b45c2c96ba457e"\ "b1a8bf075a3db28e5c24f6b923ed4ad7"\ "47c3c9e03c7079efb87cb110d3a99861"\ "e72003cbae6d6b8b827e4e6c143064ff"\ "3c00") # SIGNATURE ], [ # 13 octets hexstr2bin( "7ef4e84544236752fbb56b8f31a23a10"\ "e42814f5f55ca037cdcc11c64c9a3b29"\ "49c1bb60700314611732a6c2fea98eeb"\ "c0266a11a93970100e"), # SECRET KEY hexstr2bin( "b3da079b0aa493a5772029f0467baebe"\ "e5a8112d9d3a22532361da294f7bb381"\ "5c5dc59e176b4d9f381ca0938e13c6c0"\ "7b174be65dfa578e80"), # PUBLIC KEY hexstr2bin("64a65f3cdedcdd66811e2915e7"), # MESSAGE hexstr2bin( "6a12066f55331b6c22acd5d5bfc5d712"\ "28fbda80ae8dec26bdd306743c5027cb"\ "4890810c162c027468675ecf645a8317"\ "6c0d7323a2ccde2d80efe5a1268e8aca"\ "1d6fbc194d3f77c44986eb4ab4177919"\ "ad8bec33eb47bbb5fc6e28196fd1caf5"\ "6b4e7e0ba5519234d047155ac727a105"\ "3100") # SIGNATURE ], [ # 64 octets hexstr2bin( "d65df341ad13e008567688baedda8e9d"\ "cdc17dc024974ea5b4227b6530e339bf"\ "f21f99e68ca6968f3cca6dfe0fb9f4fa"\ "b4fa135d5542ea3f01"), # SECRET KEY hexstr2bin( "df9705f58edbab802c7f8363cfe5560a"\ "b1c6132c20a9f1dd163483a26f8ac53a"\ "39d6808bf4a1dfbd261b099bb03b3fb5"\ "0906cb28bd8a081f00"), # PUBLIC KEY hexstr2bin( "bd0f6a3747cd561bdddf4640a332461a"\ "4a30a12a434cd0bf40d766d9c6d458e5"\ "512204a30c17d1f50b5079631f64eb31"\ "12182da3005835461113718d1a5ef944"), # MESSAGE hexstr2bin( "554bc2480860b49eab8532d2a533b7d5"\ "78ef473eeb58c98bb2d0e1ce488a98b1"\ "8dfde9b9b90775e67f47d4a1c3482058"\ "efc9f40d2ca033a0801b63d45b3b722e"\ "f552bad3b4ccb667da350192b61c508c"\ "f7b6b5adadc2c8d9a446ef003fb05cba"\ "5f30e88e36ec2703b349ca229c267083"\ "3900") # SIGNATURE ], [ # 64 octets hexstr2bin( "d65df341ad13e008567688baedda8e9d"\ "cdc17dc024974ea5b4227b6530e339bf"\ "f21f99e68ca6968f3cca6dfe0fb9f4fa"\ "b4fa135d5542ea3f01"), # SECRET KEY hexstr2bin( "df9705f58edbab802c7f8363cfe5560a"\ "b1c6132c20a9f1dd163483a26f8ac53a"\ "39d6808bf4a1dfbd261b099bb03b3fb5"\ "0906cb28bd8a081f00"), # PUBLIC KEY hexstr2bin( "bd0f6a3747cd561bdddf4640a332461a"\ "4a30a12a434cd0bf40d766d9c6d458e5"\ "512204a30c17d1f50b5079631f64eb31"\ "12182da3005835461113718d1a5ef944"), # MESSAGE hexstr2bin( "554bc2480860b49eab8532d2a533b7d5"\ "78ef473eeb58c98bb2d0e1ce488a98b1"\ "8dfde9b9b90775e67f47d4a1c3482058"\ "efc9f40d2ca033a0801b63d45b3b722e"\ "f552bad3b4ccb667da350192b61c508c"\ "f7b6b5adadc2c8d9a446ef003fb05cba"\ "5f30e88e36ec2703b349ca229c267083"\ "3900") # SIGNATURE ], [ # 256 octets hexstr2bin( "2ec5fe3c17045abdb136a5e6a913e32a"\ "b75ae68b53d2fc149b77e504132d3756"\ "9b7e766ba74a19bd6162343a21c8590a"\ "a9cebca9014c636df5"), # SECRET KEY hexstr2bin( "79756f014dcfe2079f5dd9e718be4171"\ "e2ef2486a08f25186f6bff43a9936b9b"\ "fe12402b08ae65798a3d81e22e9ec80e"\ "7690862ef3d4ed3a00"), # PUBLIC KEY hexstr2bin( "15777532b0bdd0d1389f636c5f6b9ba7"\ "34c90af572877e2d272dd078aa1e567c"\ "fa80e12928bb542330e8409f31745041"\ "07ecd5efac61ae7504dabe2a602ede89"\ "e5cca6257a7c77e27a702b3ae39fc769"\ "fc54f2395ae6a1178cab4738e543072f"\ "c1c177fe71e92e25bf03e4ecb72f47b6"\ "4d0465aaea4c7fad372536c8ba516a60"\ "39c3c2a39f0e4d832be432dfa9a706a6"\ "e5c7e19f397964ca4258002f7c0541b5"\ "90316dbc5622b6b2a6fe7a4abffd9610"\ "5eca76ea7b98816af0748c10df048ce0"\ "12d901015a51f189f3888145c03650aa"\ "23ce894c3bd889e030d565071c59f409"\ "a9981b51878fd6fc110624dcbcde0bf7"\ "a69ccce38fabdf86f3bef6044819de11"), # MESSAGE hexstr2bin( "c650ddbb0601c19ca11439e1640dd931"\ "f43c518ea5bea70d3dcde5f4191fe53f"\ "00cf966546b72bcc7d58be2b9badef28"\ "743954e3a44a23f880e8d4f1cfce2d7a"\ "61452d26da05896f0a50da66a239a8a1"\ "88b6d825b3305ad77b73fbac0836ecc6"\ "0987fd08527c1a8e80d5823e65cafe2a"\ "3d00") # SIGNATURE ], [ # 1023 octets hexstr2bin( "872d093780f5d3730df7c212664b37b8"\ "a0f24f56810daa8382cd4fa3f77634ec"\ "44dc54f1c2ed9bea86fafb7632d8be19"\ "9ea165f5ad55dd9ce8"), # SECRET KEY hexstr2bin( "a81b2e8a70a5ac94ffdbcc9badfc3feb"\ "0801f258578bb114ad44ece1ec0e799d"\ "a08effb81c5d685c0c56f64eecaef8cd"\ "f11cc38737838cf400"), # PUBLIC KEY hexstr2bin( "6ddf802e1aae4986935f7f981ba3f035"\ "1d6273c0a0c22c9c0e8339168e675412"\ "a3debfaf435ed651558007db4384b650"\ "fcc07e3b586a27a4f7a00ac8a6fec2cd"\ "86ae4bf1570c41e6a40c931db27b2faa"\ "15a8cedd52cff7362c4e6e23daec0fbc"\ "3a79b6806e316efcc7b68119bf46bc76"\ "a26067a53f296dafdbdc11c77f7777e9"\ "72660cf4b6a9b369a6665f02e0cc9b6e"\ "dfad136b4fabe723d2813db3136cfde9"\ "b6d044322fee2947952e031b73ab5c60"\ "3349b307bdc27bc6cb8b8bbd7bd32321"\ "9b8033a581b59eadebb09b3c4f3d2277"\ "d4f0343624acc817804728b25ab79717"\ "2b4c5c21a22f9c7839d64300232eb66e"\ "53f31c723fa37fe387c7d3e50bdf9813"\ "a30e5bb12cf4cd930c40cfb4e1fc6225"\ "92a49588794494d56d24ea4b40c89fc0"\ "596cc9ebb961c8cb10adde976a5d602b"\ "1c3f85b9b9a001ed3c6a4d3b1437f520"\ "96cd1956d042a597d561a596ecd3d173"\ "5a8d570ea0ec27225a2c4aaff26306d1"\ "526c1af3ca6d9cf5a2c98f47e1c46db9"\ "a33234cfd4d81f2c98538a09ebe76998"\ "d0d8fd25997c7d255c6d66ece6fa56f1"\ "1144950f027795e653008f4bd7ca2dee"\ "85d8e90f3dc315130ce2a00375a318c7"\ "c3d97be2c8ce5b6db41a6254ff264fa6"\ "155baee3b0773c0f497c573f19bb4f42"\ "40281f0b1f4f7be857a4e59d416c06b4"\ "c50fa09e1810ddc6b1467baeac5a3668"\ "d11b6ecaa901440016f389f80acc4db9"\ "77025e7f5924388c7e340a732e554440"\ "e76570f8dd71b7d640b3450d1fd5f041"\ "0a18f9a3494f707c717b79b4bf75c984"\ "00b096b21653b5d217cf3565c9597456"\ "f70703497a078763829bc01bb1cbc8fa"\ "04eadc9a6e3f6699587a9e75c94e5bab"\ "0036e0b2e711392cff0047d0d6b05bd2"\ "a588bc109718954259f1d86678a579a3"\ "120f19cfb2963f177aeb70f2d4844826"\ "262e51b80271272068ef5b3856fa8535"\ "aa2a88b2d41f2a0e2fda7624c2850272"\ "ac4a2f561f8f2f7a318bfd5caf969614"\ "9e4ac824ad3460538fdc25421beec2cc"\ "6818162d06bbed0c40a387192349db67"\ "a118bada6cd5ab0140ee273204f628aa"\ "d1c135f770279a651e24d8c14d75a605"\ "9d76b96a6fd857def5e0b354b27ab937"\ "a5815d16b5fae407ff18222c6d1ed263"\ "be68c95f32d908bd895cd76207ae7264"\ "87567f9a67dad79abec316f683b17f2d"\ "02bf07e0ac8b5bc6162cf94697b3c27c"\ "d1fea49b27f23ba2901871962506520c"\ "392da8b6ad0d99f7013fbc06c2c17a56"\ "9500c8a7696481c1cd33e9b14e40b82e"\ "79a5f5db82571ba97bae3ad3e0479515"\ "bb0e2b0f3bfcd1fd33034efc6245eddd"\ "7ee2086ddae2600d8ca73e214e8c2b0b"\ "db2b047c6a464a562ed77b73d2d841c4"\ "b34973551257713b753632efba348169"\ "abc90a68f42611a40126d7cb21b58695"\ "568186f7e569d2ff0f9e745d0487dd2e"\ "b997cafc5abf9dd102e62ff66cba87"), # MESSAGE hexstr2bin( "e301345a41a39a4d72fff8df69c98075"\ "a0cc082b802fc9b2b6bc503f926b65bd"\ "df7f4c8f1cb49f6396afc8a70abe6d8a"\ "ef0db478d4c6b2970076c6a0484fe76d"\ "76b3a97625d79f1ce240e7c576750d29"\ "5528286f719b413de9ada3e8eb78ed57"\ "3603ce30d8bb761785dc30dbc320869e"\ "1a00") # SIGNATURE ] ] vectors.each do |vector| secret, pk, m, ctx, sig = vector if sig.nil? sig = ctx ctx = nil end _pk, sk = JOSE::JWA::Ed448.keypair(secret) assert_equal pk, _pk _sig = JOSE::JWA::Ed448.sign(m, sk, ctx) assert_equal sig, _sig assert JOSE::JWA::Ed448.verify(sig, m, pk, ctx) end end def test_curve448_eddsa_ed448ph vectors = [ [ # TEST abc hexstr2bin( "833fe62409237b9d62ec77587520911e"\ "9a759cec1d19755b7da901b96dca3d42"\ "ef7822e0d5104127dc05d6dbefde69e3"\ "ab2cec7c867c6e2c49"), # SECRET KEY hexstr2bin( "259b71c19f83ef77a7abd26524cbdb31"\ "61b590a48f7d17de3ee0ba9c52beb743"\ "c09428a131d6b1b57303d90d8132c276"\ "d5ed3d5d01c0f53880"), # PUBLIC KEY hexstr2bin("616263"), # MESSAGE hexstr2bin( "963cf799d20fdf51c460310c1cf65d0e"\ "83c4ef5aa73332ba5b4c1e7635ff9e9b"\ "6a12b16436fa3681b92575e7eba40ee2"\ "79c487ad724b6d1080e1860e63dbdd58"\ "9f5125505b4de024264625e61b097956"\ "8703f9d9e2bbf5523a1886ee6da1ecb2"\ "0552bb506eb35a042658ec534bfc1c2c"\ "1a00") # SIGNATURE ], [ # TEST abc (with context) hexstr2bin( "833fe62409237b9d62ec77587520911e"\ "9a759cec1d19755b7da901b96dca3d42"\ "ef7822e0d5104127dc05d6dbefde69e3"\ "ab2cec7c867c6e2c49"), # SECRET KEY hexstr2bin( "259b71c19f83ef77a7abd26524cbdb31"\ "61b590a48f7d17de3ee0ba9c52beb743"\ "c09428a131d6b1b57303d90d8132c276"\ "d5ed3d5d01c0f53880"), # PUBLIC KEY hexstr2bin("616263"), # MESSAGE hexstr2bin("666f6f"), # CONTEXT hexstr2bin( "86a6bf52f9e8f84f451b2f392a8d1c3a"\ "414425fac0068f74aeead53b0e6b53d4"\ "555cea1726da4a65202880d407267087"\ "9e8e6fa4d9694c060054f2065dc206a6"\ "e615d0d8c99b95209b696c8125c5fbb9"\ "bc82a0f7ed3d99c4c11c47798ef0f7eb"\ "97b3b72ab4ac86eaf8b43449e8ac30ff"\ "3f00") # SIGNATURE ] ] vectors.each do |vector| secret, pk, m, ctx, sig = vector if sig.nil? sig = ctx ctx = nil end _pk, sk = JOSE::JWA::Ed448.keypair(secret) assert_equal pk, _pk _sig = JOSE::JWA::Ed448.sign_ph(m, sk, ctx) assert_equal sig, _sig assert JOSE::JWA::Ed448.verify_ph(sig, m, pk, ctx) end end def test_curve448_rfc7748_curve448 vectors = [ [ 599189175373896402783756016145213256157230856085026129926891459468622403380588640249457727683869421921443004045221642549886377526240828, # Input scalar 382239910814107330116229961234899377031416365240571325148346555922438025162094455820962429142971339584360034337310079791515452463053830, # Input u-coordinate hexstr2lint("ce3e4ff95a60dc6697da1db1d85e6afbdf79b50a2412d7546d5f239fe14fbaadeb445fc66a01b0779d98223961111e21766282f73dd96b6f") # Output u-coordinate ], [ 633254335906970592779259481534862372382525155252028961056404001332122152890562527156973881968934311400345568203929409663925541994577184, # Input scalar 622761797758325444462922068431234180649590390024811299761625153767228042600197997696167956134770744996690267634159427999832340166786063, # Input u-coordinate hexstr2lint("884a02576239ff7a2f2f63b2db6a9ff37047ac13568e1e30fe63c4a7ad1b3ee3a5700df34321d62077e63633c575c1c954514e99da7c179d") # Output u-coordinate ] ] vectors.each do |(input_scalar, input_u_coordinate, output_u_coordinate)| input_scalar = JOSE::JWA::X448.coerce_scalar_fe!(input_scalar) input_u_coordinate = JOSE::JWA::X448.coerce_coordinate_fe!(input_u_coordinate) output_u_coordinate = JOSE::JWA::X448.coerce_coordinate_fe!(output_u_coordinate) assert_equal output_u_coordinate, JOSE::JWA::X448.curve448(input_scalar, input_u_coordinate) end end def test_curve448_rfc7748_x448 vectors = [ [ hexstr2bin("9a8f4925d1519f5775cf46b04b5800d4ee9ee8bae8bc5565d498c28dd9c9baf574a9419744897391006382a6f127ab1d9ac2d8c0a598726b"), # Alice's private key, f hexstr2bin("9b08f7cc31b7e3e67d22d5aea121074a273bd2b83de09c63faa73d2c22c5d9bbc836647241d953d40c5b12da88120d53177f80e532c41fa0"), # Alice's public key, X448(f, 9) hexstr2bin("1c306a7ac2a0e2e0990b294470cba339e6453772b075811d8fad0d1d6927c120bb5ee8972b0d3e21374c9c921b09d1b0366f10b65173992d"), # Bob's private key, g hexstr2bin("3eb7a829b0cd20f5bcfc0b599b6feccf6da4627107bdb0d4f345b43027d8b972fc3e34fb4232a13ca706dcb57aec3dae07bdc1c67bf33609"), # Bob's public key, X448(g, 9) hexstr2bin("07fff4181ac6cc95ec1c16a94a0f74d12da232ce40a77552281d282bb60c0b56fd2464c335543936521c24403085d59a449a5037514a879d") # Their shared secret, K ] ] vectors.each do |(alice_sk, alice_pk, bob_sk, bob_pk, k)| assert_equal k, JOSE::JWA::X448.shared_secret(alice_pk, bob_sk) assert_equal k, JOSE::JWA::X448.shared_secret(bob_pk, alice_sk) end end private def hexstr2bin(hexstr) return [hexstr].pack('H*') end def hexstr2lint(hexstr) return OpenSSL::BN.new(hexstr2bin(hexstr).reverse, 2).to_i end end
potatosalad/ruby-jose
test/cfrg_curves_test.rb
Ruby
mpl-2.0
27,819
/** * m59peacemaker's memoize * * See https://github.com/m59peacemaker/angular-pmkr-components/tree/master/src/memoize * Released under the MIT license */ angular.module('syncthing.core') .factory('pmkr.memoize', [ function() { function service() { return memoizeFactory.apply(this, arguments); } function memoizeFactory(fn) { var cache = {}; function memoized() { var args = [].slice.call(arguments); var key = JSON.stringify(args); if (cache.hasOwnProperty(key)) { return cache[key]; } cache[key] = fn.apply(this, arguments); return cache[key]; } return memoized; } return service; } ]);
atyenoria/syncthing
gui/syncthing/core/memoize.js
JavaScript
mpl-2.0
903
class VoidTile include IndefiniteArticle DEAD_COORDINATE = -9001 attr_reader :x attr_reader :y attr_reader :z attr_reader :plane def self.generate_hash(x, y, z) { x: x, y: y, z: z, name: '', description: '', colour: 'black', type: 'Void', occupants: 0} end class FakeArray < Array def <<(ignored) self end end @@fakearray = FakeArray.new def initialize(p, x, y, z) @x = x @y = y @z = z @plane = p end def colour 'black' end def type Entity::VoidTileType end def description '' end def name '' end def characters @@fakearray end def visible_character_count 0 end def occupants @@fakearray end def traversible? false end def portals_packets [] end def save end def statuses [] end def type_statuses [] end def to_h {name: self.name, type: self.type.name, type_id: self.type.id, description: self.description, x: self.x, y: self.y, z: self.z, plane: self.plane, occupants: self.visible_character_count} end def unserialise_statuses # do nothing end end
NexusClash/NexusClash
firmament/entities/void_tile.rb
Ruby
mpl-2.0
1,058
using System.Linq; using Xunit; namespace Kf.Core.Tests._extensions_.Collections { public class IEnumerableOfTExtensionsTests { [Fact] public void Index_Returns_Correct_Values_And_Index() { // Arrange var index = 0; var sut = Enumerable.Range(0, 500); // Act var foreachWithIndex = sut.Index(); // Assert foreach (var element in foreachWithIndex) { Assert.Equal(index, element.Index); Assert.Equal(index, element.Value); Assert.Equal(element.Value, element.Index); index++; } } [Fact] public void ForEachPerformsCorrectAlgorithm() { var sut = Enumerable.Range(0, 500); var result = sut.ForEach(i => { return 0; }); Assert.True(result.All(i => i == 0)); } [Fact] public void ForEachCanReturnDifferentType() { var sut = Enumerable.Range(0, 500); var result = sut.ForEach(i => { return i.ToString("000"); }); Assert.True(result.All(i => i.Length.Equals(3))); } [Fact] public void ForEachCanReturnAndCOntinueLinqStyle() { var sut = Enumerable.Range(0, 500); var result = sut.ForEach(i => { return i.ToString("000"); }); result = result.Where(x => x.Contains("449")); Assert.True(result.Count().Equals(1)); } } }
KodeFoxx/Kf.Core
Source/Kf.Core.Tests/(extensions)/Collections/IEnumerableOfTExtensionsTests.cs
C#
mpl-2.0
1,517
# coding=utf-8 ''' tagsPlorer package entry point (C) 2021-2021 Arne Bachmann https://github.com/ArneBachmann/tagsplorer ''' from tagsplorer import tp tp.Main().parse_and_run()
ArneBachmann/tagsplorer
tagsplorer/__main__.py
Python
mpl-2.0
183
/* * Copyright (c) 2014. The Trustees of Indiana University. * * This version of the code is licensed under the MPL 2.0 Open Source license with additional * healthcare disclaimer. If the user is an entity intending to commercialize any application * that uses this code in a for-profit venture, please contact the copyright holder. */ package com.muzima.api.model.algorithm; import com.muzima.api.model.PersonAttributeType; import com.muzima.search.api.model.object.Searchable; import com.muzima.util.JsonUtils; import net.minidev.json.JSONObject; import java.io.IOException; public class PersonAttributeTypeAlgorithm extends BaseOpenmrsAlgorithm { public static final String PERSON_ATTRIBUTE_TYPE_REPRESENTATION = "(uuid,name)"; private String uuid; /** * Implementation of this method will define how the object will be serialized from the String representation. * * @param serialized the string representation * @return the concrete object */ @Override public Searchable deserialize(final String serialized, final boolean isFullSerialization) throws IOException { PersonAttributeType attributeType = new PersonAttributeType(); attributeType.setUuid(JsonUtils.readAsString(serialized, "$['uuid']")); attributeType.setName(JsonUtils.readAsString(serialized, "$['name']")); return attributeType; } /** * Implementation of this method will define how the object will be de-serialized into the String representation. * * @param object the object * @return the string representation */ @Override public String serialize(final Searchable object, final boolean isFullSerialization) throws IOException { PersonAttributeType attributeType = (PersonAttributeType) object; JSONObject jsonObject = new JSONObject(); JsonUtils.writeAsString(jsonObject, "uuid", attributeType.getUuid()); JsonUtils.writeAsString(jsonObject, "name", attributeType.getName()); return jsonObject.toJSONString(); } }
sthaiya/muzima-api
src/main/java/com/muzima/api/model/algorithm/PersonAttributeTypeAlgorithm.java
Java
mpl-2.0
2,059
'use strict'; var LIVERELOAD_PORT = 35729; var lrSnippet = require('connect-livereload')({ port: LIVERELOAD_PORT }); var mountFolder = function (connect, dir) { return connect.static(require('path').resolve(dir)); }; var fs = require('fs'); var delayApiCalls = function (request, response, next) { if (request.url.indexOf('/api') !== -1) { setTimeout(function () { next(); }, 1000); } else { next(); } }; var httpMethods = function (request, response, next) { console.log("request method: " + JSON.stringify(request.method)); var rawpath = request.url.split('?')[0]; console.log("request url: " + JSON.stringify(request.url)); var path = require('path').resolve(__dirname, 'app/' + rawpath); console.log("request path : " + JSON.stringify(path)); console.log("request current dir : " + JSON.stringify(__dirname)); if ((request.method === 'PUT' || request.method === 'POST')) { console.log('inside put/post'); request.content = ''; request.addListener("data", function (chunk) { request.content += chunk; }); request.addListener("end", function () { console.log("request content: " + JSON.stringify(request.content)); if (fs.existsSync(path)) { if (request.method === 'POST') { response.statusCode = 403; response.end('Resource already exists.'); return; } fs.writeFile(path, request.content, function (err) { if (err) { response.statusCode(404); console.log('File not saved: ' + JSON.stringify(err)); response.end('Error writing to file.'); } else { console.log('File saved to: ' + path); response.end('File was saved.'); } }); return; } else { if (request.method === 'PUT') { response.statusCode = 404; response.end('Resource not found: ' + JSON.stringify(request.url)); return; } } if (request.url === '/log') { var filePath = 'server/log/server.log'; var logData = JSON.parse(request.content); fs.appendFile(filePath, logData.logUrl + '\n' + logData.logMessage + '\n', function (err) { if (err) { throw err; } console.log('log saved'); response.end('log was saved'); }); return; } }); return; } next(); }; // # Globbing // for performance reasons we're only matching one level down: // 'test/spec/{,*/}*.js' // use this if you want to recursively match all subfolders: // 'test/spec/**/*.js' module.exports = function (grunt) { require('load-grunt-tasks')(grunt); require('time-grunt')(grunt); // configurable paths var yeomanConfig = { app: 'app', dist: 'dist', doc: 'doc', test: 'test' }; try { yeomanConfig.app = require('./bower.json').appPath || yeomanConfig.app; } catch (e) {} grunt.initConfig({ yeoman: yeomanConfig, watch: { compass: { files: ['<%= yeoman.app %>/styles/**/*.{scss,sass}'], tasks: ['compass:server', 'autoprefixer:tmp'] }, styles: { files: ['<%= yeoman.app %>/styles/**/*.css'], tasks: ['autoprefixer:styles'] }, livereload: { options: { livereload: LIVERELOAD_PORT }, files: [ '<%= yeoman.app %>/**/*.html', '{.tmp,<%= yeoman.app %>}/styles/**/*.css', '{.tmp,<%= yeoman.app %>}/scripts/**/*.js', '{.tmp,<%= yeoman.app %>}/resources/**/*', '<%= yeoman.app %>/images/**/*.{png,jpg,jpeg,gif,webp,svg}' ] } // , // doc: { // files: ['{.tmp,<%= yeoman.app %>}/scripts/**/*.js'], // tasks: ['docular'] // } }, autoprefixer: { options: ['last 1 version'], tmp: { files: [{ expand: true, cwd: '.tmp/styles/', src: '**/*.css', dest: '.tmp/styles/' }] }, styles: { files: [{ expand: true, cwd: '<%= yeoman.app %>/styles/', src: '**/*.css', dest: '.tmp/styles/' }] } }, connect: { options: { protocol: 'http', port: 9000, // Change this to '0.0.0.0' to access the server from outside. hostname: 'localhost' }, livereload: { options: { middleware: function (connect) { return [ delayApiCalls, lrSnippet, mountFolder(connect, '.tmp'), mountFolder(connect, yeomanConfig.app), httpMethods ]; } } }, test: { options: { port: 9090, middleware: function (connect) { return [ mountFolder(connect, '.tmp'), mountFolder(connect, yeomanConfig.app), mountFolder(connect, '<%= yeoman.test %>'), httpMethods ]; } } }, dist: { options: { middleware: function (connect) { return [ delayApiCalls, mountFolder(connect, yeomanConfig.dist), httpMethods ]; } } }, doc: { options: { port: 3000, middleware: function (connect) { return [ mountFolder(connect, yeomanConfig.doc) ]; } } } }, open: { server: { url: '<%= connect.options.protocol %>://<%= connect.options.hostname %>:<%= connect.options.port %>' }, doc: { url: '<%= connect.options.protocol %>://<%= connect.options.hostname %>:9001' } }, clean: { dist: { files: [{ dot: true, src: [ '.tmp', '<%= yeoman.dist %>/*', '!<%= yeoman.dist %>/.git*' ] }] }, server: '.tmp' }, jshint: { options: { jshintrc: '.jshintrc' }, all: [ 'Gruntfile.js', '<%= yeoman.app %>/scripts/{,*/}*.js' ] }, compass: { options: { sassDir: '<%= yeoman.app %>/styles', cssDir: '.tmp/styles', generatedImagesDir: '.tmp/images/generated', imagesDir: '<%= yeoman.app %>/images', javascriptsDir: '<%= yeoman.app %>/scripts', fontsDir: '<%= yeoman.app %>/styles/fonts', importPath: '<%= yeoman.app %>/bower_components', httpImagesPath: '/images', httpGeneratedImagesPath: '/images/generated', httpFontsPath: '/styles/fonts', relativeAssets: false }, dist: { options: { debugInfo: false } }, server: { options: { debugInfo: true } } }, uglify: { dist: { files: { '<%= yeoman.dist %>/scripts/api/angular-jqm.js': ['<%= yeoman.app %>/scripts/api/angular-jqm.js'], '<%= yeoman.dist %>/bower_components/angular-animate/angular-animate.js': ['<%= yeoman.app %>/bower_components/angular-animate/angular-animate.js'], '<%= yeoman.dist %>/bower_components/angular-route/angular-route.js': ['<%= yeoman.app %>/bower_components/angular-route/angular-route.js'], '<%= yeoman.dist %>/bower_components/angular-touch/angular-touch.js': ['<%= yeoman.app %>/bower_components/angular-touch/angular-touch.js'] } } }, rev: { dist: { files: { src: [ '<%= yeoman.dist %>/scripts/*.js', '<%= yeoman.dist %>/styles/*.css', '<%= yeoman.dist %>/images/**/*.{png,jpg,jpeg,gif,webp,svg}', '!<%= yeoman.dist %>/images/glyphicons-*', '<%= yeoman.dist %>/styles/images/*.{gif,png}' ] } } }, useminPrepare: { html: '<%= yeoman.app %>/index.html', options: { dest: '<%= yeoman.dist %>' } }, usemin: { html: ['<%= yeoman.dist %>/*.html', '<%= yeoman.dist %>/views/**/*.html'], css: ['<%= yeoman.dist %>/styles/**/*.css'], options: { assetsDirs: ['<%= yeoman.dist %>/**'] } }, imagemin: { dist: { files: [{ expand: true, cwd: '<%= yeoman.app %>', src: [ 'styles/images/*.{jpg,jpeg,svg,gif}', 'images/*.{jpg,jpeg,svg,gif}' ], dest: '<%= yeoman.dist %>' }] } }, tinypng: { options: { apiKey: "l_QIDgceoKGF8PBNRr3cmYy_Nhfa9F1p", checkSigs: true, sigFile: '<%= yeoman.app %>/images/tinypng_sigs.json', summarize: true, showProgress: true, stopOnImageError: true }, dist: { expand: true, cwd: '<%= yeoman.app %>', src: 'images/**/*.png', dest: '<%= yeoman.app %>' } }, htmlmin: { dist: { options: { removeComments: true, removeCommentsFromCDATA: true, removeCDATASectionsFromCDATA: true, collapseWhitespace: true, // conservativeCollapse: true, collapseBooleanAttributes: true, removeAttributeQuotes: false, removeRedundantAttributes: true, useShortDoctype: true, removeEmptyAttributes: true, removeOptionalTags: true, keepClosingSlash: true, }, files: [{ expand: true, cwd: '<%= yeoman.dist %>', src: [ '*.html', 'views/**/*.html', 'template/**/*.html' ], dest: '<%= yeoman.dist %>' }] } }, // Put files not handled in other tasks here copy: { dist: { files: [{ expand: true, dot: true, cwd: '<%= yeoman.app %>', dest: '<%= yeoman.dist %>', src: [ '*.{ico,png,txt}', '.htaccess', 'api/**', 'images/{,*/}*.{gif,webp}', 'resources/**', 'styles/fonts/*', 'styles/images/*', '*.html', 'views/**/*.html', 'template/**/*.html' ] }, { expand: true, cwd: '.tmp/images', dest: '<%= yeoman.dist %>/images', src: [ 'generated/*' ] }, { expand: true, cwd: '<%= yeoman.app %>/bower_components/angular-i18n', dest: '<%= yeoman.dist %>/resources/i18n/angular', src: [ '*en-us.js', '*es-es.js', '*ja-jp.js', '*ar-eg.js' ] }] }, styles: { expand: true, cwd: '<%= yeoman.app %>/styles', dest: '.tmp/styles', src: '**/*.css' }, i18n: { expand: true, cwd: '<%= yeoman.app %>/bower_components/angular-i18n', dest: '.tmp/resources/i18n/angular', src: [ '*en-us.js', '*es-es.js', '*ja-jp.js', '*ar-eg.js' ] }, fonts: { expand: true, cwd: '<%= yeoman.app %>/bower_components/bootstrap-sass-official/assets/fonts', dest: '.tmp/fonts', src: '**/*' }, png: { expand: true, cwd: '<%= yeoman.app %>', dest: '<%= yeoman.dist %>', src: 'images/**/*.png' } }, concurrent: { server: [ 'compass:server', 'copy:i18n', 'copy:fonts' ], dist: [ 'compass:dist', 'imagemin' ] }, karma: { unit: { configFile: '<%= yeoman.test %>/karma-unit.conf.js', autoWatch: false, singleRun: true }, unit_auto: { configFile: '<%= yeoman.test %>/karma-unit.conf.js' }, midway: { configFile: '<%= yeoman.test %>/karma-midway.conf.js', autoWatch: false, singleRun: true }, midway_auto: { configFile: '<%= yeoman.test %>/karma-midway.conf.js' }, e2e: { configFile: '<%= yeoman.test %>/karma-e2e.conf.js', autoWatch: false, singleRun: true }, e2e_auto: { configFile: '<%= yeoman.test %>/karma-e2e.conf.js' } }, cdnify: { dist: { html: ['<%= yeoman.dist %>/*.html'] } }, ngAnnotate: { dist: { files: [{ expand: true, cwd: '.tmp/concat/scripts', src: '*.js', dest: '.tmp/concat/scripts' }] } }, docular: { showDocularDocs: false, showAngularDocs: true, docular_webapp_target: "doc", groups: [ { groupTitle: 'Appverse HTML5', groupId: 'appverse', groupIcon: 'icon-beer', sections: [ { id: "commonapi", title: "Common API", showSource: true, scripts: ["app/scripts/api/modules", "app/scripts/api/directives" ], docs: ["ngdocs/commonapi"], rank: {} } ] }, { groupTitle: 'Angular jQM', groupId: 'angular-jqm', groupIcon: 'icon-mobile-phone', sections: [ { id: "jqmapi", title: "API", showSource: true, scripts: ["app/scripts/api/angular-jqm.js" ], docs: ["ngdocs/jqmapi"], rank: {} } ] } ] } }); grunt.loadNpmTasks('grunt-contrib-watch'); grunt.loadNpmTasks('grunt-karma'); grunt.loadNpmTasks('grunt-docular'); grunt.registerTask('server', [ 'clean:server', 'concurrent:server', 'autoprefixer', 'connect:livereload', 'open:server', 'watch' ]); grunt.registerTask('testserver', [ 'clean:server', 'concurrent:server', 'autoprefixer', 'connect:test' ]); grunt.registerTask('test', [ 'karma:unit', 'testserver', 'karma:midway', 'karma:e2e' ]); grunt.registerTask('test:midway', [ 'testserver', 'karma:midway_auto' ]); grunt.registerTask('test:e2e', [ 'testserver', 'karma:e2e_auto' ]); grunt.registerTask('devmode', [ 'karma:unit_auto' ]); grunt.registerTask('doc', [ 'docular', 'connect:doc', 'open:doc', 'watch:doc' ]); grunt.registerTask('dist', [ 'clean:dist', 'useminPrepare', 'concurrent:dist', 'tinypng', 'copy:png', 'autoprefixer', 'concat', 'copy:dist', 'cdnify', 'ngAnnotate', 'cssmin', 'uglify', 'rev', 'usemin', 'htmlmin', 'connect:dist', // 'docular', // 'connect:doc', 'open:server', // 'open:doc', 'watch' ]); grunt.registerTask('default', [ 'server' ]); };
glarfs/training-unit-2
Gruntfile.js
JavaScript
mpl-2.0
19,182
//Copyright (c) 2017 Finjin // //This file is part of Finjin Engine (finjin-engine). // //Finjin Engine 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. // //This Source Code Form is subject to the terms of the Mozilla Public //License, v. 2.0. If a copy of the MPL was not distributed with this //file, You can obtain one at http://mozilla.org/MPL/2.0/. #pragma once //Includes---------------------------------------------------------------------- #include "finjin/engine/GenericInputDevice.hpp" //Types------------------------------------------------------------------------- namespace Finjin { namespace Engine { using namespace Finjin::Common; class WindowsUWPInputContext; } }
finjin/finjin-engine
cpp/library/src/finjin/engine/internal/input/uwpinput/WindowsUWPInputDevice.hpp
C++
mpl-2.0
821
# frozen_string_literal: true # Setup used to generate email message class ApplicationMailer < ActionMailer::Base default from: "noreply@smoothiefunds.com" layout "mailer" end
tjustino/smoothie_funds
app/mailers/application_mailer.rb
Ruby
mpl-2.0
181
/* Copyright (C) 2015 haha01haha01 * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace HaJS { public partial class MainForm : Form { public MainForm() { InitializeComponent(); } private void ofdBox_Click(object sender, EventArgs e) { OpenFileDialog ofd = new OpenFileDialog() { Filter = "XML Files|*.xml" }; if (ofd.ShowDialog() != System.Windows.Forms.DialogResult.OK) return; ((TextBox)sender).Text = ofd.FileName; } private void button1_Click(object sender, EventArgs e) { if (serverConfigPathBox.Text == "" || inputXmlBox.Text == "") return; HaJSCompiler jsc = new HaJSCompiler(serverConfigPathBox.Text); string outPath = Path.Combine(Path.GetDirectoryName(inputXmlBox.Text), Path.GetFileNameWithoutExtension(inputXmlBox.Text) + ".js"); #if !DEBUG try { #endif jsc.Compile(inputXmlBox.Text, outPath); MessageBox.Show("Finished compiling to " + outPath); #if !DEBUG } catch (Exception ex) { MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } #endif } private void button2_Click(object sender, EventArgs e) { if (serverConfigPathBox.Text == "" || inputXmlBox.Text == "") return; HaJSCompiler jsc = new HaJSCompiler(serverConfigPathBox.Text); string folder = Path.GetDirectoryName(inputXmlBox.Text); foreach (FileInfo fi in new DirectoryInfo(folder).GetFiles()) { if (fi.Extension.ToLower() == ".xml") { #if !DEBUG try { #endif jsc.Compile(fi.FullName, Path.Combine(folder, Path.GetFileNameWithoutExtension(fi.FullName) + ".js")); #if !DEBUG } catch (Exception ex) { MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); break; } #endif } } MessageBox.Show("Finished compiling " + folder); } } }
haha01haha01/HaJS
HaJS/MainForm.cs
C#
mpl-2.0
2,742
/* * Copyright © 2013-2019, The SeedStack authors <http://seedstack.org> * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package org.seedstack.seed.core.internal.configuration.tool; import com.google.common.base.Strings; import java.io.PrintStream; import org.fusesource.jansi.Ansi; import org.seedstack.shed.text.TextWrapper; class DetailPrinter { private static final TextWrapper textWrapper = new TextWrapper(120); private final PropertyInfo propertyInfo; DetailPrinter(PropertyInfo propertyInfo) { this.propertyInfo = propertyInfo; } void printDetail(PrintStream stream) { Ansi ansi = Ansi.ansi(); String title = "Details of " + propertyInfo.getName(); ansi .a(title) .newline() .a(Strings.repeat("-", title.length())) .newline().newline(); printSummary(propertyInfo, ansi); printDeclaration(propertyInfo, ansi); printLongDescription(propertyInfo, ansi); printAdditionalInfo(propertyInfo, ansi); ansi.newline(); stream.print(ansi.toString()); } private Ansi printSummary(PropertyInfo propertyInfo, Ansi ansi) { return ansi.a(propertyInfo.getShortDescription()).newline(); } private void printDeclaration(PropertyInfo propertyInfo, Ansi ansi) { ansi .newline() .a(" ") .fgBright(Ansi.Color.MAGENTA) .a(propertyInfo.getType()) .reset() .a(" ") .fgBright(Ansi.Color.BLUE) .a(propertyInfo.getName()) .reset(); Object defaultValue = propertyInfo.getDefaultValue(); if (defaultValue != null) { ansi .a(" = ") .fgBright(Ansi.Color.GREEN) .a(String.valueOf(defaultValue)) .reset(); } ansi .a(";") .newline(); } private void printLongDescription(PropertyInfo propertyInfo, Ansi ansi) { String longDescription = propertyInfo.getLongDescription(); if (longDescription != null) { ansi.newline().a(textWrapper.wrap(longDescription)).newline(); } } private void printAdditionalInfo(PropertyInfo propertyInfo, Ansi ansi) { if (propertyInfo.isMandatory() || propertyInfo.isSingleValue()) { ansi.newline(); } if (propertyInfo.isMandatory()) { ansi.a("* This property is mandatory.").newline(); } if (propertyInfo.isSingleValue()) { ansi.a("* This property is the default property of its declaring object").newline(); } } }
Sherpard/seed
core/src/main/java/org/seedstack/seed/core/internal/configuration/tool/DetailPrinter.java
Java
mpl-2.0
2,925
const html = require('choo/html'); module.exports = function(name, url) { const dialog = function(state, emit, close) { return html` <send-share-dialog class="flex flex-col items-center text-center p-4 max-w-sm m-auto" > <h1 class="text-3xl font-bold my-4"> ${state.translate('notifyUploadEncryptDone')} </h1> <p class="font-normal leading-normal text-grey-80 dark:text-grey-40"> ${state.translate('shareLinkDescription')}<br /> <span class="word-break-all">${name}</span> </p> <input type="text" id="share-url" class="w-full my-4 border rounded-lg leading-loose h-12 px-2 py-1 dark:bg-grey-80" value="${url}" readonly="true" /> <button class="btn rounded-lg w-full flex-shrink-0 focus:outline" onclick="${share}" title="${state.translate('shareLinkButton')}" > ${state.translate('shareLinkButton')} </button> <button class="link-blue my-4 font-medium cursor-pointer focus:outline" onclick="${close}" title="${state.translate('okButton')}" > ${state.translate('okButton')} </button> </send-share-dialog> `; async function share(event) { event.stopPropagation(); try { await navigator.share({ title: state.translate('-send-brand'), text: state.translate('shareMessage', { name }), url }); } catch (e) { if (e.code === e.ABORT_ERR) { return; } console.error(e); } close(); } }; dialog.type = 'share'; return dialog; };
mozilla/send
app/ui/shareDialog.js
JavaScript
mpl-2.0
1,735
using System; using System.Collections.Generic; using System.IO; using System.Windows.Input; using System.Threading; using System.Linq; using System.Text; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using Microsoft.Xna.Framework.GamerServices; namespace Sims2Online.UI.Elements { class UIButton : UIControl { MouseState oldMouseState; KeyboardState oldKBState; Vector2 selected; Texture2D backtex; public string text; public Color color = Color.White; public event EventHandler onClicked; public event EventHandler onHover; public event EventHandler onMouseLeft; public float scale; public override void Init(SpriteBatch spb) { selected = Vector2.Zero; using (var stream1 = new FileStream("./content/colour.png", FileMode.Open)) { backtex = Texture2D.FromStream(spb.GraphicsDevice, stream1); } } public override void Update(SpriteBatch spb, S2OGame game) { spb.Draw(backtex, rect, Color.Black * 0.25f); var currentMouseState = Mouse.GetState(); var currentKBState = Keyboard.GetState(); if (rect.Contains(new Point(currentMouseState.X, currentMouseState.Y)) && currentMouseState.LeftButton == ButtonState.Pressed) { this.onClicked?.Invoke(this, EventArgs.Empty); } else if (rect.Contains(new Point(currentMouseState.X, currentMouseState.Y))) { this.onHover?.Invoke(this, EventArgs.Empty); } else { this.onMouseLeft?.Invoke(this, EventArgs.Empty); } spb.DrawString(S2OGame.Font1, text, new Vector2(rect.X + ((rect.Width / 2) - ((S2OGame.Font1.MeasureString(text) * scale).X / 2)), rect.Y + ((rect.Height / 2) - ((S2OGame.Font1.MeasureString(text) * scale).Y / 2))), color, 0, Vector2.Zero, scale, SpriteEffects.None, 0.5f); oldMouseState = currentMouseState; oldKBState = currentKBState; } } }
LRB-Game-Tools/Sims2Online
Sims2Client/Sims2Online/UI/Elements/UIButton.cs
C#
mpl-2.0
2,235
<?php namespace ide\formats\form\elements; use ide\editors\value\BooleanPropertyEditor; use ide\editors\value\ColorPropertyEditor; use ide\editors\value\FontPropertyEditor; use ide\editors\value\IntegerPropertyEditor; use ide\editors\value\PositionPropertyEditor; use ide\editors\value\SimpleTextPropertyEditor; use ide\editors\value\TextPropertyEditor; use ide\formats\form\AbstractFormElement; use php\gui\designer\UXDesignProperties; use php\gui\designer\UXDesignPropertyEditor; use php\gui\layout\UXAnchorPane; use php\gui\layout\UXHBox; use php\gui\layout\UXPanel; use php\gui\UXButton; use php\gui\UXNode; use php\gui\UXTableCell; use php\gui\UXTextField; use php\gui\UXTitledPane; /** * Class ButtonFormElement * @package ide\formats\form */ class PanelFormElement extends AbstractFormElement { public function getGroup() { return 'Панели'; } public function getElementClass() { return UXPanel::class; } public function getName() { return 'Панель'; } public function getIcon() { return 'icons/panel16.png'; } public function getIdPattern() { return "panel%s"; } public function isLayout() { return true; } public function addToLayout($self, $node, $screenX = null, $screenY = null) { /** @var UXPanel $self */ $node->position = $self->screenToLocal($screenX, $screenY); $self->add($node); } public function getLayoutChildren($layout) { $children = flow($layout->children) ->find(function (UXNode $it) { return !$it->classes->has('x-system-element'); }) ->toArray(); return $children; } /** * @return UXNode */ public function createElement() { $button = new UXPanel(); $button->backgroundColor = 'white'; return $button; } public function getDefaultSize() { return [150, 100]; } public function isOrigin($any) { return get_class($any) == UXPanel::class; } }
jphp-compiler/develnext
platforms/develnext-desktop-platform/src/ide/formats/form/elements/PanelFormElement.php
PHP
mpl-2.0
2,091
package com.storage.mywarehouse.Dao; import com.storage.mywarehouse.View.WarehouseProduct; import org.hibernate.Session; import org.hibernate.Transaction; import org.hibernate.criterion.Restrictions; import java.util.List; public class WarehouseProductDAO { @SuppressWarnings("unchecked") public static List<WarehouseProduct> findById(int id) { Session session = NewHibernateUtil.getSessionFactory().openSession(); Transaction tx = session.beginTransaction(); List products = session.createCriteria(WarehouseProduct.class) .add(Restrictions.eq("productId", id)) .list(); tx.commit(); session.close(); return products; } @SuppressWarnings("unchecked") public static List<WarehouseProduct> findByQuantity(int quantity) { Session session = NewHibernateUtil.getSessionFactory().openSession(); Transaction tx = session.beginTransaction(); List emptyWarehouseProduct = session.createCriteria(WarehouseProduct.class) .add(Restrictions.eq("quantity", quantity)) .list(); tx.commit(); session.close(); return emptyWarehouseProduct; } @SuppressWarnings("unchecked") public static List<WarehouseProduct> findByParam(String param, String value) { Session session = NewHibernateUtil.getSessionFactory().openSession(); Transaction tx = session.beginTransaction(); List products = session.createCriteria(WarehouseProduct.class) .add(Restrictions.eq(param.toLowerCase(), value)) .list(); tx.commit(); session.close(); return products; } @SuppressWarnings("unchecked") public static List<WarehouseProduct> findByParamContainingValue(String param, String value) { Session session = NewHibernateUtil.getSessionFactory().openSession(); Transaction tx = session.beginTransaction(); List products = session.createCriteria(WarehouseProduct.class) .add(Restrictions.like(param.toLowerCase(), "%" + value + "%")) .list(); tx.commit(); session.close(); return products; } }
patroklossam/WareHouse
src/main/java/com/storage/mywarehouse/Dao/WarehouseProductDAO.java
Java
mpl-2.0
2,222
package iso import ( "fmt" "github.com/mitchellh/multistep" vmwcommon "github.com/mitchellh/packer/builder/vmware/common" "github.com/mitchellh/packer/packer" "log" ) // stepRemoteUpload uploads some thing from the state bag to a remote driver // (if it can) and stores that new remote path into the state bag. type stepRemoteUpload struct { Key string Message string } func (s *stepRemoteUpload) Run(state multistep.StateBag) multistep.StepAction { driver := state.Get("driver").(vmwcommon.Driver) ui := state.Get("ui").(packer.Ui) remote, ok := driver.(RemoteDriver) if !ok { return multistep.ActionContinue } path, ok := state.Get(s.Key).(string) if !ok { return multistep.ActionContinue } ui.Say(s.Message) log.Printf("Remote uploading: %s", path) newPath, err := remote.UploadISO(path) if err != nil { err := fmt.Errorf("Error uploading file: %s", err) state.Put("error", err) ui.Error(err.Error()) return multistep.ActionHalt } state.Put(s.Key, newPath) return multistep.ActionContinue } func (s *stepRemoteUpload) Cleanup(state multistep.StateBag) { }
jsoriano/packer
builder/vmware/iso/step_remote_upload.go
GO
mpl-2.0
1,105
package app.intelehealth.client.models.pushRequestApiCall; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; import java.util.List; public class Person { @SerializedName("uuid") @Expose private String uuid; @SerializedName("gender") @Expose private String gender; @SerializedName("names") @Expose private List<Name> names = null; @SerializedName("birthdate") @Expose private String birthdate; @SerializedName("attributes") @Expose private List<Attribute> attributes = null; @SerializedName("addresses") @Expose private List<Address> addresses = null; public String getUuid() { return uuid; } public void setUuid(String uuid) { this.uuid = uuid; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } public List<Name> getNames() { return names; } public void setNames(List<Name> names) { this.names = names; } public String getBirthdate() { return birthdate; } public void setBirthdate(String birthdate) { this.birthdate = birthdate; } public List<Attribute> getAttributes() { return attributes; } public void setAttributes(List<Attribute> attributes) { this.attributes = attributes; } public List<Address> getAddresses() { return addresses; } public void setAddresses(List<Address> addresses) { this.addresses = addresses; } }
Intelehealth/Android-Mobile-Client
app/src/main/java/app/intelehealth/client/models/pushRequestApiCall/Person.java
Java
mpl-2.0
1,609
using Microsoft.EntityFrameworkCore; using Anabi.DataAccess.Ef.DbModels; using Microsoft.EntityFrameworkCore.Metadata.Builders; namespace Anabi.DataAccess.Ef.EntityConfigurators { public class AssetConfig : BaseEntityConfig<AssetDb> { public override void Configure(EntityTypeBuilder<AssetDb> builder) { builder.HasOne(a => a.Address) .WithMany(b => b.Assets) .HasForeignKey(k => k.AddressId) .OnDelete(DeleteBehavior.Restrict) .HasConstraintName("FK_Assets_Addresses"); builder.HasOne(k => k.Category) .WithMany(b => b.Assets) .HasForeignKey(k => k.CategoryId) .OnDelete(DeleteBehavior.Restrict) .HasConstraintName("FK_Assets_Categories") .IsRequired(); builder.HasOne(d => d.CurrentDecision) .WithMany(b => b.Assets) .HasForeignKey(k => k.DecisionId) .OnDelete(DeleteBehavior.Restrict) .HasConstraintName("FK_Assets_Decisions"); base.Configure(builder); } } }
code4romania/anabi-gestiune-api
Anabi.DataAccess.Ef/EntityConfigurators/AssetConfig.cs
C#
mpl-2.0
1,162
import { Mongo } from 'meteor/mongo'; const SurveyCaches = new Mongo.Collection('SurveyCaches'); SimpleSchema.debug = true; SurveyCaches.schema = new SimpleSchema({ title: { type: String, }, version: { type: Number, optional: true, autoValue() { return 2; }, }, createdAt: { type: Date, label: 'Created At', optional: true, autoValue() { let val; if (this.isInsert) { val = new Date(); } else if (this.isUpsert) { val = { $setOnInsert: new Date() }; } else { this.unset(); // Prevent user from supplying their own value } return val; }, }, updatedAt: { type: Date, label: 'Updated At', optional: true, autoValue() { let val; if (this.isUpdate) { val = new Date(); } return val; }, }, }); SurveyCaches.attachSchema(SurveyCaches.schema); export default SurveyCaches;
ctagroup/home-app
imports/api/surveys/surveyCaches.js
JavaScript
mpl-2.0
945
using Alex.Blocks.Materials; namespace Alex.Blocks.Minecraft { public class BlueOrchid : FlowerBase { public BlueOrchid() { Solid = false; Transparent = true; IsFullCube = false; BlockMaterial = Material.Plants; } } }
kennyvv/Alex
src/Alex/Blocks/Minecraft/BlueOrchid.cs
C#
mpl-2.0
241
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ export interface TimeZones { name: string; abbrev: string; offset: string; }
OpenEnergyDashboard/OED
src/client/app/types/timezone.ts
TypeScript
mpl-2.0
286
/*jslint unparam: true, browser: true, indent: 2 */ ;(function ($, window, document, undefined) { 'use strict'; Foundation.libs.dropdown = { name : 'dropdown', version : '4.3.2', settings : { activeClass: 'open', is_hover: false, opened: function(){}, closed: function(){} }, init : function (scope, method, options) { this.scope = scope || this.scope; Foundation.inherit(this, 'throttle scrollLeft data_options'); if (typeof method === 'object') { $.extend(true, this.settings, method); } if (typeof method !== 'string') { if (!this.settings.init) { this.events(); } return this.settings.init; } else { return this[method].call(this, options); } }, events : function () { var self = this; $(this.scope) .on('click.fndtn.dropdown', '[data-dropdown]', function (e) { var settings = $.extend({}, self.settings, self.data_options($(this))); e.preventDefault(); if (!settings.is_hover) self.toggle($(this)); }) .on('mouseenter', '[data-dropdown]', function (e) { var settings = $.extend({}, self.settings, self.data_options($(this))); if (settings.is_hover) self.toggle($(this)); }) .on('mouseleave', '[data-dropdown-content]', function (e) { var target = $('[data-dropdown="' + $(this).attr('id') + '"]'), settings = $.extend({}, self.settings, self.data_options(target)); if (settings.is_hover) self.close.call(self, $(this)); }) .on('opened.fndtn.dropdown', '[data-dropdown-content]', this.settings.opened) .on('closed.fndtn.dropdown', '[data-dropdown-content]', this.settings.closed); $(document).on('click.fndtn.dropdown touchstart.fndtn.dropdown', function (e) { var parent = $(e.target).closest('[data-dropdown-content]'); if ($(e.target).data('dropdown') || $(e.target).parent().data('dropdown')) { return; } if (!($(e.target).data('revealId')) && (parent.length > 0 && ($(e.target).is('[data-dropdown-content]') || $.contains(parent.first()[0], e.target)))) { e.stopPropagation(); return; } self.close.call(self, $('[data-dropdown-content]')); }); $(window).on('resize.fndtn.dropdown', self.throttle(function () { self.resize.call(self); }, 50)).trigger('resize'); this.settings.init = true; }, close: function (dropdown) { var self = this; dropdown.each(function () { if ($(this).hasClass(self.settings.activeClass)) { $(this) .css(Foundation.rtl ? 'right':'left', '-99999px') .removeClass(self.settings.activeClass) .prev('[data-dropdown]') .removeClass(self.settings.activeClass); $(this).trigger('closed'); } }); }, open: function (dropdown, target) { this .css(dropdown .addClass(this.settings.activeClass), target); dropdown.prev('[data-dropdown]').addClass(this.settings.activeClass); dropdown.trigger('opened'); }, toggle : function (target) { var dropdown = $('#' + target.data('dropdown')); if (dropdown.length === 0) { // No dropdown found, not continuing return; } this.close.call(this, $('[data-dropdown-content]').not(dropdown)); if (dropdown.hasClass(this.settings.activeClass)) { this.close.call(this, dropdown); } else { this.close.call(this, $('[data-dropdown-content]')) this.open.call(this, dropdown, target); } }, resize : function () { var dropdown = $('[data-dropdown-content].open'), target = $("[data-dropdown='" + dropdown.attr('id') + "']"); if (dropdown.length && target.length) { this.css(dropdown, target); } }, css : function (dropdown, target) { var offset_parent = dropdown.offsetParent(); // if (offset_parent.length > 0 && /body/i.test(dropdown.offsetParent()[0].nodeName)) { var position = target.offset(); position.top -= offset_parent.offset().top; position.left -= offset_parent.offset().left; // } else { // var position = target.position(); // } if (this.small()) { dropdown.css({ position : 'absolute', width: '95%', 'max-width': 'none', top: position.top + this.outerHeight(target) }); dropdown.css(Foundation.rtl ? 'right':'left', '2.5%'); } else { if (!Foundation.rtl && $(window).width() > this.outerWidth(dropdown) + target.offset().left && !this.data_options(target).align_right) { var left = position.left; if (dropdown.hasClass('right')) { dropdown.removeClass('right'); } } else { if (!dropdown.hasClass('right')) { dropdown.addClass('right'); } var left = position.left - (this.outerWidth(dropdown) - this.outerWidth(target)); } dropdown.attr('style', '').css({ position : 'absolute', top: position.top + this.outerHeight(target), left: left }); } return dropdown; }, small : function () { return $(window).width() < 768 || $('html').hasClass('lt-ie9'); }, off: function () { $(this.scope).off('.fndtn.dropdown'); $('html, body').off('.fndtn.dropdown'); $(window).off('.fndtn.dropdown'); $('[data-dropdown-content]').off('.fndtn.dropdown'); this.settings.init = false; }, reflow : function () {} }; }(Foundation.zj, this, this.document));
Elfhir/apero-imac
static/js/foundation/foundation.dropdown.js
JavaScript
mpl-2.0
5,841
'use strict'; var inheritance = require('./../../helpers/inheritance'), Field = require('./field'); var FilterField = function(){}; inheritance.inherits(Field,FilterField); FilterField.prototype.isOpen = function(){ return this.world.helper.elementGetter(this._root,this._data.elements.body).isDisplayed(); }; FilterField.prototype.accordionSelf = function(status){ var _this=this; switch(status){ case 'open': return _this.isOpen() .then(function(is){ if(!is){ return _this._root.scrollIntoView() .then(function(){ return _this._root.element(by.css('span.filter__sub-title')).click(); }) .then(function(){ return _this.world.helper.elementGetter(_this._root,_this._data.elements.body).waitToBeCompletelyVisibleAndStable(); }); } }); case 'close': return _this.isOpen() .then(function(is){ if(is){ return _this._root.scrollIntoView() .then(function(){ return _this._root.element(by.css('span.filter__sub-title')).click(); }) .then(function(){ return _this.world.helper.elementGetter(_this._root,_this._data.elements.body).waitToBeHidden(); }); } }); default: throw new Error('Wrong status of slider: '+status); } }; module.exports = FilterField;
Ivan-Katovich/cms-protractor-fw
test/e2e/support/ui_elements/fields/filterField.js
JavaScript
mpl-2.0
1,775
define([ 'jquery', 'underscore', 'backbone', 'text!template/login.html', 'models/campus' ], function ($, _, Backbone, LoginTemplate, CampusModel) { var LoginView = Backbone.View.extend({ tagName: 'section', className: 'container', template: _.template(LoginTemplate), events: { 'submit #frm-login': 'frmLoginOnSubmit', 'click #chk-password': 'chkPasswordOnCheck' }, render: function () { this.el.innerHTML = this.template(); return this; }, frmLoginOnSubmit: function (e) { e.preventDefault(); var self = this; var hostName = self.$('#txt-hostname').val().trim(); var username = self.$('#txt-username').val().trim(); var password = self.$('#txt-password').val().trim(); if (!hostName) { return; } if (!username) { return; } if (!password) { return; } self.$('#btn-submit').prop('disabled', true); var checkingLogin = $.post(hostName + '/main/webservices/rest.php', { action: 'loginNewMessages', username: username, password: password }); $.when(checkingLogin).done(function (response) { if (!response.status) { self.$('#btn-submit').prop('disabled', false); return; } var campusModel = new CampusModel({ url: hostName, username: username, apiKey: response.apiKey }); var savingCampus = campusModel.save(); $.when(savingCampus).done(function () { window.location.reload(); }); $.when(savingCampus).fail(function () { self.$('#btn-submit').prop('disabled', false); }); }); $.when(checkingLogin).fail(function () { self.$('#btn-submit').prop('disabled', false); }); }, chkPasswordOnCheck: function (e) { var inputType = e.target.checked ? 'text' : 'password'; this.$('#txt-password').attr('type', inputType); } }); return LoginView; });
AngelFQC/fx-dev-edition
app/js/views/login.js
JavaScript
mpl-2.0
2,454
using System; namespace Consumer.Samples.Queries { public class DateIdQuery { public DateTime? StartDate { get; set; } public DateTime? EndDate { get; set; } public int? Id { get; set; } } }
zdenek-jelinek/SimpleSearchBuilder
Consumer/Samples/Queries/DateIdQuery.cs
C#
mpl-2.0
233
//Copyright (c) 2017 Finjin // //This file is part of Finjin Engine (finjin-engine). // //Finjin Engine 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. // //This Source Code Form is subject to the terms of the Mozilla Public //License, v. 2.0. If a copy of the MPL was not distributed with this //file, You can obtain one at http://mozilla.org/MPL/2.0/. //Includes---------------------------------------------------------------------- #include "FinjinPrecompiled.hpp" #include "XInputGameController.hpp" #include "finjin/common/Convert.hpp" #include "finjin/common/Math.hpp" #include "finjin/engine/GenericInputDevice.hpp" #include <Windows.h> #include <Xinput.h> using namespace Finjin::Engine; //Macros------------------------------------------------------------------------ #define XINPUT_AXIS_MAGNITUDE 32767 #define XINPUT_TRIGGER_MAGNITUDE 255 //Local functions--------------------------------------------------------------- static size_t XInputButtonToButtonIndex(WORD xinputButtonCode) { size_t buttonIndex = 0; for (xinputButtonCode >>= 1; xinputButtonCode != 0; xinputButtonCode >>= 1) buttonIndex++; return buttonIndex; } template <size_t count> void SetXInputButton(StaticVector<InputButton, count>& buttons, WORD xinputButton, const char* displayName, InputComponentSemantic semantic) { auto buttonIndex = XInputButtonToButtonIndex(xinputButton); assert(buttonIndex < buttons.size()); buttons[buttonIndex] .SetIndex(buttonIndex) .SetCode(xinputButton) .SetDisplayName(displayName) .SetSemantic(semantic) .Enable(true); } template <size_t count> void SetXInputAxis(StaticVector<InputAxis, count>& axes, size_t index, float minValue, float maxValue, float deadZone, const char* displayName, InputComponentSemantic semantic) { axes[index] .SetIndex(index) .SetMinMax(minValue, maxValue) .SetDeadZone(deadZone) .SetDisplayName(displayName) .SetSemantic(semantic) .SetProcessing(InputAxisProcessing::NORMALIZE); } static Utf8String XInputSubtypeToString(BYTE subtype) { #if _WIN32_WINNT >= _WIN32_WINNT_WIN8 switch (subtype) { case XINPUT_DEVSUBTYPE_GAMEPAD: return "xinput-gamepad"; case XINPUT_DEVSUBTYPE_WHEEL: return "xinput-wheel"; case XINPUT_DEVSUBTYPE_ARCADE_STICK: return "xinput-arcade-stick"; case XINPUT_DEVSUBTYPE_FLIGHT_STICK: return "xinput-flight-stick"; case XINPUT_DEVSUBTYPE_DANCE_PAD: return "xinput-dance-pad"; case XINPUT_DEVSUBTYPE_GUITAR: return "xinput-guitar"; case XINPUT_DEVSUBTYPE_GUITAR_ALTERNATE: return "xinput-guitar-alt"; case XINPUT_DEVSUBTYPE_DRUM_KIT: return "xinput-drum-kit"; case XINPUT_DEVSUBTYPE_GUITAR_BASS: return "xinput-guitar-bass"; case XINPUT_DEVSUBTYPE_ARCADE_PAD: return "xinput-arcade-pad"; default: return "xinput-gamepad"; } #else return "xinput-gamepad"; #endif } //Local types------------------------------------------------------------------- struct XInputGameController::Impl : public GenericInputDeviceImpl { using Super = GenericInputDeviceImpl; Impl() { this->index = 0; FINJIN_ZERO_ITEM(this->xinputState); } void Reset() { Super::Reset(); this->index = 0; FINJIN_ZERO_ITEM(this->xinputState); this->state.Reset(); } size_t index; XINPUT_CAPABILITIES xinputCapabilities; XINPUT_STATE xinputState; InputDeviceState<InputButton, InputAxis, InputPov, GameControllerConstants::MAX_BUTTON_COUNT, GameControllerConstants::MAX_AXIS_COUNT> state; std::array<HapticFeedback, 2> forceFeedback; //0 = left motor, 1 = right motor }; //Implementation---------------------------------------------------------------- //XInputGameController XInputGameController::XInputGameController() : impl(new Impl) { Reset(); } XInputGameController::~XInputGameController() { } void XInputGameController::Reset() { impl->Reset(); } bool XInputGameController::Create(size_t index) { impl->index = index; impl->instanceName = "XInput Game Controller "; impl->instanceName += Convert::ToString(impl->index + 1); impl->productName = "XInput Game Controller"; impl->displayName = impl->productName; BYTE subtype = XINPUT_DEVSUBTYPE_GAMEPAD; FINJIN_ZERO_ITEM(impl->xinputCapabilities); auto capsResult = XInputGetCapabilities(static_cast<DWORD>(impl->index), XINPUT_FLAG_GAMEPAD, &impl->xinputCapabilities); if (capsResult == 0) { subtype = impl->xinputCapabilities.SubType; impl->state.isConnected = true; XInputGetState(static_cast<DWORD>(impl->index), &impl->xinputState); } else { FINJIN_ZERO_ITEM(impl->xinputState); } impl->productDescriptor = XInputSubtypeToString(subtype); impl->instanceDescriptor = impl->productDescriptor; impl->instanceDescriptor += "-"; impl->instanceDescriptor += Convert::ToString(index); //Buttons impl->state.buttons.resize(sizeof(impl->xinputState.Gamepad.wButtons) * 8); //Button codes are irrengularly defined, so initialize all to disabled, then enable one by one for (auto& button : impl->state.buttons) button.Enable(false); SetXInputButton(impl->state.buttons, XINPUT_GAMEPAD_A, "A", InputComponentSemantic::ACCEPT); SetXInputButton(impl->state.buttons, XINPUT_GAMEPAD_B, "B", InputComponentSemantic::CANCEL); SetXInputButton(impl->state.buttons, XINPUT_GAMEPAD_X, "X", InputComponentSemantic::HANDBRAKE); SetXInputButton(impl->state.buttons, XINPUT_GAMEPAD_Y, "Y", InputComponentSemantic::CHANGE_VIEW); SetXInputButton(impl->state.buttons, XINPUT_GAMEPAD_LEFT_SHOULDER, "Left shoulder button", InputComponentSemantic::SHIFT_LEFT); SetXInputButton(impl->state.buttons, XINPUT_GAMEPAD_RIGHT_SHOULDER, "Right shoulder button", InputComponentSemantic::SHIFT_RIGHT); SetXInputButton(impl->state.buttons, XINPUT_GAMEPAD_LEFT_THUMB, "Left thumbstick button", InputComponentSemantic::STEER_TOGGLE); SetXInputButton(impl->state.buttons, XINPUT_GAMEPAD_RIGHT_THUMB, "Right thumbstick button", InputComponentSemantic::LOOK_TOGGLE); SetXInputButton(impl->state.buttons, XINPUT_GAMEPAD_START, "Start", InputComponentSemantic::SETTINGS); SetXInputButton(impl->state.buttons, XINPUT_GAMEPAD_BACK, "Back", InputComponentSemantic::SYSTEM_SETTINGS); SetXInputButton(impl->state.buttons, XINPUT_GAMEPAD_DPAD_UP, "D-pad up", InputComponentSemantic::TOGGLE_UP); SetXInputButton(impl->state.buttons, XINPUT_GAMEPAD_DPAD_DOWN, "D-pad down", InputComponentSemantic::TOGGLE_DOWN); SetXInputButton(impl->state.buttons, XINPUT_GAMEPAD_DPAD_LEFT, "D-pad left", InputComponentSemantic::TOGGLE_LEFT); SetXInputButton(impl->state.buttons, XINPUT_GAMEPAD_DPAD_RIGHT, "D-pad right", InputComponentSemantic::TOGGLE_RIGHT); //Axes impl->state.axes.resize(6); SetXInputAxis(impl->state.axes, 0, -XINPUT_AXIS_MAGNITUDE, XINPUT_AXIS_MAGNITUDE, XINPUT_GAMEPAD_LEFT_THUMB_DEADZONE, "Left thumbstick X", InputComponentSemantic::STEER_LEFT_RIGHT); SetXInputAxis(impl->state.axes, 1, -XINPUT_AXIS_MAGNITUDE, XINPUT_AXIS_MAGNITUDE, XINPUT_GAMEPAD_LEFT_THUMB_DEADZONE, "Left thumbstick Y", InputComponentSemantic::STEER_UP_DOWN); SetXInputAxis(impl->state.axes, 2, -XINPUT_AXIS_MAGNITUDE, XINPUT_AXIS_MAGNITUDE, XINPUT_GAMEPAD_RIGHT_THUMB_DEADZONE, "Right thumbstick X", InputComponentSemantic::LOOK_LEFT_RIGHT); SetXInputAxis(impl->state.axes, 3, -XINPUT_AXIS_MAGNITUDE, XINPUT_AXIS_MAGNITUDE, XINPUT_GAMEPAD_RIGHT_THUMB_DEADZONE, "Right thumbstick Y", InputComponentSemantic::LOOK_UP_DOWN); SetXInputAxis(impl->state.axes, 4, 0, XINPUT_TRIGGER_MAGNITUDE, XINPUT_GAMEPAD_TRIGGER_THRESHOLD, "Left trigger", InputComponentSemantic::BRAKE); SetXInputAxis(impl->state.axes, 5, 0, XINPUT_TRIGGER_MAGNITUDE, XINPUT_GAMEPAD_TRIGGER_THRESHOLD, "Right trigger", InputComponentSemantic::GAS); return true; } void XInputGameController::Destroy() { Reset(); } void XInputGameController::Update(SimpleTimeDelta elapsedTime, bool isFirstUpdate) { impl->state.connectionChanged = false; if (impl->state.isConnected) { if (XInputGetState(static_cast<DWORD>(impl->index), &impl->xinputState) == 0) { _AcceptUpdate(isFirstUpdate); _SetForce(); for (auto& forceFeedback : impl->forceFeedback) { if (forceFeedback.IsActive()) forceFeedback.Update(elapsedTime); } } else { //Became disconnected impl->state.isConnected = false; impl->state.connectionChanged = true; FINJIN_ZERO_ITEM(impl->xinputState); for (auto& button : impl->state.buttons) button.Update(false, isFirstUpdate); for (auto& axis : impl->state.axes) axis.Update(0, isFirstUpdate); StopHapticFeedback(); } } else { if (XInputGetCapabilities(static_cast<DWORD>(impl->index), XINPUT_FLAG_GAMEPAD, &impl->xinputCapabilities) == 0 && XInputGetState(static_cast<DWORD>(impl->index), &impl->xinputState) == 0) { //Became connected impl->state.isConnected = true; impl->state.connectionChanged = !isFirstUpdate && true; _AcceptUpdate(isFirstUpdate); } } } void XInputGameController::ClearChanged() { impl->state.ClearChanged(); } bool XInputGameController::IsConnected() const { return impl->state.isConnected; } bool XInputGameController::GetConnectionChanged() const { return impl->state.connectionChanged; } size_t XInputGameController::GetIndex() const { return impl->index; } const Utf8String& XInputGameController::GetDisplayName() const { return impl->displayName; } void XInputGameController::SetDisplayName(const Utf8String& value) { impl->displayName = value; } InputDeviceSemantic XInputGameController::GetSemantic() const { return impl->semantic; } void XInputGameController::SetSemantic(InputDeviceSemantic value) { impl->semantic = value; } const Utf8String& XInputGameController::GetProductDescriptor() const { return impl->productDescriptor; } const Utf8String& XInputGameController::GetInstanceDescriptor() const { return impl->instanceDescriptor; } void XInputGameController::_AcceptUpdate(bool isFirstUpdate) { //Buttons for (WORD i = 0; i < impl->state.buttons.size(); i++) impl->state.buttons[i].Update((impl->xinputState.Gamepad.wButtons & (1 << i)) != 0, isFirstUpdate); //Axes impl->state.axes[0].Update(impl->xinputState.Gamepad.sThumbLX, isFirstUpdate); impl->state.axes[1].Update(impl->xinputState.Gamepad.sThumbLY, isFirstUpdate); impl->state.axes[2].Update(impl->xinputState.Gamepad.sThumbRX, isFirstUpdate); impl->state.axes[3].Update(impl->xinputState.Gamepad.sThumbRY, isFirstUpdate); impl->state.axes[4].Update(impl->xinputState.Gamepad.bLeftTrigger, isFirstUpdate); impl->state.axes[5].Update(impl->xinputState.Gamepad.bRightTrigger, isFirstUpdate); } size_t XInputGameController::GetAxisCount() const { return impl->state.axes.size(); } InputAxis* XInputGameController::GetAxis(size_t axisIndex) { return &impl->state.axes[axisIndex]; } size_t XInputGameController::GetButtonCount() const { return impl->state.buttons.size(); } InputButton* XInputGameController::GetButton(size_t buttonIndex) { return &impl->state.buttons[buttonIndex]; } size_t XInputGameController::GetPovCount() const { return 0; } InputPov* XInputGameController::GetPov(size_t povIndex) { return nullptr; } size_t XInputGameController::GetLocatorCount() const { return 0; } InputLocator* XInputGameController::GetLocator(size_t locatorIndex) { return nullptr; } void XInputGameController::AddHapticFeedback(const HapticFeedback* forces, size_t count) { for (size_t forceIndex = 0; forceIndex < count; forceIndex++) { auto& force = forces[forceIndex]; switch (force.motorIndex) { case 0: impl->forceFeedback[0] = force; break; case 1: impl->forceFeedback[1] = force; break; case -1: impl->forceFeedback[0] = impl->forceFeedback[1] = force; break; } } } void XInputGameController::StopHapticFeedback() { //Don't pause the game or deactive the window without first stopping rumble otherwise the controller will continue to rumble XINPUT_VIBRATION vibration; vibration.wLeftMotorSpeed = 0; vibration.wRightMotorSpeed = 0; XInputSetState(static_cast<DWORD>(impl->index), &vibration); impl->forceFeedback[0].Reset(); impl->forceFeedback[1].Reset(); } size_t XInputGameController::CreateGameControllers(XInputGameController* gameControllers, size_t gameControllerCount) { gameControllerCount = std::min(gameControllerCount, (size_t)XUSER_MAX_COUNT); for (size_t gameControllerIndex = 0; gameControllerIndex < gameControllerCount; gameControllerIndex++) gameControllers[gameControllerIndex].Create(gameControllerIndex); return gameControllerCount; } size_t XInputGameController::UpdateGameControllers(SimpleTimeDelta elapsedTime, XInputGameController* gameControllers, size_t gameControllerCount) { for (size_t gameControllerIndex = 0; gameControllerIndex < gameControllerCount; gameControllerIndex++) gameControllers[gameControllerIndex].Update(elapsedTime, false); return gameControllerCount; } XInputGameController* XInputGameController::GetGameControllerByInstanceDescriptor(XInputGameController* gameControllers, size_t gameControllerCount, const Utf8String& descriptor) { for (size_t gameControllerIndex = 0; gameControllerIndex < gameControllerCount; gameControllerIndex++) { if (gameControllers[gameControllerIndex].GetInstanceDescriptor() == descriptor) return &gameControllers[gameControllerIndex]; } return nullptr; } XInputGameController* XInputGameController::GetGameControllerByIndex(XInputGameController* gameControllers, size_t gameControllerCount, size_t deviceIndex) { return &gameControllers[deviceIndex]; } void XInputGameController::_SetForce() { XINPUT_VIBRATION vibration; vibration.wLeftMotorSpeed = RoundToInt((impl->forceFeedback[0].duration > 0 ? impl->forceFeedback[0].intensity : 0.0f) * 65535); vibration.wRightMotorSpeed = RoundToInt((impl->forceFeedback[1].duration > 0 ? impl->forceFeedback[1].intensity : 0.0f) * 65535); XInputSetState(static_cast<DWORD>(impl->index), &vibration); }
finjin/finjin-engine
cpp/library/src/finjin/engine/internal/input/xinput/XInputGameController.cpp
C++
mpl-2.0
14,842
// // Aspia Project // Copyright (C) 2018 Dmitry Chapyshev <dmitry@aspia.ru> // // 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 <https://www.gnu.org/licenses/>. // #include "console/update_settings_dialog.h" #include "build/build_config.h" #include "console/console_settings.h" namespace console { UpdateSettingsDialog::UpdateSettingsDialog(QWidget* parent) : QDialog(parent) { ui.setupUi(this); Settings settings; ui.checkbox_check_updates->setChecked(settings.checkUpdates()); ui.edit_server->setText(settings.updateServer()); if (settings.updateServer() == DEFAULT_UPDATE_SERVER) { ui.checkbox_custom_server->setChecked(false); ui.edit_server->setEnabled(false); } else { ui.checkbox_custom_server->setChecked(true); ui.edit_server->setEnabled(true); } connect(ui.checkbox_custom_server, &QCheckBox::toggled, [this](bool checked) { ui.edit_server->setEnabled(checked); if (!checked) ui.edit_server->setText(DEFAULT_UPDATE_SERVER); }); connect(ui.button_box, &QDialogButtonBox::clicked, [this](QAbstractButton* button) { if (ui.button_box->standardButton(button) == QDialogButtonBox::Ok) { Settings settings; settings.setCheckUpdates(ui.checkbox_check_updates->isChecked()); settings.setUpdateServer(ui.edit_server->text()); } close(); }); } UpdateSettingsDialog::~UpdateSettingsDialog() = default; } // namespace console
aspia-org/remote-desktop
source/console/update_settings_dialog.cc
C++
mpl-2.0
2,097
<?php /** * Copyright (C) 2014 Ready Business System * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ namespace Rbs\Workflow\Documents; use Change\Workflow\Validator; /** * @name \Rbs\Workflow\Documents\Workflow */ class Workflow extends \Compilation\Rbs\Workflow\Documents\Workflow implements \Change\Workflow\Interfaces\Workflow { /** * @var array */ protected $items; /** * Return Short name * @return string */ public function getName() { return $this->getLabel(); } /** * @return \DateTime|null */ public function getStartDate() { return $this->getStartActivation(); } /** * @return \DateTime|null */ public function getEndDate() { return $this->getEndActivation(); } /** * @return string */ public function startTask() { return $this->getStartTask(); } /** * Return all Workflow items defined * @return \Change\Workflow\Interfaces\WorkflowItem[] */ public function getItems() { if ($this->items === null) { $s = new \Rbs\Workflow\Std\Serializer(); $this->items = $s->unserializeItems($this, $this->getItemsData()); } return $this->items; } /** * @param boolean $identify * @return \Rbs\Workflow\Std\Place */ public function getNewPlace($identify = true) { $place = new \Rbs\Workflow\Std\Place($this); if ($identify) { $place->setId($this->nextId()); $this->addItem($place); } return $place; } /** * @param boolean $identify * @return \Rbs\Workflow\Std\Transition */ public function getNewTransition($identify = true) { $transition = new \Rbs\Workflow\Std\Transition($this); if ($identify) { $transition->setId($this->nextId()); $this->addItem($transition); } return $transition; } /** * @param boolean $identify * @return \Rbs\Workflow\Std\Arc */ public function getNewArc($identify = true) { $arc = new \Rbs\Workflow\Std\Arc($this); if ($identify) { $arc->setId($this->nextId()); $this->addItem($arc); } return $arc; } /** * @return integer */ public function nextId() { $lastId = 0; foreach ($this->getItems() as $item) { if ($item instanceof \Change\Workflow\Interfaces\WorkflowItem) { $lastId = max($lastId, $item->getId()); } } return $lastId + 1; } /** * @param integer $id * @return \Change\Workflow\Interfaces\WorkflowItem|null */ public function getItemById($id) { if ($id !== null) { foreach ($this->getItems() as $item) { if ($item instanceof \Change\Workflow\Interfaces\WorkflowItem && $item->getId() === $id) { return $item; } } } return null; } /** * @param \Change\Workflow\Interfaces\WorkflowItem $item * @throws \RuntimeException * @return $this */ public function addItem(\Change\Workflow\Interfaces\WorkflowItem $item) { $items = $this->getItems(); if (!in_array($item, $items, true)) { if ($item->getWorkflow() !== $this) { throw new \RuntimeException('Invalid item Workflow', 999999); } if (!$item->getId()) { throw new \RuntimeException('Empty item Id', 999999); } if (!is_int($item->getId()) || $this->getItemById($item->getId()) !== null) { throw new \RuntimeException('Invalid item Id', 999999); } $items[] = $item; $this->setItems($items); } return $this; } /** * @param \Change\Workflow\Interfaces\WorkflowItem[] $items */ protected function setItems(array $items) { $this->items = $items; } /** * @return $this */ protected function serializeItems() { if ($this->items !== null) { $s = new \Rbs\Workflow\Std\Serializer(); $array = $s->serializeItems($this->items); $this->setItemsData(count($array) ? $array : null); } return $this; } /** * @return boolean */ public function isValid() { $validator = new Validator(); try { $validator->isValid($this); } catch (\Exception $e) { $this->setErrors($e->getMessage()); return false; } $this->setErrors(null); return true; } public function reset() { parent::reset(); $this->items = null; } protected function onCreate() { $this->serializeItems(); } protected function onUpdate() { $this->serializeItems(); } /** * @return \Rbs\Workflow\Documents\WorkflowInstance */ public function createWorkflowInstance() { /* @var $workflowInstance \Rbs\Workflow\Documents\WorkflowInstance */ $workflowInstance = $this->getDocumentManager()->getNewDocumentInstanceByModelName('Rbs_Workflow_WorkflowInstance'); $workflowInstance->setWorkflow($this); return $workflowInstance; } /** * @param \Change\Documents\Events\Event $event */ public function onDefaultUpdateRestResult(\Change\Documents\Events\Event $event) { parent::onDefaultUpdateRestResult($event); $document = $event->getDocument(); if (!$document instanceof Workflow) { return; } $restResult = $event->getParam('restResult'); if ($restResult instanceof \Change\Http\Rest\V1\Resources\DocumentResult) { $restResult->removeRelAction('delete'); } elseif ($restResult instanceof \Change\Http\Rest\V1\Resources\DocumentLink) { $restResult->removeRelAction('delete'); } } }
intportg/Change
Plugins/Modules/Rbs/Workflow/Documents/Workflow.php
PHP
mpl-2.0
5,317
const AWS = require('aws-sdk'); const s3 = new AWS.S3(); const conf = require('./config'); const { tmpdir } = require('os'); const fs = require('fs'); const path = require('path'); const mozlog = require('./log'); const log = mozlog('send.storage'); const redis = require('redis'); const redis_client = redis.createClient({ host: conf.redis_host, connect_timeout: 10000 }); redis_client.on('error', err => { log.error('Redis:', err); }); let tempDir = null; if (conf.s3_bucket) { module.exports = { filename: filename, exists: exists, ttl: ttl, length: awsLength, get: awsGet, set: awsSet, setField: setField, delete: awsDelete, forceDelete: awsForceDelete, ping: awsPing, flushall: flushall, quit: quit, metadata }; } else { tempDir = fs.mkdtempSync(`${tmpdir()}${path.sep}send-`); log.info('tempDir', tempDir); module.exports = { filename: filename, exists: exists, ttl: ttl, length: localLength, get: localGet, set: localSet, setField: setField, delete: localDelete, forceDelete: localForceDelete, ping: localPing, flushall: flushall, quit: quit, metadata }; } function flushall() { redis_client.flushdb(); } function quit() { redis_client.quit(); } function metadata(id) { return new Promise((resolve, reject) => { redis_client.hgetall(id, (err, reply) => { if (err || !reply) { return reject(err); } resolve(reply); }); }); } function ttl(id) { return new Promise((resolve, reject) => { redis_client.ttl(id, (err, reply) => { if (err || !reply) { return reject(err); } resolve(reply * 1000); }); }); } function filename(id) { return new Promise((resolve, reject) => { redis_client.hget(id, 'filename', (err, reply) => { if (err || !reply) { return reject(); } resolve(reply); }); }); } function exists(id) { return new Promise((resolve, reject) => { redis_client.exists(id, (rediserr, reply) => { if (reply === 1 && !rediserr) { resolve(); } else { reject(rediserr); } }); }); } function setField(id, key, value) { redis_client.hset(id, key, value); } function localLength(id) { return new Promise((resolve, reject) => { try { resolve(fs.statSync(path.join(tempDir, id)).size); } catch (err) { reject(); } }); } function localGet(id) { return fs.createReadStream(path.join(tempDir, id)); } function localSet(newId, file, filename, meta) { return new Promise((resolve, reject) => { const filepath = path.join(tempDir, newId); const fstream = fs.createWriteStream(filepath); file.pipe(fstream); file.on('limit', () => { file.unpipe(fstream); fstream.destroy(new Error('limit')); }); fstream.on('finish', () => { redis_client.hmset(newId, meta); redis_client.expire(newId, conf.expire_seconds); log.info('localSet:', 'Upload Finished of ' + newId); resolve(meta.delete); }); fstream.on('error', err => { log.error('localSet:', 'Failed upload of ' + newId); fs.unlinkSync(filepath); reject(err); }); }); } function localDelete(id, delete_token) { return new Promise((resolve, reject) => { redis_client.hget(id, 'delete', (err, reply) => { if (!reply || delete_token !== reply) { reject(); } else { redis_client.del(id); log.info('Deleted:', id); resolve(fs.unlinkSync(path.join(tempDir, id))); } }); }); } function localForceDelete(id) { return new Promise((resolve, reject) => { redis_client.del(id); resolve(fs.unlinkSync(path.join(tempDir, id))); }); } function localPing() { return new Promise((resolve, reject) => { redis_client.ping(err => { return err ? reject() : resolve(); }); }); } function awsLength(id) { const params = { Bucket: conf.s3_bucket, Key: id }; return new Promise((resolve, reject) => { s3.headObject(params, function(err, data) { if (!err) { resolve(data.ContentLength); } else { reject(); } }); }); } function awsGet(id) { const params = { Bucket: conf.s3_bucket, Key: id }; try { return s3.getObject(params).createReadStream(); } catch (err) { return null; } } function awsSet(newId, file, filename, meta) { const params = { Bucket: conf.s3_bucket, Key: newId, Body: file }; let hitLimit = false; const upload = s3.upload(params); file.on('limit', () => { hitLimit = true; upload.abort(); }); return upload.promise().then( () => { redis_client.hmset(newId, meta); redis_client.expire(newId, conf.expire_seconds); }, err => { if (hitLimit) { throw new Error('limit'); } else { throw err; } } ); } function awsDelete(id, delete_token) { return new Promise((resolve, reject) => { redis_client.hget(id, 'delete', (err, reply) => { if (!reply || delete_token !== reply) { reject(); } else { const params = { Bucket: conf.s3_bucket, Key: id }; s3.deleteObject(params, function(err, _data) { redis_client.del(id); err ? reject(err) : resolve(err); }); } }); }); } function awsForceDelete(id) { return new Promise((resolve, reject) => { const params = { Bucket: conf.s3_bucket, Key: id }; s3.deleteObject(params, function(err, _data) { redis_client.del(id); err ? reject(err) : resolve(); }); }); } function awsPing() { return localPing().then(() => s3.headBucket({ Bucket: conf.s3_bucket }).promise() ); }
dannycoates/chooloo
server/storage.js
JavaScript
mpl-2.0
5,806
# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. from socorro.lib import datetimeutil from socorro.unittest.external.es.base import ( ElasticsearchTestCase, SuperSearchWithFields, minimum_es_version, ) # Uncomment these lines to decrease verbosity of the elasticsearch library # while running unit tests. # import logging # logging.getLogger('elasticsearch').setLevel(logging.ERROR) # logging.getLogger('requests').setLevel(logging.ERROR) class IntegrationTestAnalyzers(ElasticsearchTestCase): """Test the custom analyzers we create in our indices. """ def setUp(self): super(IntegrationTestAnalyzers, self).setUp() self.api = SuperSearchWithFields(config=self.config) self.now = datetimeutil.utc_now() @minimum_es_version('1.0') def test_semicolon_keywords(self): """Test the analyzer called `semicolon_keywords`. That analyzer creates tokens (terms) by splitting the input on semicolons (;) only. """ self.index_crash({ 'date_processed': self.now, 'app_init_dlls': '/path/to/dll;;foo;C:\\bar\\boo', }) self.index_crash({ 'date_processed': self.now, 'app_init_dlls': '/path/to/dll;D:\\bar\\boo', }) self.refresh_index() res = self.api.get( app_init_dlls='/path/to/dll', _facets=['app_init_dlls'], ) assert res['total'] == 2 assert 'app_init_dlls' in res['facets'] facet_terms = [x['term'] for x in res['facets']['app_init_dlls']] assert '/path/to/dll' in facet_terms assert 'c:\\bar\\boo' in facet_terms assert 'foo' in facet_terms
Tayamarn/socorro
socorro/unittest/external/es/test_analyzers.py
Python
mpl-2.0
1,852
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ "use strict"; var fs = require("fs"); var path = require("path"); var utils = require("../utils"); var chai = require("chai"); var expect = chai.expect; var exec = utils.exec; var simpleAddonPath = path.join(__dirname, "..", "fixtures", "simple-addon"); describe("jpm xpi", function () { beforeEach(utils.setup); afterEach(utils.tearDown); it("creates a xpi of the simple-addon", function (done) { var proc = exec("xpi", { addonDir: simpleAddonPath }); proc.on("close", function () { var xpiPath = path.join(simpleAddonPath, "@simple-addon-1.0.0.xpi"); utils.unzipTo(xpiPath, utils.tmpOutputDir).then(function () { utils.compareDirs(simpleAddonPath, utils.tmpOutputDir); fs.unlink(xpiPath); done(); }); }); }); });
matraska23/jpm
test/functional/test.xpi.js
JavaScript
mpl-2.0
987
"""Django module for the OS2datascanner project."""
os2webscanner/os2webscanner
django-os2webscanner/os2webscanner/__init__.py
Python
mpl-2.0
53
<?php include_once 'include/Zend/Json.php'; include_once 'vtlib/Vtiger/Module.php'; include_once 'include/utils/VtlibUtils.php'; include_once 'include/Webservices/Create.php'; include_once 'include/QueryGenerator/QueryGenerator.php'; function do_users4entities($time_start) { global $log_active, $adb; echo "\n==========================================================\n"; $import_result = array(); $modifiedby_id = 1; $import_result['records_created']=0; $import_result['records_updated']=0; // LEADS $sql = get_sql4leads(); $result = $adb->query($sql); while($row=$adb->fetchByAssoc($result)) { echo "Processing lead ".$row['lead_no']." with id ".$row['crmid']."\n"; $user_id = get_agent4location(trim($row['state']),trim($row['code']),trim($row['city']), $row['smownerid'] ); update_user4entity($row['crmid'],$row['smownerid'] , $user_id, $modifiedby_id); $import_result['records_updated']++; } // ACCOUNTS $sql = get_sql4accounts(); $result = $adb->query($sql); while($row=$adb->fetchByAssoc($result)) { echo "Processing account ".$row['account_no']." with id ".$row['crmid']."\n"; $user_id = get_agent4location(trim($row['bill_state']),trim($row['bill_code']),trim($row['bill_city']), $row['smownerid'] ); update_user4entity($row['crmid'],$row['smownerid'] , $user_id, $modifiedby_id); $import_result['records_updated']++; } // CONTACTS $sql = get_sql4contacts(); $result = $adb->query($sql); while($row=$adb->fetchByAssoc($result)) { echo "Processing contact ".$row['contact_no']." with id ".$row['crmid']."\n"; $user_id = get_agent4location(trim($row['bill_state']),trim($row['bill_code']),trim($row['bill_city']), $row['smownerid'] ); update_user4entity($row['crmid'],$row['smownerid'] , $user_id, $modifiedby_id); $import_result['records_updated']++; } return $import_result; } function update_user4entity($entity_id,$previous_owner_id, $user_id,$modifiedby_id) { global $adb,$table_prefix; $sql = "UPDATE ".$table_prefix."_crmentity SET ".$table_prefix."_crmentity.smownerid = ".$user_id." , ".$table_prefix."_crmentity.modifiedby = ".$modifiedby_id." , ".$table_prefix."_crmentity.modifiedtime = GETDATE() WHERE ".$table_prefix."_crmentity.crmid = ".$entity_id." AND ".$table_prefix."_crmentity.smownerid = ".$previous_owner_id." "; $result = $adb->query($sql); } function get_sql4leads() { global $adb,$table_prefix; $sql = "SELECT ".$table_prefix."_crmentity.crmid, ".$table_prefix."_crmentity.setype, ".$table_prefix."_crmentity.smownerid, ".$table_prefix."_crmentity.smcreatorid, ".$table_prefix."_crmentity.createdtime, ".$table_prefix."_crmentity.description, ".$table_prefix."_leaddetails.company, ".$table_prefix."_leaddetails.email, ".$table_prefix."_leaddetails.firstname, ".$table_prefix."_leaddetails.lastname, ".$table_prefix."_leaddetails.lead_no, ".$table_prefix."_leadaddress.city, ".$table_prefix."_leadaddress.code, ".$table_prefix."_leadaddress.country, ".$table_prefix."_leadaddress.state FROM ".$table_prefix."_crmentity JOIN ".$table_prefix."_leaddetails on ".$table_prefix."_leaddetails.leadid = ".$table_prefix."_crmentity.crmid and ".$table_prefix."_leaddetails.converted = 0 JOIN ".$table_prefix."_leadaddress on ".$table_prefix."_leadaddress.leadaddressid = ".$table_prefix."_crmentity.crmid AND ".$table_prefix."_leadaddress.country like 'IT%' WHERE ".$table_prefix."_crmentity.deleted = 0 and ".$table_prefix."_crmentity.setype = 'Leads' and ".$table_prefix."_crmentity.smownerid in (0,9,167)"; return $sql; } function get_sql4accounts() { global $adb,$table_prefix; $sql = "SELECT ".$table_prefix."_crmentity.crmid, ".$table_prefix."_crmentity.setype, ".$table_prefix."_crmentity.smownerid, ".$table_prefix."_crmentity.smcreatorid, ".$table_prefix."_crmentity.createdtime, ".$table_prefix."_crmentity.description, ".$table_prefix."_account.accountname, ".$table_prefix."_account.account_no, ".$table_prefix."_account.email1, ".$table_prefix."_accountbillads.bill_country, ".$table_prefix."_accountbillads.bill_state, ".$table_prefix."_accountbillads.bill_code, ".$table_prefix."_accountbillads.bill_city FROM ".$table_prefix."_crmentity JOIN ".$table_prefix."_account on ".$table_prefix."_account.accountid = ".$table_prefix."_crmentity.crmid JOIN ".$table_prefix."_accountbillads on ".$table_prefix."_accountbillads.accountaddressid = ".$table_prefix."_crmentity.crmid AND ".$table_prefix."_accountbillads.bill_country like 'IT%' WHERE ".$table_prefix."_crmentity.deleted = 0 AND ".$table_prefix."_crmentity.setype = 'Accounts' AND ".$table_prefix."_crmentity.smownerid in (0,9,167)"; return $sql; } function get_sql4contacts() { global $adb,$table_prefix; $sql = "SELECT ".$table_prefix."_crmentity.crmid, ".$table_prefix."_crmentity.setype, ".$table_prefix."_crmentity.smcreatorid, ".$table_prefix."_crmentity.smownerid, ".$table_prefix."_crmentity.createdtime, ".$table_prefix."_crmentity.description, ".$table_prefix."_contactdetails.firstname, ".$table_prefix."_contactdetails.lastname, ".$table_prefix."_contactdetails.contact_no, ".$table_prefix."_contactdetails.email, ".$table_prefix."_contactdetails.accountid, ".$table_prefix."_accountbillads.bill_country, ".$table_prefix."_accountbillads.bill_state, ".$table_prefix."_accountbillads.bill_code, ".$table_prefix."_accountbillads.bill_city FROM ".$table_prefix."_crmentity JOIN ".$table_prefix."_contactdetails on ".$table_prefix."_contactdetails.contactid = ".$table_prefix."_crmentity.crmid JOIN ".$table_prefix."_accountbillads on ".$table_prefix."_accountbillads.accountaddressid = ".$table_prefix."_contactdetails.accountid AND ".$table_prefix."_accountbillads.bill_country like 'IT%' JOIN ".$table_prefix."_crmentity as acc_entity on acc_entity.crmid = ".$table_prefix."_accountbillads.accountaddressid and acc_entity.deleted = 0 WHERE ".$table_prefix."_crmentity.deleted = 0 and ".$table_prefix."_crmentity.setype = 'Contacts' and ".$table_prefix."_crmentity.smownerid in (0,9,167)"; return $sql; } function get_agent4location($state,$code,$city, $previous_owner_id ) { global $adb,$table_prefix, $log_active; $agent_id = $previous_owner_id; $b_Found = false; if(!empty($city) && !$b_Found) { $sql = "SELECT Agente, ".$table_prefix."_users.id , COUNT(Agente) FROM tmp_assegnazione_agenti JOIN ".$table_prefix."_users ON ".$table_prefix."_users.user_name = Agente WHERE Comune like '".$city."%' GROUP BY Agente, ".$table_prefix."_users.id"; $result = $adb->query($sql); while($row=$adb->fetchByAssoc($result)) { $b_Found = true; $agent_id = $row['id']; echo "\tFound ".$agent_id." for city=".$city."\n"; break; } } if(!empty($code) && !$b_Found) { $sql = "SELECT Agente, ".$table_prefix."_users.id , COUNT(Agente) FROM tmp_assegnazione_agenti JOIN ".$table_prefix."_users ON ".$table_prefix."_users.user_name = Agente WHERE Cap = '".$code."' GROUP BY Agente, ".$table_prefix."_users.id"; $result = $adb->query($sql); while($row=$adb->fetchByAssoc($result)) { $b_Found = true; $agent_id = $row['id']; echo "\tFound ".$agent_id." for code=".$code."\n"; break; } } if(!empty($state) && !$b_Found) { $sql = "SELECT Agente, ".$table_prefix."_users.id , COUNT(Agente) FROM tmp_assegnazione_agenti JOIN ".$table_prefix."_users ON ".$table_prefix."_users.user_name = Agente WHERE Provincia = '".$state."' GROUP BY Agente, ".$table_prefix."_users.id"; $result = $adb->query($sql); while($row=$adb->fetchByAssoc($result)) { $b_Found = true; $agent_id = $row['id']; echo "\tFound ".$agent_id." for state=".$state."\n"; break; } } if(!$b_Found) echo "\tNothing found for ".$city." - ".$code." (".$state.") , I'll keep owner with id = ".$agent_id."\n"; return $agent_id; } ?>
andreadanzi/rotho_dev
plugins/erpconnector/users4entities/users4entities_functions.php
PHP
mpl-2.0
8,018
package models.message; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import models.SecureTable; import org.codehaus.jackson.annotate.JsonProperty; import com.alvazan.orm.api.z8spi.meta.DboTableMeta; /** */ @XmlRootElement @XmlAccessorType(XmlAccessType.FIELD) public class StreamModule { @JsonProperty("module") @XmlElement(name="module") public String module; @JsonProperty("params") @XmlElement(name="params") public Map<String, String> params = new HashMap<String, String>(); //I want to do the composite pattern and push this field down into the "Container" while StreamModule is the "Component" of that pattern //but that would not work as unmarshalling the json would break since parser does not know to parse to StreamModule or the Container type which //I had previously called StreamAggregation so this field is only used for the Container type @JsonProperty("childStreams") @XmlElement(name="childStreams") public List<StreamModule> streams = new ArrayList<StreamModule>(); public String getModule() { return module; } public void setModule(String module) { this.module = module; } public Map<String, String> getParams() { return params; } public void setParams(Map<String, String> params) { this.params = params; } public List<StreamModule> getStreams() { return streams; } public void setStreams(List<StreamModule> streams) { this.streams = streams; } @Override public String toString() { return "module=" + module; } } // Register
deanhiller/databus
webapp/app/models/message/StreamModule.java
Java
mpl-2.0
1,764
// Copyright (c) 2016, 2018, 2021, Oracle and/or its affiliates. All rights reserved. // This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license. // Code generated. DO NOT EDIT. // Oracle Cloud AI Services API // // OCI AI Service solutions can help Enterprise customers integrate AI into their products immediately by using our proven, // pre-trained/custom models or containers, and without a need to set up in house team of AI and ML experts. // This allows enterprises to focus on business drivers and development work rather than AI/ML operations, shortening the time to market. // package aianomalydetection import ( "encoding/json" "github.com/oracle/oci-go-sdk/v46/common" ) // DataSourceDetailsInflux Data Source details for influx. type DataSourceDetailsInflux struct { VersionSpecificDetails InfluxDetails `mandatory:"true" json:"versionSpecificDetails"` // Username for connection to Influx UserName *string `mandatory:"true" json:"userName"` // Password Secret Id for the influx connection PasswordSecretId *string `mandatory:"true" json:"passwordSecretId"` // Measurement name for influx MeasurementName *string `mandatory:"true" json:"measurementName"` // public IP address and port to influx DB Url *string `mandatory:"true" json:"url"` } func (m DataSourceDetailsInflux) String() string { return common.PointerString(m) } // MarshalJSON marshals to json representation func (m DataSourceDetailsInflux) MarshalJSON() (buff []byte, e error) { type MarshalTypeDataSourceDetailsInflux DataSourceDetailsInflux s := struct { DiscriminatorParam string `json:"dataSourceType"` MarshalTypeDataSourceDetailsInflux }{ "INFLUX", (MarshalTypeDataSourceDetailsInflux)(m), } return json.Marshal(&s) } // UnmarshalJSON unmarshals from json func (m *DataSourceDetailsInflux) UnmarshalJSON(data []byte) (e error) { model := struct { VersionSpecificDetails influxdetails `json:"versionSpecificDetails"` UserName *string `json:"userName"` PasswordSecretId *string `json:"passwordSecretId"` MeasurementName *string `json:"measurementName"` Url *string `json:"url"` }{} e = json.Unmarshal(data, &model) if e != nil { return } var nn interface{} nn, e = model.VersionSpecificDetails.UnmarshalPolymorphicJSON(model.VersionSpecificDetails.JsonData) if e != nil { return } if nn != nil { m.VersionSpecificDetails = nn.(InfluxDetails) } else { m.VersionSpecificDetails = nil } m.UserName = model.UserName m.PasswordSecretId = model.PasswordSecretId m.MeasurementName = model.MeasurementName m.Url = model.Url return }
oracle/terraform-provider-baremetal
vendor/github.com/oracle/oci-go-sdk/v46/aianomalydetection/data_source_details_influx.go
GO
mpl-2.0
2,844
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Models { /// <summary> /// 订单状态 /// </summary> public enum OrderState { /// <summary> /// 已提交 /// </summary> Submitted = 10, /// <summary> /// 等待付款 /// </summary> WaitPaying = 30, /// <summary> /// 已付款 /// </summary> Confirming = 50 } }
tst20170901/test2
Model/OrderState.cs
C#
mpl-2.0
485
import querystring from 'querystring' import SlackRTM from './SlackRTM' import FetchService from 'shared/FetchService' import userStore from 'stores/user/userStore' import accountStore from 'stores/account/accountStore' import { remote, ipcRenderer } from 'electron' import uuid from 'uuid' import { WB_WCFETCH_SERVICE_TEXT_CLEANUP } from 'shared/ipcEvents' const BASE_URL = 'https://slack.com/api/auth.test#sync-channel' class SlackHTTP { /* **************************************************************************/ // Utils /* **************************************************************************/ /** * Rejects a call because the service has no authentication info * @param info: any information we have * @return promise - rejected */ static _rejectWithNoAuth (info) { return Promise.reject(new Error('Service missing authentication information')) } static _fetch (serviceId, url, partitionId, opts) { return Promise.race([ this._fetchRaw(serviceId, url, partitionId, opts), new Promise((resolve, reject) => { setTimeout(() => { reject(new Error('timeout')) }, 30000) }) ]) } static _fetchRaw (serviceId, url, partitionId, opts) { if (userStore.getState().wceSlackHTTPWcThread()) { const wcId = accountStore.getState().getWebcontentTabId(serviceId) if (wcId) { const wc = remote.webContents.fromId(wcId) if (wc && !wc.isDestroyed()) { let isSlack try { isSlack = (new window.URL(wc.getURL())).hostname.endsWith('slack.com') } catch (ex) { isSlack = false } if (isSlack) { return Promise.resolve() .then(() => new Promise((resolve, reject) => { const channel = uuid.v4() let ipcMessageHandler let destroyedHandler let navigationHandler ipcMessageHandler = (evt, args) => { if (args[0] === channel) { wc.removeListener('ipc-message', ipcMessageHandler) wc.removeListener('destroyed', destroyedHandler) wc.removeListener('did-start-navigation', navigationHandler) resolve(args[1]) } } destroyedHandler = () => { wc.removeListener('ipc-message', ipcMessageHandler) wc.removeListener('did-start-navigation', navigationHandler) reject(new Error('inloaderror')) } navigationHandler = () => { wc.removeListener('ipc-message', ipcMessageHandler) wc.removeListener('destroyed', destroyedHandler) wc.removeListener('did-start-navigation', navigationHandler) reject(new Error('inloaderror')) } wc.on('ipc-message', ipcMessageHandler) wc.on('destroyed', destroyedHandler) wc.on('did-start-navigation', navigationHandler) wc.send('WB_WCFETCH_SERVICE_TEXT_RUNNER', channel, url, opts) })) .then( (res) => { ipcRenderer.send(WB_WCFETCH_SERVICE_TEXT_CLEANUP, BASE_URL, partitionId) return Promise.resolve({ status: res.status, ok: res.ok, text: () => Promise.resolve(res.body), json: () => Promise.resolve(JSON.parse(res.body)) }) }, (_err) => { return FetchService.wcRequest(BASE_URL, url, partitionId, opts) } ) } } } return FetchService.wcRequest(BASE_URL, url, partitionId, opts) } else { return FetchService.request(url, partitionId, opts) } } /* **************************************************************************/ // Profile /* **************************************************************************/ /** * Tests the auth * @param auth: the auth token * @return promise */ static testAuth (serviceId, auth, partitionId) { if (!auth) { return this._rejectWithNoAuth() } const query = querystring.stringify({ token: auth, '_x_gantry': true }) return Promise.resolve() .then(() => this._fetch(serviceId, 'https://slack.com/api/auth.test?' + query, partitionId, { credentials: 'include' })) .then((res) => res.ok ? Promise.resolve(res) : Promise.reject(res)) .then((res) => res.json()) .then((res) => res.ok ? Promise.resolve(res) : Promise.reject(res)) } /* **************************************************************************/ // RTM Start /* **************************************************************************/ /** * Starts the RTM sync service * @param auth: the auth token * @return promise */ static startRTM (serviceId, auth, partitionId) { if (!auth) { return this._rejectWithNoAuth() } const query = querystring.stringify({ token: auth, mpim_aware: true, '_x_gantry': true }) return Promise.resolve() .then(() => this._fetch(serviceId, 'https://slack.com/api/rtm.start?' + query, partitionId, { credentials: 'include' })) .then((res) => res.ok ? Promise.resolve(res) : Promise.reject(res)) .then((res) => res.json()) .then((res) => res.ok ? Promise.resolve(res) : Promise.reject(res)) .then((res) => { return { response: res, rtm: new SlackRTM(res.url) } }) } /* **************************************************************************/ // Unread /* **************************************************************************/ /** * Gets the unread info from the server * @param auth: the auth token * @param simpleUnreads = true: true to return the simple unread counts */ static fetchUnreadInfo (serviceId, auth, partitionId, simpleUnreads = true) { if (!auth) { return this._rejectWithNoAuth() } const query = querystring.stringify({ token: auth, simple_unreads: simpleUnreads, mpim_aware: true, include_threads: true, '_x_gantry': true }) return Promise.resolve() .then(() => this._fetch(serviceId, 'https://slack.com/api/users.counts?' + query, partitionId, { credentials: 'include' })) .then((res) => res.ok ? Promise.resolve(res) : Promise.reject(res)) .then((res) => res.json()) .then((res) => res.ok ? Promise.resolve(res) : Promise.reject(res)) } } export default SlackHTTP
wavebox/waveboxapp
classic/src/scenes/mailboxes/src/stores/slack/SlackHTTP.js
JavaScript
mpl-2.0
6,676
/* -*- Mode: C++; tab-width: 20; indent-tabs-mode: nil; c-basic-offset: 2 -*- * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include "2D.h" #include "PathAnalysis.h" #include "PathHelpers.h" namespace mozilla { namespace gfx { static float CubicRoot(float aValue) { if (aValue < 0.0) { return -CubicRoot(-aValue); } else { return powf(aValue, 1.0f / 3.0f); } } struct BezierControlPoints { BezierControlPoints() {} BezierControlPoints(const Point &aCP1, const Point &aCP2, const Point &aCP3, const Point &aCP4) : mCP1(aCP1), mCP2(aCP2), mCP3(aCP3), mCP4(aCP4) { } Point mCP1, mCP2, mCP3, mCP4; }; void FlattenBezier(const BezierControlPoints &aPoints, PathSink *aSink, Float aTolerance); Path::Path() { } Path::~Path() { } Float Path::ComputeLength() { EnsureFlattenedPath(); return mFlattenedPath->ComputeLength(); } Point Path::ComputePointAtLength(Float aLength, Point* aTangent) { EnsureFlattenedPath(); return mFlattenedPath->ComputePointAtLength(aLength, aTangent); } void Path::EnsureFlattenedPath() { if (!mFlattenedPath) { mFlattenedPath = new FlattenedPath(); StreamToSink(mFlattenedPath); } } // This is the maximum deviation we allow (with an additional ~20% margin of // error) of the approximation from the actual Bezier curve. const Float kFlatteningTolerance = 0.0001f; void FlattenedPath::MoveTo(const Point &aPoint) { MOZ_ASSERT(!mCalculatedLength); FlatPathOp op; op.mType = FlatPathOp::OP_MOVETO; op.mPoint = aPoint; mPathOps.push_back(op); mLastMove = aPoint; } void FlattenedPath::LineTo(const Point &aPoint) { MOZ_ASSERT(!mCalculatedLength); FlatPathOp op; op.mType = FlatPathOp::OP_LINETO; op.mPoint = aPoint; mPathOps.push_back(op); } void FlattenedPath::BezierTo(const Point &aCP1, const Point &aCP2, const Point &aCP3) { MOZ_ASSERT(!mCalculatedLength); FlattenBezier(BezierControlPoints(CurrentPoint(), aCP1, aCP2, aCP3), this, kFlatteningTolerance); } void FlattenedPath::QuadraticBezierTo(const Point &aCP1, const Point &aCP2) { MOZ_ASSERT(!mCalculatedLength); // We need to elevate the degree of this quadratic B�zier to cubic, so we're // going to add an intermediate control point, and recompute control point 1. // The first and last control points remain the same. // This formula can be found on http://fontforge.sourceforge.net/bezier.html Point CP0 = CurrentPoint(); Point CP1 = (CP0 + aCP1 * 2.0) / 3.0; Point CP2 = (aCP2 + aCP1 * 2.0) / 3.0; Point CP3 = aCP2; BezierTo(CP1, CP2, CP3); } void FlattenedPath::Close() { MOZ_ASSERT(!mCalculatedLength); LineTo(mLastMove); } void FlattenedPath::Arc(const Point &aOrigin, float aRadiusX, float aRadiusY, float aRotationAngle, float aStartAngle, float aEndAngle, bool aAntiClockwise) { ArcToBezier(this, aOrigin, Size(aRadiusX, aRadiusY), aStartAngle, aEndAngle, aAntiClockwise); } Float FlattenedPath::ComputeLength() { if (!mCalculatedLength) { Point currentPoint; for (uint32_t i = 0; i < mPathOps.size(); i++) { if (mPathOps[i].mType == FlatPathOp::OP_MOVETO) { currentPoint = mPathOps[i].mPoint; } else { mCachedLength += Distance(currentPoint, mPathOps[i].mPoint); currentPoint = mPathOps[i].mPoint; } } mCalculatedLength = true; } return mCachedLength; } Point FlattenedPath::ComputePointAtLength(Float aLength, Point *aTangent) { // We track the last point that -wasn't- in the same place as the current // point so if we pass the edge of the path with a bunch of zero length // paths we still get the correct tangent vector. Point lastPointSinceMove; Point currentPoint; for (uint32_t i = 0; i < mPathOps.size(); i++) { if (mPathOps[i].mType == FlatPathOp::OP_MOVETO) { if (Distance(currentPoint, mPathOps[i].mPoint)) { lastPointSinceMove = currentPoint; } currentPoint = mPathOps[i].mPoint; } else { Float segmentLength = Distance(currentPoint, mPathOps[i].mPoint); if (segmentLength) { lastPointSinceMove = currentPoint; if (segmentLength > aLength) { Point currentVector = mPathOps[i].mPoint - currentPoint; Point tangent = currentVector / segmentLength; if (aTangent) { *aTangent = tangent; } return currentPoint + tangent * aLength; } } aLength -= segmentLength; currentPoint = mPathOps[i].mPoint; } } Point currentVector = currentPoint - lastPointSinceMove; if (aTangent) { if (hypotf(currentVector.x, currentVector.y)) { *aTangent = currentVector / hypotf(currentVector.x, currentVector.y); } else { *aTangent = Point(); } } return currentPoint; } // This function explicitly permits aControlPoints to refer to the same object // as either of the other arguments. static void SplitBezier(const BezierControlPoints &aControlPoints, BezierControlPoints *aFirstSegmentControlPoints, BezierControlPoints *aSecondSegmentControlPoints, Float t) { MOZ_ASSERT(aSecondSegmentControlPoints); *aSecondSegmentControlPoints = aControlPoints; Point cp1a = aControlPoints.mCP1 + (aControlPoints.mCP2 - aControlPoints.mCP1) * t; Point cp2a = aControlPoints.mCP2 + (aControlPoints.mCP3 - aControlPoints.mCP2) * t; Point cp1aa = cp1a + (cp2a - cp1a) * t; Point cp3a = aControlPoints.mCP3 + (aControlPoints.mCP4 - aControlPoints.mCP3) * t; Point cp2aa = cp2a + (cp3a - cp2a) * t; Point cp1aaa = cp1aa + (cp2aa - cp1aa) * t; aSecondSegmentControlPoints->mCP4 = aControlPoints.mCP4; if(aFirstSegmentControlPoints) { aFirstSegmentControlPoints->mCP1 = aControlPoints.mCP1; aFirstSegmentControlPoints->mCP2 = cp1a; aFirstSegmentControlPoints->mCP3 = cp1aa; aFirstSegmentControlPoints->mCP4 = cp1aaa; } aSecondSegmentControlPoints->mCP1 = cp1aaa; aSecondSegmentControlPoints->mCP2 = cp2aa; aSecondSegmentControlPoints->mCP3 = cp3a; } static void FlattenBezierCurveSegment(const BezierControlPoints &aControlPoints, PathSink *aSink, Float aTolerance) { /* The algorithm implemented here is based on: * http://cis.usouthal.edu/~hain/general/Publications/Bezier/Bezier%20Offset%20Curves.pdf * * The basic premise is that for a small t the third order term in the * equation of a cubic bezier curve is insignificantly small. This can * then be approximated by a quadratic equation for which the maximum * difference from a linear approximation can be much more easily determined. */ BezierControlPoints currentCP = aControlPoints; Float t = 0; while (t < 1.0f) { Point cp21 = currentCP.mCP2 - currentCP.mCP3; Point cp31 = currentCP.mCP3 - currentCP.mCP1; Float s3 = (cp31.x * cp21.y - cp31.y * cp21.x) / hypotf(cp21.x, cp21.y); t = 2 * Float(sqrt(aTolerance / (3. * abs(s3)))); if (t >= 1.0f) { aSink->LineTo(aControlPoints.mCP4); break; } Point prevCP2, prevCP3, nextCP1, nextCP2, nextCP3; SplitBezier(currentCP, nullptr, &currentCP, t); aSink->LineTo(currentCP.mCP1); } } static inline void FindInflectionApproximationRange(BezierControlPoints aControlPoints, Float *aMin, Float *aMax, Float aT, Float aTolerance) { SplitBezier(aControlPoints, nullptr, &aControlPoints, aT); Point cp21 = aControlPoints.mCP2 - aControlPoints.mCP1; Point cp41 = aControlPoints.mCP4 - aControlPoints.mCP1; if (cp21.x == 0.f && cp21.y == 0.f) { // In this case s3 becomes lim[n->0] (cp41.x * n) / n - (cp41.y * n) / n = cp41.x - cp41.y. // Use the absolute value so that Min and Max will correspond with the // minimum and maximum of the range. *aMin = aT - CubicRoot(abs(aTolerance / (cp41.x - cp41.y))); *aMax = aT + CubicRoot(abs(aTolerance / (cp41.x - cp41.y))); return; } Float s3 = (cp41.x * cp21.y - cp41.y * cp21.x) / hypotf(cp21.x, cp21.y); if (s3 == 0) { // This means within the precision we have it can be approximated // infinitely by a linear segment. Deal with this by specifying the // approximation range as extending beyond the entire curve. *aMin = -1.0f; *aMax = 2.0f; return; } Float tf = CubicRoot(abs(aTolerance / s3)); *aMin = aT - tf * (1 - aT); *aMax = aT + tf * (1 - aT); } /* Find the inflection points of a bezier curve. Will return false if the * curve is degenerate in such a way that it is best approximated by a straight * line. * * The below algorithm was written by Jeff Muizelaar <jmuizelaar@mozilla.com>, explanation follows: * * The lower inflection point is returned in aT1, the higher one in aT2. In the * case of a single inflection point this will be in aT1. * * The method is inspired by the algorithm in "analysis of in?ection points for planar cubic bezier curve" * * Here are some differences between this algorithm and versions discussed elsewhere in the literature: * * zhang et. al compute a0, d0 and e0 incrementally using the follow formula: * * Point a0 = CP2 - CP1 * Point a1 = CP3 - CP2 * Point a2 = CP4 - CP1 * * Point d0 = a1 - a0 * Point d1 = a2 - a1 * Point e0 = d1 - d0 * * this avoids any multiplications and may or may not be faster than the approach take below. * * "fast, precise flattening of cubic bezier path and ofset curves" by hain et. al * Point a = CP1 + 3 * CP2 - 3 * CP3 + CP4 * Point b = 3 * CP1 - 6 * CP2 + 3 * CP3 * Point c = -3 * CP1 + 3 * CP2 * Point d = CP1 * the a, b, c, d can be expressed in terms of a0, d0 and e0 defined above as: * c = 3 * a0 * b = 3 * d0 * a = e0 * * * a = 3a = a.y * b.x - a.x * b.y * b = 3b = a.y * c.x - a.x * c.y * c = 9c = b.y * c.x - b.x * c.y * * The additional multiples of 3 cancel each other out as show below: * * x = (-b + sqrt(b * b - 4 * a * c)) / (2 * a) * x = (-3 * b + sqrt(3 * b * 3 * b - 4 * a * 3 * 9 * c / 3)) / (2 * 3 * a) * x = 3 * (-b + sqrt(b * b - 4 * a * c)) / (2 * 3 * a) * x = (-b + sqrt(b * b - 4 * a * c)) / (2 * a) * * I haven't looked into whether the formulation of the quadratic formula in * hain has any numerical advantages over the one used below. */ static inline void FindInflectionPoints(const BezierControlPoints &aControlPoints, Float *aT1, Float *aT2, uint32_t *aCount) { // Find inflection points. // See www.faculty.idc.ac.il/arik/quality/appendixa.html for an explanation // of this approach. Point A = aControlPoints.mCP2 - aControlPoints.mCP1; Point B = aControlPoints.mCP3 - (aControlPoints.mCP2 * 2) + aControlPoints.mCP1; Point C = aControlPoints.mCP4 - (aControlPoints.mCP3 * 3) + (aControlPoints.mCP2 * 3) - aControlPoints.mCP1; Float a = Float(B.x) * C.y - Float(B.y) * C.x; Float b = Float(A.x) * C.y - Float(A.y) * C.x; Float c = Float(A.x) * B.y - Float(A.y) * B.x; if (a == 0) { // Not a quadratic equation. if (b == 0) { // Instead of a linear acceleration change we have a constant // acceleration change. This means the equation has no solution // and there are no inflection points, unless the constant is 0. // In that case the curve is a straight line, essentially that means // the easiest way to deal with is is by saying there's an inflection // point at t == 0. The inflection point approximation range found will // automatically extend into infinity. if (c == 0) { *aCount = 1; *aT1 = 0; return; } *aCount = 0; return; } *aT1 = -c / b; *aCount = 1; return; } else { Float discriminant = b * b - 4 * a * c; if (discriminant < 0) { // No inflection points. *aCount = 0; } else if (discriminant == 0) { *aCount = 1; *aT1 = -b / (2 * a); } else { /* Use the following formula for computing the roots: * * q = -1/2 * (b + sign(b) * sqrt(b^2 - 4ac)) * t1 = q / a * t2 = c / q */ Float q = sqrtf(discriminant); if (b < 0) { q = b - q; } else { q = b + q; } q *= Float(-1./2); *aT1 = q / a; *aT2 = c / q; if (*aT1 > *aT2) { std::swap(*aT1, *aT2); } *aCount = 2; } } return; } void FlattenBezier(const BezierControlPoints &aControlPoints, PathSink *aSink, Float aTolerance) { Float t1; Float t2; uint32_t count; FindInflectionPoints(aControlPoints, &t1, &t2, &count); // Check that at least one of the inflection points is inside [0..1] if (count == 0 || ((t1 < 0 || t1 > 1.0) && ((t2 < 0 || t2 > 1.0) || count == 1)) ) { FlattenBezierCurveSegment(aControlPoints, aSink, aTolerance); return; } Float t1min = t1, t1max = t1, t2min = t2, t2max = t2; BezierControlPoints remainingCP = aControlPoints; // For both inflection points, calulate the range where they can be linearly // approximated if they are positioned within [0,1] if (count > 0 && t1 >= 0 && t1 < 1.0) { FindInflectionApproximationRange(aControlPoints, &t1min, &t1max, t1, aTolerance); } if (count > 1 && t2 >= 0 && t2 < 1.0) { FindInflectionApproximationRange(aControlPoints, &t2min, &t2max, t2, aTolerance); } BezierControlPoints nextCPs = aControlPoints; BezierControlPoints prevCPs; // Process ranges. [t1min, t1max] and [t2min, t2max] are approximated by line // segments. if (t1min > 0) { // Flatten the Bezier up until the first inflection point's approximation // point. SplitBezier(aControlPoints, &prevCPs, &remainingCP, t1min); FlattenBezierCurveSegment(prevCPs, aSink, aTolerance); } if (t1max >= 0 && t1max < 1.0 && (count == 1 || t2min > t1max)) { // The second inflection point's approximation range begins after the end // of the first, approximate the first inflection point by a line and // subsequently flatten up until the end or the next inflection point. SplitBezier(aControlPoints, nullptr, &nextCPs, t1max); aSink->LineTo(nextCPs.mCP1); if (count == 1 || (count > 1 && t2min >= 1.0)) { // No more inflection points to deal with, flatten the rest of the curve. FlattenBezierCurveSegment(nextCPs, aSink, aTolerance); } } else if (count > 1 && t2min > 1.0) { // We've already concluded t2min <= t1max, so if this is true the // approximation range for the first inflection point runs past the // end of the curve, draw a line to the end and we're done. aSink->LineTo(aControlPoints.mCP4); return; } if (count > 1 && t2min < 1.0 && t2max > 0) { if (t2min > 0 && t2min < t1max) { // In this case the t2 approximation range starts inside the t1 // approximation range. SplitBezier(aControlPoints, nullptr, &nextCPs, t1max); aSink->LineTo(nextCPs.mCP1); } else if (t2min > 0 && t1max > 0) { SplitBezier(aControlPoints, nullptr, &nextCPs, t1max); // Find a control points describing the portion of the curve between t1max and t2min. Float t2mina = (t2min - t1max) / (1 - t1max); SplitBezier(nextCPs, &prevCPs, &nextCPs, t2mina); FlattenBezierCurveSegment(prevCPs, aSink, aTolerance); } else if (t2min > 0) { // We have nothing interesting before t2min, find that bit and flatten it. SplitBezier(aControlPoints, &prevCPs, &nextCPs, t2min); FlattenBezierCurveSegment(prevCPs, aSink, aTolerance); } if (t2max < 1.0) { // Flatten the portion of the curve after t2max SplitBezier(aControlPoints, nullptr, &nextCPs, t2max); // Draw a line to the start, this is the approximation between t2min and // t2max. aSink->LineTo(nextCPs.mCP1); FlattenBezierCurveSegment(nextCPs, aSink, aTolerance); } else { // Our approximation range extends beyond the end of the curve. aSink->LineTo(aControlPoints.mCP4); return; } } } } }
servo/rust-azure
libazure/Path.cpp
C++
mpl-2.0
16,363
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package components const ( TYPEDELIMITER = "::" TYPEROUTER = "router" TYPENETWORK = "network" TYPEINSTANCE = "instance" GROUPINSTANCE = "ernest.instance_group" PROVIDERTYPE = `$(components.#[_component_id="credentials::vcloud"]._provider)` DATACENTERNAME = `$(components.#[_component_id="credentials::vcloud"].vdc)` DATACENTERTYPE = `$(components.#[_component_id="credentials::vcloud"]._provider)` DATACENTERUSERNAME = `$(components.#[_component_id="credentials::vcloud"].username)` DATACENTERPASSWORD = `$(components.#[_component_id="credentials::vcloud"].password)` DATACENTERREGION = `$(components.#[_component_id="credentials::vcloud"].region)` VCLOUDURL = `$(components.#[_component_id="credentials::vcloud"].vcloud_url)` )
ernestio/definition-mapper
libmapper/providers/vcloud/components/template.go
GO
mpl-2.0
981
#include <cstdarg> #include <cstdint> #include <cstdlib> #include <ostream> #include <new> static const int32_t EXT_CONST = 0; struct ExtType { uint32_t data; }; extern "C" { void consume_ext(ExtType _ext); } // extern "C"
eqrion/cbindgen
tests/expectations/workspace.cpp
C++
mpl-2.0
230
package proxmox import ( "context" "github.com/hashicorp/packer-plugin-sdk/multistep" ) // stepSuccess runs after the full build has succeeded. // // It sets the success state, which ensures cleanup does not remove the finished template type stepSuccess struct{} func (s *stepSuccess) Run(ctx context.Context, state multistep.StateBag) multistep.StepAction { // We need to ensure stepStartVM.Cleanup doesn't delete the template (no // difference between VMs and templates when deleting) state.Put("success", true) return multistep.ActionContinue } func (s *stepSuccess) Cleanup(state multistep.StateBag) {}
ricardclau/packer
builder/proxmox/common/step_success.go
GO
mpl-2.0
619
// Our current version of MySQL doesn't support `WITH` statements. We're only // running this a few times, so no need to get fancy. It'll get cached anyway. const pilotId = `(SELECT id FROM challenges WHERE url_token='pilot')`; export const up = async function(db: any): Promise<any> { return db.runSql(` /* We're handling logos on the front-end. */ ALTER TABLE teams DROP COLUMN logo_url; ALTER TABLE achievements DROP COLUMN image_url; /* Insert seed data for the 2019 Pilot Challenge. */ INSERT INTO challenges (url_token, name, start_date) VALUES ('pilot', '2019 Pilot', '2019-11-18'); INSERT INTO teams (url_token, name, challenge_id) VALUES ('ibm', 'IBM', ${pilotId}), ('mozilla', 'Mozilla', ${pilotId}), ('sap', 'SAP', ${pilotId}); INSERT INTO achievements (name, points, challenge_id) VALUES ('sign_up_first_three_days', 50, ${pilotId}), ('first_contribution', 50, ${pilotId}), ('challenge_engagement_rank_1', 100, ${pilotId}), ('challenge_engagement_rank_2', 80, ${pilotId}), ('challenge_engagement_rank_3', 60, ${pilotId}), ('invite_signup', 50, ${pilotId}), ('invite_send', 50, ${pilotId}), ('invite_contribute_same_session', 50, ${pilotId}), ('challenge_social_rank_1', 100, ${pilotId}), ('challenge_social_rank_2', 80, ${pilotId}), ('challenge_social_rank_3', 60, ${pilotId}), ('three_day_streak', 50, ${pilotId}), ('challenge_validated_rank_1', 100, ${pilotId}), ('challenge_validated_rank_2', 80, ${pilotId}), ('challenge_validated_rank_3', 60, ${pilotId}), ('challenge_contributed_rank_1', 100, ${pilotId}), ('challenge_contributed_rank_2', 80, ${pilotId}), ('challenge_contributed_rank_3', 60, ${pilotId}), ('progress_survey', 50, ${pilotId}); `); }; export const down = function(): Promise<any> { return null; };
gozer/voice-web
server/src/lib/model/db/migrations/20191108184707-add-pilot-challenge-data.ts
TypeScript
mpl-2.0
1,914
package org.openlca.app.collaboration.navigation.actions; import java.util.List; import org.eclipse.jface.action.Action; import org.eclipse.jface.dialogs.IDialogConstants; import org.openlca.app.M; import org.openlca.app.collaboration.dialogs.SelectCommitDialog; import org.openlca.app.collaboration.views.CompareView; import org.openlca.app.db.Repository; import org.openlca.app.navigation.actions.INavigationAction; import org.openlca.app.navigation.elements.INavigationElement; import org.openlca.app.rcp.images.Icon; import org.openlca.git.model.Commit; public class OpenCompareViewAction extends Action implements INavigationAction { private final boolean compareWithHead; private List<INavigationElement<?>> selection; public OpenCompareViewAction(boolean compareWithHead) { if (compareWithHead) { setText(M.HEADRevision); } else { setText(M.Commit + "..."); setImageDescriptor(Icon.COMPARE_COMMIT.descriptor()); } this.compareWithHead = compareWithHead; } @Override public void run() { Commit commit = null; if (compareWithHead) { commit = Repository.get().commits.head(); } else { SelectCommitDialog dialog = new SelectCommitDialog(); if (dialog.open() != IDialogConstants.OK_ID) return; commit = dialog.getSelection(); } CompareView.update(commit, selection); } @Override public boolean accept(List<INavigationElement<?>> selection) { if (!Repository.isConnected()) return false; this.selection = selection; return true; } }
GreenDelta/olca-app
olca-app/src/org/openlca/app/collaboration/navigation/actions/OpenCompareViewAction.java
Java
mpl-2.0
1,504
import React, { Fragment } from 'react'; import { compose, graphql } from 'react-apollo'; import { set } from 'react-redux-values'; import ReduxForm from 'declarative-redux-form'; import { Row, Col } from 'joyent-react-styled-flexboxgrid'; import { Margin } from 'styled-components-spacing'; import { change } from 'redux-form'; import { connect } from 'react-redux'; import intercept from 'apr-intercept'; import get from 'lodash.get'; import { NameIcon, H3, Button, H4, P } from 'joyent-ui-toolkit'; import Title from '@components/create-image/title'; import Details from '@components/create-image/details'; import Description from '@components/description'; import GetRandomName from '@graphql/get-random-name.gql'; import createClient from '@state/apollo-client'; import { instanceName as validateName } from '@state/validators'; import { Forms } from '@root/constants'; const NameContainer = ({ expanded, proceeded, name, version, description, placeholderName, randomizing, handleAsyncValidate, shouldAsyncValidate, handleNext, handleRandomize, handleEdit, step }) => ( <Fragment> <Title id={step} onClick={!expanded && !name && handleEdit} collapsed={!expanded && !proceeded} icon={<NameIcon />} > Image name and details </Title> {expanded ? ( <Description> Here you can name your custom image, version it, and give it a description so that you can identify it elsewhere in the Triton ecosystem. </Description> ) : null} <ReduxForm form={Forms.FORM_DETAILS} destroyOnUnmount={false} forceUnregisterOnUnmount={true} asyncValidate={handleAsyncValidate} shouldAsyncValidate={shouldAsyncValidate} onSubmit={handleNext} > {props => expanded ? ( <Details {...props} placeholderName={placeholderName} randomizing={randomizing} onRandomize={handleRandomize} /> ) : name ? ( <Margin top="3"> <H3 bold noMargin> {name} </H3> {version ? ( <Margin top="2"> <H4 bold noMargin> {version} </H4> </Margin> ) : null} {description ? ( <Row> <Col xs="12" sm="8"> <Margin top="1"> <P>{description}</P> </Margin> </Col> </Row> ) : null} </Margin> ) : null } </ReduxForm> {expanded ? ( <Margin top="4" bottom="7"> <Button type="button" disabled={!name} onClick={handleNext}> Next </Button> </Margin> ) : proceeded ? ( <Margin top="4" bottom="7"> <Button type="button" onClick={handleEdit} secondary> Edit </Button> </Margin> ) : null} </Fragment> ); export default compose( graphql(GetRandomName, { options: () => ({ fetchPolicy: 'network-only', ssr: false }), props: ({ data }) => ({ placeholderName: data.rndName || '' }) }), connect( ({ form, values }, ownProps) => { const name = get(form, `${Forms.FORM_DETAILS}.values.name`, ''); const version = get(form, `${Forms.FORM_DETAILS}.values.version`, ''); const description = get( form, `${Forms.FORM_DETAILS}.values.description`, '' ); const proceeded = get(values, `${Forms.FORM_DETAILS}-proceeded`, false); const randomizing = get(values, 'create-image-name-randomizing', false); return { ...ownProps, proceeded, randomizing, name, version, description }; }, (dispatch, { history, match }) => ({ handleNext: () => { dispatch(set({ name: `${Forms.FORM_DETAILS}-proceeded`, value: true })); return history.push(`/images/~create/${match.params.instance}/tag`); }, handleEdit: () => { dispatch(set({ name: `${Forms.FORM_DETAILS}-proceeded`, value: true })); return history.push(`/images/~create/${match.params.instance}/name`); }, shouldAsyncValidate: ({ trigger }) => { return trigger === 'change'; }, handleAsyncValidate: validateName, handleRandomize: async () => { dispatch(set({ name: 'create-image-name-randomizing', value: true })); const [err, res] = await intercept( createClient().query({ fetchPolicy: 'network-only', query: GetRandomName }) ); dispatch(set({ name: 'create-image-name-randomizing', value: false })); if (err) { // eslint-disable-next-line no-console console.error(err); return; } const { data } = res; const { rndName } = data; return dispatch(change(Forms.FORM_DETAILS, 'name', rndName)); } }) ) )(NameContainer);
yldio/joyent-portal
consoles/my-joy-images/src/containers/create-image/details.js
JavaScript
mpl-2.0
5,062
package main.origo.core.actions; import main.origo.core.event.NodeContext; import play.mvc.Action; import play.mvc.Http; import play.mvc.Result; import play.mvc.With; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @With(ContextAware.ContextAction.class) @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) public @interface ContextAware { public static class ContextAction extends Action.Simple { @Override public Result call(Http.Context context) throws Throwable { try { NodeContext.set(); return delegate.call(context); } finally { NodeContext.clear(); } } } }
origocms/origo
modules/core/app/main/origo/core/actions/ContextAware.java
Java
mpl-2.0
811
package zyx.game.components.world.characters; import java.util.ArrayList; import org.lwjgl.util.vector.Matrix4f; import zyx.game.behavior.characters.CharacterAnimationBehavior; import zyx.game.behavior.player.OnlinePositionInterpolator; import zyx.game.components.AnimatedMesh; import zyx.game.components.GameObject; import zyx.game.components.IAnimatedMesh; import zyx.game.components.world.IItemHolder; import zyx.game.components.world.interactable.InteractionAction; import zyx.game.components.world.items.GameItem; import zyx.game.vo.CharacterType; import zyx.opengl.models.implementations.physics.PhysBox; public class GameCharacter extends GameObject implements IItemHolder { private static final ArrayList<InteractionAction> EMPTY_LIST = new ArrayList<>(); private static final ArrayList<InteractionAction> GUEST_LIST = new ArrayList<>(); static { GUEST_LIST.add(InteractionAction.TAKE_ORDER); } private AnimatedMesh mesh; public final CharacterInfo info; public GameCharacter() { info = new CharacterInfo(); mesh = new AnimatedMesh(); addChild(mesh); } public IAnimatedMesh getAnimatedMesh() { return mesh; } @Override public int getUniqueId() { return info.uniqueId; } public void load(CharacterSetupVo vo) { mesh.load("mesh.character"); setPosition(false, vo.pos); lookAt(vo.look); addBehavior(new OnlinePositionInterpolator(info)); addBehavior(new CharacterAnimationBehavior()); info.uniqueId = vo.id; info.name = vo.name; info.gender = vo.gender; info.type = vo.type; } @Override public void hold(GameItem item) { info.heldItem = item; mesh.addChildAsAttachment(item, "bone_carry"); } @Override public void removeItem(GameItem item) { if (info.heldItem != null) { mesh.removeChildAsAttachment(item); info.heldItem = null; } } @Override public boolean isInteractable() { if (info.type == CharacterType.GUEST) { return true; } return false; } @Override public PhysBox getPhysbox() { return mesh.getPhysbox(); } @Override public Matrix4f getMatrix() { return mesh.getMatrix(); } @Override public Matrix4f getBoneMatrix(int boneId) { return mesh.getBoneMatrix(boneId); } @Override public GameObject getWorldObject() { return this; } @Override public ArrayList<InteractionAction> getInteractions() { if (info.type == CharacterType.GUEST) { return GUEST_LIST; } else { return EMPTY_LIST; } } }
zyxakarene/LearningOpenGl
MainGame/src/zyx/game/components/world/characters/GameCharacter.java
Java
mpl-2.0
2,465