repo_name
stringlengths
6
101
path
stringlengths
4
300
text
stringlengths
7
1.31M
fredblain/docQE-corp
systems/2016/english-russian/newstest2016.PROMT-Rule-based.4276.en-ru/kommersant.173035.newstest2016.PROMT-Rule-based.4276.en-ru.ru
<reponame>fredblain/docQE-corp Новая Mazda CX-5 и уличный стиль. Это - то, как слово Мазда написано японскими иероглифами. Красивый, краткий, и, в то же время, довольно трудный для тех, кто привык к кириллическим или латинским алфавитам. Аналогично, новый переход CX-5, как с любой другой моделью марки, привлекателен, не будучи претенциозным на внешней стороне, и технически звучите на внутренней части. Японцы, просто на основании их «Японскости», способны к превращению приложения к продуктам из страны восходящего солнца в состояние полного восхищения. Вы можете привести столько аргументов, сколько Вам нравится за автомобили из других стран, и человек может даже согласиться с этими аргументами в принципе, но целый разговор развалится с заключительной фразой: «Но это - японский автомобиль! Нет никакого смысла в утверждении об этом! Такие люди, несомненно, должны любить не только технологию, но также и все остальное японское. Укажите Bashō от вершины их голов, добавьте васаби к их еде, соберите катаны и оденьте их подруг, не в кимоно, конечно, а согласно указам японского уличного стиля: милый, творческий, и полностью неожиданный. Возьмите японскую школьную форму: единственная униформа, которую девочки рады носить даже после окончания школы. Это обладает удивительными качествами: в то же время и чувственный и строгий. И чем более старый девочка, тем короче ее юбка. Существенное изменение в виде CX-5 является передней решеткой со своими пятью горизонтальными линиями. Но новая форма фар и задних фар значительно изменяет вид автомобиля, который немедленно делает автомобиль опознаваемым в потоке движения. Как прежде, Mazda CX-5 выглядит очень соблазнительной. Силуэт гармоничен, и формы чувственны, но, несмотря на это, у появления есть легкая серьезность. Нет никакой потребности вызвать полицию. За рулем CX-5, который является одним из самых безопасных автомобилей в мире, Вы можете испытать чистое стоическое японское спокойствие. 2.2L дизельный двигатель поставляет высокий крутящий момент по широкому спектру скоростей. Кроме того, расход топлива этого двигателя на 175 лошадиных сил только 5.9L, и к этому исключительно прилагается автоматическая коробка передач и полный привод. Черные ботинки, черное пальто, черная сумка... Чтобы добавить немного черного юмора к этому изображению, Вы можете выбрать некоторые леггинсы с полицейским принтом «Do Not Cross» на них. Кстати, Мазда приложила все усилия, чтобы гарантировать, чтобы Вы не заканчивали в автокатастрофе будучи за рулем CX-5. Чтобы еще больше увеличить комфорт, поддерживая отличную управляемость, подвеска передних и задних амортизаторов была перепроектирована, и форма передних более низких втулок рычага управления была также улучшена. Полноприводная система была адаптирована к российским условиям. Уровни шума от дороги и двигателя на высоких скоростях были снижены на 13%. Купальник в цветочек или полоску столь же скучный как бюджетный седан. Это - другая вещь полностью, когда девочка щеголяет о в купальнике с оригинальным дизайном. Например, от видеоигры дерби ролика. Тогда она привлечет столько же внимания сколько новый CX-5! Новый CX-5 лучше проектировал передние и задние сидения, которые обеспечивают оптимальное дополнительное пространство и для широких плеч и для длинных ног - кто чем обладает. Кроме того, те с длинными ногами будут, конечно, ценить то, что отдых в передней части центральной консоли теперь мягкий и не поражает Ваши лодыжки в кривых. Самый полный пакет мазды активной системы безопасности предлагается определенно на CX-5. Радары, лазеры и камеры используются, чтобы определить потенциальные угрозы. Это также включает адаптивное освещение, предупреждение о сходе с полосы, мониторинг слепых зон и ломку безопасности. У Mazda CX-5 есть один из лучших багажников в классе. Удобный и с минимальными преградами, это может приспособить грузовой объем 561L. Задние сиденья складывают в 4:2:4 конфигурация с каждой секцией, имеющей ее собственный рычаг с дистанционным управлением, который увеличивает место в багажнике до 1560L. В Японии костюм анимационного персонажа называют «кигуруми». Пижама кигуруми выглядит особенно веселой. Вы можете делать все что угодно в них! Конечно, Вы можете спать. Но также и, развлеките маленьких детей. Или просто прогулка вдоль улицы так же мало зверя... В конце концов, замечательно, когда у Вас есть способность выбрать прохладную одежду, Вашу манеру поведения или Ваш автомобиль. Благодаря Kawaicat для помощи в подготовке этого материала.
GerHobbelt/science.js
src/stats/stats.js
<filename>src/stats/stats.js science.stats = {};
totalkyos/stack-storm
st2client/tests/unit/test_util_json.py
<reponame>totalkyos/stack-storm # Licensed to the StackStorm, Inc ('StackStorm') under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import json import logging import unittest2 from st2client.utils import jsutil LOG = logging.getLogger(__name__) DOC = { 'a01': 1, 'b01': 2, 'c01': { 'c11': 3, 'd12': 4, 'c13': { 'c21': 5, 'c22': 6 }, 'c14': [7, 8, 9] } } class TestGetValue(unittest2.TestCase): def test_dot_notation(self): self.assertEqual(jsutil.get_value(DOC, 'a01'), 1) self.assertEqual(jsutil.get_value(DOC, 'c01.c11'), 3) self.assertEqual(jsutil.get_value(DOC, 'c01.c13.c22'), 6) self.assertEqual(jsutil.get_value(DOC, 'c01.c13'), {'c21': 5, 'c22': 6}) self.assertListEqual(jsutil.get_value(DOC, 'c01.c14'), [7, 8, 9]) def test_dot_notation_with_val_error(self): self.assertRaises(ValueError, jsutil.get_value, DOC, None) self.assertRaises(ValueError, jsutil.get_value, DOC, '') self.assertRaises(ValueError, jsutil.get_value, json.dumps(DOC), 'a01') def test_dot_notation_with_key_error(self): self.assertIsNone(jsutil.get_value(DOC, 'd01')) self.assertIsNone(jsutil.get_value(DOC, 'a01.a11')) self.assertIsNone(jsutil.get_value(DOC, 'c01.c11.c21.c31')) self.assertIsNone(jsutil.get_value(DOC, 'c01.c14.c31')) class TestGetKeyValuePairs(unittest2.TestCase): def test_select_kvps(self): self.assertEqual(jsutil.get_kvps(DOC, ['a01']), {'a01': 1}) self.assertEqual(jsutil.get_kvps(DOC, ['c01.c11']), {'c01': {'c11': 3}}) self.assertEqual(jsutil.get_kvps(DOC, ['c01.c13.c22']), {'c01': {'c13': {'c22': 6}}}) self.assertEqual(jsutil.get_kvps(DOC, ['c01.c13']), {'c01': {'c13': {'c21': 5, 'c22': 6}}}) self.assertEqual(jsutil.get_kvps(DOC, ['c01.c14']), {'c01': {'c14': [7, 8, 9]}}) self.assertEqual(jsutil.get_kvps(DOC, ['a01', 'c01.c11', 'c01.c13.c21']), {'a01': 1, 'c01': {'c11': 3, 'c13': {'c21': 5}}}) def test_select_kvps_with_val_error(self): self.assertRaises(ValueError, jsutil.get_kvps, DOC, [None]) self.assertRaises(ValueError, jsutil.get_kvps, DOC, ['']) self.assertRaises(ValueError, jsutil.get_kvps, json.dumps(DOC), ['a01']) def test_select_kvps_with_key_error(self): self.assertEqual(jsutil.get_kvps(DOC, ['d01']), {}) self.assertEqual(jsutil.get_kvps(DOC, ['a01.a11']), {}) self.assertEqual(jsutil.get_kvps(DOC, ['c01.c11.c21.c31']), {}) self.assertEqual(jsutil.get_kvps(DOC, ['c01.c14.c31']), {}) self.assertEqual(jsutil.get_kvps(DOC, ['a01', 'c01.c11', 'c01.c13.c23']), {'a01': 1, 'c01': {'c11': 3}})
CarlosMacaneta/Projectos-Java
Teste2/src/models/Professor.java
package models; /** * * @author CarlosMacaneta */ public class Professor extends Pessoa { private String grauAcademico; public Professor(String grauAcademico) { this.grauAcademico = grauAcademico; } public Professor(int id, String nome, String genero, String grauAcademico) { super(id, nome, genero); this.grauAcademico = grauAcademico; } public String getGrauAcademico() { return grauAcademico; } public void setGrauAcademico(String grauAcademico) { this.grauAcademico = grauAcademico; } }
samisking/samking.design
src/hooks/useTheme.js
<filename>src/hooks/useTheme.js<gh_stars>0 import { useEffect } from 'react'; import { useActiveThemeContext } from '../components/ActiveTheme'; function useTheme(themeMode, deps = []) { const { setTheme } = useActiveThemeContext(); useEffect(() => { setTheme(themeMode); }, deps); } export default useTheme;
neherlab/hivwholeseq
hivwholeseq/reference/__init__.py
<reponame>neherlab/hivwholeseq # vim: fdm=marker ''' author: <NAME> date: 26/09/13 content: Manage reference sequences. ''' # Modules from Bio import SeqIO, AlignIO from hivwholeseq.sequencing.filenames import get_HXB2_entire, get_NL43_entire, get_F10_entire, \ get_HXB2_fragmented, get_NL43_fragmented, get_F10_fragmented from hivwholeseq.utils.sequence import correct_genbank_features_load, \ correct_genbank_features_save from hivwholeseq.filenames import get_custom_reference_filename, \ get_custom_alignment_filename # Functions def load_HXB2(cropped=False, fragment=None, trim_primers=False): '''Load HXB2 reference sequence''' if fragment is None: return SeqIO.read(get_HXB2_entire(cropped=cropped), 'fasta') else: return SeqIO.read(get_HXB2_fragmented(fragment, trim_primers=trim_primers), 'fasta') def load_NL43(fragment=None, trim_primers=False): '''Load NL4-3 reference sequence''' if fragment is None: return SeqIO.read(get_NL43_entire(), 'fasta') else: return SeqIO.read(get_NL43_fragmented(fragment, trim_primers=trim_primers), 'fasta') def load_F10(fragment=None): '''Load F10 reference sequence''' if fragment is None: return SeqIO.read(get_F10_entire(), 'fasta') else: return SeqIO.read(get_F10_fragmented(fragment, trim_primers=trim_primers), 'fasta') def load_custom_reference(reference, format='fasta', region=None): '''Load a custom reference''' if region is not None: format = 'gb' record = SeqIO.read(get_custom_reference_filename(reference, format=format), format) # BUG: feature id is lost during write, fake it with the 'note' qualifier if format in ['gb' , 'genbank']: correct_genbank_features_load(record) if region is not None: for feature in record.features: if feature.id == region: return feature.extract(record) return record def save_custom_reference(record, reference, format='fasta', molecule='DNA'): '''Save a custom reference''' if format in ['gb' , 'genbank']: correct_genbank_features_save(record, molecule='DNA') return SeqIO.write(record, get_custom_reference_filename(reference, format=format), format) def load_custom_alignment(aliname, format='fasta', molecule='DNA'): '''Load a custom alignment''' fn = get_custom_alignment_filename(aliname, format=format) ali = AlignIO.read(fn, format) return ali
PolSl-PBL-7/DragonEye
data/tests/versioning/test_versioner.py
import filecmp from os import path from pathlib import Path from data.versioning.versioner import WandbDatasetVersioner, VersioningConfig CURDIR = Path(__file__).parents[2] dataset_path_read = CURDIR / "tests/test_videos" dataset_path_write = CURDIR / "tests/test_versioner_output" def test_loading_file_exists(): db = WandbDatasetVersioner() config = VersioningConfig( type='file', dataset_path=dataset_path_read / '15.avi', dataset_name='test_dataset') db.save_dataset(config) db = WandbDatasetVersioner() config = VersioningConfig( type='file', dataset_path=dataset_path_write, dataset_name='test_dataset') db.load_dataset(config) assert Path(dataset_path_write / '15.avi').exists() def test_loading_file_content_comparison(): db = WandbDatasetVersioner() config = VersioningConfig( type='file', dataset_path=dataset_path_read / '15.avi', dataset_name='test_dataset') db.save_dataset(config) db = WandbDatasetVersioner() config = VersioningConfig( type='file', dataset_path=dataset_path_write, dataset_name='test_dataset') db.load_dataset(config) assert filecmp.cmp(dataset_path_read / '15.avi', dataset_path_write / '15.avi') def test_loading_folder_exists(): db = WandbDatasetVersioner() config = VersioningConfig( type='folder', dataset_path=dataset_path_read, dataset_name='test_dataset') db.save_dataset(config) video_path_test = dataset_path_write / 'test' db = WandbDatasetVersioner() config = VersioningConfig( type='folder', dataset_path=video_path_test, dataset_name='test_dataset') db.load_dataset(config) assert Path(video_path_test).exists() def test_loading_folder_content_comparison(): db = WandbDatasetVersioner() config = VersioningConfig( type='folder', dataset_path=dataset_path_read, dataset_name='test_dataset') db.save_dataset(config) video_path_test = dataset_path_write / 'test' db = WandbDatasetVersioner() config = VersioningConfig( type='folder', dataset_path=video_path_test, dataset_name='test_dataset') db.load_dataset(config) assert len(filecmp.dircmp(dataset_path_read, dataset_path_write / 'test/').diff_files) == 0
ericmorand/idea-twigextendedplugin
src/com/nightlycommit/idea/twigextendedplugin/templating/PhpTemplateMissingInspection.java
package com.nightlycommit.idea.twigextendedplugin.templating; import com.intellij.codeInspection.LocalInspectionTool; import com.intellij.codeInspection.ProblemHighlightType; import com.intellij.codeInspection.ProblemsHolder; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiElementVisitor; import com.jetbrains.php.lang.psi.elements.MethodReference; import com.nightlycommit.idea.twigextendedplugin.Symfony2ProjectComponent; import com.nightlycommit.idea.twigextendedplugin.config.SymfonyPhpReferenceContributor; import com.nightlycommit.idea.twigextendedplugin.templating.inspection.TemplateCreateByNameLocalQuickFix; import com.nightlycommit.idea.twigextendedplugin.templating.util.TwigUtil; import com.nightlycommit.idea.twigextendedplugin.util.ParameterBag; import com.nightlycommit.idea.twigextendedplugin.util.PhpElementsUtil; import com.nightlycommit.idea.twigextendedplugin.util.PsiElementUtils; import org.apache.commons.lang.StringUtils; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; /** * @author <NAME> <<EMAIL>> */ public class PhpTemplateMissingInspection extends LocalInspectionTool { @NotNull @Override public PsiElementVisitor buildVisitor(@NotNull ProblemsHolder holder, boolean isOnTheFly) { if(!Symfony2ProjectComponent.isEnabled(holder.getProject())) { return super.buildVisitor(holder, isOnTheFly); } return new PsiElementVisitor() { @Override public void visitElement(PsiElement element) { invoke(holder, element); super.visitElement(element); } }; } private void invoke(@NotNull ProblemsHolder holder, @NotNull PsiElement psiElement) { String templateNameIfMissing = getTemplateNameIfMissing(psiElement); if(templateNameIfMissing == null) { return; } holder.registerProblem( psiElement, "Twig: Missing Template", ProblemHighlightType.GENERIC_ERROR_OR_WARNING, new TemplateCreateByNameLocalQuickFix(templateNameIfMissing) ); } @Nullable private String getTemplateNameIfMissing(@NotNull PsiElement psiElement) { MethodReference methodReference = PsiElementUtils.getMethodReferenceWithFirstStringParameter(psiElement); if (methodReference == null || !PhpElementsUtil.isMethodReferenceInstanceOf(methodReference, SymfonyPhpReferenceContributor.TEMPLATE_SIGNATURES)) { return null; } ParameterBag parameterBag = PsiElementUtils.getCurrentParameterIndex(psiElement.getParent()); if(parameterBag == null || parameterBag.getIndex() != 0) { return null; } String templateName = PhpElementsUtil.getFirstArgumentStringValue(methodReference); if(templateName == null || StringUtils.isBlank(templateName)) { return null; } if(TwigUtil.getTemplateFiles(psiElement.getProject(), templateName).size() > 0) { return null; } return templateName; } }
dingdang2012/tlsprober
alexa.py
# Copyright 2010-2012 Opera Software ASA # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import csv class Alexa: """List of Alexa top million domains""" def __init__(self,file_name): self.alexa = {} for line in csv.reader(open(file_name)): if len(line) >1: host = line[1] index = line[0] self.alexa[host] = index def IsAlexaSite(self,hostname): """return Alexa ranking for a hostname""" labels = hostname.split(".") for i in range(len(labels)-1): index = self.alexa.get(".".join(labels[i:]),-1) if index > 0: return index return 0 if __name__ == '__main__': alexa_list = Alexa("top-1m.csv") assert(alexa_list) assert(alexa_list.IsAlexaSite("google.com")>0) assert(alexa_list.IsAlexaSite("www.google.com")>0) print "PASS"
jordsti/stigame
StiGame/bindings/MouseActionMap.h
<filename>StiGame/bindings/MouseActionMap.h #ifndef MOUSEACTIONMAP_H #define MOUSEACTIONMAP_H #include "Rectangle.h" #include "ActionMap.h" namespace StiGame { /// \class MouseActionMap /// \brief Mapping of a mouse triggered action class MouseActionMap : public ActionMap { public: /// \brief Create a new Mouse Action Map MouseActionMap(void); /// \brief Create a new Mouse Action Map /// \param m_name Action Name MouseActionMap(std::string m_name); MouseActionMap(std::string m_name, Uint8 m_button); /// \brief Destructor virtual ~MouseActionMap(void); /// \brief Get string value of the bind /// \return String value std::string toString(void); /// \brief Parse String to get bind /// \param str String value void fromString(std::string str); /// \brief Get Mouse button /// \return Mouse button Uint8 getButton(void); /// \brief Set the mouse button /// \param m_button Mouse Button void setButton(Uint8 m_button); /// \brief Get Mouse Button String value /// \param m_button Mouse Button /// \return String value static std::string GetStringValue(Uint8 m_button); /// \brief Parse a string to get Mouse Button /// \param m_str String Value /// \return Mouse button static Uint8 GetIntValue(std::string m_str); bool inputEquals(InputType it, int input); bool inputMouseEquals(MouseButtonEventArgs *mbEvt); /// \brief Set X Position /// \param r_x X (px) void setX(int r_x); /// \brief Set Y Position /// \param r_y Y (px) void setY(int r_y); /// \brief Set Width /// \param r_w Width (px) void setWidth(int r_w); /// \brief Set Height /// \param r_h Height (px) void setHeight(int r_h); /// \brief Set the rectangle attributes /// \param r_x X (px) /// \param r_y Y (px) /// \param r_w Width (px) /// \param r_h Height (px) void setRect(int r_x, int r_y, int r_w, int r_h); /// \brief Set Position Checked /// \param m_positionChecked Position Checked void setPositionChecked(bool m_positionChecked); /// \brief Is Position Checked /// \return checked or not bool isPositionChecked(void); int getIntValue(void); InputType getInputType(void); protected: /// \brief Mouse Button Uint8 button; /// \brief Position rectangle Rectangle rect; /// \brief Position Check bool positionChecked; }; } #endif // MOUSEACTIONMAP_H
fangfang-zhang/MTGP
src/yimei/jss/ruleanalysis/MultipleTreeRuleTest.java
package yimei.jss.ruleanalysis; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.List; import ec.gp.GPNode; import ec.multiobjective.MultiObjectiveFitness; import yimei.jss.jobshop.Objective; import yimei.jss.jobshop.SchedulingSet; import yimei.jss.rule.AbstractRule; import yimei.jss.rule.operation.evolved.GPRule; import yimei.jss.rule.workcenter.basic.WIQ; public class MultipleTreeRuleTest{ public static final long simSeed = 968356; protected String trainPath; //the directory of training things protected RuleType ruleType; protected int numRuns; protected String testScenario; protected String testSetName; protected List<Objective> objectives; // The objectives to test. protected int numTrees; public MultipleTreeRuleTest(String trainPath, RuleType ruleType, int numRuns, String testScenario, String testSetName, List<Objective> objectives, int numTrees) { this.trainPath = trainPath; this.ruleType = ruleType; this.numRuns = numRuns; this.testScenario = testScenario; this.testSetName = testSetName; this.objectives = objectives; this.numTrees = numTrees; } public MultipleTreeRuleTest(String trainPath, RuleType ruleType, int numRuns, String testScenario, String testSetName, int numTreess) { this(trainPath, ruleType, numRuns, testScenario, testSetName, new ArrayList<>(), numTreess); } public String getTrainPath() { return trainPath; } public RuleType getRuleType() { return ruleType; } public int getNumRuns() { return numRuns; } public int getnumTrees() { return numTrees; } public String getTestScenario() { return testScenario; } public List<Objective> getObjectives() { return objectives; } public void setObjectives(List<Objective> objectives) { this.objectives = objectives; } public void addObjective(Objective objective) { this.objectives.add(objective); } public void addObjective(String objective) { addObjective(Objective.get(objective)); } //generate testset using simseed, replications public SchedulingSet generateTestSet() { return SchedulingSet.generateSet(simSeed, testScenario, testSetName, objectives, 50); } public void writeToCSV() { SchedulingSet testSet = generateTestSet(); File targetPath = new File(trainPath + "test"); //create a folder named "test" in trainPath if (!targetPath.exists()) { targetPath.mkdirs(); } File csvFile = new File(targetPath + "/" + testSetName + ".csv"); //create a .csv to save the test result List<TestResult> testResults = new ArrayList<>(); //for test: which machines are choosen by routing rule, CCGP. Scenario: run1, rule in generaiton 51 numRuns for (int i = 0; i < numRuns; i++) { System.out.println("Run "+ i); //for (int i = 0; i < 1; i++) { File sourceFile = new File(trainPath + "job." + i + ".out.stat"); //this file keeps the rule TestResult result = MultipleTreeTestResult.readFromFile(sourceFile, ruleType, numTrees); //Didn't bother saving time files File timeFile = new File(trainPath + "job." + i + ".time.csv"); result.setGenerationalTimeStat(MultipleTreeResultFileReader.readTimeFromFile(timeFile)); //24.8.2018 fzhang read badrun in CSV /* File badrunsFile = new File(trainPath + "job." + i + ".BadRun.csv"); result.setGenerationalBadRunStat(MultipleTreeResultFileReader.readBadRunFromFile(badrunsFile));*/ File aveRuleSizeFile = new File(trainPath + "job." + i + ".aveGenRulesize.csv"); result.setGenerationalAveSequencingRuleSizeStat(ResultFileReader.readAveRuleSizeFromFile(aveRuleSizeFile, 1)); result.setGenerationalAveRoutingRuleSizeStat(ResultFileReader.readAveRuleSizeFromFile(aveRuleSizeFile, 2)); result.setGenerationalAveRuleSizeStat(ResultFileReader.readAveRuleSizeFromFile(aveRuleSizeFile, 3)); long start = System.currentTimeMillis(); // result.validate(objectives); //for (int j = 42; j < result.getGenerationalRules().size(); j++) { for (int j = 0; j < result.getGenerationalRules().size(); j++) { AbstractRule[] generationalRules = result.getGenerationalRules(j); if (numTrees == 2) { generationalRules[0].calcFitness( //in calcFitness(), it will check which one is routing/sequencing rule result.getGenerationalTestFitness(j), null, testSet, generationalRules[1], objectives); } //generationalRules[1] is routing rule System.out.println("Generation " + j + ": test fitness = " + result.getGenerationalTestFitness(j).fitness()); } long finish = System.currentTimeMillis(); long duration = (finish - start)/1000; System.out.println("Duration = " + duration + " s."); testResults.add(result); } try { BufferedWriter writer = new BufferedWriter(new FileWriter(csvFile.getAbsoluteFile())); /*writer.write("Run,Generation,SeqRuleSize,SeqRuleUniqueTerminals,RoutRuleSize," + "RoutRuleUniqueTerminals,Obj,TrainFitness,TestFitness, TrainTime, BadRun");*/ /* writer.write("Run,Generation,SeqRuleSize,SeqRuleUniqueTerminals,RoutRuleSize," + "RoutRuleUniqueTerminals,Obj,TrainFitness,TestFitness, TrainTime");*/ //with average rule size writer.write("Run,Generation,SeqRuleSize,SeqRuleUniqueTerminals,RoutRuleSize," + "RoutRuleUniqueTerminals,Obj,TrainFitness,TestFitness,TrainTime, AveSeqRulesize, AveRouRuleSize, AveRuleSize"); writer.newLine(); //for (int i = 0; i < 1; i++) { for (int i = 0; i < numRuns; i++) { TestResult result = testResults.get(i); //for (int j = 42; j < result.getGenerationalRules().size(); j++) { //use rules in each generation for testing for (int j = 0; j < result.getGenerationalRules().size(); j++) { //use rules in each generation for testing MultiObjectiveFitness trainFit = (MultiObjectiveFitness)result.getGenerationalTrainFitness(j); MultiObjectiveFitness testFit = (MultiObjectiveFitness)result.getGenerationalTestFitness(j); GPRule[] rules = (GPRule[]) result.getGenerationalRules(j); GPRule seqRule = null; GPRule routRule = null; if (numTrees == 2) { if (rules[0].getType() == yimei.jss.rule.RuleType.SEQUENCING) { seqRule = rules[0]; routRule = rules[1]; } else { seqRule = rules[1]; routRule = rules[0]; } } else { seqRule = rules[0]; } UniqueTerminalsGatherer gatherer = new UniqueTerminalsGatherer(); int numUniqueTerminalsSeq = seqRule.getGPTree().child.numNodes(gatherer); int seqRuleSize = seqRule.getGPTree().child.numNodes(GPNode.NODESEARCH_ALL); int numUniqueTerminalsRout = 0; int routRuleSize = 0; if (numTrees == 2) { gatherer = new UniqueTerminalsGatherer(); numUniqueTerminalsRout = routRule.getGPTree().child.numNodes(gatherer); routRuleSize = routRule.getGPTree().child.numNodes(GPNode.NODESEARCH_ALL); } /* if (objectives.size() == 1) { writer.write(i + "," + j + "," + seqRuleSize + "," + numUniqueTerminalsSeq + "," + routRuleSize +"," + numUniqueTerminalsRout +",0," + trainFit.fitness() + "," + testFit.fitness()+ ","+ result.getGenerationalTime(j)+ ","+ result.getGenerationalBadRun(j)); writer.newLine(); }*/ //with average rule size if (objectives.size() == 1) { writer.write(i + "," + j + "," + seqRuleSize + "," + numUniqueTerminalsSeq + "," + routRuleSize + "," + numUniqueTerminalsRout + ",0," + trainFit.fitness() + "," + testFit.fitness() + "," + result.getGenerationalTime(j) + "," + //result.getGenerationalBadRun(j) + "," + result.getGenerationalAveSequencingRuleSizeStatStat(j) + "," + result.getGenerationalAveRoutingRuleSizeStatStat(j) + "," + result.getGenerationalAveRuleSizeStatStat(j) ); // writer.newLine(); } /* if (objectives.size() == 1) { writer.write(i + "," + j + "," + seqRuleSize + "," + numUniqueTerminalsSeq + "," + routRuleSize +"," + numUniqueTerminalsRout +",0," + trainFit.fitness() + "," + testFit.fitness()+ ","+ result.getGenerationalTime(j)); writer.newLine(); }*/ else { // writer.write(i + "," + j + "," + // rule.getGPTree().child.numNodes(GPNode.NODESEARCH_ALL) + "," + // numUniqueTerminals + ","); for (int k = 0; k < objectives.size(); k++) { writer.write(k + "," + trainFit.getObjective(k) + "," + testFit.getObjective(k) + ","); } writer.newLine(); } } } writer.close(); } catch (IOException e) { e.printStackTrace(); } } /** * Call this main method with several parameters * * /Users/dyska/Desktop/Uni/COMP489/GPJSS/grid_results/dynamic/raw/coevolution-fixed/0.85-max-flowtime/ * simple-rule * 30 * dynamic-job-shop * missing-0.85-4.0 * 2 * 1 * max-flowtime */ public static void main(String[] args) { int idx = 0; String trainPath = args[idx]; idx ++; RuleType ruleType = RuleType.get(args[idx]); idx ++; int numRuns = Integer.valueOf(args[idx]); //30 idx ++; String testScenario = args[idx]; //dynamic idx ++; String testSetName = args[idx]; //missing-0.85-4.0 idx ++; int numTrees = Integer.valueOf(args[idx]); //2 idx ++; int numObjectives = Integer.valueOf(args[idx]); //1 idx ++; //RuleTest ruleTest = new RuleTest(trainPath, ruleType, numRuns, testScenario, testSetName, numTrees); //modified by fzhang 24.5.2018 use multipleTreeRuleTest MultipleTreeRuleTest multipletreeruleTest = new MultipleTreeRuleTest(trainPath, ruleType, numRuns, testScenario, testSetName, numTrees); for (int i = 0; i < numObjectives; i++) { multipletreeruleTest.addObjective(args[idx]); idx ++; } multipletreeruleTest.writeToCSV(); } }
BlackIIIFOX/NodeJsTamagotchiServer
controllers/restaurants.js
<filename>controllers/restaurants.js<gh_stars>0 const express = require('express') const router = express.Router() const passport = require("passport") const ROLES = require('../models/roles') const roleChecker = require('../middlewares/role-checker') const HttpStatus = require('http-status-codes') const RestaurantCreateModel = require('../models/RestaurantCreateModel') const RestaurantUpdatableInfoModel = require('../models/RestaurantUpdatableInfoModel') const ErrorMessageModel = require('../models/ErrorMessageModel') const InvalidArgumentException = require('../models/Exceptions/InvalidArgumentException') const AlreadyExistException = require('../models/Exceptions/AlreadyExistException') const NotFoundException = require('../models/Exceptions/NotFoundException') const restaurantRepository = require('../services/RestaurantRepository') router.post("/", passport.authenticate("jwt", {session: false}), roleChecker(ROLES.Manager), createRestaurant) router.get('/', passport.authenticate("jwt", {session: false}), getAllRestaurant) router.get('/:id', passport.authenticate("jwt", {session: false}), getRestaurantById) router.put("/:id", passport.authenticate("jwt", {session: false}), roleChecker(ROLES.Manager), updateRestaurant) async function getAllRestaurant(req, res) { try { const restaurants = await restaurantRepository.Restaurants.getAll() res.json(restaurants) } catch (e) { res.status(HttpStatus.INTERNAL_SERVER_ERROR).json(new ErrorMessageModel("Internal Server Error. Error: " + e.message)) } } async function getRestaurantById(req, res) { try { const id = req.params.id const restaurant = await restaurantRepository.Restaurants.getById(id) res.json(restaurant) } catch (e) { if (e instanceof NotFoundException) { res.status(HttpStatus.NOT_FOUND).json(new ErrorMessageModel(`Restaurant ${req.params.id} not found.`)) } else { res.status(HttpStatus.INTERNAL_SERVER_ERROR).json(new ErrorMessageModel("Internal Server Error. Error: " + e.message)) } } } async function deleteRestaurant(req, res) { try { const id = req.params.id await restaurantRepository.Restaurants.delete(id) res.status(HttpStatus.OK).send() } catch (e) { if (e instanceof NotFoundException) { res.status(HttpStatus.NOT_FOUND).json(new ErrorMessageModel(`Restaurant ${req.params.id} not found.`)) } else { res.status(HttpStatus.INTERNAL_SERVER_ERROR).json(new ErrorMessageModel("Internal Server Error. Error: " + e.message)) } } } async function createRestaurant(req, res) { try { const newRestaurant = req.body if (!newRestaurant.address || !newRestaurant.positionLatitude || !newRestaurant.positionLongitude) { throw new InvalidArgumentException() } const restaurantCreateInfo = new RestaurantCreateModel(newRestaurant.address, newRestaurant.positionLatitude, newRestaurant.positionLongitude) const restaurantFullInfo = await restaurantRepository.Restaurants.add(restaurantCreateInfo) res.status(HttpStatus.CREATED).json(restaurantFullInfo) } catch (e) { if (e instanceof InvalidArgumentException) { res.status(HttpStatus.BAD_REQUEST).json(new ErrorMessageModel("Properties not set.")) } else if (e instanceof AlreadyExistException) { res.status(HttpStatus.CONFLICT).json(new ErrorMessageModel("Restaurant already exist on this position.")) } else { res.status(HttpStatus.INTERNAL_SERVER_ERROR).json(new ErrorMessageModel("Internal Server Error. Error: " + e.message)) } } } async function updateRestaurant(req, res) { try { const id = req.params.id const restaurantJson = req.body const restaurant = new RestaurantUpdatableInfoModel( restaurantJson.isParkingPresent, restaurantJson.isCardPaymentPresent, restaurantJson.isWifiPresent, restaurantJson.photos, restaurantJson.isDeleted) const updatedRestaurant = await restaurantRepository.Restaurants.update(id, restaurant) res.json(updatedRestaurant) } catch (e) { if (e instanceof NotFoundException) { res.status(HttpStatus.NOT_FOUND).json(new ErrorMessageModel(`Restaurant ${req.params.id} not found.`)) } else { res.status(HttpStatus.INTERNAL_SERVER_ERROR).json(new ErrorMessageModel("Internal Server Error. Error: " + e.message)) } } } module.exports = router
Teletha/stylist
src/main/java/stylist/property/Position.java
/* * Copyright (C) 2021 stylist Development Team * * Licensed under the MIT License (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://opensource.org/licenses/MIT */ package stylist.property; import static stylist.StyleDSL.*; import stylist.PropertyDefinition; import stylist.value.Numeric; import stylist.value.Unit; /** * @version 2018/08/30 18:27:17 */ public final class Position extends PropertyDefinition<Position> { /** * <p> * Helper method to test position property. * </p> * * @return A result. */ public boolean isRelative() { return is("relative"); } /** * <p> * Lay out all elements as though the element were not positioned, and then adjust the element's * position, without changing layout (and thus leaving a gap for the element where it would have * been had it not been positioned). The effect of position:relative on table-*-group, * table-row, table-column, table-cell, and table-caption elements is undefined. * </p> * * @return */ public Position relative() { return value("relative"); } /** * <p> * Helper method to test position property. * </p> * * @return A result. */ public boolean isAbsolute() { return is("absolute"); } /** * <p> * Do not leave space for the element. Instead, position it at a specified position relative to * its closest positioned ancestor or to the containing block. Absolutely positioned boxes can * have margins, they do not collapse with any other margins. * </p> * * @return */ public Position absolute() { return value("absolute"); } /** * <p> * Do not leave space for the element. Instead, position it at a specified position relative to * the screen's viewport and doesn't move when scrolled. When printing, position it at that * fixed position on every page. * </p> * * @return */ public Position fixed() { return value("fixed"); } /** * <p> * The element is positioned according to the normal flow of the document, and then offset * relative to its nearest scrolling ancestor and containing block (nearest block-level * ancestor), including table-related elements, based on the values of top, right, bottom, and * left. The offset does not affect the position of any other elements. * </p> * * @return */ public Position sticky() { return value("sticky"); } /** * <p> * The left CSS property specifies part of the position of positioned elements. * </p> * <p> * For absolutely positioned elements (those with position: absolute or position: fixed), it * specifies the distance between the left margin edge of the element and the left edge of its * containing block. * </p> * * @param size A position value. * @param unit A unit. * @return Chainable API. */ public Position left(double size, Unit unit) { return left(new Numeric(size, unit)); } /** * <p> * The left CSS property specifies part of the position of positioned elements. * </p> * <p> * For absolutely positioned elements (those with position: absolute or position: fixed), it * specifies the distance between the left margin edge of the element and the left edge of its * containing block. * </p> * * @param value A position value. * @return Chainable API. */ public Position left(Numeric value) { return value("left", value); } /** * <p> * The right CSS property specifies part of the position of positioned elements. * </p> * <p> * For absolutely positioned elements (those with position: absolute or position: fixed), it * specifies the distance between the right margin edge of the element and the right edge of its * containing block. * </p> * <p> * The right property has no effect on non-positioned elements. * </p> * <p> * When both the right CSS property and the left CSS property are defined, the position of the * element is overspecified. In that case, the left value has precedence when the container is * left-to-right (that is that the right computed value is set to -left), and the right value * has precedence when the container is right-to-left (that is that the left computed value is * set to -right). * </p> * * @param size A position value. * @param unit A unit. * @return Chainable API. */ public Position right(double size, Unit unit) { return right(new Numeric(size, unit)); } /** * <p> * The right CSS property specifies part of the position of positioned elements. * </p> * <p> * For absolutely positioned elements (those with position: absolute or position: fixed), it * specifies the distance between the right margin edge of the element and the right edge of its * containing block. * </p> * <p> * The right property has no effect on non-positioned elements. * </p> * <p> * When both the right CSS property and the left CSS property are defined, the position of the * element is overspecified. In that case, the left value has precedence when the container is * left-to-right (that is that the right computed value is set to -left), and the right value * has precedence when the container is right-to-left (that is that the left computed value is * set to -right). * </p> * * @param value A position value. * @return Chainable API. */ public Position right(Numeric value) { return value("right", value); } /** * <p> * The top CSS property specifies part of the position of positioned elements. It has no effect * on non-positioned elements. * </p> * <p> * For absolutely positioned elements (those with position: absolute or position: fixed), it * specifies the distance between the top margin edge of the element and the top edge of its * containing block. * </p> * <p> * For relatively positioned elements (those with position: relative), it specifies the amount * the element is moved below its normal position. * </p> * <p> * When both top and bottom are specified, the element position is over-constrained and the top * property has precedence: the computed value of bottom is set to -top, while its specified * value is ignored. * </p> * * @param size A position value. * @param unit A unit. * @return Chainable API. */ public Position top(double size, Unit unit) { return top(new Numeric(size, unit)); } /** * <p> * The top CSS property specifies part of the position of positioned elements. It has no effect * on non-positioned elements. * </p> * <p> * For absolutely positioned elements (those with position: absolute or position: fixed), it * specifies the distance between the top margin edge of the element and the top edge of its * containing block. * </p> * <p> * For relatively positioned elements (those with position: relative), it specifies the amount * the element is moved below its normal position. * </p> * <p> * When both top and bottom are specified, the element position is over-constrained and the top * property has precedence: the computed value of bottom is set to -top, while its specified * value is ignored. * </p> * * @param value A position value. * @return Chainable API. */ public Position top(Numeric value) { return value("top", value); } /** * <p> * The bottom CSS property participates in specifying the position of positioned elements. * </p> * <p> * For absolutely positioned elements, that is those with position: absolute or position: fixed, * it specifies the distance between the bottom margin edge of the element and the bottom edge * of its containing block. * </p> * <p> * For relatively positioned elements, that is those with position: relative, it specifies the * distance the element is moved above its normal position. * </p> * <p> * However, the top property overrides the bottom property, so if top is not auto, the computed * value of bottom is the negative of the computed value of top. * </p> * * @param size A position value. * @param unit A unit. * @return Chainable API. */ public Position bottom(double size, Unit unit) { return bottom(new Numeric(size, unit)); } /** * <p> * The bottom CSS property participates in specifying the position of positioned elements. * </p> * <p> * For absolutely positioned elements, that is those with position: absolute or position: fixed, * it specifies the distance between the bottom margin edge of the element and the bottom edge * of its containing block. * </p> * <p> * For relatively positioned elements, that is those with position: relative, it specifies the * distance the element is moved above its normal position. * </p> * <p> * However, the top property overrides the bottom property, so if top is not auto, the computed * value of bottom is the negative of the computed value of top. * </p> * * @return Chainable API. */ public Position bottom(Numeric value) { return value("bottom", value); } /** * <p> * Extended property for centering the box against the parent box. * </p> * * @return Chainable API. */ public Position center() { position.absolute().bottom(50, percent).right(50, percent); transform.translate(50, percent); return this; } /** * <p> * Extended property for centering the box vertically against the parent box. * </p> * * @return Chainable API. */ public Position centerVertically() { position.absolute().bottom(50, percent); transform.translateY(50, percent); return this; } /** * <p> * Extended property for centering the box horizontally against the parent box. * </p> * * @return Chainable API. */ public Position centerHorizontally() { position.absolute().right(50, percent); transform.translateX(50, percent); return this; } }
tobanteAudio/taetl
tests/set/flat_set.t.cpp
<reponame>tobanteAudio/taetl /// \copyright <NAME> 2019-2021 /// Distributed under the Boost Software License, Version 1.0. /// See accompanying file LICENSE or copy at http://boost.org/LICENSE_1_0.txt #include "etl/set.hpp" #include "etl/cstdint.hpp" #include "etl/vector.hpp" #include "testing/testing.hpp" template <typename T> constexpr auto test() -> bool { using vec_t = etl::static_vector<T, 8>; using set_t = etl::flat_set<T, vec_t>; auto s1 = set_t {}; assert(s1.size() == 0); // NOLINT assert(s1.empty()); assert(s1.max_size() == 8); auto s2 = set_t { vec_t {} }; assert(s2.size() == 0); // NOLINT assert(s2.empty()); assert(s2.max_size() == 8); return true; } constexpr auto test_all() -> bool { assert(test<etl::int8_t>()); assert(test<etl::int16_t>()); assert(test<etl::int32_t>()); assert(test<etl::int64_t>()); assert(test<etl::uint8_t>()); assert(test<etl::uint16_t>()); assert(test<etl::uint32_t>()); assert(test<etl::uint64_t>()); assert(test<float>()); assert(test<double>()); return true; } auto main() -> int { assert(test_all()); static_assert(test_all()); return 0; }
emthrm/library
test/data_structure/range_minimum_query_and_range_add_query.test.cpp
<gh_stars>1-10 /* * @brief データ構造/遅延伝播セグメント木 (range minimum query and range add query) */ #define PROBLEM "http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=DSL_2_H" #include <iostream> #include <limits> #include <vector> #include "../../data_structure/lazy_segment_tree.hpp" int main() { int n, q; std::cin >> n >> q; LazySegmentTree<monoid::RangeMinimumAndAddQuery<long long, std::numeric_limits<long long>::max()>> rmq(std::vector<long long>(n, 0)); while (q--) { int query, s, t; std::cin >> query >> s >> t; if (query == 0) { int x; std::cin >> x; rmq.apply(s, t + 1, x); } else if (query == 1) { std::cout << rmq.get(s, t + 1) << '\n'; } } return 0; }
aronjschwartz/Angel_Devil
project_files/ros/orchestrator.py
#!/usr/bin/env python """ Orchestrator ECE 578 11/24/2018 Author: <NAME> """ import time import rospy from std_msgs.msg import Int32 from std_msgs.msg import String from os import getcwd # Declare globals global play_started global play_counter global play_lines global play_motions global num_play_lines global our_turn global turing_done # Torso global torso_command # Stores the torso command that will be published global torso_done # Increments as more motions are completed global send_torso_command # Determines whether we should send the torso command global torso_command_ready # Determines whether we should send the torso command # Legs global motion_command # Stores the walker command that will be published global motion_done # Increments as more motions are completed global send_motion_command # Determines whether we should send the walker command global motion_command_ready # Determines whether we should send the walker command # Text to speech global talk_command # Stores a string of what we want to convert to speech global talk_done # Increments as more sentences are said global talk # Lets us know we are allowed to speak # Speech to text global dialog_finished # Increments as more sentences are processed global respond # Lets us know that we have a valid sentence global dialog_response # Lets us know that we should get the speech now that it's processed global dialog_intent # Lets us know what the user intent was perceived to be # Record global file_path # Return the file path of the recording file global record_done # Increments as more commands are recorded global listen # Lets us know that we should be listening global recording_ready # Lets us know that recording is ready global start_time # Stores when we started the orchestrator global rec_len # The number of seconds that we're recording # Initialize variables starting with play variables play_started = 0 play_counter = 0 num_play_lines = -1 play_lines = [] play_motions = [] our_turn = 0 turing_done = -1 # Torso section torso_command = "" torso_done = 0 send_torso_command = 0 torso_command_ready = 1 # Legs section motion_command = "" motion_done= 0 send_motion_command = 0 motion_command_ready = 1 # Text to Speech section talk_command = "" talk_done = 0 talk = 0 # Speech to text section dialog_response = "" dialog_intent = "" dialog_finished = 0 respond = 0 # Record section file_path = "" record_done = 0 listen = 0 recording_ready = 0 start_time = int(time.time()) rec_len = 4 # Initialize publishers torso_command_publisher = rospy.Publisher('torso_command', String, queue_size=1) motion_command_publisher = rospy.Publisher('motion_command', String, queue_size=1) talk_command_publisher = rospy.Publisher('talk_command', String, queue_size=1) record_command_publisher = rospy.Publisher('record_command', Int32, queue_size=1) feynman_done_publisher = rospy.Publisher('feynman_done', Int32, queue_size=1) dialog_command_publisher = rospy.Publisher('dialog_command', String, queue_size=1) # Get the lines, text files must be in same directory as orchestrator.py with open(getcwd() + '/romeoLines.txt', 'r') as file: line = file.readline() while line: num_play_lines += 1 play_lines.append(line) line = file.readline() # Get the motions with open(getcwd() + '/romeoMotions.txt', 'r') as file: motion = file.readline() while motion: play_motions.append(motion) motion = file.readline() # Collection of publisher and subscribers def orchestrator(): global play_started global send_torso_command global torso_command_ready global torso_command global send_motion_command global motion_command_ready global motion_command global talk global talk_command global respond # Respond to small talk global speech_command global recording_ready # Needed since we only want to publish once every 5 seconds curr_time = 0 prev_time = 0 # Intitialize node rospy.init_node('orchestrator', anonymous=True) # Refresh 10 times per second for now refresh_rate = rospy.Rate(10) # Subscribe to all input nodes rospy.Subscriber('motion_command_finished', Int32, motion_command_finished_callback) rospy.Subscriber('torso_command_finished', Int32, torso_command_finished_callback) rospy.Subscriber('talk_done', Int32, talk_done_callback) rospy.Subscriber('record_command_finished', Int32, record_command_finished_callback) rospy.Subscriber('file_recorded', String, file_recorded_callback) rospy.Subscriber('turing_done', Int32, turing_done_callback) rospy.Subscriber('dialog_finished', Int32, dialog_finished_callback) rospy.Subscriber('dialog_response', String, dialog_response_callback) rospy.Subscriber('dialog_intent', String, dialog_intent_callback) while not rospy.is_shutdown(): if play_started: # If play is started, go to an entirely different function execute_play() else: curr_time = int(time.time()) - start_time if curr_time != prev_time and curr_time % rec_len == 0: # If 5 seconds have elapsed prev_time = curr_time # Keep track of the time so we send just one record command record_command_publisher.publish(rec_len) print("tick") # Get file path from Charles, send it to Emma if recording_ready: print("Sending the file path \"{}\".".format(file_path)) dialog_command_publisher.publish(file_path) recording_ready = 0 # If we are allowed to send a torso command, send it if torso_command_ready and send_torso_command: print("Sending torso command \"{0}\"".format(torso_command)) torso_command_publisher.publish(torso_command) torso_command_ready = 0 send_torso_command = 0 #else: # print("Didn't move torso because ready = {0} and send = {1}".format(torso_command_ready, send_torso_command)) # If we are allowed to send a motion command, send it if motion_command_ready and send_motion_command: print("Sending motion command \"{0}\"".format(motion_command)) motion_command_publisher.publish(motion_command) motion_command_ready = 0 send_motion_command = 0 #else: # print("Didn't move legs because ready = {0} and send = {1}".format(motion_command_ready, send_motion_command)) # If there is something we heard that should be acted on, act on it if respond: small_talk() respond = 0 # If we are allowed to say something, send it if talk: talk_command_publisher.publish(talk_command) talk = 0 refresh_rate.sleep() # Keep python running until node is stopped rospy.spin() # Function for small talk def small_talk(): global dialog_response global dialog_intent global play_started global talk_command global talk global send_motion_command global send_torso_command global motion_command global torso_command # Store as local variables so there's no chance this can be updated outside the scope of this function intent = dialog_intent talk_command = dialog_response if intent == "backward_walk": motion_command = "walk 4 180" # Publish the motion send_motion_command = 1 elif intent == "dance": motion_command = "bounce 10 0.5" # Publish the motion torso_command = "monkey 5" # Publish the motion send_motion_command = 1 send_torso_command = 1 elif intent == "forward_walk": motion_command = "walk 4 0" # Publish the motion send_motion_command = 1 elif intent == "play": play_started = 1 talk = 1 # Function to execute the play def execute_play(): global play_started global play_counter global play_motions global play_lines global our_turn # True if it's our turn to speak, move, or both global motion_command_ready global torso_command_ready global talk our_turn = 1 # We're saying a monolouge # If it's our turn if our_turn: current_line = play_lines[play_counter].rstrip('\n') current_motion = play_motions[play_counter].rstrip('\n') # If we can talk and move if talk and motion_command_ready and torso_command_ready: if current_line != "WAIT_FOR_TURING": # Speak as long as the line isn't "WAIT_FOR_TURING" talk_command_publisher.publish(current_line) # Publish the line motion_command_publisher.publish(current_motion) # Publish the motion torso_command_publisher.publish(current_motion) # Publish the motion print("Sending the line \"{0}\" and the motion \"{1}\".".format(current_line, current_motion)) play_counter += 1 # Increment counter talk = 0 # Reset the flags for tts and motion motion_command_ready = 0 torso_command_ready = 0 if play_counter > num_play_lines: # At end of play, stop and reset for next play our_turn = 0 play_started = 0 play_counter = 0 print("And that concludes act I of our play.") else: our_turn = 0 # Stop talking since now it's Turing's turn play_counter += 1 # Increment counter past the wait line. We'll still be blocked because our_turn is False feynman_done_publisher.publish(play_counter) # Publish a one to tell Turing it's his turn print("Done talking and moving for now. Waiting for Turing.") else: print("Waiting on talk ({0}), motion_command_ready({1}), or torso_command_ready({2})." .format(talk, motion_command_ready, torso_command_ready)) else: # feynman_done_publisher.publish(play_counter) # Publish a new integer to tell Turing it's his turn print("Waiting for Turing") # Callback function for Turing done def turing_done_callback(data): global our_turn global turing_done if data.data == turing_done: pass else: our_turn = 1 turing_done = data.data print("Turing said he's done with his part.") # Callback function for dialog done def dialog_intent_callback(data): global dialog_intent dialog_intent = data.data if respond: print("Dialog intent is \"{}\"".format(dialog_intent)) # Callback function for dialog done def dialog_response_callback(data): global dialog_response dialog_response = data.data if respond: print("Dialog response is \"{}\"".format(dialog_response)) # Callback function for dialog done def dialog_finished_callback(data): global dialog_finished global respond if data.data == dialog_finished: # Do nothing unless dialog_finished increments from the dialog node pass else: dialog_finished = data.data respond = 1; print("Dialog said it's done.") # Callback function for file_recorded def file_recorded_callback(data): global file_path file_path = data.data # Callback function for record done def record_command_finished_callback(data): global record_done global recording_ready if data.data == record_done: # Do nothing unless record_done increments from the talk node pass else: record_done = data.data recording_ready = 1 print("Done recording.") # Callback function for talk done def talk_done_callback(data): global talk_done global talk if data.data == talk_done: # Do nothing unless talk_done increments from the talk node pass else: talk_done = data.data talk = 1 print("Done converting text to speech.") # Callback function for torso command finished def torso_command_finished_callback(data): global torso_done global torso_command_ready if data.data == torso_done: # Do nothing unless the torso_done increments pass else: torso_command_ready = 1 torso_done = data.data print("Torso command is finished.") # Callback function for motion command finished def motion_command_finished_callback(data): global motion_done global motion_command_ready if data.data == motion_done: # Do nothing unless the motion_done increments pass else: motion_command_ready = 1 motion_done = data.data print("Motion command is finished.") if __name__ == "__main__": # Call orchestrator but capture exception if thrown try: print("Starting orchestrator") orchestrator() except rospy.ROSInterruptException as e: print(e)
timberbacklabs/JavaDesignPatterns
src/main/java/StructuralPatterns/GoF/Proxy/ProtectionProxy/ProtectedProxy.java
package StructuralPatterns.GoF.Proxy.ProtectionProxy; import java.util.*; public class ProtectedProxy extends AbstractSubject { static ConcreteSubject subject; private String currentUser; private List<String> registeredUsers; public ProtectedProxy(String currentUser) { registeredUsers = Arrays.asList("me", "you", "him", "her"); this.currentUser = currentUser; } @Override public void method() { System.out.println(currentUser + " is calling proxy method()"); // "fake auth check" if (registeredUsers.contains(currentUser)) { // Lazy init. Remember this is a null check for first time init. if (subject == null) subject = new ConcreteSubject(); subject.method(); } else { System.out.println("Hit the road " + currentUser + ", you don't have permssion."); } } }
metincansiper/Paxtools
paxtools-core/src/main/java/org/biopax/paxtools/impl/level2/pathwayStepImpl.java
package org.biopax.paxtools.impl.level2; import org.biopax.paxtools.model.BioPAXElement; import org.biopax.paxtools.model.level2.pathway; import org.biopax.paxtools.model.level2.pathwayStep; import org.biopax.paxtools.model.level2.process; import java.util.HashSet; import java.util.Set; /** */ class pathwayStepImpl extends BioPAXLevel2ElementImpl implements pathwayStep { // ------------------------------ FIELDS ------------------------------ private Set<process> STEP_INTERACTIONS; private Set<pathwayStep> NEXT_STEP; private Set<pathwayStep> NEXT_STEPof; private Set<pathway> PATHWAY_COMPONENTSof; // --------------------------- CONSTRUCTORS --------------------------- public pathwayStepImpl() { this.NEXT_STEP = new HashSet<pathwayStep>(); this.NEXT_STEPof = new HashSet<pathwayStep>(); this.PATHWAY_COMPONENTSof = new HashSet<pathway>(); this.STEP_INTERACTIONS = new HashSet<process>(); } // ------------------------ INTERFACE METHODS ------------------------ // --------------------- Interface BioPAXElement --------------------- public Class<? extends BioPAXElement> getModelInterface() { return pathwayStep.class; } // --------------------- Interface pathwayComponent --------------------- public Set<pathway> isPATHWAY_COMPONENTSof() { return PATHWAY_COMPONENTSof; } // --------------------- Interface pathwayStep --------------------- public Set<process> getSTEP_INTERACTIONS() { return STEP_INTERACTIONS; } public void setSTEP_INTERACTIONS(Set<process> STEP_INTERACTIONS) { if (this.STEP_INTERACTIONS != null) { for (process process : STEP_INTERACTIONS) { process.isSTEP_INTERACTIONSOf().remove(this); } } this.STEP_INTERACTIONS = STEP_INTERACTIONS; if (this.STEP_INTERACTIONS != null) { for (process process : STEP_INTERACTIONS) { process.isSTEP_INTERACTIONSOf().add(this); } } } public void addSTEP_INTERACTIONS(process processStep) { this.STEP_INTERACTIONS.add(processStep); processStep.isSTEP_INTERACTIONSOf().add(this); } public void removeSTEP_INTERACTIONS(process processStep) { processStep.isSTEP_INTERACTIONSOf().remove(this); this.STEP_INTERACTIONS.remove(processStep); } // --------------------- ACCESORS and MUTATORS---------------`------ public Set<pathwayStep> getNEXT_STEP() { return NEXT_STEP; } public void setNEXT_STEP(Set<pathwayStep> NEXT_STEP) { if (this.NEXT_STEP != null) { for (pathwayStep pathwayStep : this.NEXT_STEP) { pathwayStep.isNEXT_STEPof().remove(this); } } this.NEXT_STEP = NEXT_STEP; if (this.NEXT_STEP != null) { for (pathwayStep pathwayStep : NEXT_STEP) { pathwayStep.isNEXT_STEPof().add(this); } } } public void addNEXT_STEP(pathwayStep NEXT_STEP) { this.NEXT_STEP.add(NEXT_STEP); NEXT_STEP.isNEXT_STEPof().add(this); } public void removeNEXT_STEP(pathwayStep NEXT_STEP) { NEXT_STEP.isNEXT_STEPof().remove(this); this.NEXT_STEP.remove(NEXT_STEP); } public Set<pathwayStep> isNEXT_STEPof() { return NEXT_STEPof; } }
ryan-williams/guacamole
src/main/scala/org/bdgenomics/guacamole/Bases.scala
/** * Licensed to Big Data Genomics (BDG) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The BDG licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bdgenomics.guacamole /** * We represent a nucleotide base as a Byte, whose value is equal to the ASCII value of the character representing the * base (e.g. A, C, T, G). We represent a nucleotide sequence as an Array[Byte]. * * This is an optimization over java Chars and Strings which use two bytes per character. * * Unfortunately, working with Bytes and especially Array[Byte] is a bit of a hassle and can be error-prone. The * functions here are for working with these types correctly. * * Things to know: * * - you can compare two bases b1, b2 as you'd expect: b1 == b2 * * - you CANNOT compare two Array[Byte] instances with == (or even .equals). Use the equal() function defined here. * * - If b is a base (say "A") then b.toString does NOT give you want (in this case it would give you "65"). Use the * baseToString() function defined here. * */ object Bases { /** Standard bases. Note that other bases are sometimes used as well (e.g. "N"). */ val A = "A".getBytes()(0) val C = "C".getBytes()(0) val T = "T".getBytes()(0) val G = "G".getBytes()(0) // Unknown Base val N = "N".getBytes()(0) // Unknown alternate base val ALT = "<ALT>".getBytes().toSeq object BasesOrdering extends Ordering[Seq[Byte]] { override def compare(x: Seq[Byte], y: Seq[Byte]): Int = { Bases.basesToString(x).compare(Bases.basesToString(y)) } } /** Is the given base one of the 4 canonical DNA bases? */ def isStandardBase(base: Byte): Boolean = { base == Bases.A || base == Bases.C || base == Bases.T || base == Bases.G } /** Throw an error if the given base is not one of the canonical DNA bases. */ def assertStandardBase(base: Byte) = { assert(isStandardBase(base), "Invalid base: %s".format(base.toChar.toString)) } /** Are all the given bases standard? */ def allStandardBases(bases: Seq[Byte]) = { assert(bases.forall(b => isStandardBase(b)), "Invalid base array: %s".format(bases.map(_.toChar).mkString)) } /** Throw an error if any of the given bases are not standard. */ def assertAllStandardBases(bases: Seq[Byte]) = { assert(bases.forall(b => isStandardBase(b)), "Invalid base array: %s".format(bases.map(_.toChar).mkString)) } /** Convert a string (e.g. "AAAGGC") to a byte array. */ def stringToBases(string: String): Seq[Byte] = { string.toUpperCase.getBytes } /** Convert a base to a 1-character string. */ def baseToString(base: Byte): String = { base.toChar.toString } /** Convert a base sequence to a String. */ def basesToString(bases: Iterable[Byte]): String = { bases.map(_.toChar).mkString } }
autumnblazey/autumnblaze
js/events/index.js
"use strict"; module.exports = autumnblaze => { const fs = require("fs"); const path = require("path"); const eventstuffs = {}; const files = fs.readdirSync(path.resolve(__dirname, ".")).filter(file => file !== "index.js" && !file.startsWith("_")); files.forEach(file => { if (file.endsWith(".js")) file = file.slice(0, file.length - 3); eventstuffs[file] = require("./" + file)(autumnblaze); autumnblaze.bot.on(file, eventstuffs[file]); }); return eventstuffs; };
tanishiking/dotty
tests/run/constValueTuple.scala
import compiletime.constValueTuple @main def Test = println(constValueTuple["foo" *: "bar" *: 10 *: 2.5 *: EmptyTuple])
mrehman29/open-vm-tools
open-vm-tools/common-agent/Cpp/Framework/Framework/src/Common/CThreadUtils.h
<filename>open-vm-tools/common-agent/Cpp/Framework/Framework/src/Common/CThreadUtils.h /* * Author: bwilliams * Created: Jan 21, 2011 * * Copyright (C) 2011-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef CThreadUtils_H_ #define CThreadUtils_H_ namespace Caf { class COMMONAGGREGATOR_LINKAGE CThreadUtils { public: typedef void* (*threadFunc) (void* data); public: static uint32 getThreadStackSizeKb(); static GThread* startJoinable(threadFunc func, void* data); static void join(GThread* thread); static void sleep(const uint32 milliseconds); private: CAF_CM_DECLARE_NOCREATE(CThreadUtils); }; } #endif /* CThreadUtils_H_ */
minigame-network/core
src/me/chasertw123/minigames/core/listeners/general/Event_AsyncPlayerChat.java
<reponame>minigame-network/core<filename>src/me/chasertw123/minigames/core/listeners/general/Event_AsyncPlayerChat.java<gh_stars>1-10 package me.chasertw123.minigames.core.listeners.general; import me.chasertw123.minigames.core.Main; import me.chasertw123.minigames.core.api.v2.CoreAPI; import me.chasertw123.minigames.core.event.UserChatEvent; import me.chasertw123.minigames.core.user.User; import me.chasertw123.minigames.shared.infraction.Punishment; import me.chasertw123.minigames.shared.infraction.PunishmentType; import org.bukkit.ChatColor; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.player.AsyncPlayerChatEvent; import java.util.stream.Collectors; /** * Created by Chase on 7/24/2017. */ public class Event_AsyncPlayerChat implements Listener { @EventHandler (priority = EventPriority.HIGHEST) public void onAsyncPlayerChat(AsyncPlayerChatEvent e) { e.setCancelled(true); User sender = CoreAPI.getUser(e.getPlayer()); for (Punishment punishment : sender.getPunishments()) if (punishment.getType() == PunishmentType.MUTE && (punishment.getDateIssued() + punishment.getTimeScale().getUnixTime()) > System.currentTimeMillis()) { sender.sendPrefixedMessage(ChatColor.RED + "You're currently muted. Remaining time: " + punishment.getTimeRemaining()); return; } UserChatEvent event = new UserChatEvent(sender, e.getMessage(), CoreAPI.getOnlinePlayers().stream() .filter(receiver -> !receiver.getUUID().equals(sender.getUUID())) .collect(Collectors.toList())); Main.getInstance().getServer().getPluginManager().callEvent(event); if (event.isCancelled()) return; if (event.getRecipientMessage() != null && event.getRecipients().size() > 0) event.getRecipients().forEach(pp -> pp.getPlayer().spigot().sendMessage(event.getRecipientMessage())); if (event.getSenderMessage() != null) sender.getPlayer().spigot().sendMessage(event.getSenderMessage()); } }
bburan/psiexperiment
psi/controller/input.py
<reponame>bburan/psiexperiment import logging log = logging.getLogger(__name__) from collections import deque, namedtuple from copy import copy from functools import partial from queue import Empty, Queue import numpy as np from scipy import signal from atom.api import (Unicode, Float, Typed, Int, Property, Enum, Bool, Callable, List) from enaml.application import deferred_call from enaml.core.api import Declarative, d_ from ..util import coroutine from .channel import Channel from .calibration.util import db, dbi, patodb from .device import Device from .queue import AbstractSignalQueue from psi.core.enaml.api import PSIContribution from psi.controller.calibration.api import FlatCalibration class InputData(np.ndarray): def __new__(cls, input_array, metadata=None): obj = np.asarray(input_array).view(cls) obj.metadata = metadata if metadata else {} return obj def __array_finalize__(self, obj): if obj is None: return self.metadata = getattr(obj, 'metadata', None) def concatenate(input_data, axis=None): b = input_data[0] for d in input_data[1:]: if d.metadata != b.metadata: log.debug('%r vs %r', d.metadata, b.metadata) raise ValueError('Cannot combine InputData set') arrays = np.concatenate(input_data, axis=axis) return InputData(arrays, b.metadata) @coroutine def broadcast(*targets): while True: data = (yield) for target in targets: target(data) class Input(PSIContribution): name = d_(Unicode()).tag(metadata=True) label = d_(Unicode()).tag(metadata=True) force_active = d_(Bool(False)).tag(metadata=True) source_name = d_(Unicode()) source = d_(Typed(Declarative).tag(metadata=True), writable=False) channel = Property() engine = Property() fs = Property().tag(metadata=True) dtype = Property().tag(metadata=True) unit = Property().tag(metadata=True) calibration = Property() active = Property() inputs = List() def _default_name(self): if self.source is not None: base_name = self.source.name else: base_name = self.parent.name return base_name + '_' + self.__class__.__name__.lower() def _default_label(self): return self.name.replace('_', ' ') def add_input(self, i): if i in self.inputs: return self.inputs.append(i) i.source = self def remove_input(self, i): if i not in self.inputs: return self.inputs.remove(i) i.source = None def _get_fs(self): return self.source.fs def _get_dtype(self): return self.source.dtype def _get_calibration(self): return self.source.calibration def _get_unit(self): return self.source.unit def _get_channel(self): source = self.source while True: if isinstance(source, Channel): return source else: source = source.source def _get_engine(self): return self.channel.engine def configure(self): cb = self.configure_callback() self.engine.register_ai_callback(cb, self.channel.name) def configure_callback(self): targets = [i.configure_callback() for i in self.inputs if i.active] log.debug('Configured callback for %s with %d targets', self.name, len(targets)) if len(targets) == 1: return targets[0] # If we have more than one target, need to add a broadcaster return broadcast(*targets).send def add_callback(self, cb): callback = Callback(function=cb) self.add_input(callback) def _get_active(self): return self.force_active or any(i.active for i in self.inputs) class ContinuousInput(Input): pass class EventInput(Input): pass class EpochInput(Input): duration = Property().tag(metadata=True) def _get_duration(self): return self.source.duration class Callback(Input): function = d_(Callable()) def configure_callback(self): log.debug('Configuring callback for {}'.format(self.name)) return self.function def _get_active(self): return True ################################################################################ # Continuous input types ################################################################################ @coroutine def custom_input(function, target): while True: data = (yield) function(data, target) class CustomInput(Input): function = d_(Callable()) def configure_callback(self): cb = super().configure_callback() return custom_input(self.function, cb).send @coroutine def calibrate(calibration, target): sens = dbi(calibration.get_sens(1000)) while True: data = (yield) target(data/sens) class CalibratedInput(ContinuousInput): def _get_calibration(self): return FlatCalibration(0) def configure_callback(self): cb = super().configure_callback() return calibrate(self.source.calibration, cb).send @coroutine def rms(n, target): data = None while True: if data is None: data = (yield) else: data = np.concatenate((data, (yield)), axis=-1) while data.shape[-1] >= n: result = np.mean(data[..., :n]**2, axis=0)**0.5 target(result[np.newaxis]) data = data[..., n:] class RMS(ContinuousInput): duration = d_(Float()).tag(metadata=True) def _get_fs(self): n = round(self.duration*self.source.fs) return self.source.fs/n def configure_callback(self): n = round(self.duration*self.source.fs) cb = super().configure_callback() return rms(n, cb).send @coroutine def spl(target, sens): v_to_pa = dbi(sens) while True: data = (yield) data /= v_to_pa spl = patodb(data) target(spl) class SPL(ContinuousInput): def configure_callback(self): cb = super().configure_callback() sens = self.calibration.get_sens(1000) return spl(cb, sens).send @coroutine def iirfilter(N, Wn, rp, rs, btype, ftype, target): b, a = signal.iirfilter(N, Wn, rp, rs, btype, ftype=ftype) if np.any(np.abs(np.roots(a)) > 1): raise ValueError('Unstable filter coefficients') # Initialize the state of the filter and scale it by y[0] to avoid a # transient. zi = signal.lfilter_zi(b, a) y = (yield) zo = zi*y[0] while True: y, zo = signal.lfilter(b, a, y, zi=zo) target(y) y = (yield) class IIRFilter(ContinuousInput): # Allows user to deactivate the filter entirely during configuration if # desired. Ideally we could just remove it from the graph, but it seems a # bit tricky to do so as some other components may be looking for the # output of this block. passthrough = d_(Bool(False)).tag(metadata=True) N = d_(Int(1)).tag(metadata=True) btype = d_(Enum('bandpass', 'lowpass', 'highpass', 'bandstop')).tag(metadata=True) ftype = d_(Enum('butter', 'cheby1', 'cheby2', 'ellip', 'bessel')).tag(metadata=True) f_highpass = d_(Float()).tag(metadata=True) f_lowpass = d_(Float()).tag(metadata=True) wn = Property() def _get_wn(self): if self.btype == 'lowpass': log.debug('Lowpass at %r (fs=%r)', self.f_lowpass, self.fs) return self.f_lowpass/(0.5*self.fs) elif self.btype == 'highpass': log.debug('Highpass at %r (fs=%r)', self.f_lowpass, self.fs) return self.f_highpass/(0.5*self.fs) else: log.debug('Bandpass %r to %r (fs=%r)', self.f_highpass, self.f_lowpass, self.fs) return (self.f_highpass/(0.5*self.fs), self.f_lowpass/(0.5*self.fs)) def configure_callback(self): cb = super().configure_callback() if self.passthrough: return cb return iirfilter(self.N, self.wn, None, None, self.btype, self.ftype, cb).send @coroutine def blocked(block_size, target): data = [] n = 0 while True: d = (yield) if d is Ellipsis: data = [] target(d) continue n += d.shape[-1] data.append(d) if n >= block_size: merged = concatenate(data, axis=-1) while merged.shape[-1] >= block_size: target(merged[..., :block_size]) merged = merged[..., block_size:] data = [merged] n = merged.shape[-1] class Blocked(ContinuousInput): ''' Chunk data based on time ''' duration = d_(Float()).tag(metadata=True) def configure_callback(self): if self.duration <= 0: m = 'Duration for {} must be > 0'.format(self.name) raise ValueError(m) cb = super().configure_callback() block_size = round(self.duration*self.fs) return blocked(block_size, cb).send @coroutine def accumulate(n, axis, newaxis, status_cb, target): data = [] while True: d = (yield) if d is Ellipsis: data = [] target(d) continue if newaxis: data.append(d[np.newaxis]) else: data.append(d) if len(data) == n: data = concatenate(data, axis=axis) target(data) data = [] if status_cb is not None: status_cb(len(data)) class Accumulate(ContinuousInput): ''' Chunk data based on number of calls ''' n = d_(Int()).tag(metadata=True) axis = d_(Int(-1)).tag(metadata=True) newaxis = d_(Bool(False)).tag(metadata=True) status_cb = d_(Callable(lambda x: None)) def configure_callback(self): cb = super().configure_callback() return accumulate(self.n, self.axis, self.newaxis, self.status_cb, cb).send @coroutine def capture(fs, queue, target): s0 = 0 t_start = None # Time, in seconds, of capture start s_next = None # Sample number fo rcapture active = False while True: # Wait for new data to come in data = (yield) try: # We've recieved a new command. The command will either be None # (i.e., no more acquisition for a bit) or a floating-point value # (indicating when next acquisition should begin). t_start = queue.get(block=False) if t_start is not None: log.debug('Starting capture at %f', t_start) s_next = round(t_start*fs) target(Ellipsis) elif t_start is None: log.debug('Ending capture') s_next = None elif t_start < t0: raise SystemError('Data lost') except Empty: pass if (s_next is not None) and (s_next >= s0): i = s_next-s0 if i < data.shape[-1]: d = data[i:] d.metadata['capture'] = t_start target(d) s_next += d.shape[-1] s0 += data.shape[-1] class Capture(ContinuousInput): queue = Typed(Queue) def configure_callback(self): self.queue = Queue() cb = super().configure_callback() return capture(self.fs, self.queue, cb).send @coroutine def downsample(q, target): y_remainder = np.array([]) while True: y = np.r_[y_remainder, (yield)] remainder = len(y) % q if remainder != 0: y, y_remainder = y[:-remainder], y[-remainder:] else: y_remainder = np.array([]) result = y[::q] if len(result): target(result) class Downsample(ContinuousInput): q = d_(Int()).tag(metadata=True) def _get_fs(self): return self.source.fs/self.q def configure_callback(self): cb = super().configure_callback() return downsample(self.q, cb).send @coroutine def decimate(q, target): b, a = signal.cheby1(4, 0.05, 0.8/q) if np.any(np.abs(np.roots(a)) > 1): raise ValueError('Unstable filter coefficients') zf = signal.lfilter_zi(b, a) y_remainder = np.array([]) while True: y = np.r_[y_remainder, (yield)] remainder = len(y) % q if remainder != 0: y, y_remainder = y[:-remainder], y[-remainder:] else: y_remainder = np.array([]) y, zf = signal.lfilter(b, a, y, zi=zf) result = y[::q] if len(result): target(result) class Decimate(ContinuousInput): q = d_(Int()).tag(metadata=True) def _get_fs(self): return self.source.fs/self.q def configure_callback(self): cb = super().configure_callback() return decimate(self.q, cb).send @coroutine def discard(discard_samples, cb): discarded = discard_samples while True: samples = (yield) if samples is Ellipsis: to_discard = discarded cb(samples) continue if discard_samples == 0: cb(samples) elif samples.shape[-1] <= discard_samples: discard_samples -= samples.shape[-1] elif samples.shape[-1] > discard_samples: s = samples[..., discard_samples:] discard_samples -= s.shape[-1] cb(s) class Discard(ContinuousInput): duration = d_(Float()).tag(metadata=True) def configure_callback(self): cb = super().configure_callback() samples = round(self.duration*self.fs) return discard(samples, cb).send @coroutine def threshold(threshold, target): while True: samples = (yield) target(samples >= threshold) class Threshold(ContinuousInput): threshold = d_(Float(0)).tag(metadata=True) def configure_callback(self): cb = super().configure_callback() return threshold(self.threshold, cb).send @coroutine def average(n, target): data = (yield) axis = 0 while True: while data.shape[axis] >= n: s = [Ellipsis]*data.ndim s[axis] = np.s_[:block_size] target(data[s].mean(axis=axis)) s[axis] = np.s_[block_size:] data = data[s] new_data = (yield) data = np.concatenate((data, new_data), axis=axis) class Average(ContinuousInput): n = d_(Float()).tag(metadata=True) def configure_callback(self): cb = super().configure_callback() return average(self.n, cb).send @coroutine def delay(n, target): data = np.full(n, np.nan) while True: target(data) data = (yield) class Delay(ContinuousInput): # This can be set to account for things such as the AO and AI filter delays # on the 4461. For AO at 100 kHz, the output delay is ~0.48 msec. For the # AI at 25e-3, the input delay is 63 samples (divide this by the # acquisition rate). delay = d_(Float(0)).tag(metadata=True) def configure_callback(self): cb = super().configure_callback() n = int(self.delay * self.fs) return delay(n, cb).send @coroutine def transform(function, target): while True: data = (yield) transformed_data = function(data) target(transformed_data) class Transform(ContinuousInput): function = d_(Callable()) def configure_callback(self): cb = super().configure_callback() return transform(self.function, cb).send ################################################################################ # Event input types ################################################################################ @coroutine def edges(initial_state, min_samples, fs, target): if min_samples < 1: raise ValueError('min_samples must be greater than 1') prior_samples = np.tile(initial_state, min_samples) t_prior = -min_samples while True: # Wait for new data to become available new_samples = (yield) samples = np.r_[prior_samples, new_samples] ts_change = np.flatnonzero(np.diff(samples, axis=-1)) + 1 ts_change = np.r_[ts_change, samples.shape[-1]] events = [] for tlb, tub in zip(ts_change[:-1], ts_change[1:]): if (tub-tlb) >= min_samples: if initial_state == samples[tlb]: continue edge = 'rising' if samples[tlb] == 1 else 'falling' initial_state = samples[tlb] ts = t_prior + tlb events.append((edge, ts/fs)) if events: target(events) t_prior += new_samples.shape[-1] prior_samples = samples[..., -min_samples:] class Edges(EventInput): initial_state = d_(Int(0)).tag(metadata=True) debounce = d_(Int()).tag(metadata=True) def configure_callback(self): cb = super().configure_callback() return edges(self.initial_state, self.debounce, self.fs, cb).send ################################################################################ # Epoch input types ################################################################################ @coroutine def capture_epoch(epoch_t0, epoch_samples, info, callback): ''' Coroutine to facilitate epoch acquisition ''' # This coroutine will continue until it acquires all the samples it needs. # It then provides the samples to the callback function and exits the while # loop. accumulated_data = [] while True: tlb, data = (yield) samples = data.shape[-1] if epoch_t0 < tlb: # We have missed the start of the epoch. Notify the callback of this m = 'Missed samples for epoch of %d samples starting at %d' log.warn(m, epoch_samples, epoch_t0) callback({'signal': None, 'info': info}) break elif epoch_t0 <= (tlb + samples): # The start of the epoch is somewhere inside `data`. Find the start # `i` and determine how many samples `d` to extract from `data`. # It's possible that data does not contain the entire epoch. In # that case, we just pull out what we can and save it in # `accumulated_data`. We then update start to point to the last # acquired sample `i+d` and update duration to be the number of # samples we still need to capture. i = int(epoch_t0-tlb) d = int(min(epoch_samples, samples-i)) accumulated_data.append(data[..., i:i+d]) epoch_t0 += d epoch_samples -= d # Check to see if we've finished acquiring the entire epoch. If so, # send it to the callback. if epoch_samples == 0: accumulated_data = np.concatenate(accumulated_data, axis=-1) callback({'signal': accumulated_data, 'info': info}) break @coroutine def extract_epochs(fs, queue, epoch_size, poststim_time, buffer_size, target, empty_queue_cb=None): # The variable `tlb` tracks the number of samples that have been acquired # and reflects the lower bound of `data`. For example, if we have acquired # 300,000 samples, then the next chunk of data received from (yield) will # start at sample 300,000 (remember that Python is zero-based indexing, so # the first sample has an index of 0). tlb = 0 epoch_coroutines = [] prior_samples = [] # How much historical data to keep (for retroactively capturing epochs) buffer_samples = int(buffer_size*fs) # Since we may capture very short, rapidly occuring epochs (at, say, 80 per # second), I find it best to accumulate as many epochs as possible before # calling the next target. This list will maintain the accumulated set. epochs = [] while True: # Wait for new data to become available data = (yield) prior_samples.append((tlb, data)) # Send the data to each coroutine. If a StopIteration occurs, this means # that the epoch has successfully been acquired and has been sent to the # callback and we can remove it. Need to operate on a copy of list since # it's bad form to modify a list in-place. for epoch_coroutine in epoch_coroutines[:]: try: epoch_coroutine.send((tlb, data)) except StopIteration: epoch_coroutines.remove(epoch_coroutine) # Check to see if more epochs have been requested. Information will be # provided in seconds, but we need to convert this to number of # samples. while queue: info = queue.popleft() # Figure out how many samples to capture for that epoch t0 = round(info['t0'] * fs) info['poststim_time'] = poststim_time if epoch_size: info['epoch_size'] = epoch_size total_epoch_size = epoch_size + poststim_time else: info['epoch_size'] = info['duration'] total_epoch_size = info['duration'] + poststim_time epoch_samples = round(total_epoch_size * fs) epoch_coroutine = capture_epoch(t0, epoch_samples, info, epochs.append) try: # Go through the data we've been caching to facilitate # historical acquisition of data. If this completes without a # StopIteration, then we have not finished capturing the full # epoch. for prior_sample in prior_samples: epoch_coroutine.send(prior_sample) epoch_coroutines.append(epoch_coroutine) except StopIteration: pass tlb = tlb + data.shape[-1] # Once the new segment of data has been processed, pass all complete # epochs along to the next target. if len(epochs) != 0: target(epochs[:]) epochs[:] = [] # Check to see if any of the cached samples are older than the specified # `buffer_samples` and discard them. while True: oldest_samples = prior_samples[0] tub = oldest_samples[0] + oldest_samples[1].shape[-1] if tub < (tlb-buffer_samples): prior_samples.pop(0) else: break if not (queue or epoch_coroutines) and empty_queue_cb: # If queue and epoch coroutines are complete, call queue callback. empty_queue_cb() empty_queue_cb = None class ExtractEpochs(EpochInput): queue = d_(Typed(deque, {})) buffer_size = d_(Float(0)).tag(metadata=True) #: Defines the size of the epoch (if NaN, this is automatically drawn from #: the information provided by the queue). epoch_size = d_(Float(0)).tag(metadata=True) #: Defines the extra time period to capture beyond the epoch duration. poststim_time = d_(Float(0).tag(metadata=True)) complete = Bool(False) def mark_complete(self): self.complete = True def configure_callback(self): #if self.epoch_size == 0: #raise ValueError('Epoch size not configured') if np.isinf(self.epoch_size): m = f'ExtractEpochs {self.name} has an infinite epoch size' raise ValueError(m) cb = super().configure_callback() return extract_epochs(self.fs, self.queue, self.epoch_size, self.poststim_time, self.buffer_size, cb, self.mark_complete).send def _get_duration(self): return self.epoch_size + self.poststim_time # force change notification for duration def _observe_epoch_size(self, event): self.notify('duration', self.duration) def _observe_poststim_time(self, event): self.notify('duration', self.duration) @coroutine def reject_epochs(reject_threshold, mode, status, valid_target): if mode == 'absolute value': accept = lambda s: np.max(np.abs(s)) < reject_threshold elif mode == 'amplitude': accept = lambda s: np.ptp(s) < reject_threshold while True: epochs = (yield) # Check for valid epochs and send them if there are any valid = [e for e in epochs if accept(e['signal'])] if len(valid): valid_target(valid) def update(): # Update the status. Must be wrapped in a deferred call to ensure # that the update occurs on the GUI thread. status.total += len(epochs) status.rejects += len(epochs)-len(valid) status.reject_ratio = status.rejects / status.total deferred_call(update) class RejectEpochs(EpochInput): ''' Rejects epochs whose amplitude exceeds a specified threshold. Attributes ---------- threshold : float Reject threshold mode : {'absolute value', 'amplitude'} If absolute value, rejects epoch if the minimum or maximum exceeds the reject threshold. If amplitude, rejects epoch if the difference between the minimum and maximum exceeds the reject threshold. ''' threshold = d_(Float()).tag(metadata=True) mode = d_(Enum('absolute value', 'amplitude')).tag(metadata=True) total = Int() rejects = Int() reject_ratio = Float() def configure_callback(self): valid_cb = super().configure_callback() return reject_epochs(self.threshold, self.mode, self, valid_cb).send @coroutine def detrend(mode, target): if mode is None: do_detrend = lambda x: x else: do_detrend = partial(signal.detrend, type=mode) while True: epochs = [] for epoch in (yield): epoch = { 'signal': do_detrend(epoch['signal']), 'info': epoch['info'] } epochs.append(epoch) target(epochs) class Detrend(EpochInput): ''' Removes linear trend from epoch Attributes ---------- mode : {None, 'linear', 'constant'} If None, this acts as a passthrough. If 'linear', the result of a linear least-squares fit is subtracted from the epoch. If 'constant', only the mean of the epoch is subtracted. ''' mode = d_(Enum('constant', 'linear', None)) def configure_callback(self): cb = super().configure_callback() return detrend(self.mode, cb).send
catmaid/catpy
tests/test_catpy.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ test_client ---------------------------------- Tests for `catpy.client` module. """ from __future__ import absolute_import import catpy.client import catpy.util def test_make_url_double_slash(): """Tests for catpy.client.make_url """ url = catpy.client.make_url("foo/", "/bar") assert url == "foo/bar", "Duplicate slashes should be removed" def test_make_url_no_slash(): """Tests for catpy.client.make_url """ url = catpy.client.make_url("foo", "bar") assert url == "foo/bar", "Elements should be joined with a slash" def test_make_url_trailing_slash_unchanged(): """Tests for catpy.client.make_url """ url1 = catpy.client.make_url("foo", "bar") assert url1 == "foo/bar", "Should not add trailing slash" url2 = catpy.client.make_url("foo", "bar/") assert url2 == "foo/bar/", "Should not remove trailing slash"
jacobtolar/archiva
archiva-modules/archiva-base/archiva-maven2-indexer/src/main/java/org/apache/archiva/indexer/merger/MergedRemoteIndexesTask.java
<filename>archiva-modules/archiva-base/archiva-maven2-indexer/src/main/java/org/apache/archiva/indexer/merger/MergedRemoteIndexesTask.java package org.apache.archiva.indexer.merger; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import org.apache.maven.index.context.IndexingContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * @author <NAME> * @since 2.0.0 */ public class MergedRemoteIndexesTask implements Runnable { private Logger logger = LoggerFactory.getLogger( getClass() ); private MergedRemoteIndexesTaskRequest mergedRemoteIndexesTaskRequest; public MergedRemoteIndexesTask( MergedRemoteIndexesTaskRequest mergedRemoteIndexesTaskRequest ) { this.mergedRemoteIndexesTaskRequest = mergedRemoteIndexesTaskRequest; } @Override public void run() { try { this.execute(); } catch ( IndexMergerException e ) { logger.error( e.getMessage(), e ); } } public MergedRemoteIndexesTaskResult execute() throws IndexMergerException { IndexMerger indexMerger = mergedRemoteIndexesTaskRequest.getIndexMerger(); IndexingContext indexingContext = indexMerger.buildMergedIndex( mergedRemoteIndexesTaskRequest.getIndexMergerRequest() ); return new MergedRemoteIndexesTaskResult( indexingContext ); } @Override public boolean equals( Object o ) { if ( this == o ) { return true; } if ( !( o instanceof MergedRemoteIndexesTask ) ) { return false; } MergedRemoteIndexesTask that = (MergedRemoteIndexesTask) o; return mergedRemoteIndexesTaskRequest.equals( that.mergedRemoteIndexesTaskRequest ); } @Override public int hashCode() { return mergedRemoteIndexesTaskRequest.hashCode(); } }
markbgrdt/gardener
pkg/mock/gardener/utils/errors/funcs.go
// Code generated by MockGen. DO NOT EDIT. // Source: github.com/gardener/gardener/pkg/utils/errors (interfaces: TaskFunc) // Package errors is a generated GoMock package. package errors import ( reflect "reflect" errors "github.com/gardener/gardener/pkg/utils/errors" gomock "github.com/golang/mock/gomock" ) // MockTaskFunc is a mock of TaskFunc interface type MockTaskFunc struct { ctrl *gomock.Controller recorder *MockTaskFuncMockRecorder } // MockTaskFuncMockRecorder is the mock recorder for MockTaskFunc type MockTaskFuncMockRecorder struct { mock *MockTaskFunc } // NewMockTaskFunc creates a new mock instance func NewMockTaskFunc(ctrl *gomock.Controller) *MockTaskFunc { mock := &MockTaskFunc{ctrl: ctrl} mock.recorder = &MockTaskFuncMockRecorder{mock} return mock } // EXPECT returns an object that allows the caller to indicate expected use func (m *MockTaskFunc) EXPECT() *MockTaskFuncMockRecorder { return m.recorder } // Do mocks base method func (m *MockTaskFunc) Do(arg0 *errors.ErrorContext) (string, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Do", arg0) ret0, _ := ret[0].(string) ret1, _ := ret[1].(error) return ret0, ret1 } // Do indicates an expected call of Do func (mr *MockTaskFuncMockRecorder) Do(arg0 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Do", reflect.TypeOf((*MockTaskFunc)(nil).Do), arg0) }
Rohisbo/escehmd
node_modules/encode-utf8/index.js
'use strict' module.exports = function encodeUtf8 (input) { var result = [] var size = input.length for (var index = 0; index < size; index++) { var point = input.charCodeAt(index) if (point >= 0xD800 && point <= 0xDBFF && size > index + 1) { var second = input.charCodeAt(index + 1) if (second >= 0xDC00 && second <= 0xDFFF) { // https://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae point = (point - 0xD800) * 0x400 + second - 0xDC00 + 0x10000 index += 1 } } // US-ASCII if (point < 0x80) { result.push(point) continue } // 2-byte UTF-8 if (point < 0x800) { result.push((point >> 6) | 192) result.push((point & 63) | 128) continue } // 3-byte UTF-8 if (point < 0xD800 || (point >= 0xE000 && point < 0x10000)) { result.push((point >> 12) | 224) result.push(((point >> 6) & 63) | 128) result.push((point & 63) | 128) continue } // 4-byte UTF-8 if (point >= 0x10000 && point <= 0x10FFFF) { result.push((point >> 18) | 240) result.push(((point >> 12) & 63) | 128) result.push(((point >> 6) & 63) | 128) result.push((point & 63) | 128) continue } // Invalid character result.push(0xEF, 0xBF, 0xBD) } return new Uint8Array(result).buffer }
darrenmossman/AdventOfCode
app/src/main/java/com/mossman/darren/adventofcode/Y2K20/Y2K20_20.java
<reponame>darrenmossman/AdventOfCode package com.mossman.darren.adventofcode.Y2K20; import com.mossman.darren.adventofcode.InfiniteGrid; import com.mossman.darren.adventofcode.Utils; import com.mossman.darren.adventofcode.Y2K18.Y2K18_Puzzle; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; public class Y2K20_20 extends Y2K18_Puzzle { public static void main(String[] args) { Y2K20_20 puzzle = new Y2K20_20(true); long i = puzzle.part1(); System.out.printf("day 20: part 1a = %d\n", i); test(i, 20899048083289L); puzzle = new Y2K20_20(false); i = puzzle.part1(); System.out.printf("day 20: part 1b = %d\n", i); test(i, 21599955909991L); i = puzzle.part2(); System.out.printf("day 20: part 2 = %d\n", i); test(i, 2495); } //-------------------------------------------------------------------------------------------- private class Match { int edge; Tile targetTile; int targetEdge; public Match(int edge, Tile targetTile, int targetEdge) { this.edge = edge; this.targetTile = targetTile; this.targetEdge = targetEdge; } } private class Tile { long id; List<Tile> tiles; List<String> rows = new ArrayList<>(); List<Match> matches = new ArrayList<>(); boolean processed; Tile(List<Tile> tiles) { this.tiles = tiles; if (tiles != null) { tiles.add(this); } } boolean isCorner() { return matches.size() == 2; } boolean noneMatch(int edge) { return (matches.stream().noneMatch(m -> m.edge == edge)); } String columns(int c) { StringBuilder builder = new StringBuilder(); for (String r: rows) { builder.append(r.charAt(c)); } return builder.toString(); } void flipRows() { //System.out.printf("Flip Rows id: %d\n", id); for (int i = 0; i < (height()+1) / 2; i++) { int j = height()-i-1; String s1 = rows.get(i); String s2 = rows.get(j); rows.set(i, s2); rows.set(j, s1); } } void flipColumns() { //System.out.printf("Flip Columns id: %d\n", id); for (int r = 0; r < height(); r++) { StringBuilder builder = new StringBuilder(); String s = rows.get(r); for (int c = 0; c < width(); c++) { builder.insert(0, s.charAt(c)); } rows.set(r, builder.toString()); } } void rotate(int rot) { //System.out.printf("Rotate id: %d - %d\n", id, r); switch (rot) { case 1: List<String> newRows = new ArrayList<>(); for (int i = 0; i < width(); i++) { StringBuilder builder = new StringBuilder(); for (int j = 0; j < height(); j++) { String s = rows.get(height()-j-1); builder.append(s.charAt(i)); } newRows.add(builder.toString()); } rows = newRows; break; case 2: for (int i = 0; i <= (height()-1) / 2; i++) { int j = height()-i-1; String s1 = Utils.reverse(rows.get(i)); String s2 = Utils.reverse(rows.get(j)); rows.set(i, s2); rows.set(j, s1); } break; case 3: rotate(2); rotate(1); break; } } int height() { return rows.size(); } int width() { return rows.get(0).length(); } String pattern(int edge) { switch (edge) { case 0: return rows.get(0); case 1: return columns(width()-1); case 2: return rows.get(height()-1); case 3: return columns(0); default: return ""; } } boolean match(Tile targetTile) { if (this == targetTile) { return false; } for (int edge = 0; edge < 4; edge++) { String pattern = pattern(edge); for (int targetEdge = 0; targetEdge < 4; targetEdge++) { String targetPattern = targetTile.pattern(targetEdge); if (pattern.equals(targetPattern) || Utils.reverse(pattern).equals(targetPattern)) { matches.add(new Match(edge, targetTile, targetEdge)); return true; } } } return false; } void match() { matches.clear(); tiles.forEach(this::match); } void place(InfiniteGrid<Character> grid, int x, int y) { int xx = x * (width()-2); int yy = y * (height()-2); for (int r = 1; r < height()-1; r++) { String s = rows.get(r); for (int c = 1; c < width()-1; c++) { grid.put(xx+c-1, yy+r-1, s.charAt(c)); } } } void process(InfiniteGrid<Character> grid, int x, int y) { processed = true; place(grid, x,y); match(); matches.stream() .filter(m -> !m.targetTile.processed) .forEach(m -> { int requiredEdge = (m.edge + 2) % 4; int targetEdge = m.targetEdge; int rot = 0; while (targetEdge != requiredEdge) { rot++; targetEdge = (targetEdge + 1) % 4; } m.targetTile.rotate(rot); if (!pattern(m.edge).equals(m.targetTile.pattern(targetEdge))) { if (targetEdge % 2 == 1) { m.targetTile.flipRows(); } else { m.targetTile.flipColumns(); } } int xx = x; int yy = y; switch (m.edge) { case 0: yy--; break; case 1: xx++; break; case 2: yy++; break; case 3: xx--; break; } m.targetTile.process(grid, xx, yy); }); } @Override public String toString() { String res = String.format("id = %d, matchCount = %d\n", id, matches.size()); res = res + rows.stream().collect(Collectors.joining("\n")); for (int e = 0; e < 4; e++) { res = res + String.format("\n%d - %s", e, pattern(e)); } return res; } int read(ArrayList<String> input, int r) { Pattern pId = Pattern.compile("Tile (\\d+):"); String row = input.get(r); Matcher matcher = pId.matcher(row); if (matcher.matches()) { id = Integer.parseInt(matcher.group(1)); } else { r--; } while (r < input.size()-1) { r++; row = input.get(r); if (!row.isEmpty()) { rows.add(row); } else { r++; break; } } return r; } } private ArrayList<String> input; public Y2K20_20(boolean test) { input = Utils.readFile(getFilename(test)); } private List<Tile> initTiles() { List<Tile> tiles = new ArrayList<>(); int r = 0; while (r < input.size()-1) { Tile tile = new Tile(tiles); r = tile.read(input, r); } tiles.forEach(Tile::match); return tiles; } public long part1() { List<Tile> tiles = initTiles(); return tiles.stream() .filter(Tile::isCorner) .map(t -> t.id) .reduce(1L, (a,b) -> a*b); } private Tile findCorner(List<Tile> tiles) { return tiles.stream() .filter(Tile::isCorner) .findFirst().orElse(null); } private void testTransformations(List<Tile> tiles) { tiles.forEach(tile -> { String s = tile.toString(); for (int i = 0; i < 4; i++) { tile.rotate(1); } assert s.equals(tile.toString()); for (int i = 0; i < 2; i++) { tile.rotate(2); } assert s.equals(tile.toString()); for (int i = 0; i < 2; i++) { tile.flipRows(); } assert s.equals(tile.toString()); for (int i = 0; i < 2; i++) { tile.flipColumns(); } assert s.equals(tile.toString()); }); } private Tile initMonster() { String filename = getFilename(true); filename = filename.replace("_test", "_monster"); ArrayList<String> monsterInput = Utils.readFile(filename); Tile monster = new Tile(null); monster.read(monsterInput, 0); return monster; } private boolean findMonsterAt(InfiniteGrid<Character> grid, Tile monster, int x, int y) { for (int r = 0; r < monster.height(); r++) { String s = monster.rows.get(r); int yy = y + r; for (int c = 0; c < s.length(); c++) { if (s.charAt(c) == '#') { int xx = x + c; Character ch = grid.get(xx, yy); if (ch != '#') return false; } } } return true; } private boolean findMonster(InfiniteGrid<Character> grid, Tile monster) { for (int r = 0; r < grid.size()-monster.height()+1; r++) { HashMap<Integer, Character> row = grid.getRow(r); for (int c = 0; c < row.size()-monster.width()+1; c++) { if (findMonsterAt(grid, monster, c, r)) { return true; } } } return false; } private void blockMonsterAt(InfiniteGrid<Character> grid, Tile monster, int x, int y) { for (int r = 0; r < monster.height(); r++) { String s = monster.rows.get(r); int yy = y + r; for (int c = 0; c < s.length(); c++) { if (s.charAt(c) == '#') { grid.put(x+c, y+r, 'O'); } } } } private void blockMonster(InfiniteGrid<Character> grid, Tile monster) { for (int r = 0; r < grid.size()-monster.height()+1; r++) { HashMap<Integer, Character> row = grid.getRow(r); for (int c = 0; c < row.size()-monster.width()+1; c++) { if (findMonsterAt(grid, monster, c, r)) { blockMonsterAt(grid, monster, c, r); } } } } private int countWaves(InfiniteGrid<Character> grid) { int res = 0; for (int r = 0; r < grid.size(); r++) { HashMap<Integer, Character> row = grid.getRow(r); for (int c = 0; c < row.size(); c++) { if (row.get(c) == '#') { res++; } } } return res; } public long part2() { List<Tile> tiles = initTiles(); InfiniteGrid<Character> grid = new InfiniteGrid<>(); //testTransformations(tiles); Tile corner = findCorner(tiles); if (corner.noneMatch(1)) { corner.rotate(2); } else if (corner.noneMatch( 2)) { corner.rotate(1); } corner.process(grid,0,0); //grid.display(); Tile monster = initMonster(); boolean found = false; for (int rot = 0; rot < 4; rot++) { found = findMonster(grid, monster); if (found) { break; } monster.rotate(1); } if (!found) { monster.flipRows(); for (int rot = 0; rot < 4; rot++) { found = findMonster(grid, monster); if (found) { break; } monster.rotate(1); } } if (found) { blockMonster(grid, monster); //grid.display(); return countWaves(grid); } return 0; } }
robertaird/Create
src/main/java/com/simibubi/create/lib/event/FogEvents.java
<reponame>robertaird/Create<gh_stars>100-1000 package com.simibubi.create.lib.event; import net.fabricmc.api.EnvType; import net.fabricmc.api.Environment; import net.fabricmc.fabric.api.event.Event; import net.fabricmc.fabric.api.event.EventFactory; import net.minecraft.client.Camera; @Environment(EnvType.CLIENT) public class FogEvents { public static final Event<SetDensity> SET_DENSITY = EventFactory.createArrayBacked(SetDensity.class, callbacks -> (info, density) -> { for (SetDensity callback : callbacks) { return callback.setDensity(info, density); } return density; }); public static final Event<SetColor> SET_COLOR = EventFactory.createArrayBacked(SetColor.class, callbacks -> data -> { for (SetColor callback : callbacks) { callback.setColor(data); } }); private FogEvents() { } @FunctionalInterface public interface SetDensity { float setDensity(Camera activeRenderInfo, float density); } @FunctionalInterface public interface SetColor { void setColor(ColorData d); } public static class ColorData { private final Camera camera; private float red; private float green; private float blue; public ColorData(Camera camera, float r, float g, float b) { this.camera = camera; this.red = r; this.green = g; this.blue = b; } public Camera getCamera() { return camera; } public float getRed() { return red; } public float getGreen() { return green; } public float getBlue() { return blue; } public void setRed(float red) { this.red = red; } public void setGreen(float green) { this.green = green; } public void setBlue(float blue) { this.blue = blue; } } }
LaurensMakel1/iaf
core/src/main/java/nl/nn/adapterframework/pipes/CrlPipe.java
<gh_stars>0 /* Copyright 2016 Nationale-Nederlanden Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package nl.nn.adapterframework.pipes; import java.io.IOException; import java.io.InputStream; import java.security.cert.CRLException; import java.security.cert.CertificateException; import java.security.cert.CertificateFactory; import java.security.cert.X509CRL; import java.security.cert.X509CRLEntry; import java.security.cert.X509Certificate; import java.util.Iterator; import nl.nn.adapterframework.core.IPipeLineSession; import nl.nn.adapterframework.core.PipeRunException; import nl.nn.adapterframework.core.PipeRunResult; import nl.nn.adapterframework.doc.IbisDoc; import nl.nn.adapterframework.util.XmlBuilder; /** * Pipe that reads a CRL from an input stream and transforms it to an XML. * The steam is closed after reading. * * Example configuration: * <code><pre> <pipe name="Read issuer" className="nl.nn.adapterframework.pipes.FilePipe" actions="read" fileName="dir/issuer.cer" preserveInput="true" outputType="stream" storeResultInSessionKey="issuer" > <forward name="success" path="Read CRL" /> </pipe> <pipe name="Read CRL" className="nl.nn.adapterframework.pipes.FilePipe" actions="read" fileName="dir/CRL.crl" outputType="stream" > <forward name="success" path="Transform CRL" /> </pipe> <pipe name="Transform CRL" className="nl.nn.adapterframework.pipes.CrlPipe" issuerSessionKey="issuer" > <forward name="success" path="EXIT" /> </pipe> * </pre></code> * * * @author <NAME> * @author <NAME> * @author <NAME> */ public class CrlPipe extends FixedForwardPipe { private String issuerSessionKey; public PipeRunResult doPipe(Object input, IPipeLineSession session) throws PipeRunException { X509CRL crl; InputStream inputStream = (InputStream)input; try { CertificateFactory cf = CertificateFactory.getInstance("X.509"); crl = (X509CRL)cf.generateCRL(inputStream); } catch (CertificateException e) { throw new PipeRunException(this, "Could not read CRL", e); } catch (CRLException e) { throw new PipeRunException(this, "Could not read CRL", e); } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { log.warn("Could not close CRL input stream", e); } } } String result = null; if (isCRLOK(crl, (InputStream)session.get(getIssuerSessionKey()))) { XmlBuilder root = new XmlBuilder("SerialNumbers"); Iterator <? extends X509CRLEntry> it = crl.getRevokedCertificates().iterator(); while (it.hasNext()) { X509CRLEntry e = (X509CRLEntry) it.next(); XmlBuilder serialNumber = new XmlBuilder("SerialNumber"); serialNumber.setValue(e.getSerialNumber().toString(16)); root.addSubElement(serialNumber); } result = root.toXML(); } return new PipeRunResult(getForward(), result); } private boolean isCRLOK(X509CRL x509crl, InputStream issuer) throws PipeRunException { try { CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509"); X509Certificate issuerCertificate = (X509Certificate)certificateFactory.generateCertificate(issuer); if (x509crl.getIssuerX500Principal().equals(issuerCertificate.getSubjectX500Principal())) { return true; } } catch (CertificateException e) { throw new PipeRunException(this, "Could not read issuer certificate", e); } finally { if (issuer != null) { try { issuer.close(); } catch (IOException e) { log.warn("Could not close issuer input stream", e); } } } return false; } public String getIssuerSessionKey() { return issuerSessionKey; } @IbisDoc({"name of the sessionkey that holds a stream to the certificate of the issuer who signed the crl. the steam is closed after reading", ""}) public void setIssuerSessionKey(String issuerSessionKey) { this.issuerSessionKey = issuerSessionKey; } }
corner4world/hasor
hasor-core/src/test/java/net/hasor/core/event/EventLinkTest.java
<filename>hasor-core/src/test/java/net/hasor/core/event/EventLinkTest.java /* * Copyright 2008-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.hasor.core.event; import net.hasor.core.EventContext; import net.hasor.core.EventListener; import org.junit.Test; import java.util.concurrent.atomic.AtomicInteger; public class EventLinkTest { @Test public void syncEventTest() throws InterruptedException { EventContext ec = new StandardEventManager(20, "TestEvent", Thread.currentThread().getContextClassLoader()); // final String SubEvent = "SubEvent"; final String FirstEvent = "FirstEvent"; final AtomicInteger atomicInteger = new AtomicInteger(); //1.添加事件监听器 ec.addListener(SubEvent, (event, eventData) -> atomicInteger.incrementAndGet()); ec.addListener(FirstEvent, (EventListener<EventContext>) (event, eventEC) -> { eventEC.fireAsyncEvent(SubEvent, 1); eventEC.fireAsyncEvent(SubEvent, 2); }); //2.引发种子事件 ec.fireAsyncEvent(FirstEvent, ec); Thread.sleep(1000); assert atomicInteger.get() == 2; } }
slamavl/quantarhei
examples/rc_single.py
<filename>examples/rc_single.py # -*- coding: utf-8 -*- #****************************************************************************** # # Simulation of single molecule spectra of RC ... # using Quantarhei package, version .... # # Author: <NAME> # # Last changes: July 14th, 2016 # # # #****************************************************************************** # # About the code # -------------- # # The code is explained in details in the comments throughout this file. # If you are new to Quantarhei and/or Python and/or the simulated problem, # it is recommended that you read the code, including the comments, as # a single text. All concepts of Quantarhei and # the simulation model are explained when encountered, or a reference is # provided. # # # # # Simulation Code # --------------- # # First the components of the Quantarhei package used for the simulations # are imported to Python. Comments above the code lines explain what is # happening. # # Importing ... # basic Quantarhei class to represent molecules from quantarhei import Molecule # basic Quantarhei class to represent 1D coordinate in molecules # (e.g. harmonic oscillator) from quantarhei import Mode # basic Quantathei class to represent bath correlation function from quantarhei import CorrelationFunction # class representing the time interval on which we simulate from quantarhei import TimeAxis # # Comment on Quantarhei: internally, Quantarhei uses the units of cycles per # femtosecond, or 2pi/fs, for energy. This is useful when simulating processes # on femtosecond time scale. To define energies of optical transitions, one # might find it useful (from a human perspective) to use something else. Below # we use inverse centimeters (1/cm) which is a very common unit in # spectroscopy. To tell Quantarhei that you enter values in other than the # internal units, we use Python's context manager clause "with", and a special # object "energy_units" below. # # context manager for physical units of energy is imported from quantarhei import energy_units from quantarhei import eigenbasis_of # class representing Redfield relaxation rate matrix (and does its calculation) from quantarhei.qm import RedfieldRateMatrix from quantarhei import PopulationPropagator # Here we import a very useful library for dealing with matrices import numpy # To produce figures, we import the pyplot from the matplotlib library import matplotlib.pyplot as plt from quantarhei.core.managers import Manager # # First we create a molecule object representing the P state of the RC # and its charge transfer (CT) state. For the details of the mode, and its # justification, see the article text (!!!!!) # print("\nQuantarhei version ",Manager().version) # if "verbose" is set to True, the script prints some info on the screen verbose = True # if "show_plots" is set to True, the script will show plots show_plots = False if verbose: print("\nSingle photosynthetic reaction center fluorescence simulation") print( "-------------------------------------------------------------\n") # # All definitions below are done with energy units of inverse # centimeters (1/cm). We use Python's context manager concept for this. # # Here we switch to the 1/cm units with energy_units("1/cm"): # Molecule named "RC-P" with three states (ground, CT and exciton state) # is created en = [0.0, 14500, 15500] m = Molecule("RC-P",en) # Transition dipole moment from 0 -> 2 (exciton state) is set to # a unit vector in the direction of x-axis (this choice is arbitrary) di = numpy.sqrt(23.0)*0.20819434 m.set_dipole(0,2,[di,0.0,0.0]) # # To represent CT coordinate, we add an explicite harmonic mode # to the molecule. # # First the mode with frequency 10 1/cm is created qct = Mode(frequency=10.0) # and registered with the molecule m.add_Mode(qct) # In the CT state, the equilibrium coordinate is shifted towards # charge separation. In the ground state and the exciton, no shift # of the coordinate is assumed (see the text (!!!!) for justification.) qct.set_shift(1,1.0) # By default, the Mode we created is harmonic. The number of states # by which it is represented is set to 2 (which is a very small number). # Let us increase the number of states to represent the oscillators # in the three electronic states of the molecule to some chosen N[0], N[1] # and N[2] (see the text (!!!!) for the choice of values). # # we create an array of 3 zeros N = numpy.zeros(3,dtype=numpy.int) # set all of them to the value of 10 N[0] = 10 N[1] = 20 N[2] = 20 # loop from 0 to 2 for i in range(3): # and set the number of vibrational states qct.set_nmax(i,N[i]) # Now we create a bath correlation function for the two electronic states. # This is done by creating a Python dictionary of parameters. These are: # - Type of the correlation function ftype = "OverdampedBrownian" # - Temperature T = 300 K # - Correlation time cortime = 100 fs # - Reorganization energy reorg = 100 1/cm (we are still in # the energy_units context) corfunc_ct_params = {"ftype":"OverdampedBrownian", "T":300,"cortime":100,"reorg":100} # We also need to specify a time interval on which the function is # defined. In principle, this will be the interval on which we will # calculate excited state dynamics. Quantarhei has an object which defines # the time interval. It is called TimeAxis. Arguments are # 1) starting time, 2) Number of steps and 3) time step timeAxis = TimeAxis(0.0, 2000, 1.0) # Now we create a correlation function object corfunc_ct = CorrelationFunction(timeAxis,corfunc_ct_params) # The same is done below for a second correlation function, which represents # the interaction of the excitonic transition with the bath. Notice that # the reorganization energy is smaller here. corfunc_ex_params = {"ftype":"OverdampedBrownian", "T":300,"cortime":100,"reorg":30} corfunc_ex = CorrelationFunction(timeAxis,corfunc_ex_params) # In addition to the above two system-bath interactions, we also have to # specify how the vibrational modes are damped in different electronic # states. We use the same system-bath interaction theory and require # correlation function to describe the coupling. Again we need two, # one for each excited electronic state. We do not need the relaxation # in the ground state for anything in our calculations, but because # the ground state is an isolated state, we can at least use it to # see how fast the relaxation is in a pure harmonic oscillator. corfunc_ct_q_params = {"ftype":"OverdampedBrownian", "T":300,"cortime":100,"reorg":5.0} corfunc_ct_q = CorrelationFunction(timeAxis,corfunc_ct_q_params) corfunc_ex_q_params = {"ftype":"OverdampedBrownian", "T":300,"cortime":100,"reorg":5.0} corfunc_ex_q = CorrelationFunction(timeAxis,corfunc_ex_q_params) # Here we plot the bath correlation functions if verbose and show_plots: print("Bath correlation functions:") # FIXME: give the plot a title and describe axes # CT correlation function # plot real part of the correlation function plt.plot(timeAxis.time,numpy.real(corfunc_ct.data),"-k") # plot imaginary part of the correlation function plt.plot(timeAxis.time,numpy.imag(corfunc_ct.data),"-r") # # Exciton correlation function # plot real part of the correlation function plt.plot(timeAxis.time,numpy.real(corfunc_ex.data),"-b") # plot imaginary part of the correlation function plt.plot(timeAxis.time,numpy.imag(corfunc_ex.data),"-g") plt.show() # # Molecular transitions from the ground state will now be # assigned the bath correlation functions we defined above. # # egcf = energy gap correlation function # # state 1 is the CT state m.set_egcf((0,1),corfunc_ct) # # state 2 is the exciton state m.set_egcf((0,2),corfunc_ex) # # Oscillator damping environments have to be specified in each electronic # state separately # m.set_mode_environment(mode=0,elstate=1,corfunc=corfunc_ct_q) m.set_mode_environment(mode=0,elstate=2,corfunc=corfunc_ex_q) # in the ground state we set the same environment as in the state 2 ###m.set_mode_environment(mode=0,elstate=0,corfunc=corfunc_ex_q) # Now we will set adiabatic coupling between the CT state and the exciton # state m.set_adiabatic_coupling(1,2,100.0) # # We will not set any more numbers, so we can leave the context manager # # We ask the molecule object to create and return an object representing # the Hamiltonian operator hh = m.get_Hamiltonian() #print(hh.data) # Next we need transition dipole moment operator. It will be usefull # for setting initial condition of the simulation. dd = m.get_TransitionDipoleMoment() with energy_units("1/cm"): #if True: # inspect the molecule by eyes if verbose: print("Molecule specification:") print(m) # The last ingredient missing before we can start calculating excited state # dynamics is to determine ralaxation dynamics among the excited state # levels. For this we need an object which holds information about the # system-bath interaction in our system. Not suprisingly, the corresponding # class is called SystemBathInteraction, and the Molecule class objects # can return it upon request. sbi = m.get_SystemBathInteraction(timeAxis) # The sbi object now contains all information needed to calculate rates # of energy transfer within the excited state manifold which is caused # by the pure dephasing described by the correlation functions # "corfunc_ex" and "corfunc_ct". It also contains the damping of # vibrational modes which we prescribed by correlation functions # "corfunc_ct_q" and "corfunc_ex_q" (!!!!) # With the system-bath interaction at hand, we can calculate e.g. Redfield # excitonic population relaxation matrix. # !!! This can take a while !!! RRM = RedfieldRateMatrix(hh,sbi) if verbose: print("Relaxation times") for k in range(hh.getDim(0)): for l in range(hh.getDim(0)): if (RRM.data[k,l] > 0) and ((l-k)==1): print(k,l,1.0/RRM.data[k,l]," fs") # # We are in position to calculate excited state dynamics of charge transfer # process. # # We set initial condition for the calculation. Sofar everything was # specified in the site-basis. We will switch to exciton basis with eigenbasis_of(hh): # get the ground state thermal density matrix rho_eq = m.get_thermal_ReducedDensityMatrix() # we set initial condition by exciting the molecule with the polarization # along its transition dipole moment # # # rho_ini = numpy.dot(dd.data[:,:,0],numpy.dot(rho_eq,dd.data[:,:,0])) rho_ini = rho_eq.excite_delta(dmoment=dd,epolarization=[1.0, 0.0, 0.0]) # we normalize the population of excited state to 1.0 rho_ini.normalize2(norm=1.0) # we need only population dynamics, so let us convert density matrix to # a vector of populations pop_ini = rho_ini.get_populations() # Now we set up a popagator for the population vector prop = PopulationPropagator(timeAxis,RRM) # # Here starts the intersting part! # # We calculate population dynamics # !!! This can take a while !!! pop_in_time = prop.propagate(pop_ini) for n in range(pop_in_time.shape[1]): plt.plot(timeAxis.time,pop_in_time[:,n]) lft_ct = m.get_electronic_natural_lifetime(1,epsilon_r=2.34) lft_ex = m.get_electronic_natural_lifetime(2,epsilon_r=2.34) print(lft_ct/1000000.0," ns") print(lft_ex/1000000.0," ns") """ # We are after fluorescence. FluorescenceSpect class knows how to deal # with that. We submit the TimeAxis object and the Molecule object fl = FluorescenceSpect(timeAxis,m) # # calculate various spectra # # accumulated fluorescence calculated from equilibrium fspect = fl.accumulated_fluorescence() fspect.save_to_file("fluorecence.dat") # time correlated photon counting tcpc = fl.get_time_correlated_single_photon_counting(pop_in_time, spectral_range=(10000,18000), time_resolution=50000) tcpc.save_to_file("tcspc.dat") """ """ # # Production calculations are based on scanning the position of CT state # and then sampling the results randomly # energy_of_CT_start = 9000 energy_of_CT_step = 100 energy_of_CT_Number_of_steps = 100 with energy_units("1/cm"): for n in range(energy_of_CT_Number_of_steps): energy_CT = energy_of_CT_start + energy_of_CT_step*n m.elenergies[1] = energy_CT hh = m.get_Hamiltonian() # # Do the following objects change? # dd = m.get_TransitionDipoleMoment() sbi = m.get_SystemBathInteraction() rho_ini = numpy.dot(dd.data[:,:,0],numpy.dot(rho_eq,dd.data[:,:,0])) # we normalize the population of excited state to 1.0 rho_ini = util.normalize_trace2(rho_ini,norm=1.0) pop_ini = rho_ini.get_population_vector() RRM = RedfieldRateMatrix(hh,sbi) prop = PopulationPropagator(timeAxis,RRM) pop_in_time = prop.propagate(pop_ini) # presumably we can use the same FluorescenceSpect object, because it # has an access # to the changed Molecule object fspect = fl.steady_state_fluorescence() tcpc = fl.get_time_correlated_photon_counting(pop_in_time, spectral_range=(10000,18000), time_resolution=50000) # append new results to the result file """
rnarla123/aliyun-openapi-java-sdk
aliyun-java-sdk-msccommonquery/src/main/java/com/aliyuncs/msccommonquery/model/v20210407/ListMessagesRequest.java
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.aliyuncs.msccommonquery.model.v20210407; import com.aliyuncs.RpcAcsRequest; import com.aliyuncs.http.MethodType; /** * @author auto create * @version */ public class ListMessagesRequest extends RpcAcsRequest<ListMessagesResponse> { private Long startTimestamp; private String locale; private Long endTimestamp; private String channelType; public ListMessagesRequest() { super("MscCommonQuery", "2021-04-07", "ListMessages"); setMethod(MethodType.POST); } public Long getStartTimestamp() { return this.startTimestamp; } public void setStartTimestamp(Long startTimestamp) { this.startTimestamp = startTimestamp; if(startTimestamp != null){ putBodyParameter("StartTimestamp", startTimestamp.toString()); } } public String getLocale() { return this.locale; } public void setLocale(String locale) { this.locale = locale; if(locale != null){ putQueryParameter("Locale", locale); } } public Long getEndTimestamp() { return this.endTimestamp; } public void setEndTimestamp(Long endTimestamp) { this.endTimestamp = endTimestamp; if(endTimestamp != null){ putBodyParameter("EndTimestamp", endTimestamp.toString()); } } public String getChannelType() { return this.channelType; } public void setChannelType(String channelType) { this.channelType = channelType; if(channelType != null){ putBodyParameter("ChannelType", channelType); } } @Override public Class<ListMessagesResponse> getResponseClass() { return ListMessagesResponse.class; } }
terebentina/mongui
src/client/utils/mixins.js
class MixinBuilder { constructor(superclass) { this.superclass = superclass; } with() { return Array.from(arguments).reduce((c, m) => m(c), this.superclass); } } const mix = (superclass) => new MixinBuilder(superclass); export default mix;
pulumi/pulumi-azure-nextgen
sdk/python/pulumi_azure_nextgen/network/v20180201/__init__.py
<filename>sdk/python/pulumi_azure_nextgen/network/v20180201/__init__.py # coding=utf-8 # *** WARNING: this file was generated by the Pulumi SDK Generator. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** # Export this package's modules as members: from ._enums import * from .application_gateway import * from .application_security_group import * from .connection_monitor import * from .ddos_protection_plan import * from .endpoint import * from .express_route_circuit import * from .express_route_circuit_authorization import * from .express_route_circuit_connection import * from .express_route_circuit_peering import * from .express_route_cross_connection_peering import * from .get_application_gateway import * from .get_application_security_group import * from .get_connection_monitor import * from .get_ddos_protection_plan import * from .get_endpoint import * from .get_express_route_circuit import * from .get_express_route_circuit_authorization import * from .get_express_route_circuit_connection import * from .get_express_route_circuit_peering import * from .get_express_route_cross_connection_peering import * from .get_inbound_nat_rule import * from .get_load_balancer import * from .get_local_network_gateway import * from .get_network_interface import * from .get_network_security_group import * from .get_network_watcher import * from .get_packet_capture import * from .get_profile import * from .get_public_ip_address import * from .get_route import * from .get_route_filter import * from .get_route_filter_rule import * from .get_route_table import * from .get_security_rule import * from .get_subnet import * from .get_virtual_network import * from .get_virtual_network_gateway import * from .get_virtual_network_gateway_advertised_routes import * from .get_virtual_network_gateway_bgp_peer_status import * from .get_virtual_network_gateway_connection import * from .get_virtual_network_gateway_learned_routes import * from .get_virtual_network_gateway_vpnclient_ipsec_parameters import * from .get_virtual_network_peering import * from .inbound_nat_rule import * from .load_balancer import * from .local_network_gateway import * from .network_interface import * from .network_security_group import * from .network_watcher import * from .packet_capture import * from .profile import * from .public_ip_address import * from .route import * from .route_filter import * from .route_filter_rule import * from .route_table import * from .security_rule import * from .subnet import * from .virtual_network import * from .virtual_network_gateway import * from .virtual_network_gateway_connection import * from .virtual_network_peering import * from ._inputs import * from . import outputs def _register_module(): import pulumi from ... import _utilities class Module(pulumi.runtime.ResourceModule): _version = _utilities.get_semver_version() def version(self): return Module._version def construct(self, name: str, typ: str, urn: str) -> pulumi.Resource: if typ == "azure-nextgen:network/v20180201:ApplicationGateway": return ApplicationGateway(name, pulumi.ResourceOptions(urn=urn)) elif typ == "azure-nextgen:network/v20180201:ApplicationSecurityGroup": return ApplicationSecurityGroup(name, pulumi.ResourceOptions(urn=urn)) elif typ == "azure-nextgen:network/v20180201:ConnectionMonitor": return ConnectionMonitor(name, pulumi.ResourceOptions(urn=urn)) elif typ == "azure-nextgen:network/v20180201:DdosProtectionPlan": return DdosProtectionPlan(name, pulumi.ResourceOptions(urn=urn)) elif typ == "azure-nextgen:network/v20180201:Endpoint": return Endpoint(name, pulumi.ResourceOptions(urn=urn)) elif typ == "azure-nextgen:network/v20180201:ExpressRouteCircuit": return ExpressRouteCircuit(name, pulumi.ResourceOptions(urn=urn)) elif typ == "azure-nextgen:network/v20180201:ExpressRouteCircuitAuthorization": return ExpressRouteCircuitAuthorization(name, pulumi.ResourceOptions(urn=urn)) elif typ == "azure-nextgen:network/v20180201:ExpressRouteCircuitConnection": return ExpressRouteCircuitConnection(name, pulumi.ResourceOptions(urn=urn)) elif typ == "azure-nextgen:network/v20180201:ExpressRouteCircuitPeering": return ExpressRouteCircuitPeering(name, pulumi.ResourceOptions(urn=urn)) elif typ == "azure-nextgen:network/v20180201:ExpressRouteCrossConnectionPeering": return ExpressRouteCrossConnectionPeering(name, pulumi.ResourceOptions(urn=urn)) elif typ == "azure-nextgen:network/v20180201:InboundNatRule": return InboundNatRule(name, pulumi.ResourceOptions(urn=urn)) elif typ == "azure-nextgen:network/v20180201:LoadBalancer": return LoadBalancer(name, pulumi.ResourceOptions(urn=urn)) elif typ == "azure-nextgen:network/v20180201:LocalNetworkGateway": return LocalNetworkGateway(name, pulumi.ResourceOptions(urn=urn)) elif typ == "azure-nextgen:network/v20180201:NetworkInterface": return NetworkInterface(name, pulumi.ResourceOptions(urn=urn)) elif typ == "azure-nextgen:network/v20180201:NetworkSecurityGroup": return NetworkSecurityGroup(name, pulumi.ResourceOptions(urn=urn)) elif typ == "azure-nextgen:network/v20180201:NetworkWatcher": return NetworkWatcher(name, pulumi.ResourceOptions(urn=urn)) elif typ == "azure-nextgen:network/v20180201:PacketCapture": return PacketCapture(name, pulumi.ResourceOptions(urn=urn)) elif typ == "azure-nextgen:network/v20180201:Profile": return Profile(name, pulumi.ResourceOptions(urn=urn)) elif typ == "azure-nextgen:network/v20180201:PublicIPAddress": return PublicIPAddress(name, pulumi.ResourceOptions(urn=urn)) elif typ == "azure-nextgen:network/v20180201:Route": return Route(name, pulumi.ResourceOptions(urn=urn)) elif typ == "azure-nextgen:network/v20180201:RouteFilter": return RouteFilter(name, pulumi.ResourceOptions(urn=urn)) elif typ == "azure-nextgen:network/v20180201:RouteFilterRule": return RouteFilterRule(name, pulumi.ResourceOptions(urn=urn)) elif typ == "azure-nextgen:network/v20180201:RouteTable": return RouteTable(name, pulumi.ResourceOptions(urn=urn)) elif typ == "azure-nextgen:network/v20180201:SecurityRule": return SecurityRule(name, pulumi.ResourceOptions(urn=urn)) elif typ == "azure-nextgen:network/v20180201:Subnet": return Subnet(name, pulumi.ResourceOptions(urn=urn)) elif typ == "azure-nextgen:network/v20180201:VirtualNetwork": return VirtualNetwork(name, pulumi.ResourceOptions(urn=urn)) elif typ == "azure-nextgen:network/v20180201:VirtualNetworkGateway": return VirtualNetworkGateway(name, pulumi.ResourceOptions(urn=urn)) elif typ == "azure-nextgen:network/v20180201:VirtualNetworkGatewayConnection": return VirtualNetworkGatewayConnection(name, pulumi.ResourceOptions(urn=urn)) elif typ == "azure-nextgen:network/v20180201:VirtualNetworkPeering": return VirtualNetworkPeering(name, pulumi.ResourceOptions(urn=urn)) else: raise Exception(f"unknown resource type {typ}") _module_instance = Module() pulumi.runtime.register_resource_module("azure-nextgen", "network/v20180201", _module_instance) _register_module()
thirtyfiveparts/live
repos/live/packages/log/live-log/index.js
export * from './src' export {default} from './src'
prophecy/Pillar
Dependencies/Include/cml/matrix/matrix_promotions.h
<gh_stars>10-100 /* -*- C++ -*- ------------------------------------------------------------ Copyright (c) 2007 <NAME> and <NAME> http://cmldev.net/ The Configurable Math Library (CML) is distributed under the terms of the Boost Software License, v1.0 (see cml/LICENSE for details). *-----------------------------------------------------------------------*/ /** @file * @brief * * Defines promotions for matrices used in matrix/matrix or matrix/scalar * expressions. * * @sa UnaryMat4_TOp * @sa BinaryMat4_TOp */ #ifndef matrix_promotions_h #define matrix_promotions_h #include <cml/core/cml_meta.h> #include <cml/et/scalar_promotions.h> #include <cml/et/array_promotions.h> #include <cml/fixed.h> #include <cml/dynamic.h> /* This is used below to create a more meaningful compile-time error when * either argument to OuterPromote has the wrong orientation. */ struct outer_promote_expects_properly_oriented_args_error; namespace cml { namespace et { /** Promote two types to a matrixt type. */ template<typename LeftT, typename RightT> struct MatrixPromote { /* Default matrix type promotion template. */ template<typename M1, typename M2> struct MatrixPromoteHelper; /** Type promotion for two matrix types. * * @note This always uses the basis orientation of the left-hand matrix. * @bug This always uses the basis orientation of the left-hand matrix, * which is not always correct. */ template<typename E1, class AT1, typename L1, typename BO1, typename E2, class AT2, typename L2, typename BO2> struct MatrixPromoteHelper< cml::matrix<E1,AT1,BO1,L1>, cml::matrix<E2,AT2,BO2,L2> > { /* Promote the arrays: */ typedef typename ArrayPromote< typename cml::matrix<E1,AT1,BO1,L1>::array_type, typename cml::matrix<E2,AT2,BO2,L2>::array_type >::type promoted_array; /* The deduced matrix result type: */ typedef cml::matrix< typename promoted_array::value_type, typename promoted_array::generator_type, BO1, typename promoted_array::layout > type; /* The deduced temporary type: */ typedef typename type::temporary_type temporary_type; }; /** Type promotion for a matrix and a scalar. */ template<typename E, class AT, typename BO, typename L, typename S> struct MatrixPromoteHelper<cml::matrix<E,AT,BO,L>, S> { /* The deduced matrix result type (the array type is the same): */ typedef cml::matrix<typename ScalarPromote<E,S>::type, AT, BO, L> type; /* The deduced temporary type: */ typedef typename type::temporary_type temporary_type; }; /** Type promotion for a scalar and a matrix. */ template<typename S, typename E, class AT, typename BO, typename L> struct MatrixPromoteHelper<S, cml::matrix<E,AT,BO,L> > { /* The deduced matrix result type (the array type is the same): */ typedef cml::matrix<typename ScalarPromote<S,E>::type, AT, BO, L> type; /* The deduced temporary type: */ typedef typename type::temporary_type temporary_type; }; /** Type promotion for outer product. */ template<typename E1, class AT1, typename E2, class AT2> struct MatrixPromoteHelper< cml::vector<E1,AT1>, cml::vector<E2,AT2> > { typedef cml::vector<E1,AT1> left_type; typedef cml::vector<E2,AT2> right_type; typedef CML_DEFAULT_BASIS_ORIENTATION basis_orient; /* Get matrix size: */ enum { array_rows = left_type::array_size, array_cols = right_type::array_size }; /* Deduce the corresponding matrix types for the vectors: */ typedef CML_DEFAULT_ARRAY_LAYOUT layout; typedef typename select_if< array_rows == -1, dynamic<>, fixed<array_rows,1> >::result left_storage; typedef cml::matrix<E1,left_storage,basis_orient,layout> left_matrix; typedef typename select_if< array_cols == -1, dynamic<>, fixed<1,array_cols> >::result right_storage; typedef cml::matrix<E2,right_storage,basis_orient,layout> right_matrix; /* Finally, promote the matrix types to get the result: */ typedef typename et::MatrixPromote<left_matrix,right_matrix>::type type; typedef typename type::temporary_type temporary_type; }; /** Remove const and & from the to-be-promoted types. */ typedef typename remove_const< typename remove_reference<LeftT>::type>::type LeftBaseT; typedef typename remove_const< typename remove_reference<RightT>::type>::type RightBaseT; typedef typename MatrixPromoteHelper<LeftBaseT,RightBaseT>::type type; typedef typename type::temporary_type temporary_type; }; /** * NOTE: MatrixPromote* are somewhat ad hoc, and were added to * simplify the code for matrix slerp/squad/etc. */ /** Type promotion for two matrix types. */ template < class Mat1_T, class Mat2_T > struct MatrixPromote2 { typedef typename MatrixPromote< typename Mat1_T::temporary_type, typename Mat2_T::temporary_type >::temporary_type temporary_type; typedef typename temporary_type::value_type value_type; }; /** Type promotion for three matrix types. */ template < class Mat1_T, class Mat2_T, class Mat3_T > struct MatrixPromote3 { typedef typename MatrixPromote< typename Mat1_T::temporary_type, typename MatrixPromote< typename Mat2_T::temporary_type, typename Mat3_T::temporary_type >::temporary_type >::temporary_type temporary_type; typedef typename temporary_type::value_type value_type; }; /** Type promotion for four matrix types. */ template < class Mat1_T, class Mat2_T, class Mat3_T, class Mat4_T > struct MatrixPromote4 { typedef typename MatrixPromote< typename Mat1_T::temporary_type, typename MatrixPromote< typename Mat2_T::temporary_type, typename MatrixPromote< typename Mat3_T::temporary_type, typename Mat4_T::temporary_type >::temporary_type >::temporary_type >::temporary_type temporary_type; typedef typename temporary_type::value_type value_type; }; } // namespace et } // namespace cml #endif // ------------------------------------------------------------------------- // vim:ft=cpp
PeterKassenaar/voorbeeldenNodejs
H03/0307/app.js
<filename>H03/0307/app.js<gh_stars>1-10 //app.js - Array met personen maken en tonen in de console var Persoon = require('./Persoon'); var colors = require('colors'); var arrayPersonen = []; // array vullen met personen arrayPersonen.push(new Persoon('Peter', 'Kassenaar', '<EMAIL>')); arrayPersonen.push(new Persoon('Bob', '<NAME>', '<EMAIL>')); arrayPersonen.push(new Persoon('Michiel', '<NAME>', '<EMAIL>')); // persoonsarray naar de console schrijven arrayPersonen.forEach(function (persoon) { console.log('Naam: ', persoon.voornaam, persoon.achternaam); console.log(persoon.email.blue.underline); // OF: console.log(colors.blue.underline(persoon.email)); console.log('/*-------------------*/') });
mbuckaway/CrossMgr
CrossMgrVideo/Database.py
import wx import os import sys import six import time from datetime import datetime, timedelta import sqlite3 import CVUtil from collections import defaultdict from six.moves.queue import Queue, Empty import unicodedata def removeDiacritic( s ): return unicodedata.normalize('NFKD', u'{}'.format(s)).encode('ascii', 'ignore').decode() now = datetime.now def createTable( c, table, fields ): def default_str( d ): return ' DEFAULT {}'.format(d) if d is not None else '' c.execute( 'CREATE TABLE IF NOT EXISTS {} ({})'.format(table, ','.join('{} {}{}'.format( field, type, default_str(default) ) for field, type, idx, default in fields ) ) ) for field, type, idx, default in fields: if idx: c.execute( 'CREATE INDEX IF NOT EXISTS {}_{}_idx on {} ({} ASC)'.format(table, field, table, field) ) class Database( object ): UpdateSeconds = 10*60*60 triggerFieldsAll = ( 'id','ts','s_before','s_after','ts_start','bib','first_name','last_name','team','wave','race_name', 'note','kmh','frames', ) triggerFieldsInput = triggerFieldsAll[1:-3] # ignore note, mph and frames triggerFieldsUpdate = ('wave','race_name',) triggerEditFields = ('bib', 'first_name', 'last_name', 'team', 'wave', 'race_name', 'note',) def __init__( self, fname=None, initTables=True, fps=30 ): self.fname = (fname or os.path.join( os.path.expanduser("~"), 'CrossMgrVideo.sqlite3' ) ) self.fps = fps ''' try: six.print_( 'database bytes: {}'.format( os.stat(self.fname).st_size ) ) except: pass ''' self.conn = sqlite3.connect( self.fname, detect_types=sqlite3.PARSE_DECLTYPES, timeout=45.0 ) if initTables: # Add kmh, ts_start, sBefore and sAfter to the trigger table if necessary. with self.conn: cur = self.conn.cursor() cur.execute( 'PRAGMA table_info(trigger)' ) cols = cur.fetchall() if cols: col_names = [col[1] for col in cols] if 'note' not in col_names: self.conn.execute( 'ALTER TABLE trigger ADD COLUMN note TEXT DEFAULT ""' ) if 'kmh' not in col_names: self.conn.execute( 'ALTER TABLE trigger ADD COLUMN kmh DOUBLE DEFAULT 0.0' ) if 'ts_start' not in col_names: self.conn.execute( 'ALTER TABLE trigger ADD COLUMN ts_start timestamp DEFAULT 0' ) self.conn.execute( 'UPDATE trigger SET ts_start=ts' ) # Seconds before and after the ts time that frames were captured. if 's_before' not in col_names: self.conn.execute( 'ALTER TABLE trigger ADD COLUMN s_before DOUBLE DEFAULT 0.0' ) self.conn.execute( 'ALTER TABLE trigger ADD COLUMN s_after DOUBLE DEFAULT 0.0' ) # Cache of number of frames. if 'frames' not in col_names: self.conn.execute( 'ALTER TABLE trigger ADD COLUMN frames INTEGER DEFAULT 0' ) with self.conn: createTable( self.conn, 'photo', ( ('id', 'INTEGER PRIMARY KEY', False, None), ('ts', 'timestamp', 'ASC', None), ('jpg', 'BLOB', False, None), ) ) createTable( self.conn, 'trigger', ( ('id', 'INTEGER PRIMARY KEY', False, None), ('ts', 'timestamp', 'ASC', None), # Capture timestamp. ('s_before', 'DOUBLE', False, None), # Seconds before ts of capture. ('s_after', 'DOUBLE', False, None), # Seconds after ts of capture. ('ts_start', 'timestamp', False, None), # race timestamp. ('bib', 'INTEGER', 'ASC', None), ('first_name', 'TEXT', 'ASC', None), ('last_name', 'TEXT', 'ASC', None), ('team', 'TEXT', 'ASC', None), ('wave', 'TEXT', 'ASC', None), ('race_name', 'TEXT', 'ASC', None), ('note', 'TEXT', False, None), ('kmh', 'DOUBLE', False, 0.0), ('frames', 'INTEGER', False, 0), # Number of frames with this trigger. ) ) self.photoTsCache = set( row[0] for row in self.conn.execute( 'SELECT ts FROM photo WHERE ts BETWEEN ? AND ?', (now() - timedelta(seconds=self.UpdateSeconds), now()) ) ) self.deleteExistingTriggerDuplicates() else: self.photoTsCache = set() self.lastUpdate = now() - timedelta(seconds=self.UpdateSeconds) self.tsJpgsKeyLast = None self.tsJpgsLast = None def clone( self ): return Database( self.fname, initTables=False, fps=self.fps ) def getfname( self ): return self.fname def getsize( self ): try: return os.path.getsize( self.fname ) except: return None def purgeTriggerWriteDuplicates( self, tsTriggers ): """ Remove all triggers that are already in the database. """ if not tsTriggers: return tsTriggers tsTriggersUnique = [] for t in tsTriggers: if self.conn.execute( 'SELECT id FROM trigger WHERE {}'.format(' AND '.join('{}=?'.format(f) for f in self.triggerFieldsInput)), t).fetchone() is None: tsTriggersUnique.append( t ) return tsTriggersUnique def write( self, tsTriggers=None, tsJpgs=None ): tsTriggers = self.purgeTriggerWriteDuplicates( tsTriggers ) if not tsTriggers and not tsJpgs: return if tsJpgs: # Purge duplicate photos, or with the same timestamp. jpgSeen = set() tsJpgsUnique = [] for ts_jpg in tsJpgs: if ts_jpg[1] and ts_jpg[0] not in self.photoTsCache and ts_jpg[1] not in jpgSeen: jpgSeen.add( ts_jpg[1] ) tsJpgsUnique.append( ts_jpg ) tsJpgs = tsJpgsUnique with self.conn: if tsTriggers: self.conn.executemany( 'INSERT INTO trigger ({}) VALUES ({})'.format(','.join(self.triggerFieldsInput), ','.join('?'*len(self.triggerFieldsInput))), tsTriggers ) if tsJpgs: assert not any(ts is None for ts, jpg in tsJpgs) self.conn.executemany( 'INSERT INTO photo (ts,jpg) VALUES (?,?)', tsJpgs ) if tsJpgs: self.photoTsCache.update( ts for ts, jpg in tsJpgs ) if (now() - self.lastUpdate).total_seconds() > self.UpdateSeconds: expired = now() - timedelta(seconds=self.UpdateSeconds) self.photoTsCache = set( ts for ts in self.photoTsCache if ts > expired ) self.lastUpdate = now() def updateTriggerRecord( self, id, data ): with self.conn: self.conn.execute( 'UPDATE trigger SET {} WHERE id=?'.format(','.join('{}=?'.format(f) for f in data.keys())), list(data.values()) + [id] ) def updateTriggerKMH( self, id, kmh ): self.updateTriggerRecord(id, {'kmh':kmh}) def updateTriggerBeforeAfter( self, id, s_before, s_after ): self.updateTriggerRecord(id, {'s_before':s_before, 's_after':s_after}) def initCaptureTriggerData( self, id ): ''' Initialize some fields from the previous record. ''' with self.conn: rows = list( self.conn.execute( 'SELECT ts FROM trigger WHERE id=?', (id,) ) ) if not rows: return ts = rows[0][0] tsLower, tsUpper = ts - timedelta(days=1), ts, rows = list( self.conn.execute( 'SELECT {} FROM trigger WHERE ? < ts AND ts < ? ORDER BY ts DESC LIMIT 1'.format(','.join(self.triggerFieldsUpdate)), (tsLower, tsUpper) ) ) if rows: self.conn.execute( 'UPDATE trigger SET {} WHERE id = ?'.format(','.join('{}=?'.format(f) for f in self.triggerFieldsUpdate)), rows[0] + (id,) ) def getTriggers( self, tsLower, tsUpper, bib=None ): with self.conn: if not bib: return list( self.conn.execute( 'SELECT {} FROM trigger WHERE ts BETWEEN ? AND ? ORDER BY ts'.format(','.join(self.triggerFieldsAll)), (tsLower, tsUpper) )) else: return list( self.conn.execute( 'SELECT {} FROM trigger WHERE bib=? AND ts BETWEEN ? AND ? ORDER BY ts'.format(','.join(self.triggerFieldsAll)), (bib, tsLower, tsUpper) )) def getPhotos( self, tsLower, tsUpper ): # Cache the results of the last query. key = (tsLower, tsUpper) if key == self.tsJpgsKeyLast: return self.tsJpgsLast with self.conn: tsJpgs = list( self.conn.execute( 'SELECT ts,jpg FROM photo WHERE ts BETWEEN ? AND ? ORDER BY ts', (tsLower, tsUpper)) ) self.tsJpgsKeyLast, self.tsJpgsLast = key, tsJpgs return tsJpgs def getPhotoCount( self, tsLower, tsUpper ): key = (tsLower, tsUpper) with self.conn: count = self.conn.execute( 'SELECT COUNT(id) FROM photo WHERE ts BETWEEN ? AND ?', (tsLower, tsUpper)).fetchone() return count[0] if count else 0 def getPhotoClosest( self, ts ): deltaSecondsBest = 1.0 tsBest = ts + timedelta(seconds=deltaSecondsBest) jpgBest = None for ts, jpg in self.getPhotos(ts - timedelta(seconds=0.1), ts + timedelta(seconds=0.1)): deltaSecondsCur = abs((tsBest - ts).total_seconds()) if deltaSecondsCur < deltaSecondsBest: deltaSecondsBest = deltaSecondsCur tsBest = ts jpgBest = jpg return tsBest if jpgBest else None, jpgBest def getTriggerPhotoCount( self, id, s_before_default=0.5, s_after_default=2.0 ): with self.conn: trigger = list( self.conn.execute( 'SELECT ts,s_before,s_after FROM trigger WHERE id=?', (id,) ) ) if not trigger: return 0 ts, s_before, s_after = trigger[0] if s_before == 0.0 and s_after == 0.0: s_before, s_after = s_before_default, s_after_default tsLower, tsUpper = ts - timedelta(seconds=s_before), ts + timedelta(seconds=s_after) return self.getPhotoCount(tsLower, tsUpper) def updateTriggerPhotoCount( self, id, frames=None ): frames = frames or self.getTriggerPhotoCount( id ) self.conn.execute( 'UPDATE trigger SET frames=? WHERE id=? AND frames!=?', (frames, id, frames) ) return frames def getTriggerPhotoCounts( self, tsLower, tsUpper ): counts = defaultdict( int ) with self.conn: triggers = { r[0]:(r[1]-timedelta(seconds=r[2]), r[1]+timedelta(seconds=r[3])) for r in self.conn.execute( 'SELECT id,ts,s_before,s_after FROM trigger WHERE ts BETWEEN ? AND ?', (tsLower, tsUpper) ) } if not triggers: return counts tsLowerPhoto = min( tsBefore for tsBefore,tsAfter in six.itervalues(triggers) ) tsUpperPhoto = max( tsAfter for tsBefore,tsAfter in six.itervalues(triggers) ) rangeSecs = (tsUpperPhoto - tsLowerPhoto).total_seconds() if rangeSecs == 0.0: return counts # Create a bucket list containing every intersecting trigger interval. bucketMax = min( len(triggers)*2+10, 256 ) bucketSecs = (rangeSecs + 0.001) / bucketMax # Ensure the timestamps equal to tsUpperPhoto go into the last bucket. def tsToB( ts ): return int((ts - tsLowerPhoto).total_seconds() / bucketSecs) buckets = [[] for b in six.moves.range(bucketMax)] for id, (tsBefore,tsAfter) in six.iteritems(triggers): for b in six.moves.range(tsToB(tsBefore), tsToB(tsAfter)+1): buckets[b].append(id) # Increment the count for every trigger intersecting this photo in the bucket. for r in self.conn.execute( 'SELECT ts FROM photo WHERE ts BETWEEN ? AND ?', (tsLowerPhoto, tsUpperPhoto) ): tsPhoto = r[0] for id in buckets[tsToB(tsPhoto)]: tsBefore,tsAfter = triggers[id] if tsBefore <= tsPhoto <= tsAfter: counts[id] += 1 return counts def updateTriggerPhotoCounts( self, counts ): with self.conn: self.conn.executemany( 'UPDATE trigger SET frames=? WHERE id=? AND frames!=?', [(count, id, count) for id, count in six.iteritems(counts)] ) def getLastPhotos( self, count ): with self.conn: tsJpgs = list( self.conn.execute( 'SELECT ts,jpg FROM photo ORDER BY ts DESC LIMIT ?', (count,)) ) tsJpgs.reverse() return tsJpgs def getLastTimestamp( self, tsLower, tsUpper ): c = self.conn.cursor() c.execute( 'SELECT ts FROM trigger WHERE ts BETWEEN ? AND ? ORDER BY ts', (tsLower, tsUpper) ) return c.fetchone()[0] def getTimestampRange( self ): c = self.conn.cursor() c.execute( 'SELECT ts FROM trigger ORDER BY ts ASC' ) row = c.fetchone() if not row: return None, None trigFirst = row[0] c.execute( 'SELECT ts FROM trigger ORDER BY ts DESC' ) trigLast = c.fetchone()[0] return trigFirst, trigLast def getTriggerDates( self ): dates = defaultdict( int ) for row in self.conn.execute( 'SELECT ts FROM trigger' ): if row[0]: dates[row[0].date()] += 1 return sorted( dates.items() ) def getTriggerEditFields( self, id ): with self.conn: rows = list( self.conn.execute('SELECT {} FROM trigger WHERE id=?'.format(','.join(self.triggerEditFields)), (id,) ) ) return rows[0] if rows else [] def setTriggerEditFields( self, id, *args ): with self.conn: self.conn.execute( 'UPDATE trigger SET {} WHERE id=?'.format(','.join('{}=?'.format(f) for f in self.triggerEditFields)), args + (id,) ) def isDup( self, ts ): return ts in self.photoTsCache def deleteExistingTriggerDuplicates( self ): rowPrev = None duplicateIds = [] for row in self.conn.execute( 'SELECT id,{} from trigger ORDER BY ts ASC,kmh DESC'.format(','.join(self.triggerFieldsInput)) ): if rowPrev is not None and row[1:] == rowPrev[1:]: duplicateIds.append( rowPrev[0] ) else: rowPrev = row chunkSize = 500 while duplicateIds: ids = duplicateIds[:chunkSize] self.conn.execute( 'DELETE FROM trigger WHERE id IN ({})'.format( ','.join('?'*len(ids)) ), ids ) del duplicateIds[:chunkSize] def cleanBetween( self, tsLower, tsUpper ): if not tsLower and not tsUpper: return tsLower = tsLower or datetime.datetime(1900,1,1,0,0,0) tsUpper = tsUpper or datetime.datetime(datetime.datetime.now().year+1000,1,1,0,0,0) with self.conn: self.conn.execute( 'DELETE from photo WHERE ts BETWEEN ? AND ?', (tsLower,tsUpper) ) self.conn.execute( 'DELETE from trigger WHERE ts BETWEEN ? AND ?', (tsLower,tsUpper) ) def deleteTrigger( self, id, s_before_default=0.5, s_after_default=2.0 ): with self.conn: rows = list( self.conn.execute( 'SELECT ts,s_before,s_after FROM trigger WHERE id=?', (id,) ) ) if not rows: return ts, s_before, s_after = rows[0] with self.conn: self.conn.execute( 'DELETE FROM trigger WHERE id=?', (id,) ) tsLower, tsUpper = ts - timedelta(seconds=s_before), ts + timedelta(seconds=s_after) # Get all other intervals that intersect this one. intervals = [] with self.conn: for ts,s_before,s_after in self.conn.execute( 'SELECT ts,s_before,s_after FROM trigger WHERE ts BETWEEN ? AND ?', (tsLower - timedelta(minutes=15),tsUpper + timedelta(minutes=15)) ): if s_before == 0.0 and s_after == 0.0: s_before, s_after = s_before_default, s_after_default tsStart, tsEnd = ts - timedelta(seconds=s_before), ts + timedelta(seconds=s_after) if tsEnd <= tsLower or tsUpper <= tsStart: continue intervals.append( (max(tsLower,tsStart), min(tsUpper,tsEnd)) ) # Merge overlapping and adjacent intervals together. if intervals: intervals.sort() intervalsNormal = [intervals[0]] for a, b in intervals[1:]: if a <= intervalsNormal[-1][1]: if b > intervalsNormal[-1][1]: intervalsNormal[-1] = (intervalsNormal[-1][0], b) elif a != b: intervalsNormal.append( (a, b) ) intervals = intervalsNormal toRemove = [(tsLower, tsUpper)] for a, b in intervals: # Split the last interval to accommodate the interval. u, v = toRemove.pop() if u != a: toRemove.append( (u, a) ) if b != v: toRemove.append( (b, v) ) if toRemove: with self.conn: for a, b in toRemove: self.conn.execute( 'DELETE from photo WHERE ts BETWEEN ? AND ?', (a,b) ) def vacuum( self ): self.conn.execute( 'VACUUM' ) tsJpgs = [] tsTriggers = [] def flush( db, triggerWriteCB = None ): if db: db.write( tsTriggers, tsJpgs ) if tsTriggers and triggerWriteCB: triggerWriteCB() del tsTriggers[:] del tsJpgs[:] def DBWriter( q, triggerWriteCB=None, fname=None ): db = Database( fname=fname ) keepGoing = True while keepGoing: try: v = q.get( timeout=2 ) except Empty: if tsTriggers or tsJpgs: flush( db, triggerWriteCB ) continue doFlush = True if v[0] == 'photo': doFlush = False if not db.isDup( v[1] ): tsJpgs.append( (v[1], sqlite3.Binary(CVUtil.frameToJPeg(v[2]))) ) elif v[0] == 'trigger': fieldLen = len(Database.triggerFieldsInput) tsTriggers.append( (list(v[1:]) + [u''] * fieldLen)[:fieldLen] ) elif v[0] == 'kmh': db.updateTriggerKMH( v[1], v[2] ) # id, kmh elif v[0] == 'flush': pass elif v[0] == 'terminate': keepGoing = False if doFlush or len(tsJpgs) >= 30*3: flush( db, triggerWriteCB ) q.task_done() flush( db ) def DBReader( q, callback, fname=None ): db = Database( initTables=False, fname=fname ) keepGoing = True while keepGoing: v = q.get() if v[0] == 'getphotos': flush( db ) callback( db.getPhotos(v[1], v[2]) ) elif v[0] == 'terminate': keepGoing = False q.task_done() if __name__ == '__main__': if False: try: os.remove( os.path.join( os.path.expanduser("~"), 'CrossMgrVideo.sqlite3' ) ) except: pass d = Database() ts = d.getLastTimestamp(datetime(2000,1,1), datetime(2200,1,1)) six.print_( ts ) def printTriggers(): qTriggers = 'SELECT {} FROM trigger ORDER BY ts LIMIT 8'.format(','.join(d.triggerFieldsInput)) six.print_( '*******************' ) for row in d.conn.execute(qTriggers): six.print_( removeDiacritic(u','.join( u'{}'.format(v) for v in row )) ) # Create existing duplicates all the triggers. tsTriggers = d.conn.execute('SELECT {} FROM trigger'.format(','.join(d.triggerFieldsInput))).fetchall() d.conn.executemany( 'INSERT INTO trigger ({}) VALUES ({})'.format(','.join(d.triggerFieldsInput), ','.join('?'*len(d.triggerFieldsInput))), tsTriggers ) printTriggers() # Delete the existing duplicates. d.deleteExistingTriggerDuplicates() printTriggers() # Now, test for checking duplicate triggers on add. d.write( tsTriggers, None ) printTriggers() six.print_( d.getTriggerDates() ) ''' tsTriggers = [((time.sleep(0.1) and False) or now(), 100+i, u'', u'', u'', u'', u'') for i in six.moves.range(100)] tsJpgs = [((time.sleep(0.01) and False) or now(), b'asdfasdfasdfasdfasdf') for i in six.moves.range(100)] d.write( tsTriggers, tsJpgs ) d.write( [], tsJpgs ) six.print_( len(d.getTriggers( now() - timedelta(seconds=5), now() )) ) six.print_( len(d.getPhotos( now() - timedelta(seconds=5), now() )) ) '''
homobel/makebird-node
test/projects/large/c67.js
<filename>test/projects/large/c67.js //~ name c67 alert(c67); //~ component c68.js
aarshkshah1992/go-ipld-prime
adl/rot13adl/rot13prototypes.go
package rot13adl // Prototype embeds a NodePrototype for every kind of Node implementation in this package. // This includes both the synthesized node as well as the substrate root node // (other substrate interior node prototypes are not exported here; // it's unlikely they'll be useful outside of the scope of the ADL's implementation package.) // // You can use it like this: // // rot13adl.Prototype.Node.NewBuilder() //... // // and: // // rot13adl.Prototype.SubstrateRoot.NewBuilder() // ... // var Prototype prototype // This may seem a tad mundane, but we do it for consistency with the way // other Node implementation packages (like basicnode) do this: // it's a convention for "pkgname.Prototype.SpecificThing.NewBuilder()" to be defined. type prototype struct { Node _R13String__Prototype SubstrateRoot _Substrate__Prototype } // REVIEW: In ADLs that use codegenerated substrate types defined by an IPLD Schema, the `Prototype.SubstrateRoot` field... // should it be a `_SubstrateRoot__Prototype`, or a `_SubstrateRoot__ReprPrototype`? // Probably the latter, because the only thing an external user of this package should be interested in is how to read data into memory in an optimal path. // But does this answer all questions? Codegen ReprPrototypes currently still return the type-level node from their Build method! // This probably would functionally work -- we could make the Reify methods check for either the type-level or repr-level types -- but would it be weird/surprising/hard-to-use?
lordHodges/gerarquiaModificada
core/src/contexts/registros/usuario/index.js
<filename>core/src/contexts/registros/usuario/index.js<gh_stars>0 module.exports = { // !casos de uso CrearUsuario: require("./aplication/useCase/crearUsuario"), ObtenerUsuarios: require("./aplication/useCase/obtenerUsuarios"), Login: require("./aplication/useCase/login"), // !clases UsuarioDalRepository: require("./dal/usuario.dalRepository"), UsuarioDomainRepository: require("./domain/usuario.domainRepository"), UsuarioDomainService: require("./domain/usuario.domainService"), UsuarioController: require("./interface/controllers/usuario.controller"), LoginController: require("./interface/controllers/login.controller"), AccessToken: require("./aplication/security/accessToken.secure"), };
urids/XSCALAMPI
ompi/contrib/vt/vt/include/vt_user_message.h
/** * VampirTrace * http://www.tu-dresden.de/zih/vampirtrace * * Copyright (c) 2005-2013, ZIH, TU Dresden, Federal Republic of Germany * * Copyright (c) 1998-2005, Forschungszentrum Juelich, Juelich Supercomputing * Centre, Federal Republic of Germany * * See the file COPYING in the package base directory for details **/ #ifndef _VT_USER_H # error "vt_user_message.h should only be included from vt_user.h" #endif /* _VT_USER_H */ #ifndef VT_USER_MESSAGE_H_ #define VT_USER_MESSAGE_H_ #define VT_MSG_DEFCOMM -1 #if (defined(VTRACE)) && !(defined(VTRACE_NO_MSG)) __VT_EXTERN_DECL unsigned int VT_User_msg_comm_def__(const char* cname); __VT_EXTERN_DECL void VT_User_msg_send__(unsigned int cid, unsigned int tag, unsigned int sent); __VT_EXTERN_DECL void VT_User_msg_recv__(unsigned int cid, unsigned int tag, unsigned int recvd); # define VT_MSG_COMM_DEF(n) VT_User_msg_comm_def__((n)) # define VT_MSG_SEND(c, t, s) VT_User_msg_send__((c), (t), (s)) # define VT_MSG_RECV(c, t, r) VT_User_msg_recv__((c), (t), (r)) #else /* VTRACE && !VTRACE_NO_MSG */ # define VT_MSG_COMM_DEF(n) 0 # define VT_MSG_SEND(c, t, s) # define VT_MSG_RECV(c, t, r) #endif /* VTRACE && !VTRACE_NO_MSG */ /* macros for more convenient access */ #define VT_COMM_WORLD VT_MSG_DEFCOMM #define VT_COMM_DEF VT_MSG_COMM_DEF #define VT_SEND VT_MSG_SEND #define VT_RECV VT_MSG_RECV #endif /* VT_USER_MESSAGE_H_ */
a471925688/yy-service
src/main/java/com/game/xiaoyan/system/repository/CaptchaRepository.java
package com.game.xiaoyan.system.repository; import com.game.xiaoyan.system.entity.Captcha; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; @Repository public interface CaptchaRepository extends JpaRepository<Captcha,String> { Captcha findByCaptchaPhoneAndCaptchaData(String captchaPhone, String captchaData);//根據驗證碼獲取信息 }
sspooky13/shopsys
packages/framework/assets/js/common/validation/ConstraintRange.js
import { parseNumber } from '../utils/number'; (function (window) { const SymfonyComponentValidatorConstraintsRange = function () { this.maxMessage = ''; this.minMessage = ''; this.invalidMessage = ''; this.max = null; this.min = null; this.validate = function (value) { const f = FpJsFormValidator; const compareValue = parseNumber(value); if (f.isValueEmty(value) || (compareValue !== null && compareValue >= this.min && compareValue <= this.max)) { return []; } else if (compareValue < this.min) { return [ this.minMessage.replace('{{ limit }}', String(this.min)) ]; } else if (compareValue > this.max) { return [ this.maxMessage.replace('{{ limit }}', String(this.max)) ]; } else { return [ this.invalidMessage ]; } }; }; window.SymfonyComponentValidatorConstraintsRange = SymfonyComponentValidatorConstraintsRange; })(window);
jbrodman/SYCL-CTS
tests/accessor/accessor_constructors_buffer.cpp
<filename>tests/accessor/accessor_constructors_buffer.cpp<gh_stars>0 /******************************************************************************* // // SYCL 1.2.1 Conformance Test Suite // // Copyright: (c) 2018 by Codeplay Software LTD. All Rights Reserved. // *******************************************************************************/ #define TEST_NAME accessor_constructors_buffer #include "../common/common.h" #include "accessor_constructors_utility.h" #include "accessor_constructors_buffer_utility.h" namespace TEST_NAMESPACE { struct user_struct { float a; int b; char c; }; /** tests the constructors for cl::sycl::accessor */ class TEST_NAME : public util::test_base { public: /** return information about this test */ void get_info(test_base::info &out) const override { set_test_info(out, TOSTRING(TEST_NAME), TEST_FILE); } template <typename T> void check_all_dims(util::logger &log, cl::sycl::queue &queue) { buffer_accessor_dims<T, 0, is_host_buffer::false_t, cl::sycl::access::placeholder::false_t>::check(log, queue); buffer_accessor_dims<T, 1, is_host_buffer::false_t, cl::sycl::access::placeholder::false_t>::check(log, queue); buffer_accessor_dims<T, 2, is_host_buffer::false_t, cl::sycl::access::placeholder::false_t>::check(log, queue); buffer_accessor_dims<T, 3, is_host_buffer::false_t, cl::sycl::access::placeholder::false_t>::check(log, queue); buffer_accessor_dims<T, 0, is_host_buffer::true_t, cl::sycl::access::placeholder::false_t>::check(log, queue); buffer_accessor_dims<T, 1, is_host_buffer::true_t, cl::sycl::access::placeholder::false_t>::check(log, queue); buffer_accessor_dims<T, 2, is_host_buffer::true_t, cl::sycl::access::placeholder::false_t>::check(log, queue); buffer_accessor_dims<T, 3, is_host_buffer::true_t, cl::sycl::access::placeholder::false_t>::check(log, queue); } /** execute this test */ void run(util::logger &log) override { try { auto queue = util::get_cts_object::queue(); /** check accessor constructors for int */ check_all_dims<int>(log, queue); /** check accessor constructors for float */ check_all_dims<float>(log, queue); /** check accessor constructors for char */ check_all_dims<char>(log, queue); /** check accessor constructors for vec */ check_all_dims<cl::sycl::int2>(log, queue); /** check accessor constructors for vec */ check_all_dims<cl::sycl::int3>(log, queue); /** check accessor constructors for vec */ check_all_dims<cl::sycl::float4>(log, queue); /** check accessor constructors for user_struct */ check_all_dims<user_struct>(log, queue); queue.wait_and_throw(); } catch (const cl::sycl::exception &e) { log_exception(log, e); cl::sycl::string_class errorMsg = "a SYCL exception was caught: " + cl::sycl::string_class(e.what()); FAIL(log, errorMsg.c_str()); } } }; // register this test with the test_collection util::test_proxy<TEST_NAME> proxy; } // namespace TEST_NAMESPACE
lefevre-fraser/openmeta-mms
src/Python27Packages/testbenchexecutor/progress_service/gen/progress_feedback_pb2.py
<filename>src/Python27Packages/testbenchexecutor/progress_service/gen/progress_feedback_pb2.py # -*- coding: utf-8 -*- # Generated by the protocol buffer compiler. DO NOT EDIT! # source: progress_feedback.proto from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.protobuf import reflection as _reflection from google.protobuf import symbol_database as _symbol_database # @@protoc_insertion_point(imports) _sym_db = _symbol_database.Default() DESCRIPTOR = _descriptor.FileDescriptor( name='progress_feedback.proto', package='progress_feedback', syntax='proto3', serialized_options=b'\252\002(JobManagerFramework.ProgressFeedback.Gen', serialized_pb=b'\n\x17progress_feedback.proto\x12\x11progress_feedback\"c\n\x0eProgressUpdate\x12\x0e\n\x06job_id\x18\x01 \x01(\t\x12\x0f\n\x07message\x18\x02 \x01(\t\x12\x18\n\x10\x63urrent_progress\x18\x03 \x01(\x11\x12\x16\n\x0etotal_progress\x18\x04 \x01(\x11\"\x10\n\x0eProgressResult2l\n\x10ProgressFeedback\x12X\n\x0eUpdateProgress\x12!.progress_feedback.ProgressUpdate\x1a!.progress_feedback.ProgressResult\"\x00\x42+\xaa\x02(JobManagerFramework.ProgressFeedback.Genb\x06proto3' ) _PROGRESSUPDATE = _descriptor.Descriptor( name='ProgressUpdate', full_name='progress_feedback.ProgressUpdate', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='job_id', full_name='progress_feedback.ProgressUpdate.job_id', index=0, number=1, type=9, cpp_type=9, label=1, has_default_value=False, default_value=b"".decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='message', full_name='progress_feedback.ProgressUpdate.message', index=1, number=2, type=9, cpp_type=9, label=1, has_default_value=False, default_value=b"".decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='current_progress', full_name='progress_feedback.ProgressUpdate.current_progress', index=2, number=3, type=17, cpp_type=1, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='total_progress', full_name='progress_feedback.ProgressUpdate.total_progress', index=3, number=4, type=17, cpp_type=1, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), ], extensions=[ ], nested_types=[], enum_types=[ ], serialized_options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=46, serialized_end=145, ) _PROGRESSRESULT = _descriptor.Descriptor( name='ProgressResult', full_name='progress_feedback.ProgressResult', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ ], extensions=[ ], nested_types=[], enum_types=[ ], serialized_options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=147, serialized_end=163, ) DESCRIPTOR.message_types_by_name['ProgressUpdate'] = _PROGRESSUPDATE DESCRIPTOR.message_types_by_name['ProgressResult'] = _PROGRESSRESULT _sym_db.RegisterFileDescriptor(DESCRIPTOR) ProgressUpdate = _reflection.GeneratedProtocolMessageType('ProgressUpdate', (_message.Message,), { 'DESCRIPTOR' : _PROGRESSUPDATE, '__module__' : 'progress_feedback_pb2' # @@protoc_insertion_point(class_scope:progress_feedback.ProgressUpdate) }) _sym_db.RegisterMessage(ProgressUpdate) ProgressResult = _reflection.GeneratedProtocolMessageType('ProgressResult', (_message.Message,), { 'DESCRIPTOR' : _PROGRESSRESULT, '__module__' : 'progress_feedback_pb2' # @@protoc_insertion_point(class_scope:progress_feedback.ProgressResult) }) _sym_db.RegisterMessage(ProgressResult) DESCRIPTOR._options = None _PROGRESSFEEDBACK = _descriptor.ServiceDescriptor( name='ProgressFeedback', full_name='progress_feedback.ProgressFeedback', file=DESCRIPTOR, index=0, serialized_options=None, serialized_start=165, serialized_end=273, methods=[ _descriptor.MethodDescriptor( name='UpdateProgress', full_name='progress_feedback.ProgressFeedback.UpdateProgress', index=0, containing_service=None, input_type=_PROGRESSUPDATE, output_type=_PROGRESSRESULT, serialized_options=None, ), ]) _sym_db.RegisterServiceDescriptor(_PROGRESSFEEDBACK) DESCRIPTOR.services_by_name['ProgressFeedback'] = _PROGRESSFEEDBACK # @@protoc_insertion_point(module_scope)
camperoo/subscriptions
spec/models/subscriptions/payment_spec.rb
<reponame>camperoo/subscriptions<filename>spec/models/subscriptions/payment_spec.rb require 'spec_helper' require 'active_merchant' ActiveMerchant::Billing::Base.mode = :test describe Subscriptions::Payment do describe ".is_successful?" do it "should return true if status is 'Ok'" do subject.status = Subscriptions::Payment::STATUS_COMPLETE subject.is_successful?.should be_true end it "should return false if status anything but STATUS_COMPLETE" do subject.status = Subscriptions::Payment::STATUS_ERROR subject.is_successful?.should be_false end end end
TAAPArthur/Syncrop
Syncrop/SyncropGUI/src/gui/tabs/Optimization.java
package gui.tabs; import static syncrop.Syncrop.logger; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.IOException; import javax.swing.BoxLayout; import javax.swing.JButton; import javax.swing.JPanel; import gui.SyncropGUI; import listener.FileWatcher; import listener.actions.RemoveSyncropConflictsAction; public class Optimization extends JPanel implements SyncropTab,ActionListener{ /** * */ private static final long serialVersionUID = 1L; JButton removeFileInfo=new JButton("Remove metadata for disabled and deleted files"); JButton removeConflicts=new JButton("Remove conflicts locally "); JButton forceSync=new JButton("Force Sync"); public Optimization(){ setName("Optimization"); initialize(); } private void initialize(){ setLayout(new BoxLayout(this, BoxLayout.Y_AXIS)); JButton[] optimizations={removeFileInfo,removeConflicts,forceSync}; for(JButton optimization:optimizations){ add(optimization); optimization.addActionListener(this); } } @Override public void actionPerformed(ActionEvent e) { if(e.getSource().equals(removeFileInfo)) try { FileWatcher.checkMetadataForAllFiles(false); } catch (IOException e1) { logger.logError(e1); } else if(e.getSource().equals(removeConflicts)) try { new FileWatcher(null).checkAllFiles(new RemoveSyncropConflictsAction()); } catch (IOException e1) { logger.logError(e1); } else if(e.getSource().equals(forceSync)) try { SyncropGUI.getSyncropCommunicationThread().sync(true); } catch (IOException e1) { e1.printStackTrace(); } } @Override public void reload() { forceSync.setEnabled(SyncropGUI.getSyncropCommunicationThread().isSyncropRunning()); } }
daniel-thom/jade
tests/unit/jobs/test_job_configuration.py
<reponame>daniel-thom/jade<filename>tests/unit/jobs/test_job_configuration.py<gh_stars>0 import os import shutil import pytest from jade.exceptions import InvalidConfiguration from jade.extensions.generic_command.generic_command_inputs import GenericCommandInputs from jade.extensions.generic_command.generic_command_configuration import GenericCommandConfiguration from jade.utils.subprocess_manager import run_command TEST_FILENAME = "inputs.txt" CONFIG_FILE = "test-config.json" OUTPUT = "test-output" SUBMIT_JOBS = "jade submit-jobs" @pytest.fixture def job_fixture(): yield for path in (TEST_FILENAME, CONFIG_FILE, OUTPUT): if os.path.isdir(path): shutil.rmtree(path) elif os.path.exists(path): os.remove(path) if "FAKE_HPC_CLUSTER" in os.environ: os.environ.pop("FAKE_HPC_CLUSTER") def test_job_configuration__check_job_dependencies(job_fixture): with open(TEST_FILENAME, "w") as f_out: f_out.write("echo hello world\n") inputs = GenericCommandInputs(TEST_FILENAME) config = GenericCommandConfiguration(job_inputs=inputs) for job_param in inputs.iter_jobs(): config.add_job(job_param) assert config.get_num_jobs() == 1 job = config.get_job("1") job.blocked_by.add("10") with pytest.raises(InvalidConfiguration): config.check_job_dependencies() # While we have this setup, verify that submit-jobs calls this function. config.dump(CONFIG_FILE) cmd = f"{SUBMIT_JOBS} {CONFIG_FILE} --output={OUTPUT} " \ "--poll-interval=.1 " ret = run_command(cmd) assert ret != 0
AntonKondratkov/akondratkov
chapter_002/src/main/java/ru/job4j/tracker/actions/MenuTracker.java
package ru.job4j.tracker.actions; import ru.job4j.tracker.StartUI; import ru.job4j.tracker.input.Input; import ru.job4j.tracker.model.Item; import ru.job4j.tracker.strogare.ITracker; import ru.job4j.tracker.strogare.Tracker; import java.util.List; import java.util.function.Consumer; /** * @author <NAME> * @since 25.07.18. * Класс редактирует заявку. */ class EditItem extends BaseAction { public EditItem(int key, String name) { super(key, name); } @Override public void execute(Input input, ITracker tracker) { String id = input.ask("Please, enter the task's id: "); if (tracker.findById(id) != null && tracker.findById(id).getId().equals(id)) { String name = input.ask("Please, enter the task's name: "); String desc = input.ask("Please, enter the task's desc: "); Item item = new Item(name, desc); if (tracker.replace(id, item)) { System.out.println("Item was update"); } } else { System.out.println("Item not found"); } } } /** * Класс ищет заявку по имени. */ class FindNameItems extends BaseAction { public FindNameItems(int key, String name) { super(key, name); } @Override public void execute(Input input, ITracker tracker) { String name = input.ask("Please, enter the task's name: "); List<Item> item = tracker.findByName(name); if (item.size() == 0) { System.out.println("Item not found"); } for (Item item1 : item) { System.out.println( String.format("%s. %s", item1.getId(), item1.getName())); } } } /** * Класс реализует меню трекера. */ public class MenuTracker { /** * @param хранит ссылку на объект . */ private Input input; /** * @param хранит ссылку на объект . */ private ITracker tracker; /** * @param хранит ссылку с выходными данными. */ private final Consumer<String> output; /** * @param хранит ссылку на массив типа UserAction. */ private UserAction[] actions = new UserAction[7]; /** * Конструктор. * * @param input объект типа Input * @param tracker объект типа Tracker */ public MenuTracker(Input input, ITracker tracker, Consumer<String> output) { this.input = input; this.tracker = tracker; this.output = output; } /** * Метод заполняет массив. */ public void fillActions(StartUI ui) { this.actions[0] = this.new AddItem(0, "Add the new item."); this.actions[1] = new MenuTracker.ShowItems(1, "Show the all items."); this.actions[2] = new EditItem(2, "Edit the new item."); this.actions[3] = this.new DeleteItem(3, "Delete the item."); this.actions[4] = new MenuTracker.FindIdItem(4, "Find the item by id."); this.actions[5] = new FindNameItems(5, "Find the item by name."); this.actions[6] = this.new Exit(6, "Exit programm.", ui); } /** * Метод передаёт числовой диапазон значений меню. * @return Числовой диапазон значений. */ public int[] getRange() { int[] result = new int[this.actions.length]; for (int i = 0; i < this.actions.length; i++) { result[i] = i; } return result; } /** * Метод в зависимости от указанного ключа, выполняет соотвествующие действие. * * @param key ключ операции */ public void select(int key) { this.actions[key].execute(this.input, this.tracker); } /** * Метод выводит на экран меню. */ public void show() { for (UserAction action : this.actions) { if (action != null) { System.out.println(action.info()); } } } /** * Класс реализует добавление новой заявки в хранилище. */ private class AddItem extends BaseAction { public AddItem(int key, String name) { super(key, name); } @Override public void execute(Input input, ITracker tracker) { String name = input.ask("Please, enter the task's name: "); String desc = input.ask("Please, enter the task's desc: "); Item item = new Item(name, desc); if (tracker.add(item) != null) { System.out.println("Task added"); System.out.println(tracker.findByName(item.getName())); } } } /** * Класс отображает все заявки в хранилище. */ private class ShowItems extends BaseAction { public ShowItems(int key, String name) { super(key, name); } @Override public void execute(Input input, ITracker tracker) { List<Item> item = tracker.findAll(); if (item.size() == 0) { System.out.println("Items not found"); } for (Item item1: item) { if (item1 != null) { output.accept(String.format("%s. %s", item1.getId(), item1.getName())); } } } } /** * Класс удаляет заявку. */ private class DeleteItem extends BaseAction { public DeleteItem(int key, String name) { super(key, name); } @Override public void execute(Input input, ITracker tracker) { String id = input.ask("Please, enter the task's id: "); if (tracker.delete(id)) { System.out.println("Item delete"); } else { System.out.println("Item not delete"); } } } /** * Класс ищет заявку по id. */ private static class FindIdItem extends BaseAction { public FindIdItem(int key, String name) { super(key, name); } @Override public void execute(Input input, ITracker tracker) { String id = input.ask("Please, enter the task's id: "); Item item = tracker.findById(id); if (item != null) { System.out.println( String.format("%s. %s", item.getId(), item.getName())); } else { System.out.println("Item not found"); } } } /** * Класс осуществляет выход из программы. */ private class Exit extends BaseAction { private final StartUI ui; public Exit(int key, String name, StartUI ui) { super(key, name); this.ui = ui; } @Override public void execute(Input input, ITracker tracker) { System.out.println("Menu item selected \"Exit programm.\""); this.ui.setExit(); } } }
vihahb/Xoso
app/src/main/java/com/xProject/XosoVIP/xoso/view/adapter/AdapterLoto.java
package com.xProject.XosoVIP.xoso.view.adapter; import android.content.Context; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.xProject.XosoVIP.R; import java.util.List; /** * Created by vivhp on 9/12/2017. */ public class AdapterLoto extends RecyclerView.Adapter<RecyclerView.ViewHolder> { List<String> lotoList; Context context; public AdapterLoto(List<String> lotoList, Context context) { this.lotoList = lotoList; this.context = context; } @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = LayoutInflater.from(context).inflate(R.layout.item_loto_analytics, parent, false); return new ViewHolder(view); } @Override public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) { if (holder instanceof ViewHolder) { String loto_value = lotoList.get(position); ViewHolder viewHolder = (ViewHolder) holder; viewHolder.tv_loto.setText(loto_value); if (position == 0) { viewHolder.tv_loto.setTextColor(context.getResources().getColor(R.color.colorPrimary)); } } } @Override public int getItemCount() { return lotoList.size(); } public void refreshLotoList(List<String> loto_list) { lotoList.clear(); lotoList.addAll(loto_list); notifyDataSetChanged(); } public class ViewHolder extends RecyclerView.ViewHolder { private TextView tv_loto; public ViewHolder(View itemView) { super(itemView); tv_loto = (TextView) itemView.findViewById(R.id.tv_loto); } } }
MikhailGorobets/FaceGenBaseLibrary
source/LibFgBase/src/Fg3dMeshPly.cpp
// // Coypright (c) 2020 Singular Inversions Inc. (facegen.com) // Use, modification and distribution is subject to the MIT License, // see accompanying file LICENSE.txt or facegen.com/base_library_license.txt // #include "stdafx.h" #include "Fg3dMeshOps.hpp" #include "Fg3dMeshIo.hpp" #include "Fg3dNormals.hpp" #include "FgStdStream.hpp" #include "FgFileSystem.hpp" #include "FgCommand.hpp" #include "FgTestUtils.hpp" using namespace std; namespace Fg { void savePly( Ustring const & fname, Meshes const & meshes, string imgFormat) { Mesh mesh = mergeMeshes(meshes); Path path(fname); path.ext = "ply"; Ofstream ofs(path.str()); ofs << "ply\n" "format ascii 1.0\n" "comment created by FaceGen\n"; size_t imgCnt = 0; for (size_t ii=0; ii<mesh.surfaces.size(); ++ii) { if (mesh.surfaces[ii].material.albedoMap) { Ustring texFile = path.base + toStr(ii) + "." + imgFormat; saveImage(path.dir()+texFile,*mesh.surfaces[ii].material.albedoMap); ofs << "comment TextureFile " << texFile << "\n"; } } ofs << "element vertex " << mesh.verts.size() << "\n" "property float x\n" "property float y\n" "property float z\n" "property float nx\n" "property float ny\n" "property float nz\n" "element face " << mesh.numTriEquivs() << "\n" "property list uchar int vertex_indices\n" "property list uchar float texcoord\n" "property int texnumber\n" "end_header\n"; MeshNormals norms = cNormals(mesh); for (size_t vv=0; vv<mesh.verts.size(); ++vv) { Vec3F pos = mesh.verts[vv], nrm = norms.vert[vv]; ofs << pos[0] << " " << pos[1] << " " << pos[2] << " " << nrm[0] << " " << nrm[1] << " " << nrm[2] << "\n"; } imgCnt = 0; for (size_t ss=0; ss<mesh.surfaces.size(); ++ss) { Surf const & surf = mesh.surfaces[ss]; FacetInds<3> tris = surf.getTriEquivs(); for (size_t ii=0; ii<tris.size(); ++ii) { Vec3UI vinds = tris.posInds[ii]; ofs << "3 " << vinds[0] << " " << vinds[1] << " " << vinds[2] << " 6 "; if (surf.tris.uvInds.empty()) ofs << "0 0 0 0 0 0 "; else { Vec3UI uvInds = tris.uvInds[ii]; for (uint vv=0; vv<3; ++vv) { Vec2F uv = mesh.uvs[uvInds[vv]]; ofs << uv[0] << " " << uv[1] << " "; } } ofs << imgCnt << "\n"; } if (mesh.surfaces[ss].material.albedoMap) ++imgCnt; } } void fgSavePlyTest(CLArgs const & args) { FGTESTDIR Ustring dd = dataDir(); string rd = "base/"; Mesh mouth = loadTri(dd+rd+"Mouth.tri"); mouth.surfaces[0].setAlbedoMap(loadImage(dd+rd+"MouthSmall.png")); Mesh glasses = loadTri(dd+rd+"Glasses.tri"); glasses.surfaces[0].setAlbedoMap(loadImage(dd+rd+"Glasses.tga")); savePly("meshExportPly",svec(mouth,glasses)); regressFileRel("meshExportPly.ply","base/test/"); regressFileRel("meshExportPly0.png","base/test/"); regressFileRel("meshExportPly1.png","base/test/"); } } // */
daodao10/chart
cn/002293_d.js
<gh_stars>1-10 var data=[['20090910',3.598], ['20090911',3.778], ['20090914',3.798], ['20090915',3.569], ['20090916',3.582], ['20090917',3.615], ['20090918',3.560], ['20090921',3.276], ['20090922',3.104], ['20090923',3.011], ['20090924',2.911], ['20090925',2.944], ['20090928',2.815], ['20090929',2.525], ['20090930',2.556], ['20091009',2.742], ['20091012',2.662], ['20091013',2.738], ['20091014',2.760], ['20091015',2.707], ['20091016',2.662], ['20091019',2.909], ['20091020',3.007], ['20091021',2.893], ['20091022',3.105], ['20091023',3.411], ['20091026',3.656], ['20091027',3.276], ['20091028',3.618], ['20091029',3.449], ['20091030',3.324], ['20091102',3.345], ['20091103',3.415], ['20091104',3.342], ['20091105',3.413], ['20091106',3.575], ['20091109',3.660], ['20091110',3.589], ['20091111',3.551], ['20091112',3.522], ['20091116',3.813], ['20091117',4.135], ['20091118',4.267], ['20091119',4.398], ['20091120',4.409], ['20091123',4.773], ['20091124',4.538], ['20091125',5.244], ['20091126',4.682], ['20091127',4.542], ['20091130',4.951], ['20091201',5.302], ['20091202',5.291], ['20091203',5.485], ['20091204',4.978], ['20091207',5.085], ['20091208',4.975], ['20091209',4.704], ['20091210',4.720], ['20091211',4.687], ['20091214',4.751], ['20091215',4.765], ['20091216',4.651], ['20091217',4.387], ['20091218',4.233], ['20091221',4.353], ['20091222',4.378], ['20091223',4.460], ['20091224',4.715], ['20091225',4.665], ['20091228',4.795], ['20091229',4.813], ['20091230',4.647], ['20091231',4.735], ['20100104',4.815], ['20100105',5.124], ['20100106',5.247], ['20100107',5.078], ['20100108',5.169], ['20100111',5.560], ['20100112',5.633], ['20100113',5.742], ['20100114',5.813], ['20100115',5.880], ['20100118',5.860], ['20100119',5.635], ['20100120',5.104], ['20100121',5.182], ['20100122',4.944], ['20100125',4.887], ['20100126',4.760], ['20100127',4.664], ['20100128',4.687], ['20100129',5.005], ['20100201',4.796], ['20100202',4.411], ['20100203',4.342], ['20100204',4.402], ['20100205',4.207], ['20100208',4.324], ['20100209',4.507], ['20100210',4.576], ['20100211',4.720], ['20100212',4.869], ['20100222',4.564], ['20100223',4.427], ['20100224',5.044], ['20100225',5.095], ['20100226',5.144], ['20100301',5.293], ['20100302',5.115], ['20100303',5.075], ['20100304',4.807], ['20100305',4.929], ['20100308',5.078], ['20100309',5.078], ['20100310',4.916], ['20100311',4.916], ['20100312',4.980], ['20100315',5.233], ['20100316',5.342], ['20100317',5.402], ['20100318',5.495], ['20100319',5.447], ['20100322',5.471], ['20100323',5.484], ['20100324',5.687], ['20100325',5.695], ['20100326',5.615], ['20100329',5.351], ['20100330',5.396], ['20100331',5.616], ['20100401',5.620], ['20100402',5.342], ['20100406',5.347], ['20100407',5.535], ['20100408',5.442], ['20100409',5.589], ['20100412',5.678], ['20100413',6.078], ['20100414',5.995], ['20100415',5.915], ['20100416',5.913], ['20100419',5.815], ['20100421',6.524], ['20100422',6.667], ['20100423',6.396], ['20100426',6.785], ['20100427',6.960], ['20100428',6.729], ['20100429',6.360], ['20100430',5.973], ['20100504',6.144], ['20100505',6.813], ['20100506',6.687], ['20100507',6.956], ['20100510',6.287], ['20100512',5.825], ['20100513',6.060], ['20100514',6.196], ['20100517',5.985], ['20100518',5.905], ['20100519',5.996], ['20100520',6.029], ['20100521',6.215], ['20100524',6.453], ['20100525',6.513], ['20100526',6.400], ['20100527',6.542], ['20100528',6.413], ['20100531',6.216], ['20100601',6.233], ['20100602',6.558], ['20100603',6.611], ['20100604',6.576], ['20100607',6.709], ['20100608',6.835], ['20100609',6.775], ['20100610',7.251], ['20100611',7.249], ['20100617',6.751], ['20100618',6.791], ['20100621',7.093], ['20100622',7.287], ['20100623',7.469], ['20100624',7.469], ['20100625',7.469], ['20100628',7.076], ['20100629',7.016], ['20100630',7.100], ['20100701',6.938], ['20100702',6.487], ['20100705',6.485], ['20100706',6.576], ['20100707',6.687], ['20100708',6.711], ['20100709',7.211], ['20100712',7.209], ['20100713',7.191], ['20100714',7.033], ['20100715',6.762], ['20100716',6.775], ['20100719',6.787], ['20100720',6.969], ['20100721',6.955], ['20100722',7.005], ['20100723',7.278], ['20100726',7.344], ['20100727',7.378], ['20100728',7.480], ['20100730',7.602], ['20100802',7.851], ['20100803',7.596], ['20100804',7.924], ['20100805',8.065], ['20100806',8.142], ['20100809',8.345], ['20100810',8.040], ['20100811',7.942], ['20100812',7.942], ['20100813',8.296], ['20100817',8.364], ['20100818',8.293], ['20100819',8.296], ['20100820',8.087], ['20100823',8.002], ['20100824',8.187], ['20100825',8.084], ['20100826',8.060], ['20100827',8.251], ['20100830',8.907], ['20100831',8.969], ['20100901',8.800], ['20100902',8.829], ['20100903',8.833], ['20100906',8.724], ['20100907',8.771], ['20100908',8.942], ['20100909',8.993], ['20100910',9.067], ['20100913',9.467], ['20100914',9.587], ['20100915',9.447], ['20100916',9.367], ['20100917',9.487], ['20100920',9.942], ['20100921',10.002], ['20100927',10.018], ['20100928',10.131], ['20100929',10.669], ['20100930',10.840], ['20101008',11.596], ['20101011',10.524], ['20101012',9.795], ['20101013',9.124], ['20101014',9.384], ['20101015',9.593], ['20101018',9.942], ['20101019',10.022], ['20101020',10.360], ['20101021',9.889], ['20101022',9.905], ['20101025',10.569], ['20101026',10.062], ['20101027',9.915], ['20101028',10.033], ['20101029',10.102], ['20101101',10.015], ['20101102',9.833], ['20101103',9.689], ['20101104',9.787], ['20101105',10.069], ['20101108',10.291], ['20101109',10.651], ['20101110',11.069], ['20101111',10.671], ['20101112',10.004], ['20101115',10.433], ['20101116',10.307], ['20101117',9.942], ['20101118',10.233], ['20101119',10.664], ['20101122',10.851], ['20101123',10.760], ['20101124',11.124], ['20101125',11.451], ['20101126',11.242], ['20101129',11.396], ['20101130',11.033], ['20101201',10.993], ['20101202',10.805], ['20101203',10.667], ['20101206',10.478], ['20101207',11.576], ['20101208',11.256], ['20101209',11.275], ['20101210',11.736], ['20101213',11.704], ['20101214',11.396], ['20101215',11.033], ['20101216',10.705], ['20101217',10.985], ['20101220',10.724], ['20101221',10.651], ['20101222',10.667], ['20101223',10.356], ['20101224',10.125], ['20101227',10.036], ['20101228',9.940], ['20101229',10.396], ['20101230',10.469], ['20101231',10.647], ['20110104',10.669], ['20110105',10.889], ['20110106',10.327], ['20110107',10.342], ['20110110',9.891], ['20110111',9.760], ['20110112',9.811], ['20110113',9.975], ['20110114',9.835], ['20110117',9.031], ['20110118',9.015], ['20110119',9.187], ['20110120',8.851], ['20110121',9.031], ['20110124',8.685], ['20110125',8.615], ['20110126',8.755], ['20110127',8.782], ['20110128',9.215], ['20110131',9.160], ['20110201',9.191], ['20110209',9.024], ['20110210',9.260], ['20110211',9.402], ['20110214',9.215], ['20110215',9.356], ['20110216',9.507], ['20110217',9.480], ['20110218',9.758], ['20110221',9.813], ['20110222',9.796], ['20110223',9.838], ['20110224',9.905], ['20110225',10.009], ['20110228',9.760], ['20110301',9.633], ['20110302',9.425], ['20110303',9.422], ['20110304',9.578], ['20110307',9.464], ['20110308',9.502], ['20110309',9.587], ['20110310',9.627], ['20110311',9.707], ['20110314',9.709], ['20110315',9.605], ['20110316',9.651], ['20110317',9.789], ['20110318',9.598], ['20110321',9.376], ['20110322',9.315], ['20110323',9.305], ['20110324',9.178], ['20110325',9.033], ['20110328',8.655], ['20110329',8.533], ['20110330',8.542], ['20110331',8.487], ['20110401',8.976], ['20110406',8.815], ['20110407',9.000], ['20110408',9.360], ['20110411',9.195], ['20110412',9.285], ['20110413',9.562], ['20110414',9.684], ['20110415',9.582], ['20110418',9.587], ['20110419',10.015], ['20110420',10.069], ['20110421',10.105], ['20110422',10.022], ['20110425',10.124], ['20110426',9.831], ['20110428',9.709], ['20110429',10.196], ['20110503',10.722], ['20110504',10.507], ['20110505',10.851], ['20110506',10.873], ['20110509',11.122], ['20110510',10.764], ['20110511',10.822], ['20110512',10.938], ['20110513',10.925], ['20110516',10.885], ['20110517',10.891], ['20110518',10.927], ['20110519',11.260], ['20110520',11.455], ['20110523',11.029], ['20110524',11.113], ['20110525',10.911], ['20110526',10.927], ['20110527',10.555], ['20110530',10.927], ['20110531',10.891], ['20110601',11.655], ['20110602',11.607], ['20110603',11.635], ['20110607',11.524], ['20110608',11.695], ['20110609',11.495], ['20110610',11.471], ['20110613',11.336], ['20110614',11.658], ['20110615',11.867], ['20110616',12.018], ['20110617',11.587], ['20110620',11.440], ['20110621',11.196], ['20110622',11.651], ['20110623',11.645], ['20110624',11.536], ['20110627',11.884], ['20110628',11.818], ['20110629',11.473], ['20110630',11.755], ['20110701',11.691], ['20110704',12.198], ['20110705',12.200], ['20110706',12.018], ['20110707',12.213], ['20110708',12.542], ['20110711',12.687], ['20110712',12.682], ['20110713',13.007], ['20110714',12.998], ['20110715',12.982], ['20110718',12.745], ['20110719',12.224], ['20110720',12.325], ['20110721',12.551], ['20110722',12.484], ['20110725',12.131], ['20110726',12.740], ['20110727',13.385], ['20110728',13.480], ['20110729',13.740], ['20110801',13.305], ['20110802',13.618], ['20110803',13.709], ['20110804',13.705], ['20110805',13.613], ['20110808',13.364], ['20110809',13.347], ['20110810',13.800], ['20110811',14.300], ['20110812',14.222], ['20110815',13.836], ['20110816',13.656], ['20110817',14.380], ['20110818',14.291], ['20110819',14.018], ['20110822',13.691], ['20110823',13.836], ['20110824',13.771], ['20110825',13.651], ['20110826',13.745], ['20110829',14.227], ['20110830',14.111], ['20110831',13.745], ['20110901',13.596], ['20110902',13.255], ['20110905',13.395], ['20110906',13.527], ['20110907',13.655], ['20110908',13.945], ['20110909',14.071], ['20110913',13.831], ['20110914',14.000], ['20110915',13.745], ['20110916',13.905], ['20110919',13.145], ['20110920',13.147], ['20110921',13.564], ['20110922',13.469], ['20110923',13.291], ['20110926',13.196], ['20110927',13.007], ['20110928',12.927], ['20110929',12.745], ['20110930',12.745], ['20111010',12.487], ['20111011',12.745], ['20111012',13.073], ['20111013',13.287], ['20111014',12.900], ['20111017',13.027], ['20111018',12.927], ['20111019',12.291], ['20111020',12.018], ['20111021',12.000], ['20111024',12.473], ['20111025',12.655], ['20111026',12.836], ['20111027',12.905], ['20111028',12.491], ['20111031',12.491], ['20111101',12.509], ['20111102',12.858], ['20111103',13.196], ['20111104',13.089], ['20111107',13.040], ['20111108',12.836], ['20111109',12.669], ['20111110',12.691], ['20111111',12.927], ['20111114',13.018], ['20111115',12.955], ['20111116',12.764], ['20111117',12.836], ['20111118',12.542], ['20111121',12.391], ['20111122',12.367], ['20111123',12.373], ['20111124',12.524], ['20111125',12.656], ['20111129',12.953], ['20111130',12.745], ['20111201',13.091], ['20111202',12.836], ['20111205',12.836], ['20111206',12.707], ['20111207',13.018], ['20111208',13.160], ['20111209',12.913], ['20111212',12.220], ['20111213',11.982], ['20111214',11.815], ['20111215',11.745], ['20111216',11.985], ['20111219',11.655], ['20111220',11.691], ['20111221',11.562], ['20111222',11.744], ['20111223',11.727], ['20111226',11.436], ['20111227',10.973], ['20111228',10.815], ['20111229',10.836], ['20111230',11.291], ['20120105',10.745], ['20120106',10.836], ['20120109',10.925], ['20120110',11.055], ['20120111',10.869], ['20120112',10.844], ['20120113',10.133], ['20120116',9.289], ['20120117',9.615], ['20120118',9.382], ['20120119',9.329], ['20120120',9.798], ['20120130',9.760], ['20120131',9.764], ['20120201',9.785], ['20120202',9.964], ['20120203',10.064], ['20120206',9.955], ['20120207',10.000], ['20120208',10.069], ['20120209',10.275], ['20120210',10.473], ['20120213',10.838], ['20120214',10.855], ['20120215',10.711], ['20120216',10.713], ['20120217',10.745], ['20120220',10.818], ['20120221',10.984], ['20120222',11.200], ['20120223',11.458], ['20120224',11.495], ['20120227',11.382], ['20120228',10.822], ['20120229',10.745], ['20120301',10.651], ['20120302',10.671], ['20120305',10.473], ['20120306',10.647], ['20120307',10.495], ['20120308',10.404], ['20120309',10.655], ['20120312',10.967], ['20120313',11.036], ['20120314',10.836], ['20120315',10.791], ['20120316',11.336], ['20120319',11.527], ['20120320',11.382], ['20120321',11.138], ['20120322',11.069], ['20120323',11.073], ['20120326',10.880], ['20120327',10.782], ['20120328',10.473], ['20120329',10.491], ['20120330',10.827], ['20120405',11.200], ['20120406',11.018], ['20120409',10.845], ['20120410',10.918], ['20120411',10.527], ['20120412',10.524], ['20120413',10.436], ['20120416',10.204], ['20120417',9.818], ['20120418',10.045], ['20120419',9.965], ['20120420',9.925], ['20120423',9.273], ['20120424',9.258], ['20120425',9.309], ['20120426',9.440], ['20120427',9.476], ['20120502',9.545], ['20120503',9.736], ['20120504',10.015], ['20120507',10.491], ['20120509',10.336], ['20120510',10.327], ['20120511',10.375], ['20120514',10.309], ['20120515',10.364], ['20120516',10.075], ['20120517',10.025], ['20120518',10.000], ['20120521',10.175], ['20120522',10.200], ['20120523',10.200], ['20120524',10.415], ['20120525',10.382], ['20120528',10.289], ['20120529',10.629], ['20120530',10.882], ['20120531',11.109], ['20120601',11.218], ['20120604',11.073], ['20120605',11.109], ['20120606',10.925], ['20120607',10.982], ['20120608',10.900], ['20120611',10.745], ['20120612',10.929], ['20120613',12.018], ['20120614',12.007], ['20120615',11.736], ['20120618',11.736], ['20120619',11.655], ['20120620',11.645], ['20120621',11.631], ['20120625',11.255], ['20120626',11.100], ['20120627',11.033], ['20120628',11.038], ['20120629',11.400], ['20120702',11.611], ['20120703',11.864], ['20120704',11.655], ['20120705',11.655], ['20120706',11.655], ['20120709',11.295], ['20120710',10.907], ['20120711',9.600], ['20120712',9.324], ['20120713',9.411], ['20120716',8.745], ['20120717',8.645], ['20120718',8.691], ['20120719',8.693], ['20120720',8.787], ['20120723',8.656], ['20120724',8.673], ['20120725',8.635], ['20120726',8.764], ['20120727',8.796], ['20120730',8.707], ['20120731',8.745], ['20120801',8.876], ['20120802',8.564], ['20120803',8.655], ['20120806',8.673], ['20120807',8.618], ['20120808',8.745], ['20120809',8.742], ['20120810',8.531], ['20120813',8.347], ['20120814',8.378], ['20120815',8.445], ['20120816',8.309], ['20120817',8.325], ['20120820',8.069], ['20120821',7.795], ['20120822',7.644], ['20120823',7.420], ['20120824',7.613], ['20120827',7.564], ['20120828',7.400], ['20120829',7.118], ['20120830',6.996], ['20120831',6.982], ['20120903',7.105], ['20120904',7.009], ['20120905',6.800], ['20120906',6.625], ['20120907',6.920], ['20120910',7.247], ['20120911',7.205], ['20120912',7.109], ['20120913',6.971], ['20120914',6.936], ['20120917',6.547], ['20120918',6.304], ['20120919',6.302], ['20120920',5.927], ['20120921',6.055], ['20120924',6.178], ['20120925',6.189], ['20120926',6.109], ['20120927',6.213], ['20120928',6.324], ['20121008',6.355], ['20121009',6.527], ['20121010',6.747], ['20121011',6.618], ['20121012',6.436], ['20121015',6.527], ['20121016',6.518], ['20121017',6.200], ['20121018',6.009], ['20121019',5.616], ['20121022',5.573], ['20121023',5.500], ['20121024',5.535], ['20121025',5.507], ['20121026',5.229], ['20121029',5.276], ['20121030',5.180], ['20121031',5.145], ['20121101',5.395], ['20121102',5.445], ['20121105',5.460], ['20121106',5.400], ['20121107',5.400], ['20121108',5.291], ['20121109',5.173], ['20121112',5.218], ['20121113',5.225], ['20121114',5.373], ['20121115',5.344], ['20121116',5.255], ['20121119',5.164], ['20121120',5.055], ['20121121',5.164], ['20121122',5.093], ['20121123',5.100], ['20121126',4.964], ['20121127',4.491], ['20121128',4.165], ['20121129',4.073], ['20121130',4.113], ['20121203',3.835], ['20121204',3.956], ['20121205',4.218], ['20121206',4.167], ['20121207',4.302], ['20121210',4.622], ['20121211',4.935], ['20121212',4.967], ['20121213',4.911], ['20121214',5.116], ['20121217',5.273], ['20121218',5.315], ['20121219',5.427], ['20121220',5.702], ['20121221',5.691], ['20121224',5.873], ['20121225',6.085], ['20121226',6.291], ['20121227',6.091], ['20121228',5.924], ['20121231',5.700], ['20130104',5.618], ['20130107',5.680], ['20130108',5.764], ['20130109',5.998], ['20130110',5.840], ['20130111',5.473], ['20130114',5.636], ['20130115',5.902], ['20130116',5.945], ['20130117',6.282], ['20130118',6.453], ['20130121',6.371], ['20130122',6.251], ['20130123',6.162], ['20130124',5.613], ['20130129',6.391], ['20130130',6.687], ['20130131',6.853], ['20130201',6.749], ['20130204',6.495], ['20130205',6.520], ['20130206',6.502], ['20130207',6.544], ['20130208',6.807], ['20130218',6.724], ['20130219',7.055], ['20130220',7.498], ['20130221',7.284], ['20130222',7.093], ['20130225',7.109], ['20130226',6.891], ['20130227',6.796], ['20130228',7.109], ['20130301',7.205], ['20130304',6.269], ['20130305',6.505], ['20130306',6.402], ['20130307',6.100], ['20130308',6.162], ['20130311',6.075], ['20130312',5.913], ['20130313',5.400], ['20130314',5.291], ['20130315',5.396], ['20130318',5.238], ['20130319',5.264], ['20130320',5.491], ['20130321',5.564], ['20130322',5.351], ['20130325',5.111], ['20130326',5.353], ['20130327',5.233], ['20130328',4.964], ['20130329',4.836], ['20130401',4.891], ['20130402',4.818], ['20130403',4.409], ['20130408',4.191], ['20130409',4.227], ['20130410',4.273], ['20130411',4.356], ['20130412',4.320], ['20130415',4.178], ['20130416',4.380], ['20130417',4.565], ['20130418',4.511], ['20130419',4.616], ['20130422',5.262], ['20130423',5.016], ['20130424',5.435], ['20130425',5.256], ['20130426',5.018], ['20130502',4.691], ['20130503',4.818], ['20130506',5.105], ['20130507',5.149], ['20130508',5.367], ['20130509',5.276], ['20130510',5.342], ['20130513',5.260], ['20130514',5.080], ['20130515',5.327], ['20130516',5.527], ['20130517',5.562], ['20130520',5.718], ['20130521',5.825], ['20130522',5.615], ['20130523',5.649], ['20130524',5.682], ['20130527',6.467], ['20130528',6.418], ['20130529',6.502], ['20130530',6.376], ['20130531',5.876], ['20130603',5.560], ['20130604',5.451], ['20130605',5.509], ['20130606',5.138], ['20130607',4.862], ['20130613',4.767], ['20130614',4.996], ['20130617',5.247], ['20130618',5.113], ['20130619',4.956], ['20130620',4.647], ['20130621',4.571], ['20130624',4.102], ['20130625',4.276], ['20130626',4.262], ['20130627',4.004], ['20130628',4.051], ['20130701',4.073], ['20130702',4.222], ['20130703',4.022], ['20130704',4.051], ['20130705',4.029], ['20130708',3.622], ['20130709',3.607], ['20130710',3.738], ['20130711',3.924], ['20130712',3.931], ['20130715',4.393], ['20130716',4.767], ['20130717',4.822], ['20130718',4.709], ['20130719',4.498], ['20130722',4.738], ['20130723',4.996], ['20130724',4.884], ['20130725',4.800], ['20130726',4.771], ['20130729',4.727], ['20130730',4.902], ['20130731',4.793], ['20130801',4.902], ['20130802',4.825], ['20130805',5.331], ['20130806',5.316], ['20130807',5.382], ['20130808',5.458], ['20130809',5.229], ['20130812',5.269], ['20130813',5.400], ['20130814',5.244], ['20130815',5.051], ['20130816',4.887], ['20130819',4.985], ['20130820',4.945], ['20130821',4.920], ['20130822',4.982], ['20130823',4.833], ['20130826',5.204], ['20130827',5.393], ['20130828',5.244], ['20130829',5.258], ['20130830',5.262], ['20130902',5.327], ['20130903',5.480], ['20130904',5.236], ['20130905',5.320], ['20130906',5.255], ['20130909',5.258], ['20130910',5.276], ['20130911',5.560], ['20130912',5.527], ['20130913',5.749], ['20130916',5.924], ['20130917',5.636], ['20130918',5.669], ['20130923',5.785], ['20130924',5.593], ['20130925',5.658], ['20130926',5.560], ['20130927',5.164], ['20130930',5.247], ['20131008',5.255], ['20131009',5.182], ['20131010',4.865], ['20131011',5.011], ['20131014',5.327], ['20131015',5.455], ['20131016',5.440], ['20131017',5.436], ['20131018',5.440], ['20131021',6.055], ['20131022',6.865], ['20131023',6.691], ['20131024',6.302], ['20131025',6.185], ['20131028',6.073], ['20131029',5.564], ['20131030',5.705], ['20131031',5.327], ['20131101',5.353], ['20131104',5.455], ['20131105',6.204], ['20131106',5.847], ['20131107',5.847], ['20131108',5.665], ['20131111',5.829], ['20131112',5.756], ['20131113',5.418], ['20131114',5.564], ['20131115',5.665], ['20131118',5.822], ['20131119',6.029], ['20131120',6.036], ['20131121',5.818], ['20131122',5.818], ['20131125',5.716], ['20131126',5.629], ['20131127',5.855], ['20131128',5.855], ['20131129',5.916], ['20131202',5.513], ['20131203',5.673], ['20131204',5.989], ['20131205',6.076], ['20131206',5.964], ['20131209',6.465], ['20131210',6.480], ['20131211',6.280], ['20131212',6.265], ['20131213',6.647], ['20131216',6.567], ['20131217',6.356], ['20131218',6.655], ['20131219',6.469], ['20131220',6.255], ['20131223',6.298], ['20131224',6.265], ['20131225',6.480], ['20131226',6.298], ['20131227',6.455], ['20131230',6.633], ['20131231',6.622], ['20140102',7.124], ['20140103',7.018], ['20140106',6.545], ['20140107',6.618], ['20140108',6.658], ['20140109',6.400], ['20140110',6.218], ['20140113',6.251], ['20140114',6.389], ['20140115',6.196], ['20140116',6.225], ['20140117',5.800], ['20140120',5.629], ['20140121',5.633], ['20140122',5.818], ['20140123',5.927], ['20140124',5.869], ['20140127',5.640], ['20140128',5.745], ['20140129',5.840], ['20140130',5.742], ['20140207',5.782], ['20140210',6.091], ['20140211',6.040], ['20140212',6.233], ['20140213',6.025], ['20140214',6.182], ['20140217',6.309], ['20140218',6.236], ['20140219',6.298], ['20140220',6.022], ['20140221',6.036], ['20140224',5.767], ['20140225',5.567], ['20140226',5.640], ['20140227',5.345], ['20140228',5.444], ['20140303',5.625], ['20140304',5.600], ['20140305',5.782], ['20140306',5.927], ['20140307',5.756], ['20140310',5.429], ['20140311',5.495], ['20140312',5.596], ['20140313',5.709], ['20140314',5.655], ['20140317',5.709], ['20140318',5.884], ['20140319',5.767], ['20140320',5.491], ['20140321',5.764], ['20140324',5.825], ['20140325',5.825], ['20140326',6.145], ['20140327',5.960], ['20140328',5.844], ['20140331',5.964], ['20140401',6.022], ['20140402',5.964], ['20140403',6.087], ['20140404',6.218], ['20140408',6.149], ['20140409',6.131], ['20140410',6.062], ['20140411',5.996], ['20140414',6.007], ['20140415',5.778], ['20140416',5.815], ['20140417',5.644], ['20140418',5.709], ['20140421',5.484], ['20140422',5.327], ['20140423',5.404], ['20140424',5.371], ['20140425',5.382], ['20140428',5.207], ['20140429',5.305], ['20140430',5.331], ['20140505',5.527], ['20140506',5.687], ['20140507',5.593], ['20140508',5.545], ['20140509',5.440], ['20140512',5.545], ['20140513',5.564], ['20140514',5.484], ['20140515',5.545], ['20140516',5.491], ['20140519',5.345], ['20140520',5.295], ['20140521',5.367], ['20140522',5.407], ['20140523',5.560], ['20140526',5.578], ['20140527',5.673], ['20140528',5.676], ['20140529',5.655], ['20140530',5.600], ['20140603',5.469], ['20140604',5.378], ['20140605',5.400], ['20140606',5.284], ['20140609',5.251], ['20140610',5.375], ['20140611',5.364], ['20140612',5.400], ['20140613',5.520], ['20140616',5.680], ['20140617',5.495], ['20140618',5.473], ['20140619',5.265], ['20140620',5.265], ['20140623',5.429], ['20140624',5.433], ['20140625',5.320], ['20140626',5.415], ['20140627',5.418], ['20140630',5.400], ['20140701',5.516], ['20140702',5.455], ['20140703',5.502], ['20140704',5.444], ['20140707',5.422], ['20140708',5.447], ['20140709',5.458], ['20140710',5.491], ['20140711',5.502], ['20140714',5.575], ['20140715',5.585], ['20140716',5.487], ['20140717',5.538], ['20140718',5.393], ['20140721',5.324], ['20140722',5.309], ['20140723',5.262], ['20140724',5.273], ['20140725',5.338], ['20140728',5.444], ['20140729',5.538], ['20140730',5.535], ['20140731',5.538], ['20140801',5.484], ['20140804',5.731], ['20140805',5.749], ['20140806',5.720], ['20140807',5.589], ['20140808',5.607], ['20140811',5.742], ['20140812',5.869], ['20140813',5.804], ['20140814',5.949], ['20140815',5.996], ['20140818',6.033], ['20140819',5.975], ['20140820',5.985], ['20140821',5.880], ['20140822',5.971], ['20140825',5.847], ['20140826',5.644], ['20140827',5.691], ['20140828',5.680], ['20140829',5.705], ['20140901',5.818], ['20140902',5.927], ['20140903',5.938], ['20140904',6.018], ['20140905',6.036], ['20140909',5.971], ['20140910',6.185], ['20140911',6.098], ['20140912',6.345], ['20140915',6.727], ['20140916',6.498], ['20140917',6.585], ['20140918',6.764], ['20140919',6.865], ['20140922',6.600], ['20140923',6.644], ['20140924',6.665], ['20140925',6.691], ['20140926',6.705], ['20140929',6.902], ['20140930',6.964], ['20141008',6.956], ['20141009',6.938], ['20141010',6.673], ['20141013',6.556], ['20141014',6.702], ['20141015',6.676], ['20141016',6.564], ['20141017',6.447], ['20141020',6.782], ['20141021',6.778], ['20141022',6.749], ['20141023',6.571], ['20141024',6.545], ['20141027',6.531], ['20141028',6.793], ['20141029',6.847], ['20141030',6.935], ['20141031',7.135], ['20141103',7.487], ['20141104',7.415], ['20141105',7.455], ['20141106',7.375], ['20141107',7.305], ['20141110',7.404], ['20141111',6.949], ['20141112',7.036], ['20141113',6.865], ['20141114',6.858], ['20141117',6.902], ['20141118',6.844], ['20141119',6.953], ['20141120',6.956], ['20141121',7.044], ['20141124',7.058], ['20141125',7.116], ['20141126',7.229], ['20141127',7.182], ['20141128',7.073], ['20141201',6.825], ['20141202',7.193], ['20141203',7.320], ['20141204',7.629], ['20141205',7.378], ['20141208',7.364], ['20141209',7.145], ['20141210',7.429], ['20141211',7.796], ['20141212',8.040], ['20141215',8.080], ['20141216',7.956], ['20141217',7.807], ['20141218',7.731], ['20141219',7.709], ['20141222',7.353], ['20141223',7.433], ['20141224',7.673], ['20141225',7.698], ['20141226',7.789], ['20141229',7.516], ['20141230',7.495], ['20141231',7.458], ['20150105',7.909], ['20150106',8.029], ['20150107',8.033], ['20150108',7.836], ['20150109',7.607], ['20150112',7.611], ['20150113',7.615], ['20150114',7.436], ['20150115',7.615], ['20150116',7.625], ['20150119',7.149], ['20150120',7.389], ['20150121',7.582], ['20150122',7.764], ['20150123',7.636], ['20150126',7.851], ['20150127',8.015], ['20150128',7.964], ['20150129',7.804], ['20150130',7.745], ['20150202',7.818], ['20150203',7.945], ['20150204',7.844], ['20150205',8.007], ['20150206',8.280], ['20150209',8.851], ['20150210',8.745], ['20150211',8.629], ['20150212',8.636], ['20150213',8.629], ['20150216',8.647], ['20150217',8.807], ['20150225',8.855], ['20150226',8.607], ['20150227',8.575], ['20150302',8.949], ['20150303',8.767], ['20150304',8.742], ['20150305',8.873], ['20150306',8.571], ['20150309',8.651], ['20150310',8.753], ['20150311',8.775], ['20150312',8.775], ['20150313',8.775], ['20150316',9.353], ['20150317',9.436], ['20150318',9.545], ['20150319',10.691], ['20150320',10.691], ['20150323',10.796], ['20150324',10.818], ['20150325',11.145], ['20150326',10.735], ['20150327',10.629], ['20150330',10.571], ['20150331',10.607], ['20150401',11.411], ['20150402',11.273], ['20150403',12.076], ['20150407',12.375], ['20150408',12.127], ['20150409',12.047], ['20150410',12.193], ['20150413',13.102], ['20150414',12.924], ['20150415',12.491], ['20150416',12.542], ['20150417',13.655], ['20150420',13.564], ['20150421',14.382], ['20150422',14.913], ['20150423',16.567], ['20150424',16.964], ['20150427',16.876], ['20150428',16.164], ['20150429',15.818], ['20150430',15.902], ['20150504',15.520], ['20150505',15.131], ['20150506',15.531], ['20150507',15.375], ['20150508',15.840], ['20150511',16.782], ['20150512',16.745], ['20150513',17.040], ['20150514',17.240], ['20150515',17.251], ['20150518',18.222], ['20150519',19.545], ['20150520',19.585], ['20150521',21.691], ['20150522',23.909], ['20150525',26.091], ['20150526',28.884], ['20150527',26.473], ['20150528',23.673], ['20150529',22.145], ['20150601',22.700], ['20150602',22.809], ['20150603',25.245], ['20150604',27.900], ['20150605',26.755], ['20150608',24.564], ['20150609',25.000], ['20150610',24.618], ['20150611',24.618], ['20150612',24.245], ['20150615',22.727], ['20150616',21.273], ['20150617',22.291], ['20150618',21.382], ['20150619',19.091], ['20150623',18.164], ['20150624',18.527], ['20150625',17.000], ['20150626',15.145], ['20150629',13.473], ['20150630',14.900], ['20150701',13.355], ['20150702',12.545], ['20150703',11.973], ['20150706',13.327], ['20150707',12.873], ['20150708',13.418], ['20150709',14.918], ['20150710',16.564], ['20150713',18.373], ['20150714',17.191], ['20150715',15.318], ['20150716',15.918], ['20150717',17.227], ['20150720',16.955], ['20150721',16.827], ['20150722',17.527], ['20150723',17.809], ['20150724',16.764], ['20150727',14.936], ['20150728',14.500], ['20150729',15.345], ['20150730',14.155], ['20150731',14.218], ['20150803',14.982], ['20150804',15.973], ['20150805',15.182], ['20150806',14.655], ['20150807',15.127], ['20150810',15.918], ['20150811',17.664], ['20150812',19.045], ['20150813',18.500], ['20150814',18.364], ['20150817',17.782], ['20150818',15.845], ['20150819',16.909], ['20150820',15.536], ['20150821',14.491], ['20150824',12.891], ['20150825',11.464], ['20150826',11.745], ['20150827',12.127], ['20150828',13.036], ['20150831',12.064], ['20150901',10.818], ['20150902',11.491], ['20150907',11.464], ['20150908',11.864], ['20150909',12.455], ['20150910',11.891], ['20150911',12.273], ['20150914',12.400], ['20150915',11.009], ['20150916',12.182], ['20150917',11.500], ['20150918',11.391], ['20150921',11.709], ['20150922',11.773], ['20150923',11.555], ['20150924',11.909], ['20150925',11.591], ['20150928',11.600], ['20150929',11.173], ['20150930',11.327], ['20151008',11.818], ['20151009',11.945], ['20151019',13.291], ['20151020',14.036], ['20151021',12.555], ['20151022',13.136], ['20151023',13.264], ['20151026',13.882], ['20151027',14.091], ['20151028',13.964], ['20151029',13.991], ['20151030',14.818], ['20151102',14.245], ['20151103',13.818], ['20151104',14.927], ['20151105',14.636], ['20151106',14.800], ['20151109',14.882], ['20151110',15.327], ['20151111',15.182], ['20151112',14.882], ['20151113',14.382], ['20151116',14.536], ['20151117',14.555], ['20151118',14.073], ['20151119',14.300], ['20151120',14.709], ['20151123',15.627], ['20151124',15.445], ['20151125',15.364], ['20151126',15.409], ['20151127',13.927], ['20151130',13.773], ['20151201',13.945], ['20151202',14.000], ['20151203',14.218], ['20151204',14.018], ['20151207',14.864], ['20151208',15.273], ['20151209',15.209], ['20151210',15.091], ['20151211',15.218], ['20151214',15.445], ['20151215',15.355], ['20151216',15.345], ['20151217',16.091], ['20151218',16.582], ['20151221',16.336], ['20151222',16.218], ['20151223',15.464], ['20151224',15.536], ['20151225',15.473], ['20151228',14.818], ['20151229',15.082], ['20151230',15.073], ['20151231',15.036], ['20160104',13.518], ['20160105',13.182], ['20160106',14.000], ['20160107',12.455], ['20160108',12.655], ['20160111',11.273], ['20160112',11.082], ['20160113',10.864], ['20160114',11.209], ['20160115',10.445], ['20160118',10.509], ['20160119',10.873], ['20160120',10.755], ['20160121',10.300], ['20160122',10.527], ['20160125',10.909], ['20160126',9.736], ['20160127',9.327], ['20160128',9.036], ['20160129',9.409], ['20160201',9.364], ['20160202',9.682], ['20160203',9.700], ['20160204',9.891], ['20160205',9.782], ['20160215',9.618], ['20160216',10.245], ['20160217',10.345], ['20160218',10.236], ['20160219',10.291], ['20160222',10.555], ['20160223',10.364], ['20160224',10.391], ['20160225',9.482], ['20160226',9.618], ['20160229',9.055], ['20160301',9.255], ['20160302',10.336], ['20160303',10.491], ['20160304',10.091], ['20160307',10.291], ['20160308',10.209], ['20160309',9.836], ['20160310',9.500], ['20160311',9.509], ['20160314',9.918], ['20160315',9.818], ['20160316',9.655], ['20160317',10.000], ['20160318',10.518], ['20160321',10.755], ['20160322',10.600], ['20160323',10.691], ['20160324',10.418], ['20160325',10.782], ['20160328',11.027], ['20160329',10.655], ['20160330',11.009], ['20160331',10.855], ['20160401',10.855], ['20160405',11.036], ['20160406',11.109], ['20160407',11.018], ['20160408',10.727], ['20160411',11.309], ['20160412',11.545], ['20160505',11.927], ['20160506',11.273], ['20160509',10.518], ['20160510',10.445], ['20160511',10.464], ['20160512',10.273], ['20160513',10.127], ['20160516',10.264], ['20160517',10.164], ['20160518',9.636], ['20160519',9.700], ['20160520',9.873], ['20160523',10.027], ['20160524',10.091], ['20160525',9.982], ['20160526',10.009], ['20160527',9.991], ['20160530',9.882], ['20160531',10.345], ['20160601',10.264], ['20160602',10.273], ['20160603',10.373], ['20160606',10.891], ['20160607',10.691], ['20160608',10.627], ['20160613',9.955], ['20160614',9.991], ['20160615',10.418], ['20160616',10.182], ['20160617',10.282], ['20160620',10.236], ['20160621',10.255], ['20160622',10.618], ['20160623',10.636], ['20160624',10.845], ['20160627',10.982], ['20160628',10.909], ['20160629',10.873], ['20160630',11.091], ['20160701',10.936], ['20160704',11.055], ['20160705',11.036], ['20160706',11.018], ['20160707',11.182], ['20160708',10.964], ['20160711',11.027], ['20160712',11.564], ['20160713',11.482], ['20160714',11.364], ['20160715',11.282], ['20160718',11.373], ['20160719',11.218], ['20160720',11.373], ['20160721',11.255], ['20160722',11.164], ['20160725',11.255], ['20160726',11.336], ['20160727',10.800], ['20160728',10.864], ['20160729',10.855], ['20160801',10.564], ['20160802',10.755], ['20160803',10.909], ['20160804',10.818], ['20160805',11.082], ['20160808',11.527], ['20160809',11.400], ['20160810',11.273], ['20160811',11.209], ['20160812',11.345], ['20160815',11.564], ['20160816',11.600], ['20160817',11.591], ['20160818',11.509], ['20160819',11.491], ['20160822',11.336], ['20160823',11.382], ['20160824',11.200], ['20160825',11.164], ['20160826',11.291], ['20160829',11.227], ['20160830',11.227], ['20160831',11.227], ['20160901',11.045], ['20160902',11.100], ['20160905',11.045], ['20160906',11.200], ['20160907',11.191], ['20160908',11.145], ['20160909',11.436], ['20160912',11.209], ['20160913',11.318], ['20160914',11.318], ['20160919',11.418], ['20160920',11.155], ['20160921',11.164], ['20160922',11.164], ['20160923',11.136], ['20160926',10.909], ['20160927',11.009], ['20160928',10.955], ['20160929',11.000], ['20160930',11.055], ['20161010',11.218], ['20161011',11.236], ['20161012',11.300], ['20161013',11.273], ['20161014',11.264], ['20161017',11.127], ['20161018',11.300], ['20161019',11.145], ['20161020',11.145], ['20161021',11.164], ['20161024',11.182], ['20161025',11.209], ['20161026',11.291], ['20161027',11.173], ['20161028',11.027], ['20161031',11.064], ['20161101',11.191], ['20161102',11.091], ['20161103',11.136], ['20161104',11.100], ['20161107',11.527], ['20161108',11.545], ['20161109',11.382], ['20161110',11.636], ['20161111',11.536], ['20161114',11.436], ['20161115',11.573], ['20161116',11.655], ['20161117',12.082], ['20161118',11.955], ['20161121',11.964], ['20161122',12.064], ['20161123',11.845], ['20161124',11.882], ['20161125',11.864], ['20161128',11.718], ['20161129',11.573], ['20161130',11.509], ['20161201',11.518], ['20161202',11.300], ['20161205',11.236], ['20161206',11.255], ['20161207',11.373], ['20161208',11.282], ['20161209',11.345], ['20161212',10.727], ['20161213',10.755], ['20161214',10.827], ['20161215',10.855], ['20161216',10.836], ['20161219',10.873], ['20161220',10.955], ['20161221',10.955], ['20161222',10.973], ['20161223',10.918], ['20161226',10.909], ['20161227',10.818], ['20161228',10.727], ['20161229',10.745], ['20161230',10.864], ['20170103',10.945], ['20170104',11.282], ['20170105',11.173], ['20170106',11.073], ['20170109',11.036], ['20170110',11.027], ['20170111',10.891], ['20170112',10.800], ['20170113',10.882], ['20170116',10.418], ['20170117',10.527], ['20170118',10.427], ['20170119',10.345], ['20170120',10.473], ['20170123',10.591], ['20170124',10.536], ['20170125',10.645], ['20170126',10.682], ['20170203',10.645], ['20170206',10.764], ['20170207',10.800], ['20170208',10.818], ['20170209',10.800], ['20170210',10.791], ['20170213',10.791], ['20170214',10.818], ['20170215',10.800], ['20170216',10.718], ['20170217',10.673], ['20170220',10.718], ['20170221',10.864], ['20170222',10.773], ['20170223',10.827], ['20170224',10.873], ['20170227',10.782], ['20170228',10.818], ['20170301',10.782], ['20170302',10.764], ['20170303',10.745], ['20170306',10.955], ['20170307',11.018], ['20170308',10.955], ['20170309',10.845], ['20170310',10.873], ['20170313',10.891], ['20170314',10.800], ['20170315',10.782], ['20170316',10.809], ['20170317',10.709], ['20170320',10.691], ['20170321',10.709], ['20170322',10.582], ['20170323',10.518], ['20170324',10.673], ['20170327',10.700], ['20170328',10.718], ['20170329',10.564], ['20170330',10.436], ['20170331',10.500], ['20170405',10.600], ['20170406',10.655], ['20170407',10.618], ['20170410',10.473], ['20170411',10.518], ['20170412',10.682], ['20170413',10.555], ['20170414',10.473], ['20170417',10.400], ['20170418',10.127], ['20170419',9.855], ['20170420',10.000], ['20170421',9.864], ['20170424',9.736], ['20170425',9.809], ['20170426',9.891], ['20170427',9.936], ['20170428',9.955], ['20170502',10.027], ['20170503',10.364], ['20170504',10.200], ['20170505',10.055], ['20170508',9.745], ['20170509',9.745], ['20170510',9.564], ['20170511',9.327], ['20170512',9.191], ['20170515',9.155], ['20170516',9.227], ['20170517',9.227], ['20170518',9.082], ['20170519',9.000], ['20170522',8.718], ['20170523',8.500], ['20170524',8.591], ['20170525',8.545], ['20170526',8.582], ['20170531',8.773], ['20170601',8.718], ['20170602',8.818], ['20170605',8.845], ['20170606',8.827], ['20170607',9.118], ['20170608',9.045], ['20170609',9.045], ['20170612',9.064], ['20170613',9.191], ['20170614',9.064], ['20170615',9.109], ['20170616',9.100], ['20170619',9.173], ['20170620',9.309], ['20170621',9.300], ['20170622',9.082], ['20170623',9.036], ['20170626',9.155], ['20170627',9.118], ['20170628',9.136], ['20170629',9.164], ['20170630',9.236], ['20170703',9.364], ['20170704',9.309], ['20170705',9.327], ['20170706',9.300], ['20170707',9.345], ['20170710',9.327], ['20170711',9.236], ['20170712',8.964], ['20170713',9.055], ['20170714',9.545], ['20170717',9.009], ['20170718',9.000], ['20170719',9.055], ['20170720',9.064], ['20170721',9.000], ['20170724',9.045], ['20170725',8.927], ['20170726',8.891], ['20170727',9.045], ['20170728',9.000], ['20170731',9.045], ['20170801',9.145], ['20170802',9.009], ['20170803',8.918], ['20170804',8.727], ['20170807',8.709], ['20170808',8.555], ['20170809',8.773], ['20170810',8.609], ['20170811',8.473], ['20170814',8.636], ['20170815',8.691], ['20170816',8.764], ['20170817',8.800], ['20170818',8.818], ['20170821',8.855], ['20170822',8.855], ['20170823',8.882], ['20170824',8.682], ['20170825',8.827], ['20170828',8.900], ['20170829',8.955], ['20170830',8.927], ['20170831',8.864], ['20170901',9.082], ['20170904',9.182], ['20170905',9.155], ['20170906',9.200], ['20170907',9.036], ['20170908',9.055], ['20170911',9.064], ['20170912',9.036], ['20170913',8.991], ['20170914',9.091], ['20170915',9.009], ['20170918',9.055], ['20170919',8.955], ['20170920',8.936], ['20170921',8.891], ['20170922',8.818], ['20170925',8.818], ['20170926',8.827], ['20170927',8.818], ['20170928',8.791], ['20170929',8.827], ['20171009',8.955], ['20171010',9.155], ['20171011',9.245], ['20171012',9.264], ['20171013',9.209], ['20171016',9.073], ['20171017',9.091], ['20171018',8.945], ['20171019',8.864], ['20171020',8.991], ['20171023',8.973], ['20171024',9.127], ['20171025',9.718], ['20171026',10.382], ['20171027',10.191], ['20171030',10.218], ['20171031',10.218], ['20171101',10.545], ['20171102',10.255], ['20171103',10.209], ['20171106',10.509], ['20171107',10.500], ['20171108',10.773], ['20171109',10.736], ['20171110',10.445], ['20171113',10.036], ['20171114',9.973], ['20171115',9.991], ['20171116',10.000], ['20171117',9.664], ['20171120',9.673], ['20171121',9.664], ['20171122',9.727], ['20171123',9.427], ['20171124',9.282], ['20171127',9.691], ['20171128',9.764], ['20171129',9.855], ['20171130',10.055], ['20171201',10.009], ['20171204',10.091], ['20171205',9.673], ['20171206',10.309], ['20171207',10.173], ['20171208',10.400], ['20171211',10.336], ['20171212',10.082], ['20171213',10.127], ['20171214',10.182], ['20171215',10.327], ['20171218',10.300], ['20171219',10.636], ['20171220',10.682], ['20171221',10.945], ['20171222',10.809], ['20171225',11.091], ['20171226',11.000], ['20171227',11.364], ['20171228',11.800], ['20171229',12.273], ['20180102',12.064], ['20180103',11.909], ['20180104',11.909], ['20180105',11.673], ['20180108',11.836], ['20180109',12.282], ['20180110',11.545], ['20180111',12.345], ['20180112',11.655], ['20180115',11.409], ['20180116',11.673], ['20180117',11.664], ['20180118',11.709], ['20180119',12.000], ['20180122',11.927], ['20180123',11.955], ['20180124',11.973], ['20180125',11.900], ['20180126',11.636], ['20180129',11.709], ['20180130',11.891], ['20180131',13.073], ['20180201',12.927], ['20180202',12.827], ['20180205',12.818], ['20180206',11.418], ['20180207',10.718], ['20180208',10.591], ['20180209',10.045], ['20180212',10.836], ['20180213',10.845], ['20180214',10.891], ['20180222',11.455], ['20180223',11.645], ['20180226',11.664], ['20180227',11.873], ['20180228',12.491], ['20180301',12.682], ['20180302',12.545], ['20180305',12.900], ['20180306',12.673], ['20180307',12.318], ['20180308',12.545], ['20180309',13.273], ['20180312',13.227], ['20180313',13.045], ['20180314',13.027], ['20180315',13.218], ['20180316',13.100], ['20180319',12.864], ['20180320',12.855], ['20180321',12.545], ['20180322',12.409], ['20180323',11.827], ['20180326',12.473], ['20180327',12.491], ['20180328',12.364], ['20180329',12.364], ['20180330',12.500], ['20180402',12.118], ['20180403',12.518], ['20180404',12.445], ['20180409',12.418], ['20180410',12.336], ['20180411',12.373], ['20180412',12.209], ['20180413',12.773], ['20180416',13.091], ['20180417',12.455], ['20180418',12.691], ['20180419',12.736], ['20180420',11.891], ['20180423',11.727], ['20180424',11.855], ['20180425',11.882], ['20180426',11.409], ['20180427',11.200], ['20180502',11.227], ['20180503',11.645], ['20180504',11.418], ['20180507',11.627], ['20180508',11.791], ['20180509',12.327], ['20180510',12.364], ['20180511',12.327], ['20180514',12.445], ['20180515',12.573], ['20180516',13.045], ['20180517',12.773], ['20180518',13.164], ['20180521',13.045], ['20180522',13.291], ['20180523',13.182], ['20180524',12.827], ['20180525',12.973], ['20180528',13.655], ['20180529',14.118], ['20180530',14.936], ['20180531',15.273], ['20180601',14.618], ['20180604',14.864], ['20180605',14.864], ['20180606',14.673], ['20180607',14.227], ['20180608',14.236], ['20180611',13.745], ['20180612',14.300], ['20180613',13.536], ['20180614',13.455], ['20180615',13.345], ['20180619',12.409], ['20180620',13.209], ['20180621',12.409], ['20180622',12.809], ['20180625',13.273], ['20180626',12.818], ['20180627',12.191], ['20180628',12.227], ['20180629',12.800], ['20180702',12.518], ['20180703',12.145], ['20180704',11.982], ['20180705',11.318], ['20180706',11.382], ['20180709',11.682], ['20180710',11.682], ['20180711',11.609], ['20180712',12.045], ['20180713',12.282], ['20180716',12.118], ['20180717',12.427], ['20180718',12.173], ['20180719',12.200], ['20180720',12.209], ['20180723',12.464], ['20180724',12.736], ['20180725',12.482], ['20180726',12.473], ['20180727',12.355], ['20180730',11.691], ['20180731',11.900], ['20180801',11.545], ['20180802',11.291], ['20180803',10.609], ['20180806',10.536], ['20180807',10.518], ['20180808',9.864], ['20180809',9.718], ['20180810',9.964], ['20180813',10.127], ['20180814',10.055], ['20180815',9.736], ['20180816',9.591], ['20180817',9.545], ['20180820',9.264], ['20180821',9.500], ['20180822',9.318], ['20180823',9.409], ['20180824',9.282], ['20180827',9.618], ['20180828',9.727], ['20180829',9.464], ['20180830',9.627], ['20180831',9.300], ['20180903',9.118], ['20180904',9.373], ['20180905',9.273], ['20180906',9.091], ['20180907',9.227], ['20180910',8.909], ['20180911',8.845], ['20180912',8.864], ['20180913',8.927], ['20180914',8.882], ['20180917',8.609], ['20180918',8.727], ['20180919',8.882], ['20180920',8.773], ['20180921',9.291], ['20180925',9.255], ['20180926',9.218], ['20180927',9.000], ['20180928',9.127], ['20181008',8.473], ['20181009',8.473], ['20181010',8.409], ['20181011',7.818], ['20181012',7.682], ['20181015',7.509], ['20181016',7.355], ['20181017',7.418], ['20181018',7.164], ['20181019',7.318], ['20181022',7.791], ['20181023',7.136], ['20181024',7.145], ['20181025',7.064], ['20181026',7.100], ['20181029',7.000], ['20181030',7.182], ['20181031',7.191], ['20181101',7.218], ['20181102',7.609], ['20181105',7.536], ['20181106',7.455], ['20181107',7.655], ['20181108',7.509], ['20181109',7.545], ['20181112',7.736], ['20181113',7.991], ['20181114',8.073], ['20181115',8.273], ['20181116',8.409], ['20181119',8.245], ['20181120',8.027], ['20181121',7.936], ['20181122',7.982], ['20181123',7.455], ['20181126',7.355], ['20181127',7.373], ['20181128',7.555], ['20181129',7.555], ['20181130',7.409], ['20181203',7.709], ['20181204',7.736], ['20181205',7.573], ['20181206',7.473], ['20181207',7.464], ['20181210',7.318], ['20181211',7.255], ['20181212',7.336], ['20181213',7.518], ['20181214',7.345], ['20181217',7.273], ['20181218',7.145], ['20181219',7.018], ['20181220',7.118], ['20181221',7.118], ['20181224',7.173], ['20181225',7.145], ['20181226',7.264], ['20181227',7.018], ['20181228',7.000], ['20190102',6.909], ['20190103',6.755], ['20190104',7.027], ['20190107',7.100], ['20190108',7.200], ['20190109',7.191], ['20190110',7.091], ['20190111',7.164], ['20190114',7.118], ['20190115',7.273], ['20190116',7.336], ['20190117',7.182], ['20190118',7.345], ['20190121',7.436], ['20190122',7.336], ['20190123',7.355], ['20190124',7.355], ['20190125',7.482], ['20190128',7.482], ['20190129',7.364], ['20190130',7.227], ['20190131',7.245], ['20190201',7.473], ['20190211',7.700], ['20190212',7.782], ['20190213',7.964], ['20190214',7.864], ['20190215',7.873], ['20190218',8.064], ['20190219',7.918], ['20190220',7.945], ['20190221',7.882], ['20190222',7.918], ['20190225',8.327], ['20190226',8.336], ['20190227',8.391], ['20190228',8.418], ['20190301',8.436], ['20190304',8.527], ['20190305',9.136], ['20190306',9.155], ['20190307',9.464], ['20190308',9.045], ['20190311',9.245], ['20190312',9.136], ['20190313',8.809], ['20190314',8.782], ['20190315',8.845], ['20190318',9.227], ['20190319',9.636], ['20190320',9.891], ['20190321',9.727], ['20190322',9.636], ['20190325',9.636], ['20190326',9.491], ['20190327',10.027], ['20190328',10.073], ['20190329',10.500], ['20190401',10.864], ['20190402',10.691], ['20190403',10.691], ['20190404',10.455], ['20190408',10.391], ['20190409',10.464], ['20190410',10.464], ['20190411',10.027], ['20190412',10.009], ['20190415',9.864], ['20190416',10.009], ['20190417',9.973], ['20190418',9.991], ['20190419',9.627], ['20190422',9.336], ['20190423',9.373], ['20190424',9.464], ['20190425',9.309], ['20190426',9.136], ['20190429',9.364], ['20190430',9.500], ['20190506',8.682], ['20190507',8.891], ['20190508',8.955], ['20190509',8.818], ['20190510',9.109], ['20190513',9.200], ['20190514',9.482], ['20190515',9.573], ['20190516',9.500], ['20190517',9.282], ['20190520',8.982], ['20190521',9.109], ['20190522',9.664], ['20190523',9.118], ['20190524',9.045], ['20190527',9.209], ['20190528',9.309], ['20190529',9.300], ['20190530',9.360], ['20190531',9.390], ['20190603',9.430], ['20190604',9.310], ['20190605',9.420], ['20190606',9.380], ['20190610',9.230], ['20190611',9.440], ['20190612',9.290], ['20190613',9.040], ['20190614',8.860], ['20190617',8.910], ['20190618',8.950], ['20190619',8.980], ['20190620',9.140], ['20190621',9.310], ['20190624',9.400], ['20190625',9.300], ['20190626',9.360], ['20190627',9.380], ['20190628',9.410], ['20190701',9.530], ['20190702',9.610], ['20190703',9.560], ['20190704',9.500], ['20190705',9.480], ['20190708',9.240], ['20190709',9.290], ['20190710',9.250], ['20190711',9.250], ['20190712',9.290], ['20190715',9.330], ['20190716',9.190], ['20190717',9.170], ['20190718',9.000], ['20190719',9.180], ['20190722',8.980], ['20190723',9.040], ['20190724',9.040], ['20190725',9.120], ['20190726',9.110], ['20190729',9.110], ['20190730',9.130], ['20190731',9.090], ['20190801',9.110], ['20190802',9.030], ['20190805',9.070], ['20190806',8.990], ['20190807',8.840], ['20190808',8.750], ['20190809',8.560], ['20190812',8.650], ['20190813',8.600], ['20190814',8.680], ['20190815',8.590], ['20190816',8.600], ['20190819',8.810], ['20190820',8.850], ['20190821',8.860], ['20190822',8.810], ['20190823',8.690], ['20190826',8.520], ['20190827',8.600], ['20190828',8.670], ['20190829',8.760], ['20190830',8.700], ['20190902',8.800], ['20190903',8.880], ['20190904',8.910], ['20190905',8.940], ['20190906',8.940], ['20190909',8.920], ['20190910',8.860], ['20190911',8.830], ['20190912',8.790], ['20190916',8.810], ['20190917',8.680], ['20190918',8.700], ['20190919',8.700], ['20190920',8.720], ['20190923',8.620], ['20190924',8.630], ['20190925',8.560], ['20190926',8.530], ['20190927',8.520], ['20190930',8.540], ['20191008',8.550], ['20191009',8.580], ['20191010',8.650], ['20191011',8.710], ['20191014',8.690], ['20191015',8.650], ['20191016',8.700], ['20191017',8.630], ['20191018',8.520], ['20191021',8.520], ['20191022',8.530], ['20191023',8.650], ['20191024',8.580], ['20191025',8.610], ['20191028',8.630], ['20191029',8.550], ['20191030',8.570], ['20191031',8.530], ['20191101',8.540], ['20191104',8.590], ['20191105',8.680], ['20191106',8.700], ['20191107',8.690], ['20191108',8.670], ['20191111',8.500], ['20191112',8.560], ['20191113',8.460], ['20191114',8.490], ['20191115',8.460], ['20191118',8.450], ['20191119',8.440], ['20191120',8.310], ['20191121',8.250], ['20191122',8.150], ['20191125',8.190], ['20191126',8.260], ['20191127',8.240], ['20191128',8.140], ['20191129',8.120], ['20191202',8.130], ['20191203',8.130], ['20191204',8.090], ['20191205',8.090], ['20191206',8.090], ['20191209',8.050], ['20191210',8.290], ['20191211',8.400], ['20191212',8.350], ['20191213',8.380], ['20191216',8.440], ['20191217',8.410], ['20191218',8.300], ['20191219',8.400], ['20191220',8.380], ['20191223',8.380], ['20191224',8.430], ['20191225',8.570], ['20191226',8.550], ['20191227',8.540], ['20191230',8.610], ['20191231',8.580], ['20200102',8.680], ['20200103',8.680], ['20200106',8.590], ['20200107',8.640], ['20200108',8.540], ['20200109',8.580], ['20200110',8.700], ['20200113',8.700], ['20200114',8.680], ['20200115',8.600], ['20200116',8.580], ['20200117',8.600], ['20200120',8.630], ['20200121',8.420], ['20200122',8.370], ['20200123',8.270], ['20200203',7.390], ['20200204',7.470], ['20200205',7.620], ['20200206',7.680], ['20200207',7.750], ['20200210',7.750], ['20200211',7.840], ['20200212',7.760], ['20200213',7.650], ['20200214',7.660], ['20200217',7.940], ['20200218',7.950], ['20200219',7.920], ['20200220',8.040], ['20200221',8.020], ['20200224',8.100], ['20200225',8.070], ['20200226',8.310], ['20200227',8.340], ['20200228',8.210], ['20200302',8.480], ['20200303',8.480], ['20200304',8.720], ['20200305',8.760], ['20200306',8.930], ['20200309',8.600], ['20200310',8.550], ['20200311',8.400], ['20200312',8.190], ['20200313',8.010], ['20200316',7.710], ['20200317',7.700], ['20200318',7.660], ['20200319',7.870], ['20200320',7.900], ['20200323',7.830], ['20200324',8.010], ['20200325',8.110], ['20200326',8.010], ['20200327',8.260], ['20200330',8.360], ['20200331',8.410], ['20200401',8.190], ['20200402',8.140], ['20200403',8.200], ['20200407',8.370], ['20200408',8.360], ['20200409',8.430], ['20200410',8.310], ['20200413',8.370], ['20200414',8.410], ['20200415',8.320], ['20200416',8.330], ['20200417',8.270], ['20200420',8.590], ['20200421',8.510], ['20200422',8.520], ['20200423',8.430], ['20200424',8.300], ['20200427',8.310], ['20200428',8.340], ['20200429',8.460], ['20200430',8.550], ['20200506',8.540], ['20200507',8.600], ['20200508',8.670], ['20200511',8.550], ['20200512',8.580], ['20200513',9.300], ['20200514',9.590], ['20200515',9.430], ['20200518',9.140], ['20200519',9.260], ['20200520',9.380], ['20200521',9.520], ['20200522',9.220], ['20200525',9.120], ['20200526',9.190], ['20200527',9.470], ['20200528',9.440], ['20200529',9.400], ['20200601',9.620], ['20200602',9.800], ['20200603',9.770], ['20200604',9.910], ['20200605',9.860], ['20200608',9.660], ['20200609',9.830], ['20200610',9.950], ['20200611',9.700], ['20200612',9.560], ['20200615',9.400], ['20200616',9.550], ['20200617',9.550], ['20200618',9.410], ['20200619',9.360], ['20200622',9.250], ['20200623',9.320], ['20200624',9.270], ['20200629',9.050], ['20200630',9.240], ['20200701',9.290], ['20200702',9.400], ['20200703',9.770], ['20200706',10.120], ['20200707',10.080], ['20200708',10.150], ['20200709',10.540], ['20200710',10.570], ['20200713',10.750], ['20200714',11.050], ['20200715',10.960], ['20200716',10.550], ['20200717',10.650], ['20200720',11.000], ['20200721',10.990], ['20200722',11.100], ['20200723',11.010], ['20200724',10.600], ['20200727',10.580], ['20200728',10.640], ['20200729',10.830], ['20200730',10.870], ['20200731',10.890], ['20200803',11.030], ['20200804',10.980], ['20200805',10.920], ['20200806',10.720], ['20200807',10.530], ['20200810',10.680], ['20200811',10.910], ['20200812',10.720], ['20200813',11.100], ['20200814',11.020], ['20200817',11.500], ['20200818',11.800], ['20200819',11.760], ['20200820',11.720], ['20200821',11.720], ['20200824',11.630], ['20200825',11.740], ['20200826',11.560], ['20200827',11.770], ['20200828',11.880], ['20200831',12.700], ['20200901',12.450], ['20200902',12.310], ['20200903',12.430], ['20200904',12.400], ['20200907',11.980], ['20200908',11.900], ['20200909',11.550], ['20200910',11.350], ['20200911',11.420], ['20200914',11.360], ['20200915',11.440], ['20200916',11.210], ['20200917',11.430], ['20200918',11.410], ['20200921',11.260], ['20200922',11.120], ['20200923',11.110], ['20200924',10.830], ['20200925',10.820], ['20200928',10.690], ['20200929',10.820], ['20200930',10.780]]; var source='wstock.net';
SammyEnigma/im-desktop
libomicron/src/omicron_impl.cpp
<gh_stars>10-100 #include "stdafx.h" #ifdef OMICRON_USE_LIBCURL #include <curl.h> #include "curl_tools/curl_ssl_callbacks.h" #endif #include <omicron/omicron_conf.h> #include <omicron/omicron.h> #include "omicron_impl.h" #ifdef OMICRON_USE_LIBCURL static size_t write_data(void *ptr, size_t size, size_t nitems, void *stream) { std::string data((const char*)ptr, size * nitems); *((std::stringstream*)stream) << data << std::endl; return size * nitems; } static bool internal_download_json(const omicronlib::omicron_proxy_settings& _proxy_settings, const std::string& _url, std::string& _json_data, long& _response_code) { CURL* curl = curl_easy_init(); curl_easy_setopt(curl, CURLOPT_URL, _url.c_str()); curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 1L); curl_easy_setopt(curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_2TLS); curl_easy_setopt(curl, CURLOPT_PIPEWAIT, long(1)); curl_easy_setopt(curl, CURLOPT_SSL_CTX_FUNCTION, omicronlib::ssl_ctx_callback); curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 2L); curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L); curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1L); curl_easy_setopt(curl, CURLOPT_ACCEPT_ENCODING, "deflate"); std::stringstream out; curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data); curl_easy_setopt(curl, CURLOPT_WRITEDATA, &out); if (_proxy_settings.use_proxy_) { curl_easy_setopt(curl, CURLOPT_PROXY, _proxy_settings.server_.c_str()); curl_easy_setopt(curl, CURLOPT_PROXYTYPE, (long)_proxy_settings.type_); curl_easy_setopt(curl, CURLOPT_PROXYPORT, (long)_proxy_settings.port_); if (_proxy_settings.need_auth_) { std::string auth_params = _proxy_settings.login_ + ':' + _proxy_settings.password_; curl_easy_setopt(curl, CURLOPT_PROXYUSERPWD, auth_params.c_str()); } } if (omicronlib::build::is_debug()) std::cout << "GET request: " << _url << "\n\n"; CURLcode res = curl_easy_perform(curl); long code; curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &code); _response_code = code; curl_easy_cleanup(curl); if (res != CURLE_OK) return false; _json_data = out.str(); if (omicronlib::build::is_debug()) std::cout << "GET response (" << _response_code << "): " << _json_data << "\n\n"; return true; } #endif namespace omicronlib { omicron_impl& omicron_impl::instance() { static std::shared_ptr<omicron_impl> instance; if (!instance) instance.reset(new omicron_impl()); return *instance; } omicron_code omicron_impl::init(const omicron_config& _conf, const std::wstring& _file_name) { config_ = make_unique<omicron_config>(_conf); file_name_ = _file_name; logger_func_ = config_->get_logger(); callback_updater_func_ = config_->get_callback_updater(); #ifdef OMICRON_USE_LIBCURL if (config_->get_json_downloader() == nullptr) config_->set_json_downloader(internal_download_json); #endif if (load()) callback_updater(); return update_data(); } bool omicron_impl::start_auto_updater() { std::weak_ptr<omicron_impl> wr_this = shared_from_this(); constexpr auto tick_timeout = internal_tick_timeout(); schedule_thread_ = make_unique<std::thread>([wr_this, tick_timeout]() { bool fl_once = true; for (;;) { auto ptr_this = wr_this.lock(); if (!ptr_this) return; if (fl_once) { tools::set_this_thread_name("omicron_scheduler"); ptr_this->write_to_log("started update service"); fl_once = false; } std::unique_lock<std::mutex> lock(ptr_this->schedule_mutex_); const auto wait_res = ptr_this->schedule_condition_.wait_for(lock, tick_timeout); const auto current_time = std::chrono::system_clock::now(); const auto update_interval = ptr_this->config_->get_update_interval(); if (ptr_this->is_schedule_stop_) return; if (wait_res == std::cv_status::timeout) if (current_time - ptr_this->last_update_time_ >= update_interval) ptr_this->update_data(); } }); if (!schedule_thread_->joinable()) return false; return true; } omicron_code omicron_impl::update_data() { if (is_updating_) return OMICRON_ALREADY_UPDATING; is_updating_ = true; last_update_status_ = OMICRON_IS_UPDATING; last_update_time_ = std::chrono::system_clock::now(); std::weak_ptr<omicron_impl> wr_this = shared_from_this(); std::thread update_thread([wr_this]() { auto ptr_this = wr_this.lock(); if (!ptr_this) return; tools::set_this_thread_name("omicron_update"); ptr_this->last_update_status_ = ptr_this->get_omicron_data(); ptr_this->last_update_time_ = std::chrono::system_clock::now(); ptr_this->is_updating_ = false; }); update_thread.detach(); return OMICRON_OK; } void omicron_impl::cleanup() { is_schedule_stop_ = true; is_json_data_init_ = false; schedule_condition_.notify_all(); if (schedule_thread_) { if (schedule_thread_->joinable()) { schedule_thread_->join(); write_to_log("stopped update service"); } } schedule_thread_.reset(); config_.reset(); json_data_.reset(); last_update_status_ = OMICRON_NOT_INITIALIZED; } time_t omicron_impl::get_last_update_time() const { return std::chrono::system_clock::to_time_t(last_update_time_); } omicron_code omicron_impl::get_last_update_status() const { return last_update_status_; } void omicron_impl::add_fingerprint(std::string _name, std::string _value) { if (config_) config_->add_fingerprint(std::move(_name), std::move(_value)); } bool omicron_impl::bool_value(const char* _key_name, bool _default_value) const { if (is_json_data_init_) { const auto json_data = get_json_data(); const auto it = json_data->FindMember(_key_name); if (it != json_data->MemberEnd() && it->value.IsBool()) return it->value.GetBool(); } return _default_value; } int omicron_impl::int_value(const char* _key_name, int _default_value) const { if (is_json_data_init_) { const auto json_data = get_json_data(); const auto it = json_data->FindMember(_key_name); if (it != json_data->MemberEnd() && it->value.IsInt()) return it->value.GetInt(); } return _default_value; } unsigned int omicron_impl::uint_value(const char* _key_name, unsigned int _default_value) const { if (is_json_data_init_) { const auto json_data = get_json_data(); const auto it = json_data->FindMember(_key_name); if (it != json_data->MemberEnd() && it->value.IsInt()) return it->value.GetUint(); } return _default_value; } int64_t omicron_impl::int64_value(const char* _key_name, int64_t _default_value) const { if (is_json_data_init_) { const auto json_data = get_json_data(); const auto it = json_data->FindMember(_key_name); if (it != json_data->MemberEnd() && it->value.IsInt64()) return it->value.GetInt64(); } return _default_value; } uint64_t omicron_impl::uint64_value(const char* _key_name, uint64_t _default_value) const { if (is_json_data_init_) { const auto json_data = get_json_data(); const auto it = json_data->FindMember(_key_name); if (it != json_data->MemberEnd() && it->value.IsInt64()) return it->value.GetUint64(); } return _default_value; } double omicron_impl::double_value(const char* _key_name, double _default_value) const { if (is_json_data_init_) { const auto json_data = get_json_data(); const auto it = json_data->FindMember(_key_name); if (it != json_data->MemberEnd() && it->value.IsDouble()) return it->value.GetDouble(); } return _default_value; } std::string omicron_impl::string_value(const char* _key_name, std::string _default_value) const { if (is_json_data_init_) { const auto json_data = get_json_data(); const auto it = json_data->FindMember(_key_name); if (it != json_data->MemberEnd() && it->value.IsString()) return std::string(it->value.GetString(), it->value.GetStringLength()); } return _default_value; } json_string omicron_impl::json_value(const char* _key_name, json_string _default_value) const { if (is_json_data_init_) { const auto json_data = get_json_data(); const auto it = json_data->FindMember(_key_name); if (it != json_data->MemberEnd() && (it->value.IsObject() || it->value.IsArray())) { rapidjson::StringBuffer buffer; rapidjson::Writer<rapidjson::StringBuffer> writer(buffer); it->value.Accept(writer); return json_string(buffer.GetString(), buffer.GetSize()); } } return _default_value; } omicron_impl::omicron_impl() : is_json_data_init_(false) , json_data_(std::make_shared<rapidjson::Document>(rapidjson::kObjectType)) , is_schedule_stop_(false) , is_updating_(false) , last_update_time_(std::chrono::system_clock::now()) , last_update_status_(OMICRON_NOT_INITIALIZED) , logger_func_(nullptr) , callback_updater_func_(nullptr) { } bool omicron_impl::load() { std::string json_str; if (const auto load_helper = config_->get_load_helper()) { json_str = load_helper(file_name_); } else { if (!tools::is_exist(file_name_)) return false; auto ifile = tools::open_file_for_read(file_name_); if (!ifile.is_open()) return false; std::stringstream data; data << ifile.rdbuf(); ifile.close(); json_str = data.str(); } if (!parse_json(json_str)) return false; std::string log; log += "loaded data from the cache:\n"; log += json_str; write_to_log(log); return true; } bool omicron_impl::save(const std::string& _data) const { if (const auto save_helper = config_->get_save_helper()) return save_helper(file_name_, _data); if (!tools::create_parent_directories_for_file(file_name_)) return false; auto temp_file_name = file_name_ + L".tmp"; auto ofile = tools::open_file_for_write(temp_file_name, std::ofstream::trunc); if (!ofile.is_open()) return false; if (!_data.empty()) ofile << _data; ofile.flush(); ofile.close(); tools::rename_file(temp_file_name, file_name_); return true; } std::shared_ptr<const rapidjson::Document> omicron_impl::get_json_data() const { std::lock_guard<spin_lock> lock(data_spin_lock_); return json_data_; } std::string omicron_impl::get_json_data_string() const { if (is_json_data_init_) { const auto json_data = get_json_data(); rapidjson::StringBuffer buffer; rapidjson::Writer<rapidjson::StringBuffer> writer(buffer); json_data->Accept(writer); return std::string(buffer.GetString(), buffer.GetSize()); } return "{}"; } omicron_code omicron_impl::get_omicron_data(bool _is_save) { if (!config_) return OMICRON_NOT_INITIALIZED; auto downloader = config_->get_json_downloader(); if (downloader == nullptr) return OMICRON_DOWNLOAD_NOT_IMPLEMENTED; std::string data; long code = -1; auto request_str = config_->generate_request_string(); write_to_log("send request:\n" + request_str); auto download_res = downloader(config_->get_proxy_settings(), request_str, data, code); if (!download_res || (code != 200 && code != 304)) { write_to_log("request failed with HTTP status " + std::to_string(code)); return OMICRON_DOWNLOAD_FAILED; } if (code == 200) { if (!parse_json(data)) { write_to_log("get wrong data:\n" + data); return OMICRON_WRONG_JSON_DATA; } write_to_log("get new data:\n" + data); if (_is_save) { std::weak_ptr<omicron_impl> wr_this = shared_from_this(); std::thread save_thread([wr_this, data = std::move(data)]() { auto ptr_this = wr_this.lock(); if (!ptr_this) return; tools::set_this_thread_name("omicron_save"); if (!ptr_this->save(data)) ptr_this->write_to_log("failure to write data to disk"); }); save_thread.detach(); } callback_updater(); } else { write_to_log("data is not changed"); } return OMICRON_OK; } bool omicron_impl::parse_json(const std::string& _json) { if (_json.empty()) return false; rapidjson::Document doc; const auto& parse_result = doc.Parse(_json.c_str()); if (parse_result.HasParseError()) return false; auto new_config = make_unique<omicron_config>(*config_); const auto it_version = doc.FindMember("config_v"); if (it_version == doc.MemberEnd() || !it_version->value.IsInt()) return false; new_config->set_config_v(it_version->value.GetInt()); const auto it_condition = doc.FindMember("cond_s"); if (it_condition == doc.MemberEnd() || !it_condition->value.IsString()) return false; new_config->set_cond_s(std::string(it_condition->value.GetString(), it_condition->value.GetStringLength())); new_config->reset_segments(); const auto it_segments = doc.FindMember("segments"); if (it_segments != doc.MemberEnd() && it_segments->value.IsObject()) { for (auto it = it_segments->value.MemberBegin(), end = it_segments->value.MemberEnd(); it != end; ++it) { if (it->name.IsString() && it->value.IsString()) new_config->add_segment(std::string(it->name.GetString(), it->name.GetStringLength()), std::string(it->value.GetString(), it->value.GetStringLength())); } } const auto it_config = doc.FindMember("config"); if (it_config == doc.MemberEnd() || !it_config->value.IsObject()) return false; auto new_json_data = std::make_shared<rapidjson::Document>(rapidjson::kObjectType); new_json_data->CopyFrom(it_config->value, new_json_data->GetAllocator()); config_.swap(new_config); { std::lock_guard<spin_lock> lock(data_spin_lock_); json_data_.swap(new_json_data); } if (!is_json_data_init_) is_json_data_init_ = true; return true; } void omicron_impl::write_to_log(const std::string& _text) const { if (logger_func_) { std::string log; log += "omicron: "; log += _text; log += "\r\n"; logger_func_(log); } } void omicron_impl::callback_updater() { if (callback_updater_func_) callback_updater_func_(get_json_data_string()); } }
iplo/Chain
content/child/thread_safe_sender.h
// Copyright (c) 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CONTENT_CHILD_THREAD_SAFE_SENDER_H_ #define CONTENT_CHILD_THREAD_SAFE_SENDER_H_ #include "base/gtest_prod_util.h" #include "base/memory/ref_counted.h" #include "content/common/content_export.h" #include "ipc/ipc_sender.h" namespace base { class MessageLoopProxy; } namespace IPC { class SyncMessageFilter; } namespace content { class ChildThread; // The class of Sender returned by ChildThread::thread_safe_sender(). class CONTENT_EXPORT ThreadSafeSender : public IPC::Sender, public base::RefCountedThreadSafe<ThreadSafeSender> { public: virtual bool Send(IPC::Message* msg) OVERRIDE; private: friend class ChildThread; // for construction friend class IndexedDBDispatcherTest; friend class WebIDBCursorImplTest; friend class base::RefCountedThreadSafe<ThreadSafeSender>; ThreadSafeSender(base::MessageLoopProxy* main_loop, IPC::SyncMessageFilter* sync_filter); virtual ~ThreadSafeSender(); scoped_refptr<base::MessageLoopProxy> main_loop_; scoped_refptr<IPC::SyncMessageFilter> sync_filter_; DISALLOW_COPY_AND_ASSIGN(ThreadSafeSender); }; } // namespace content #endif // CONTENT_CHILD_THREAD_SAFE_SENDER_H_
FoseFx/SponsorBlockServer
test/cases/segmentShift.js
const request = require('request'); const utils = require('../utils.js'); const { db } = require('../../src/databases/databases.js'); const getHash = require('../../src/utils/getHash.js'); function dbSponsorTimesAdd(db, videoID, startTime, endTime, UUID, category) { const votes = 0, userID = 0, timeSubmitted = 0, views = 0, shadowHidden = 0, hashedVideoID = `hash_${UUID}`; db.exec(`INSERT INTO sponsorTimes (videoID, startTime, endTime, votes, UUID, userID, timeSubmitted, views, category, shadowHidden, hashedVideoID) VALUES ('${videoID}', ${startTime}, ${endTime}, ${votes}, '${UUID}', '${userID}', ${timeSubmitted}, ${views}, '${category}', ${shadowHidden}, '${hashedVideoID}') `); } function dbSponsorTimesSetByUUID(db, UUID, startTime, endTime) { db.prepare('run', `UPDATE sponsorTimes SET startTime = ?, endTime = ? WHERE UUID = ?`, [startTime, endTime, UUID]); } function dbSponsorTimesCompareExpect(db, expect) { for (let i=0, len=expect.length; i<len; i++) { const expectSeg = expect[i]; let seg = db.prepare('get', "SELECT startTime, endTime FROM sponsorTimes WHERE UUID = ?", [expectSeg.UUID]); if ('removed' in expect) { if (expect.removed === true && seg.votes === -2) { return; } else { return `${expectSeg.UUID} doesnt got removed`; } } if (seg.startTime !== expectSeg.startTime) { return `${expectSeg.UUID} startTime is incorrect. seg.startTime is ${seg.startTime} expected ${expectSeg.startTime}`; } if (seg.endTime !== expectSeg.endTime) { return `${expectSeg.UUID} endTime is incorrect. seg.endTime is ${seg.endTime} expected ${expectSeg.endTime}`; } } return; } describe('segmentShift', function() { const privateVipUserID = 'VIPUser-segmentShift'; const vipUserID = getHash(privateVipUserID); const baseURL = utils.getbaseURL(); before(function(done) { // startTime and endTime get set in beforeEach for consistency dbSponsorTimesAdd(db, 'vsegshift01', 0, 0, 'vsegshifttest01uuid01', 'intro'); dbSponsorTimesAdd(db, 'vsegshift01', 0, 0, 'vsegshifttest01uuid02', 'sponsor'); dbSponsorTimesAdd(db, 'vsegshift01', 0, 0, 'vsegshifttest01uuid03', 'interaction'); dbSponsorTimesAdd(db, 'vsegshift01', 0, 0, 'vsegshifttest01uuid04', 'outro'); db.exec(`INSERT INTO vipUsers (userID) VALUES ('${vipUserID}')`); done(); }); beforeEach(function(done) { // resetting startTime and endTime to reuse them dbSponsorTimesSetByUUID(db, 'vsegshifttest01uuid01', 0, 10); dbSponsorTimesSetByUUID(db, 'vsegshifttest01uuid02', 60, 90); dbSponsorTimesSetByUUID(db, 'vsegshifttest01uuid03', 40, 45); dbSponsorTimesSetByUUID(db, 'vsegshifttest01uuid04', 120, 140); done(); }); it('Reject none VIP user', function(done) { request.post(`${baseURL}/api/segmentShift`, { json: { videoID: 'vsegshift01', userID: 'segshift_randomuser001', startTime: 20, endTime: 30, } }, (err, res, body) => { if (err) return done(err); return done(res.statusCode === 403 ? undefined : res.statusCode); }); }); it('Shift is outside segments', function(done) { request.post(`${baseURL}/api/segmentShift`, { json: { videoID: 'vsegshift01', userID: privateVipUserID, startTime: 20, endTime: 30, } }, (err, res, body) => { if (err) return done(err); if (res.statusCode !== 200) return done(`Status code was ${res.statusCode}`); const expect = [ { UUID: 'vsegshifttest01uuid01', startTime: 0, endTime: 10, }, { UUID: 'vsegshifttest01uuid02', startTime: 50, endTime: 80, }, { UUID: 'vsegshifttest01uuid03', startTime: 30, endTime: 35, }, { UUID: 'vsegshifttest01uuid04', startTime: 110, endTime: 130, }, ]; done(dbSponsorTimesCompareExpect(db, expect)); }); }); it('Shift is inside segment', function(done) { request.post(`${baseURL}/api/segmentShift`, { json: { videoID: 'vsegshift01', userID: privateVipUserID, startTime: 65, endTime: 75, } }, (err, res, body) => { if (err) return done(err); if (res.statusCode !== 200) return done(`Status code was ${res.statusCode}`); const expect = [ { UUID: 'vsegshifttest01uuid01', startTime: 0, endTime: 10, }, { UUID: 'vsegshifttest01uuid02', startTime: 60, endTime: 80, }, { UUID: 'vsegshifttest01uuid03', startTime: 40, endTime: 45, }, { UUID: 'vsegshifttest01uuid04', startTime: 110, endTime: 130, }, ]; done(dbSponsorTimesCompareExpect(db, expect)); }); }); it('Shift is overlaping startTime of segment', function(done) { request.post(`${baseURL}/api/segmentShift`, { json: { videoID: 'vsegshift01', userID: privateVipUserID, startTime: 32, endTime: 42, } }, (err, res, body) => { if (err) return done(err); if (res.statusCode !== 200) return done(`Status code was ${res.statusCode}`); const expect = [ { UUID: 'vsegshifttest01uuid01', startTime: 0, endTime: 10, }, { UUID: 'vsegshifttest01uuid02', startTime: 50, endTime: 80, }, { UUID: 'vsegshifttest01uuid03', startTime: 32, endTime: 35, }, { UUID: 'vsegshifttest01uuid04', startTime: 110, endTime: 130, }, ]; done(dbSponsorTimesCompareExpect(db, expect)); }); }); it('Shift is overlaping endTime of segment', function(done) { request.post(`${baseURL}/api/segmentShift`, { json: { videoID: 'vsegshift01', userID: privateVipUserID, startTime: 85, endTime: 95, } }, (err, res, body) => { if (err) return done(err); if (res.statusCode !== 200) return done(`Status code was ${res.statusCode}`); const expect = [ { UUID: 'vsegshifttest01uuid01', startTime: 0, endTime: 10, }, { UUID: 'vsegshifttest01uuid02', startTime: 60, endTime: 85, }, { UUID: 'vsegshifttest01uuid03', startTime: 40, endTime: 45, }, { UUID: 'vsegshifttest01uuid04', startTime: 110, endTime: 130, }, ]; done(dbSponsorTimesCompareExpect(db, expect)); }); }); it('Shift is overlaping segment', function(done) { request.post(`${baseURL}/api/segmentShift`, { json: { videoID: 'vsegshift01', userID: privateVipUserID, startTime: 35, endTime: 55, } }, (err, res, body) => { if (err) return done(err); if (res.statusCode !== 200) return done(`Status code was ${res.statusCode}`); const expect = [ { UUID: 'vsegshifttest01uuid01', startTime: 0, endTime: 10, }, { UUID: 'vsegshifttest01uuid02', startTime: 40, endTime: 70, }, { UUID: 'vsegshifttest01uuid03', startTime: 40, endTime: 45, removed: true, }, { UUID: 'vsegshifttest01uuid04', startTime: 100, endTime: 120, }, ]; done(dbSponsorTimesCompareExpect(db, expect)); }); }); });
CLIMB-COVID/majora2
tatl/management/commands/userapprove.py
<filename>tatl/management/commands/userapprove.py import sys import json from django.core.management.base import BaseCommand, CommandError from django.utils import timezone from majora2.models import Profile from tatl import models as tmodels from django.contrib.auth.models import User from django.http.request import HttpRequest from django.contrib.auth.forms import PasswordResetForm from django.conf import settings class Command(BaseCommand): help = "Forcibly approve a new user" def add_arguments(self, parser): parser.add_argument('username', help="Username of user to be approved") def handle(self, *args, **options): su = User.objects.get(is_superuser=True) try: profile = Profile.objects.get(user__username=options["username"]) except Profile.DoesNotExist: sys.stderr.write("No user with that username\n") sys.exit(1) user = profile.user if user.is_active and profile.is_site_approved: sys.stderr.write("User already approved\n") sys.exit(0) # Approve profile.is_site_approved = True # force local site approval profile.save() user.is_active = True # sysadmin override user.save() sys.stderr.write("%s approved!\n" % user.username) # Flex perm treq = tmodels.TatlPermFlex( user = su, substitute_user = None, used_permission = "tatl.management.commands.userapprove", timestamp = timezone.now(), content_object = user, extra_context = json.dumps({ }), ) treq.save() # Flex verb tmodels.TatlVerb(request=None, verb="UPDATE", content_object=user, extra_context = json.dumps({ }), ).save()
irisengine/iris
include/iris/networking/server_socket_data.h
<reponame>irisengine/iris<filename>include/iris/networking/server_socket_data.h //////////////////////////////////////////////////////////////////////////////// // Distributed under the Boost Software License, Version 1.0. // // (See accompanying file LICENSE or copy at // // https://www.boost.org/LICENSE_1_0.txt) // //////////////////////////////////////////////////////////////////////////////// #pragma once #include "core/data_buffer.h" #include "networking/socket.h" namespace iris { /** * Struct for data returned from a ServerSocket read. */ struct ServerSocketData { /** A Socket which can be used to communicate with the client. */ Socket *client; /** The data read. */ DataBuffer data; /** Whether this is a new connection or not. */ bool new_connection; }; }
chandlerprall/kibana
src/dev/build/tasks/os_packages/index.js
<filename>src/dev/build/tasks/os_packages/index.js export { CreateRpmPackageTask, CreateDebPackageTask } from './create_os_package_tasks';
PearsonEducation/apigee-ios-sdk
source/Classes/AppServices/ApigeeActivity.h
#import <Foundation/Foundation.h> #import "ApigeeEntity.h" @interface ApigeeActivity : ApigeeEntity + (BOOL)isSameType:(NSString*)type; - (id)initWithDataClient:(ApigeeDataClient*)dataClient; // In order for an activity to be valid, you must call setBasics and one of the setActor functions. // In all cases, the return value will be YES if the function succeeded and NO if there // was a problem with the set. A response of NO will usually mean you sent nil for a required field. // these are the basics of the activity. // verb: the action being taken // category: The type of activity it is // content: The content of this activity. The format is defined by the category // title: The title of this category. -(BOOL) setBasics: (NSString *)verb category:(NSString *)category content:(NSString *)content title:(NSString *)title; // actorUserName: The username of the entity doing this activity // actorDisplayName: The visible name of the entity doing this activity // actorUUID: The UUID of the entity doing this activity -(BOOL) setActorInfo: (NSString *)actorUserName actorDisplayName:(NSString *)actorDisplayName actorUUID:(NSString *)actorUUID; // actorUserName: The username of the entity doing this activity // actorDisplayName: The visible name of the entity doing this activity // actorUUID: The UUID of the entity doing this activity -(BOOL) setActorInfo: (NSString *)actorUserName actorDisplayName:(NSString *)actorDisplayName actorEmail:(NSString *)actorEmail; // Associating an object with the Activity is optional. You don't have to supply an object at all. // objectType: the type of the object associated with this activity // displayName: The visible name of the object associated with this activity // entityType: the entity type of this object within UserGrid. The actual type that it is stored under // entityUUID: The uuid of the object associated with this activity -(BOOL)setObjectInfo: (NSString *)objectType displayName:(NSString *)displayName entityType:(NSString *)entityType entityUUID:(NSString *)entityUUID; // similar to the function above, but it takes an arbitrary object content (which can be new and unique) instead of an already-defined object -(BOOL)setObjectInfo: (NSString *)objectType displayName:(NSString *)displayName objectContent:(NSString *)objectContent; // similar to the other two functions, but simply has the type and displayName. In this case, the // "content" value supplied in setBasics will be used as the object content. -(BOOL)setObjectInfo: (NSString *)objectType displayName:(NSString *)displayName; // returns YES if this is properly set up. NO if it has not been properly set up -(BOOL)isValid; // turn this object in to an NSDictionary. Used internally by ApigeeClient -(NSDictionary *)toNSDictionary; -(void)setProperties:(NSDictionary*)dictProperties; @end
pauldaustin/gba_revolsys
revolsys-web/src/main/java/com/revolsys/ui/web/security/oauth/MicrosoftOAuthHandler.java
package com.revolsys.ui.web.security.oauth; import java.io.IOException; import java.security.Principal; import java.util.function.Function; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.apache.http.client.methods.RequestBuilder; import org.jeometry.common.logging.Logs; import com.revolsys.net.oauth.OpenIdBearerToken; import com.revolsys.net.oauth.OpenIdConnectClient; import com.revolsys.ui.web.utils.HttpServletUtils; public class MicrosoftOAuthHandler { private final OpenIdConnectClient oauthClient; private final String scope = "openid offline_access profile email"; private final String prompt = "select_account"; private final Function<OpenIdBearerToken, Principal> principalFactory; public MicrosoftOAuthHandler(final String clientId, final String clientSecret, final Function<OpenIdBearerToken, Principal> principalFactory) { this.oauthClient = OpenIdConnectClient// .microsoftCommon() .setClientId(clientId) .setClientSecret(clientSecret); this.principalFactory = principalFactory; } protected RequestBuilder authorizationUrlBuilder(final HttpServletRequest request, final OAuthLoginState loginState) { final String redirectUri = getOAuthRedirectUri(request); final String state = loginState.getStateParam(); final RequestBuilder urlBuilder = this.oauthClient.authorizationUrlBuilder(this.scope, redirectUri, state, loginState.getNonce(), this.prompt); return urlBuilder; } public String authorize(final HttpServletRequest request, final OAuthLoginState loginState) throws IOException { final RequestBuilder urlBuilder = authorizationUrlBuilder(request, loginState); return urlBuilder.build().getURI().toASCIIString(); } public String callback(final OAuthLoginState loginState, final HttpServletRequest request, final HttpServletResponse response) throws IOException { final HttpSession session = request.getSession(); try { final String code = request.getParameter("code"); final String redirectUri = getOAuthRedirectUri(request); final OpenIdBearerToken token = this.oauthClient.tokenAuthorizationCode(code, redirectUri, this.scope); final String tokenNonce = token.getStringClaim("nonce"); if (!loginState.equalsNonce(tokenNonce)) { throw new IllegalStateException( "Failed to validate data received from Authorization service - could not validate nonce"); } session.setAttribute("bearerToken", token); final Principal principal = this.principalFactory.apply(token); session.setAttribute("principal", principal); } catch (final IllegalStateException e) { } catch (final Exception e) { Logs.error(this, "Login Error", e); } return loginState.getOriginalRequestUri(); } public String getOAuthRedirectUri(final HttpServletRequest request) { final String serverUrl = HttpServletUtils.getServerUrl(request); return serverUrl + "/auth/openid/return"; } public String getState(final HttpServletRequest request) { final String requestURI = request.getRequestURI(); if (requestURI == null || requestURI.length() == 0) { return "/"; } else { return requestURI; } } public boolean isValid(final HttpServletRequest request, final String requestUri) throws IOException { final HttpSession session = request.getSession(); try { OpenIdBearerToken token = (OpenIdBearerToken)session.getAttribute("bearerToken"); if (token != null) { if (token.isExpired()) { token = token.getValid(); if (token != null) { session.setAttribute("bearerToken", token); return true; } } else { return true; } } } catch (final Exception e) { Logs.error(this, requestUri, e); } return false; } protected OpenIdConnectClient newClient(final String clientId) { throw new UnsupportedOperationException(); } public void redirectToPath(final HttpServletRequest request, final HttpServletResponse response, final String path) throws IOException { final String serverUrl = HttpServletUtils.getServerUrl(request); String successRedirectUrl; if (path == null || path.length() == 0) { successRedirectUrl = serverUrl; } else { successRedirectUrl = serverUrl + path; } response.sendRedirect(successRedirectUrl); } public void signOff(final HttpServletRequest request, final HttpServletResponse response) throws IOException { request.getSession().invalidate(); final String serverUrl = HttpServletUtils.getServerUrl(request); final String redirectUrl = this.oauthClient.endSessionUrl(serverUrl).toASCIIString(); response.sendRedirect(redirectUrl); } }
kounoike/cpp-mp4
src/box_types.cpp
<filename>src/box_types.cpp #include "shiguredo/mp4/box_types.hpp" #include <string> #include <boost/functional/factory.hpp> #include "shiguredo/mp4/box/boxes.hpp" #include "shiguredo/mp4/box_map.hpp" #include "shiguredo/mp4/box_type.hpp" namespace shiguredo::mp4 { void register_box_map(BoxMap* boxMap) { boxMap->addBoxDef(boost::factory<box::Btrt*>(), BoxType("btrt"), {}); boxMap->addBoxDef(boost::factory<box::Co64*>(), BoxType("co64"), {0}); boxMap->addBoxDef(boost::factory<box::Colr*>(), BoxType("colr"), {}); boxMap->addBoxDef(boost::factory<box::Ctts*>(), BoxType("ctts"), {0, 1}); boxMap->addBoxDef(boost::factory<box::Data*>(), BoxType("data"), {}); boxMap->addBoxDef(boost::factory<box::Dinf*>(), BoxType("dinf"), {}); boxMap->addBoxDef(boost::factory<box::DOps*>(), BoxType("dOps"), {}); boxMap->addBoxDef(boost::factory<box::Dref*>(), BoxType("dref"), {0}); boxMap->addBoxDef(boost::factory<box::Edts*>(), BoxType("edts"), {}); boxMap->addBoxDef(boost::factory<box::Elst*>(), BoxType("elst"), {0, 1}); boxMap->addBoxDef(boost::factory<box::Emsg*>(), BoxType("emsg"), {0, 1}); boxMap->addBoxDef(boost::factory<box::Esds*>(), BoxType("esds"), {0}); boxMap->addBoxDef(boost::factory<box::Free*>(), BoxType("free"), {}); boxMap->addBoxDef(boost::factory<box::Ftyp*>(), BoxType("ftyp"), {}); boxMap->addBoxDef(boost::factory<box::Hdlr*>(), BoxType("hdlr"), {0}); boxMap->addBoxDef(boost::factory<box::Ilst*>(), BoxType("ilst"), {}); boxMap->addBoxDef(boost::factory<box::Iods*>(), BoxType("iods"), {0}); boxMap->addBoxDef(boost::factory<box::Mdat*>(), BoxType("mdat"), {}); boxMap->addBoxDef(boost::factory<box::Mdhd*>(), BoxType("mdhd"), {0, 1}); boxMap->addBoxDef(boost::factory<box::Mdia*>(), BoxType("mdia"), {}); boxMap->addBoxDef(boost::factory<box::Mehd*>(), BoxType("mehd"), {0, 1}); boxMap->addBoxDef(boost::factory<box::Meta*>(), BoxType("meta"), {0}); boxMap->addBoxDef(boost::factory<box::Mfhd*>(), BoxType("mfhd"), {0}); boxMap->addBoxDef(boost::factory<box::Mfra*>(), BoxType("mfra"), {}); boxMap->addBoxDef(boost::factory<box::Mfro*>(), BoxType("mfro"), {0}); boxMap->addBoxDef(boost::factory<box::Minf*>(), BoxType("minf"), {}); boxMap->addBoxDef(boost::factory<box::Moof*>(), BoxType("moof"), {}); boxMap->addBoxDef(boost::factory<box::Moov*>(), BoxType("moov"), {}); boxMap->addBoxDef(boost::factory<box::Mvex*>(), BoxType("mvex"), {}); boxMap->addBoxDef(boost::factory<box::Mvhd*>(), BoxType("mvhd"), {0, 1}); boxMap->addBoxDef(boost::factory<box::Pssh*>(), BoxType("pssh"), {0, 1}); boxMap->addBoxDef(boost::factory<box::Sbgp*>(), BoxType("sbgp"), {0, 1}); boxMap->addBoxDef(boost::factory<box::Schi*>(), BoxType("schi"), {}); boxMap->addBoxDef(boost::factory<box::Sdtp*>(), BoxType("sdtp"), {0}); boxMap->addBoxDef(boost::factory<box::Sgpd*>(), BoxType("sgpd"), {1, 2}); boxMap->addBoxDef(boost::factory<box::Sidx*>(), BoxType("sidx"), {0, 1}); boxMap->addBoxDef(boost::factory<box::Sinf*>(), BoxType("sinf"), {}); boxMap->addBoxDef(boost::factory<box::Skip*>(), BoxType("skip"), {}); boxMap->addBoxDef(boost::factory<box::Smhd*>(), BoxType("smhd"), {0}); boxMap->addBoxDef(boost::factory<box::Stbl*>(), BoxType("stbl"), {}); boxMap->addBoxDef(boost::factory<box::Stco*>(), BoxType("stco"), {}); boxMap->addBoxDef(boost::factory<box::Stsc*>(), BoxType("stsc"), {0}); boxMap->addBoxDef(boost::factory<box::Stsd*>(), BoxType("stsd"), {0}); boxMap->addBoxDef(boost::factory<box::Stss*>(), BoxType("stss"), {0}); boxMap->addBoxDef(boost::factory<box::Stsz*>(), BoxType("stsz"), {0}); boxMap->addBoxDef(boost::factory<box::Stts*>(), BoxType("stts"), {0}); boxMap->addBoxDef(boost::factory<box::Styp*>(), BoxType("styp"), {}); boxMap->addBoxDef(boost::factory<box::Tfdt*>(), BoxType("tfdt"), {0, 1}); boxMap->addBoxDef(boost::factory<box::Tfhd*>(), BoxType("tfhd"), {0}); boxMap->addBoxDef(boost::factory<box::Tfra*>(), BoxType("tfra"), {0, 1}); boxMap->addBoxDef(boost::factory<box::Tkhd*>(), BoxType("tkhd"), {0, 1}); boxMap->addBoxDef(boost::factory<box::Traf*>(), BoxType("traf"), {}); boxMap->addBoxDef(boost::factory<box::Trak*>(), BoxType("trak"), {}); boxMap->addBoxDef(boost::factory<box::Trex*>(), BoxType("trex"), {0}); boxMap->addBoxDef(boost::factory<box::Trun*>(), BoxType("trun"), {0, 1}); boxMap->addBoxDef(boost::factory<box::Udta*>(), BoxType("udta"), {}); boxMap->addBoxDef(boost::factory<box::Vmhd*>(), BoxType("vmhd"), {0}); boxMap->addBoxDef(boost::factory<box::Url*>(), BoxType("url "), {0}); boxMap->addBoxDef(boost::factory<box::Urn*>(), BoxType("urn "), {0}); boxMap->addBoxDef(boost::factory<box::Wave*>(), BoxType("wave"), {0}); boxMap->addBoxDef(boost::factory<box::VisualSampleEntry*>(), BoxType("avc1"), {0}); boxMap->addBoxDef(boost::factory<box::VisualSampleEntry*>(), BoxType("encv"), {0}); boxMap->addBoxDef(boost::factory<box::VisualSampleEntry*>(), BoxType("vp08"), {0}); boxMap->addBoxDef(boost::factory<box::VisualSampleEntry*>(), BoxType("vp09"), {0}); boxMap->addBoxDef(boost::factory<box::VisualSampleEntry*>(), BoxType("vp10"), {0}); boxMap->addBoxDef(boost::factory<box::VisualSampleEntry*>(), BoxType("av01"), {0}); boxMap->addBoxDef(boost::factory<box::AudioSampleEntry*>(), BoxType("mp4a"), {0}); boxMap->addBoxDef(boost::factory<box::AudioSampleEntry*>(), BoxType("enca"), {0}); boxMap->addBoxDef(boost::factory<box::AudioSampleEntry*>(), BoxType("Opus"), {0}); boxMap->addBoxDef(boost::factory<box::AVCDecoderConfiguration*>(), BoxType("avcC"), {0}); boxMap->addBoxDef(boost::factory<box::VPCodecConfiguration*>(), BoxType("vpcC"), {1, 0}); boxMap->addBoxDef(boost::factory<box::AV1CodecConfiguration*>(), BoxType("av1C"), {}); boxMap->addBoxDef(boost::factory<box::PixelAspectRatio*>(), BoxType("pasp"), {0}); boxMap->addBoxDef(boost::factory<box::IlstMeta*>(), BoxType("----"), {}); boxMap->addBoxDef(boost::factory<box::IlstMeta*>(), BoxType("aART"), {}); boxMap->addBoxDef(boost::factory<box::IlstMeta*>(), BoxType("akID"), {}); boxMap->addBoxDef(boost::factory<box::IlstMeta*>(), BoxType("apID"), {}); boxMap->addBoxDef(boost::factory<box::IlstMeta*>(), BoxType("atID"), {}); boxMap->addBoxDef(boost::factory<box::IlstMeta*>(), BoxType("cmID"), {}); boxMap->addBoxDef(boost::factory<box::IlstMeta*>(), BoxType("cnID"), {}); boxMap->addBoxDef(boost::factory<box::IlstMeta*>(), BoxType("covr"), {}); boxMap->addBoxDef(boost::factory<box::IlstMeta*>(), BoxType("cpil"), {}); boxMap->addBoxDef(boost::factory<box::IlstMeta*>(), BoxType("cprt"), {}); boxMap->addBoxDef(boost::factory<box::IlstMeta*>(), BoxType("desc"), {}); boxMap->addBoxDef(boost::factory<box::IlstMeta*>(), BoxType("disk"), {}); boxMap->addBoxDef(boost::factory<box::IlstMeta*>(), BoxType("egid"), {}); boxMap->addBoxDef(boost::factory<box::IlstMeta*>(), BoxType("geID"), {}); boxMap->addBoxDef(boost::factory<box::IlstMeta*>(), BoxType("gnre"), {}); boxMap->addBoxDef(boost::factory<box::IlstMeta*>(), BoxType("pcst"), {}); boxMap->addBoxDef(boost::factory<box::IlstMeta*>(), BoxType("pgap"), {}); boxMap->addBoxDef(boost::factory<box::IlstMeta*>(), BoxType("plID"), {}); boxMap->addBoxDef(boost::factory<box::IlstMeta*>(), BoxType("purd"), {}); boxMap->addBoxDef(boost::factory<box::IlstMeta*>(), BoxType("purl"), {}); boxMap->addBoxDef(boost::factory<box::IlstMeta*>(), BoxType("rtng"), {}); boxMap->addBoxDef(boost::factory<box::IlstMeta*>(), BoxType("sfID"), {}); boxMap->addBoxDef(boost::factory<box::IlstMeta*>(), BoxType("soaa"), {}); boxMap->addBoxDef(boost::factory<box::IlstMeta*>(), BoxType("soal"), {}); boxMap->addBoxDef(boost::factory<box::IlstMeta*>(), BoxType("soar"), {}); boxMap->addBoxDef(boost::factory<box::IlstMeta*>(), BoxType("soco"), {}); boxMap->addBoxDef(boost::factory<box::IlstMeta*>(), BoxType("sonm"), {}); boxMap->addBoxDef(boost::factory<box::IlstMeta*>(), BoxType("sosn"), {}); boxMap->addBoxDef(boost::factory<box::IlstMeta*>(), BoxType("stik"), {}); boxMap->addBoxDef(boost::factory<box::IlstMeta*>(), BoxType("tmpo"), {}); boxMap->addBoxDef(boost::factory<box::IlstMeta*>(), BoxType("trkn"), {}); boxMap->addBoxDef(boost::factory<box::IlstMeta*>(), BoxType("tven"), {}); boxMap->addBoxDef(boost::factory<box::IlstMeta*>(), BoxType("tves"), {}); boxMap->addBoxDef(boost::factory<box::IlstMeta*>(), BoxType("tvnn"), {}); boxMap->addBoxDef(boost::factory<box::IlstMeta*>(), BoxType("tvsh"), {}); boxMap->addBoxDef(boost::factory<box::IlstMeta*>(), BoxType("tvsn"), {}); boxMap->addBoxDef(boost::factory<box::IlstMeta*>(), BoxType(std::array<std::uint8_t, 4>{0xa9, 'A', 'R', 'T'}), {}); boxMap->addBoxDef(boost::factory<box::IlstMeta*>(), BoxType(std::array<std::uint8_t, 4>{0xa9, 'a', 'l', 'b'}), {}); boxMap->addBoxDef(boost::factory<box::IlstMeta*>(), BoxType(std::array<std::uint8_t, 4>{0xa9, 'c', 'm', 't'}), {}); boxMap->addBoxDef(boost::factory<box::IlstMeta*>(), BoxType(std::array<std::uint8_t, 4>{0xa9, 'c', 'o', 'm'}), {}); boxMap->addBoxDef(boost::factory<box::IlstMeta*>(), BoxType(std::array<std::uint8_t, 4>{0xa9, 'd', 'a', 'y'}), {}); boxMap->addBoxDef(boost::factory<box::IlstMeta*>(), BoxType(std::array<std::uint8_t, 4>{0xa9, 'g', 'e', 'n'}), {}); boxMap->addBoxDef(boost::factory<box::IlstMeta*>(), BoxType(std::array<std::uint8_t, 4>{0xa9, 'g', 'r', 'p'}), {}); boxMap->addBoxDef(boost::factory<box::IlstMeta*>(), BoxType(std::array<std::uint8_t, 4>{0xa9, 'n', 'a', 'm'}), {}); boxMap->addBoxDef(boost::factory<box::IlstMeta*>(), BoxType(std::array<std::uint8_t, 4>{0xa9, 't', 'o', 'o'}), {}); boxMap->addBoxDef(boost::factory<box::IlstMeta*>(), BoxType(std::array<std::uint8_t, 4>{0xa9, 'w', 'r', 't'}), {}); } } // namespace shiguredo::mp4
xcorail/andstatus
app/src/main/java/org/andstatus/app/user/CachedUsersAndActors.java
<gh_stars>0 package org.andstatus.app.user; import android.database.Cursor; import android.support.annotation.NonNull; import org.andstatus.app.context.MyContext; import org.andstatus.app.data.ActorSql; import org.andstatus.app.data.DbUtils; import org.andstatus.app.data.MyQuery; import org.andstatus.app.data.SqlActorIds; import org.andstatus.app.database.table.ActorTable; import org.andstatus.app.database.table.FriendshipTable; import org.andstatus.app.database.table.TimelineTable; import org.andstatus.app.database.table.UserTable; import org.andstatus.app.net.social.Actor; import org.andstatus.app.origin.Origin; import org.andstatus.app.util.CollectionsUtil; import org.andstatus.app.util.MyLog; import org.andstatus.app.util.TriState; import java.util.Collection; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.function.Function; import java.util.function.Supplier; import static org.andstatus.app.util.RelativeTime.SOME_TIME_AGO; public class CachedUsersAndActors { private final MyContext myContext; public final Map<Long, User> users = new ConcurrentHashMap<>(); public final Map<Long, Actor> actors = new ConcurrentHashMap<>(); public final Map<Long, User> myUsers = new ConcurrentHashMap<>(); public final Map<Long, Actor> myActors = new ConcurrentHashMap<>(); /** key - friendId, set of values - IDs of my actors */ public final Map<Long, Set<Long>> friendsOfMyActors = new ConcurrentHashMap<>(); public static CachedUsersAndActors newEmpty(MyContext myContext) { return new CachedUsersAndActors(myContext); } private CachedUsersAndActors(MyContext myContext) { this.myContext = myContext; } public int size() { return myUsers.size(); } public CachedUsersAndActors initialize() { initializeMyUsers(); initializeFriendsOfMyActors(); loadTimelineActors(); MyLog.v(this, () -> "Users list initialized, " + myUsers.size() + " users, " + myActors.size() + " my actors, " + friendsOfMyActors.size() + " friends"); return this; } private void initializeMyUsers() { users.clear(); actors.clear(); myUsers.clear(); myActors.clear(); final String sql = "SELECT " + ActorSql.select() + " FROM " + ActorSql.tables() + " WHERE " + UserTable.IS_MY + "=" + TriState.TRUE.id; final Function<Cursor, Actor> function = cursor -> Actor.fromCursor(myContext, cursor); MyQuery.get(myContext, sql, function).forEach(this::updateCache); } private void initializeFriendsOfMyActors() { friendsOfMyActors.clear(); final String sql = "SELECT DISTINCT " + ActorSql.select() + ", " + FriendshipTable.TABLE_NAME + "." + FriendshipTable.ACTOR_ID + " AS " + FriendshipTable.FOLLOWER_ID + " FROM (" + ActorSql.tables() + ")" + " INNER JOIN " + FriendshipTable.TABLE_NAME + " ON " + FriendshipTable.FRIEND_ID + "=" + ActorTable.TABLE_NAME + "." + ActorTable._ID + " AND " + FriendshipTable.FOLLOWED + "=1" + " AND " + FriendshipTable.TABLE_NAME + "." + FriendshipTable.ACTOR_ID + SqlActorIds.fromIds(myActors.keySet()).getSql(); final Function<Cursor, Void> function = cursor -> { Actor friend = Actor.fromCursor(myContext, cursor); Actor me = Actor.load(myContext, DbUtils.getLong(cursor, FriendshipTable.FOLLOWER_ID)); friendsOfMyActors.compute(friend.actorId, CollectionsUtil.addValue(me.actorId)); return null; }; MyQuery.get(myContext, sql, function); } public Actor reload(Actor actor) { return reload(actor.actorId); } public Actor reload(long actorId) { Actor reloaded = Actor.load(myContext, actorId, true, Actor::getEmpty); if (isMe(reloaded)) updateFriendsOfMy(reloaded); return reloaded; } private void updateFriendsOfMy(Actor actor) { friendsOfMyActors.entrySet().stream().filter( entry -> entry.getValue().contains(actor.actorId)) .forEach(entry -> friendsOfMyActors.compute(entry.getKey(), CollectionsUtil.removeValue(actor.actorId))); MyQuery.getFriendsIds(actor.actorId) .forEach(friendId -> friendsOfMyActors.compute(friendId, CollectionsUtil.addValue(actor.actorId)) ); } private void loadTimelineActors() { final String sql = "SELECT " + ActorSql.select() + " FROM " + ActorSql.tables() + " WHERE " + ActorTable.TABLE_NAME + "." + ActorTable._ID + " IN (" + " SELECT DISTINCT " + TimelineTable.ACTOR_ID + " FROM " + TimelineTable.TABLE_NAME + ")"; final Function<Cursor, Actor> function = cursor -> Actor.fromCursor(myContext, cursor); MyQuery.get(myContext, sql, function); } public boolean containsMe(@NonNull Collection<Actor> actors) { return actors.stream().anyMatch(this::isMe); } @Override public String toString() { return "MyUsers{\n" + myUsers + "\nMy actors: " + myActors + "\nMy friends: " + friendsOfMyActors + '}'; } public boolean isMeOrMyFriend(Actor actor) { return actor.nonEmpty() && (isMe(actor) || friendsOfMyActors.containsKey(actor.actorId)); } public boolean isMe(@NonNull Actor actor) { return isMe(actor.actorId); } public boolean isMe(long actorId) { return actorId != 0 && ( myActors.containsKey(actorId) || myUsers.values().stream().anyMatch(user -> user.actorIds.contains(actorId)) ); } public Actor lookupUser(Actor actor) { if (actor.user == User.EMPTY && actor.actorId != 0) { actor.user = User.load(myContext, actor.actorId); } if (actor.user == User.EMPTY && actor.isWebFingerIdValid()) { actor.user = User.load(myContext, MyQuery.webFingerIdToId(0, actor.getWebFingerId())); } if (actor.user == User.EMPTY) { actor.user = User.getNew(); } else { updateCache(actor); } return actor; } /** Tries to find this actor in the home origin (the same host...). * Returns the same Actor, if not found */ public Actor toHomeOrigin(Actor actor) { return actor.origin.getHost().equals(actor.getHost()) ? actor : actor.user.actorIds.stream().map(id -> actors.getOrDefault(id, Actor.EMPTY)) .filter(a -> a != Actor.EMPTY && a.origin.getHost().equals(actor.getHost())) .findAny().orElse(actor); } /** Tries to find this actor in this origin * Returns the same Actor, if not found */ public Actor toOrigin(Actor actor, Origin origin) { return actor.origin.equals(origin) ? actor : actor.user.actorIds.stream().map(id -> actors.getOrDefault(id, Actor.EMPTY)) .filter(a -> a != Actor.EMPTY && a.origin.equals(origin)) .findAny().orElse(actor); } @NonNull public User userFromActorId(long actorId, Supplier<User> userSupplier) { if (actorId == 0) return User.EMPTY; final User user1 = actors.getOrDefault(actorId, Actor.EMPTY).user; return user1.nonEmpty() ? user1 : users.values().stream().filter(user -> user.actorIds.contains(actorId)).findFirst().orElseGet(userSupplier); } public void updateCache(@NonNull Actor actor) { if (actor.isEmpty()) return; final User user = actor.user; final long userId = user.userId; final long actorId = actor.actorId; if (actorId != 0) { user.actorIds.add(actorId); updateCachedActor(actors, actor); if (user.isMyUser().isTrue) updateCachedActor(myActors, actor); } if (userId == 0) return; User cached = users.getOrDefault(userId, User.EMPTY); if (cached.isEmpty()) { users.putIfAbsent(userId, user); if (user.isMyUser().isTrue) myUsers.putIfAbsent(userId, user); } else if (user.isMyUser().isTrue && cached.isMyUser().untrue) { user.actorIds.addAll(cached.actorIds); users.put(userId, user); myUsers.put(userId, user); } else if (actorId != 0) { cached.actorIds.add(actorId); } } private void updateCachedActor(Map<Long, Actor> actors, Actor actor) { if (actor.isEmpty()) return; if (actor.getUpdatedDate() <= SOME_TIME_AGO) { actors.putIfAbsent(actor.actorId, actor); return; } if (actor.isBetterToCacheThan(actors.get(actor.actorId))) { actors.put(actor.actorId, actor); myActors.computeIfPresent(actor.actorId, (id, actor1) -> actor); } } }
lizhongyi1992/xuanxuan
xxc/app/core/ui.js
<gh_stars>1-10 import Config from '../config'; // eslint-disable-line import Server from './server'; import MemberProfileDialog from '../views/common/member-profile-dialog'; import Messager from '../components/messager'; import ContextMenu from '../components/context-menu'; import modal from '../components/modal'; import {isWebUrl, getSearchParam} from '../utils/html-helper'; import Lang, {onLangChange} from './lang'; import events from './events'; import profile from './profile'; import Notice from './notice'; import ImageViewer from '../components/image-viewer'; import Store from '../utils/store'; import {executeCommandLine, registerCommand, executeCommand} from './commander'; import WebViewDialog from '../views/common/webview-dialog'; import {addContextMenuCreator, showContextMenu} from './context-menu'; import platform from '../platform'; /** * 平台提供的剪切板功能访问对象 * @type {Object} * @private */ const clipboard = platform.access('clipboard'); /** * 平台提供的快捷键功能访问对象 * @type {Object} * @private */ const shortcut = platform.access('shortcut'); /** * 平台提供的对话框功能访问对象 * @type {Object} * @private */ const dialog = platform.access('dialog'); /** * 平台提供的通用界面交互访问对象 * @type {Object} * @private */ const platformUI = platform.access('ui'); /** * 事件表 * @type {Object<string, string>} * @private */ const EVENT = { app_link: 'app.link', net_online: 'app.net.online', net_offline: 'app.net.offline', ready: 'app.ready', update_view_style: 'app.updateViewStyle' }; // 添加图片上下文菜单生成器 addContextMenuCreator('image', ({url, dataType}) => { const items = [{ label: Lang.string('menu.image.view'), click: () => { ImageViewer.show(url); } }]; if (clipboard && clipboard.writeImageFromUrl) { items.push({ label: Lang.string('menu.image.copy'), click: () => { clipboard.writeImageFromUrl(url, dataType); } }); } if (dialog && dialog.saveAsImageFromUrl) { items.push({ label: Lang.string('menu.image.saveAs'), click: () => { if (url.startsWith('file://')) { url = url.substr(7); } return dialog.saveAsImageFromUrl(url, dataType).then(filename => { if (filename) { Messager.show(Lang.format('file.fileSavedAt.format', filename), { actions: platformUI.openFileItem ? [{ label: Lang.string('file.open'), click: () => { platformUI.openFileItem(filename); } }, { label: Lang.string('file.openFolder'), click: () => { platformUI.showItemInFolder(filename); } }] : null }); } }); } }); } if (platformUI.openFileItem && dataType !== 'base64') { items.push({ label: Lang.string('menu.image.open'), click: () => { if (url.startsWith('file://')) { url = url.substr(7); } platformUI.openFileItem(url); } }); } return items; }); // 添加成员上下文菜单生成器 addContextMenuCreator('member', ({member}) => { return [{ label: Lang.string('member.profile.view'), click: () => { MemberProfileDialog.show(member); } }]; }); // 注册打开成员资料对话框命令 registerCommand('showMemberProfile', (context, memberId) => { const {options} = context; memberId = memberId || options.memberId; MemberProfileDialog.show(memberId); }); /** * 绑定界面上链接点击事件 * @param {string} type 链接目标类型 * @param {function(target: string, element: Element)} listener 事件回调函数 * @return {Symbol} 使用 `Symbol` 存储的事件 ID,用于取消事件 */ export const onAppLinkClick = (type, listener) => { return events.on(`${EVENT.app_link}.${type}`, listener); }; /** * 触发界面上链接点击事件 * @param {Element} element 触发元素 * @param {string} type 链接目标类型 * @param {string} target 链接目标 * @param {...any} params 其他参数 * @return {void} */ export const emitAppLinkClick = (element, type, target, ...params) => { return events.emit(`${EVENT.app_link}.${type}`, target, element, ...params); }; // 处理点击成员名称链接事件(弹出个人资料对话框) onAppLinkClick('Member', target => { MemberProfileDialog.show(target); }); /** * 自动清除拷贝成功提示计时器 ID * @type {number} * @private */ let clearCopyCodeTip = null; if (clipboard && clipboard.writeText) { // 注册处理拷贝代码命令 registerCommand('copyCode', context => { const {targetElement: element} = context; if (element) { if (clearCopyCodeTip) { clearTimeout(clearCopyCodeTip); clearCopyCodeTip = null; } const code = element.nextElementSibling.innerText; clipboard.writeText(code); element.setAttribute('data-hint', Lang.string('common.copied')); element.classList.add('hint--success'); clearCopyCodeTip = setTimeout(() => { clearCopyCodeTip = null; element.setAttribute('data-hint', Lang.string('common.copyCode')); element.classList.remove('hint--success'); }, 2000); return true; } return false; }); } // 处理用户登录事件 Server.onUserLogin((user, loginError) => { if (Config.ui.showDailySignMessage && !loginError && user.isFirstSignedToday) { Messager.show(Lang.string('login.signed'), { type: 'success', icon: 'calendar-check', autoHide: true, }); } if (typeof Pace !== 'undefined') { Pace.stop(); } }); // 处理用户退出登录事件 Server.onUserLogout((user, code, reason, unexpected) => { if (user) { let errorCode = null; if (reason === 'KICKOFF') { errorCode = 'KICKOFF'; } if (errorCode) { Messager.show(Lang.error(errorCode), { rootClassName: 'message-kickoff-confirm', type: 'danger', icon: 'alert', actions: [{ label: Lang.string('login.retry'), click: () => { Server.login(user); } }] }); if (Notice.requestAttention) { Notice.requestAttention(); } } } }); // 为 `<body>` 添加操作系统辅助类,例如 `'os-mac'` 或 `'os-win'` document.body.classList.add(`os-${platform.access('env.os')}`); /** * 在扩展应用中功能打开链接 * @param {string} url 要打开的地址 * @param {string} appName 应用名称 * @return {void} */ export const openUrlInApp = (url, appName) => { executeCommandLine(`openInApp/${appName}/${encodeURIComponent(url)}`, {appName, url}); }; /** * 在对话框中打开链接 * @param {string} url 要打开的链接 * @param {Object} options 选项 * @param {function} callback 对话框显示后的回调函数 * @return {void} */ export const openUrlInDialog = (url, options, callback) => { options = Object.assign({url}, options); WebViewDialog.show(url, options, callback); }; // 注册在对话框中打开链接命令 registerCommand('openUrlInDialog', (context, url) => { const {options} = context; if (!url && options && options.url) { url = options.url; } if (url) { openUrlInDialog(url, options); return true; } return false; }); // 注册关闭对话框命令 registerCommand('closeModal', (context, modalId, remove) => { modalId = modalId || context.modalId; if (remove === undefined) { if (context.removeModal === undefined) { remove = true; } else { remove = context.removeModal; } } modal.hide(modalId, null, remove); }); // 注册路由跳转命令 registerCommand('#', (context, ...params) => { window.location.hash = `#/${params.join('/')}`; }); /** * 在系统默认浏览器中打开链接 * @param {stirng} url 要打开的链接 * @return {void} */ export const openUrlInBrowser = url => { return platformUI.openExternal(url); }; // 注册在系统默认浏览器中打开链接命令 registerCommand('openUrlInBrowser', (context, url) => { if (!url && context.options && context.options.url) { url = context.options.url; } if (url) { openUrlInBrowser(url); return true; } return false; }); /** * 根据界面事件打开链接,自动选择打开的方式 * @param {string} url 要打开的链接 * @param {Element} targetElement 触发事件元素 * @param {Event} event 界面事件对象 * @param {Object} context 命令参数 * @returns {boolean} 如果返回 `true` 则打开成功,否则为打开失败 */ export const openUrl = (url, targetElement, event, context) => { if (DEBUG) { console.collapse('Open Url', 'redBg', url, 'redPale'); console.log('targetElement', targetElement); console.log('event', event); console.log('context', context); console.groupEnd(); } if (isWebUrl(url)) { if (global.ExtsRuntime) { const extInspector = global.ExtsRuntime.getUrlOpener(url, targetElement); if (extInspector && extInspector) { const openResult = extInspector.open(url); if (openResult === true || openResult === false) { return openResult; } if (typeof openResult === 'string') { if (isWebUrl(openResult)) { return openUrlInBrowser(openResult); } return openUrl(openResult, targetElement); } } } openUrlInBrowser(url); return true; } if (url[0] === '@') { const params = url.substr(1).split('/').map(decodeURIComponent); emitAppLinkClick(targetElement, ...params); return true; } if (url[0] === '!' || url.startsWith('xxc:')) { // eslint-disable-next-line no-nested-ternary url = url.substr(url[0] === '!' ? 1 : (url.startsWith('xxc://') ? 6 : 4)); executeCommandLine(url, Object.assign({targetElement, event}, context)); return true; } }; // 监听页面上的点击事件 document.addEventListener('click', e => { let {target} = e; while (target && !((target.classList && target.classList.contains('app-link')) || (target.tagName === 'A' && target.attributes.href))) { target = target.parentNode; } if (target && ((target.tagName === 'A' && (!target.attributes.href || !target.attributes.href.value.startsWith('#/'))) || target.classList.contains('app-link')) && (target.attributes.href || target.attributes['data-url'])) { const link = (target.attributes['data-url'] || target.attributes.href).value; if (openUrl(link, target, e)) { e.preventDefault(); } } }); // 监听网络成功连接事件 window.addEventListener('online', () => { if (profile.user) { if (!Server.socket.isLogging) { Server.login(profile.user); } } }); // 监听网络连接断开事件 window.addEventListener('offline', () => { if (profile.isUserOnline) { profile.user.markDisconnect(); Server.socket.close(null, 'net_offline'); } }); /** * 检查拖拽结束计时任务 ID * @type {number} * @private */ let dragLeaveTask; /** * 完成拖拽事件 * @return {void} * @private */ const completeDragNDrop = () => { document.body.classList.remove('drag-n-drop-over-in'); setTimeout(() => { document.body.classList.remove('drag-n-drop-over'); }, 350); }; // 监听界面上拖拽过程中事件 window.ondragover = e => { clearTimeout(dragLeaveTask); if (e.dataTransfer && e.dataTransfer.types.includes('Files')) { document.body.classList.add('drag-n-drop-over'); setTimeout(() => { document.body.classList.add('drag-n-drop-over-in'); }, 10); } e.preventDefault(); return false; }; // 监听界面上拖拽离开 window.ondragleave = e => { clearTimeout(dragLeaveTask); dragLeaveTask = setTimeout(completeDragNDrop, 300); e.preventDefault(); return false; }; // 监听界面上拖拽完成 window.ondrop = e => { clearTimeout(dragLeaveTask); completeDragNDrop(); if (DEBUG) { console.collapse('DRAG FILE', 'redBg', (e.dataTransfer && e.dataTransfer.files && e.dataTransfer.files.length ? e.dataTransfer.files[0].path : ''), 'redPale'); console.log(e); console.groupEnd(); } e.preventDefault(); return false; }; // 如果平台支持自主处理退出策略则询问用户如何退出 if (platformUI.onRequestQuit) { platformUI.onRequestQuit(closeReason => { if (closeReason !== 'quit') { const user = profile.user; if (user && !user.isUnverified) { const appCloseOption = user.config.appCloseOption; if (appCloseOption === 'minimize' || !platformUI.showQuitConfirmDialog) { platformUI.hideWindow(); return false; } else if (appCloseOption !== 'close' && platformUI.showQuitConfirmDialog) { platformUI.showQuitConfirmDialog(Lang.string('dialog.appClose.title'), Lang.string('dialog.appClose.rememberOption'), [Lang.string('dialog.appClose.minimizeMainWindow'), Lang.string('dialog.appClose.quitApp'), Lang.string('dialog.appClose.cancelAction')], (result, checked) => { if (checked && result) { user.config.appCloseOption = result; } if (result === 'close') { Server.logout(); } return result; }); return false; } } } Server.logout(); }); } /** * 立即退出应用 * @private * @type {function} */ let _quit = null; if (platformUI.quit) { _quit = (delay = 1000, ignoreListener = true) => { if (ignoreListener) { Server.logout(); } platformUI.quit(delay, ignoreListener); }; } /** * 立即退出应用 * @type {function} */ export const quit = _quit; // 监听应用窗口最小化事件 if (platformUI.onWindowMinimize) { platformUI.onWindowMinimize(() => { const {userConfig} = profile; if (userConfig && userConfig.removeFromTaskbarOnHide) { platformUI.setShowInTaskbar(false); } }); } // 监听应用窗口失去焦点事件 if (platformUI.onWindowBlur && platformUI.hideWindow) { platformUI.onWindowBlur(() => { const {userConfig} = profile; if (userConfig && userConfig.hideWindowOnBlur) { platformUI.hideWindow(); } }); } /** * 重新加载窗口 * @returns {Promise} 使用 Promise 异步返回处理结果 */ export const reloadWindow = () => { return modal.confirm(Lang.string('dialog.reloadWindowConfirmTip'), {title: Lang.string('dialog.reloadWindowConfirm')}).then(confirmed => { if (confirmed) { Server.logout(); setTimeout(() => { Store.set('autoLoginNextTime', true); if (platformUI.reloadWindow) { platformUI.reloadWindow(); } else { window.location.reload(); } }, 1000); } return Promise.resolve(confirmed); }); }; /** * 判断是否在下次启动自动登录 * @returns {boolean} 如果返回 `true` 则为下次启动自动登录,否则为不自动登录 */ export const isAutoLoginNextTime = () => { const autoLoginNextTime = Store.get('autoLoginNextTime'); if (autoLoginNextTime) { Store.remove('autoLoginNextTime'); } return autoLoginNextTime; }; /** * 通过浏览器查询字符串传入的登录参数 * @type {object} */ export const entryParams = getSearchParam(); /** * 触发界面准备就绪事件 * @return {void} */ export const triggerReady = () => { events.emit(EVENT.ready); }; /** * 绑定界面准备就绪事件 * @param {funcion} listener 事件回调函数 * @return {Symbol} 使用 `Symbol` 存储的事件 ID,用于取消事件 */ export const onReady = listener => { return events.on(EVENT.ready, listener); }; /** * 设置应用窗口标题 * @param {string} title 窗口标题 * @return {void} */ export const setTitle = title => { const platformSetTitle = platform.access('ui.setWindowTitle'); if (platformSetTitle) { platformSetTitle(title); } else { document.title = title; } }; /** * 浏览器地址解析缓存 * @private * @type {Object} */ const urlMetaCaches = {}; /** * 最大浏览器解析缓存大小 * @type {number} * @private */ const maxUrlCacheSize = 20; /** * 解析浏览器地址信息 * @param {string} url 要解析的地址 * @param {boolean} [disableCache=false] 是否禁止使用缓存 * @returns {Promise} 使用 Promise 异步返回处理结果 */ export const getUrlMeta = (url, disableCache = false) => { if (!Config.ui['chat.urlInspector']) { return Promise.resolve({url, title: url}); } if (!disableCache) { const urlMetaCache = urlMetaCaches[url]; if (urlMetaCache) { return Promise.resolve(urlMetaCache.meta); } } if (platformUI.getUrlMeta) { let extInspector = null; if (global.ExtsRuntime) { extInspector = global.ExtsRuntime.getUrlInspector(url); } const getUrl = () => { if (extInspector && extInspector.getUrl) { const urlResult = extInspector.getUrl(url); if (urlResult instanceof Promise) { return urlResult; } return Promise.resolve(urlResult); } return Promise.resolve(url); }; if (extInspector && extInspector.noMeta && extInspector.inspect) { return getUrl().then(entryUrl => { const cardMeta = extInspector.inspect(entryUrl, url); if (cardMeta instanceof Promise) { return cardMeta; } return Promise.resolve(cardMeta); }); } return getUrl().then(platformUI.getUrlMeta).then(meta => { const {favicon} = meta; let cardMeta = { url, title: meta.title, image: meta.image, subtitle: (meta.title && meta.title !== url) ? url : null, content: meta.description && meta.description.length > 200 ? `${meta.description.substring(0, 150)}...` : meta.description, icon: favicon ? favicon.href : null }; if (meta.isImage) { cardMeta.contentUrl = url; cardMeta.contentType = 'image'; cardMeta.icon = 'mdi-image text-green icon-2x'; } else if (meta.isVideo) { cardMeta.contentUrl = url; cardMeta.contentType = 'video'; cardMeta.clickable = 'title'; cardMeta.icon = 'mdi-video text-red icon-2x'; } else if (!cardMeta.title && !cardMeta.subtitle) { cardMeta.title = url; } if (cardMeta.image && cardMeta.image.startsWith('//')) { cardMeta.image = `https:${cardMeta.image}`; } if (cardMeta.icon && cardMeta.icon.startsWith('//')) { cardMeta.icon = `https:${cardMeta.icon}`; } if (extInspector && extInspector.inspect) { try { cardMeta = extInspector.inspect(url, meta, cardMeta); } catch (err) { if (DEBUG) { console.error('Inspect url error', { err, meta, cardMeta, extInspector }); } } if (cardMeta instanceof Promise) { return cardMeta.then(cardMeta => { cardMeta.provider = extInspector.provider; return Promise.resolve(cardMeta); }); } else if (cardMeta) { cardMeta.provider = extInspector.provider; return Promise.resolve(cardMeta); } } // Save cache let cacheKeys = Object.keys(urlMetaCaches); if (cacheKeys.length > maxUrlCacheSize) { cacheKeys = cacheKeys.sort((x, y) => { return x.time - y.time; }); for (let i = 0; i < (cacheKeys.length - maxUrlCacheSize); ++i) { delete urlMetaCaches[cacheKeys[i]]; } } urlMetaCaches[url] = {meta: cardMeta, time: new Date().getTime()}; return Promise.resolve(cardMeta); }); } return Promise.resolve({url, title: url}); }; /** * 全局快捷键是否可用 * @type {boolean} * @private */ let isGlobalShortcutDisabled = false; /** * 全局快捷键表 * @private * @type {Object} */ let globalHotkeys = null; /** * 注册全局快捷键 * @param {User} loginUser 当前登录的用户 * @param {Error} loginError 登录错误信息 * @return {void} * @private */ const registerShortcut = (loginUser, loginError) => { if (!shortcut) { return; } if (loginError) { return; } const {userConfig} = profile; if (userConfig) { // eslint-disable-next-line prefer-destructuring globalHotkeys = userConfig.globalHotkeys; Object.keys(globalHotkeys).forEach(name => { shortcut.registerGlobalShortcut(name, globalHotkeys[name], () => { if (!isGlobalShortcutDisabled) { executeCommandLine(`shortcut.${name}`); } else if (DEBUG) { console.log(`Global shortcut command '${name}' skiped.`); } }); }); } }; /** * 取消注册全局快捷键 * @return {void} * @private */ const unregisterGlobalShortcut = () => { if (!shortcut) { return; } if (globalHotkeys) { Object.keys(globalHotkeys).forEach(name => { shortcut.unregisterGlobalShortcut(name); }); globalHotkeys = null; } }; profile.onUserConfigChange((change, config) => { if (shortcut && change && Object.keys(change).some(x => x.startsWith('shortcut.'))) { registerShortcut(); } if (config.needSave) { Server.socket.uploadUserSettings(); } }); // // 处理全局快捷键注册和反注册 if (shortcut) { Server.onUserLogin(registerShortcut); Server.onUserLogout(unregisterGlobalShortcut); if (platformUI.showAndFocusWindow) { registerCommand('shortcut.focusWindowHotkey', () => { if (platformUI.hideWindow && platformUI.isWindowOpenAndFocus) { platformUI.hideWindow(); } else { platformUI.showAndFocusWindow(); } }); } } // 注册显示上下文菜单命令 registerCommand('showContextMenu', (context, name) => { const {options, event} = context; showContextMenu(name, {options, event}); }); /** * 判断当前应用窗口是否是小窗口模式 * @returns {boolean} 如果返回 `true` 则为是小窗口模式,否则为不是小窗口模式 */ export const isSmallScreen = () => { return window.innerWidth < 768; }; /** * 切换显示小窗口模式,实际是在 `<body>` 元素上切换添加 `'app-show-chats-menu'` 类,用于应用不同的 CSS 样式 * @param {boolean} [toggle=null] 是否显示小窗口模式,如果为 `true` 则切换为小窗口模式,如果为 `false` 则取消切换小窗口模式,如果为其他值则根据当前的模式自动切换(到另一种模式) * @return {void} */ export const showMobileChatsMenu = (toggle = null) => { if (!isSmallScreen()) { return; } const {classList} = document.body; if (toggle === true) { classList.add('app-show-chats-menu'); } else if (toggle === false) { classList.remove('app-show-chats-menu'); } else { classList.toggle('app-show-chats-menu'); } }; /** * 禁用全局快捷键 * @param {boolean} [disabled=true] 是否禁用全局快捷键,如果为 `false` 则为取消禁用,否则为禁用 * @return {void} */ export const disableGlobalShortcut = (disabled = true) => { isGlobalShortcutDisabled = disabled; unregisterGlobalShortcut(); }; /** * 启用全局快捷键 * @return {void} */ export const enableGlobalShortcut = () => { isGlobalShortcutDisabled = false; registerShortcut(); }; // 监听浏览器地址栏 hash 参数变更事件 window.addEventListener('hashchange', () => { const {hash} = window.location; if (DEBUG) { console.color('➜', 'orangeBg', hash.substr(1), 'orangePale'); } if (hash.includes('/:filterType/')) { window.location.hash = hash.replace('/:filterType/', '/recents/'); } }, false); if (platformUI.onRequestOpenUrl) { platformUI.onRequestOpenUrl((e, url) => { openUrl(url); }); } // 注册更新组件样式命令,触发一个事件来响应命令 registerCommand('updateViewStyle', (context, viewID, style) => { if (viewID) { if (context.options && style === undefined) { ({style} = context.options); } if (typeof style === 'string') { style = JSON.parse(style); } if (style) { if (style.width && typeof style.width === 'number') { style.width = `${style.width}px`; } if (style.height && typeof style.height === 'number') { style.height = `${style.height}px`; } } events.emit(`${EVENT.update_view_style}.${viewID}`, style, context.options); } }); /** * 请求更新指定视图样式 * @param {String} viewID 组件 ID * @param {Object|String} style 样式 */ export const requestUpdateViewStyle = (viewID, style) => { executeCommand('updateViewStyle', viewID, style); }; /** * 绑定 组件更新样式事件 * @param {String} viewID 组件 ID * @param {funcion} listener 事件回调函数 * @return {Symbol} 使用 `Symbol` 存储的事件 ID,用于取消事件 */ export const onUpdateViewStyle = (viewID, listener) => events.on(`${EVENT.update_view_style}.${viewID}`, listener); onLangChange(() => { // 设置默认标题 setTitle(Lang.string('app.title')); }); export default { entryParams, get canQuit() { return !!platformUI.quit; }, isSmallScreen, showMobileChatsMenu, disableGlobalShortcut, enableGlobalShortcut, onAppLinkClick, emitAppLinkClick, quit, showMessger: Messager.show, showContextMenu: ContextMenu.show, modal, reloadWindow, triggerReady, onReady, isAutoLoginNextTime, openUrl, getUrlMeta, openUrlInDialog, openUrlInBrowser, openUrlInApp, requestUpdateViewStyle, };
Tiny-Fendy/koa-structure
frame/config/config.default.js
module.exports = { key: '', port: '8001', session: { maxAge: 86400000 }, mongodb: { enable: false } };
ScenidDev/cube.js
packages/cubejs-query-orchestrator/driver/BaseDriver.js
const { reduce } = require('ramda'); const sortByKeys = (unordered) => { const ordered = {}; Object.keys(unordered).sort().forEach(function(key) { ordered[key] = unordered[key]; }); return ordered; }; const DbTypeToGenericType = { 'timestamp without time zone': 'timestamp', 'integer': 'int', 'character varying': 'text', 'varchar': 'text', 'text': 'text', 'string': 'text', 'boolean': 'boolean', 'bigint': 'bigint', 'time': 'string', 'datetime': 'timestamp', 'date': 'date', 'double precision': 'decimal' }; class BaseDriver { informationSchemaQuery() { return ` SELECT columns.column_name as ${this.quoteIdentifier('column_name')}, columns.table_name as ${this.quoteIdentifier('table_name')}, columns.table_schema as ${this.quoteIdentifier('table_schema')}, columns.data_type as ${this.quoteIdentifier('data_type')} FROM information_schema.columns WHERE columns.table_schema NOT IN ('information_schema', 'mysql', 'performance_schema', 'sys') `; } testConnection() { throw new Error('Not implemented'); } query() { throw new Error('Not implemented'); } downloadQueryResults() { throw new Error('Not implemented'); } readOnly() { return false; } tablesSchema() { const query = this.informationSchemaQuery(); const reduceCb = (result, i) => { let schema = (result[i.table_schema] || {}); let tables = (schema[i.table_name] || []); tables.push({ name: i.column_name, type: i.data_type, attributes: i.key_type ? ['primaryKey'] : [] }); tables.sort(); schema[i.table_name] = tables; schema = sortByKeys(schema); result[i.table_schema] = schema; return sortByKeys(result); }; return this.query(query).then(data => reduce(reduceCb, {}, data)); } createSchemaIfNotExists(schemaName) { return this.query( `SELECT schema_name FROM information_schema.schemata WHERE schema_name = ${this.param(0)}`, [schemaName] ).then((schemas) => { if (schemas.length === 0) { return this.query("CREATE SCHEMA IF NOT EXISTS " + schemaName); } }); } getTablesQuery(schemaName) { return this.query( `SELECT table_name FROM information_schema.tables WHERE table_schema = ${this.param(0)}`, [schemaName] ); } loadPreAggregationIntoTable(preAggregationTableName, loadSql, params, tx) { return this.query(loadSql, params, tx); } dropTable(tableName, tx) { return this.query(`DROP TABLE ${tableName}`, [], tx); } param(/* paramIndex */) { return '?'; } testConnectionTimeout() { return 10000; } async downloadTable(table) { return { rows: await this.query(`SELECT * FROM ${table}`) }; } async uploadTable(table, columns, tableData) { if (!tableData.rows) { throw new Error(`${this.constructor} driver supports only rows upload`); } await this.createTable(table, columns); try { for (let i = 0; i < tableData.rows.length; i++) { await this.query( `INSERT INTO ${table} (${columns.map(c => this.quoteIdentifier(c.name)).join(', ')}) VALUES (${columns.map((c, paramIndex) => this.param(paramIndex)).join(', ')})`, columns.map(c => this.toColumnValue(tableData.rows[i][c.name], c.type)) ); } } catch (e) { await this.dropTable(table); throw e; } } toColumnValue(value, genericType) { return value; } async tableColumnTypes(table) { const [schema, name] = table.split('.'); const columns = await this.query( `SELECT columns.column_name, columns.table_name, columns.table_schema, columns.data_type FROM information_schema.columns WHERE table_name = ${this.param(0)} AND table_schema = ${this.param(1)}`, [name, schema] ); return columns.map(c => ({ name: c.column_name, type: this.toGenericType(c.data_type) })); } createTable(quotedTableName, columns) { return this.query(this.createTableSql(quotedTableName, columns), []); } createTableSql(quotedTableName, columns) { columns = columns.map(c => `${this.quoteIdentifier(c.name)} ${this.fromGenericType(c.type)}`); return `CREATE TABLE ${quotedTableName} (${columns.join(', ')})`; } toGenericType(columnType) { return DbTypeToGenericType[columnType.toLowerCase()] || columnType; } fromGenericType(columnType) { return columnType; } quoteIdentifier(identifier) { return `"${identifier}"`; } } module.exports = BaseDriver;
palikhov/5ET-mirror
js/seo-loader.js
<gh_stars>1-10 window.addEventListener("load", async () => { Renderer.get().setBaseUrl("/"); const fullPage = `${_SEO_PAGE}.html`; const it = await Renderer.hover.pCacheAndGet(fullPage, _SEO_SOURCE, _SEO_HASH); document.title = `${it.name} - 5etools`; $(`.page__title`).text(`${_SEO_PAGE.toTitleCase()}: ${it.name}`); $(`<div class="col-12 ve-flex-vh-center my-2 pt-3"> <button class="btn btn-primary"> <a href="/${_SEO_PAGE}.html" style="font-size: 1.7em; color: white;">${_SEO_STYLE === 1 ? `View All` : `View Complete`} ${_SEO_PAGE.toTitleCase()}</a> </button> </div>`).appendTo($(`#link-page`)); const $wrpContent = $(`#wrp-pagecontent`); const $content = $(`#pagecontent`).addClass("shadow-big").empty(); $(`.nav__link`).each((i, e) => { const $e = $(e); const href = $e.attr("href"); if (!href.startsWith("http") && href.endsWith(".html")) $e.attr("href", `../${href}`); if (href.startsWith("https://wiki.tercept.net")) $e.remove(); }); switch (_SEO_PAGE) { case "spells": $content.append(RenderSpells.$getRenderedSpell(it, {})); break; case "bestiary": { Renderer.utils.bindPronounceButtons(); $content.append(RenderBestiary.$getRenderedCreature(it)); $(`.mon__name--token`).css({paddingRight: 5}); break; } case "items": $content.append(RenderItems.$getRenderedItem(it)); break; // TODO expand this as required // case "races": { // Renderer.utils.bindPronounceButtons(); // break; // } } if (_SEO_FLUFF) { const fluff = await Renderer.hover.pCacheAndGet(`fluff__${fullPage}`, _SEO_SOURCE, _SEO_HASH); if (fluff) { $$`<div class="mt-5 py-2"> ${Renderer.hover.$getHoverContent_fluff(_SEO_PAGE, fluff, null, {isSkipNameRow: true, isSkipPageRow: true}).addClass("shadow-big stats--book stats--book-large")} </div>`.insertAfter($wrpContent); } } });
wjguan/phenocell
clarity/CellTypeDetection/old/phenotypeCells.py
import numpy as np import matplotlib.pyplot as pyplt import clarity.IO as io import cv2, sklearn, os, time, sys import scipy.ndimage.filters as fi import matplotlib.pyplot as pyplt import clarity.Visualization.Plot as plt import multiprocessing as mp from functools import partial from clarity.CellTypeDetection.parallelProcess import kernel def profileCells(centers, searchRadius, marker_channel_img, option='1', sigma = 1.0, threshold=None): # Threshold = some predetermined threshold for determining whether something is a cell? # threshold = also can be a vector of local thresholds for each given cell center # SearchRadius = tuple of cube half length of pixels around the detected cneter over which to sum the intensities # Option 1: Choose an intensity threshold over which we consider it to be a positive cell: global or adaptive threshold # Option 2: Use some kind of adaptive/global histogramming technique to determine a good threshold with a weight map # Option 3: Use some kind of histogramming on the intensities vector itself intensities = [] if option == '2': weight_map = calcGaussianFilter(searchRadius, sigma) else: weight_map = 1 # Pad the image to deal with edge cases marker_channel_img = np.pad(marker_channel_img, ((searchRadius[0],searchRadius[0]),(searchRadius[1],searchRadius[1]),(searchRadius[2],searchRadius[2])), 'reflect') for center in centers: intensity = np.sum(weight_map * marker_channel_img[center[0]:(center[0]+2*searchRadius[0]+1), center[1]:(center[1]+2*searchRadius[1]+1), center[2]:(center[2]+2*searchRadius[2]+1)]) intensities.append(intensity) if option == '1' or option == '2' and threshold is not None: expressionVector = np.asarray(intensities) > threshold elif option == '3': # Use clustering on the options means, expressionVector = sklearn.cluster.k_means(np.expand_dims(np.asarray(intensities),axis=1), 3) label = np.argwhere(means == np.amax(means))[0] expressionVector = (expressionVector == label) print(label, means[label]) else: raise RuntimeError('Enter a valid option (1,2,3)') return expressionVector def calcGaussianFilter(searchRadius, sigma=1.0): x,y,z = searchRadius inp = np.zeros((2*x+1,2*y+1,2*z+1)) inp[x,y,z] = 1 weight_map = fi.gaussian_filter(inp,sigma) weight_map = weight_map / np.amax(weight_map) return weight_map def calcThreshold(marker_channel_img, searchRadius, percent): ## Calculate waht the threshold should be for option 1 # pyplt.hist(marker_channel_img.ravel()) # pyplt.show() x,y,z = searchRadius threshold = np.percentile(marker_channel_img, percent)*(2*x+1)*(2*y+1)*(2*z+1) print("Threshold:",threshold) return threshold def calcAdaptiveThreshold(marker_channel_img, searchRadius, percent, centers, localArea): ## Calculate an adaptive threshold based on local images # Serial version of the code # localArea: (x,y,z) = histogram area for local thresholding. if just one value, assume it's just z # Returns a vector of thresholds start = time.time() xr, yr, zr = searchRadius if isinstance(localArea, int): z = localArea elif len(localArea) == 2: x = localArea[0]; y = localArea[0]; z = localArea[1] elif len(localArea) == 3: x = localArea[0]; y = localArea[1]; z = localArea[2] threshold = [] for center in centers: if isinstance(localArea, int): newimg = marker_channel_img[:,:,max(0,center[2]-z):min(marker_channel_img.shape[2],center[2]+z)] else: newimg = marker_channel_img[max(0,center[0]-x):min(marker_channel_img.shape[0],center[0]+x), max(0,center[1]-y):min(marker_channel_img.shape[1],center[1]+y), max(0,center[2]-z):min(marker_channel_img.shape[2],center[2]+z)] threshold.append(np.percentile(newimg, percent)*(2*xr+1)*(2*yr+1)*(2*zr+1)) print("Adaptive threshold took %f seconds" %(time.time()-start)) return threshold def parallel_calcAdaptiveThreshold(marker_channel_img, searchRadius, percent, points, localArea, num_workers): # Parallel kernel for doing this start = time.time() g = mp.Pool(num_workers) func = partial(kernel, marker_channel_img, searchRadius, percent, localArea) threshold = g.map(func, points) g.close() g.join() return threshold def calcImageShape(DataFile): img_shape = np.array([0,0,0]) r = {'x':all,'y':[0,1],'z':[0,1]} tempImg = io.readData(DataFile, **r) img_shape[0] = tempImg.shape[0] r = {'x':[0,1],'y':all,'z':[0,1]} tempImg = io.readData(DataFile, **r) img_shape[1] = tempImg.shape[1] r = {'x':[0,1],'y':[0,1],'z':all} tempImg = io.readData(DataFile, **r) img_shape[2] = tempImg.shape[2] return img_shape def main(ResultDirectory, DataFile, searchRadius, percent, sigma, option, thresholdType, localArea, num_workers, DataFileRange=[{'x':all,'y':all,'z':all}],save_cells=True): bdir = lambda f: os.path.join(ResultDirectory, f) finalPoints = np.array([[0,0,0]]) for ValRange in DataFileRange: # list of dictionaries points = io.readPoints(bdir(r'spots_filtered.npy'),**ValRange) new_points = points.copy() # so we can modify this # account for if we load in the middle of the image: if ValRange['x'] is not all or ValRange['y'] is not all or ValRange['z'] is not all: img_shape = calcImageShape(DataFile) newValRange = ValRange.copy() if ValRange['x'] is not all: # Change the range for which we load image which will be larger by the searchRadius newValRange['x'] = [max(0,ValRange['x'][0]-searchRadius[0]),min(img_shape[0], ValRange['x'][1]+searchRadius[0]+1)] new_points[:,0] = points[:,0] - newValRange['x'][0] if ValRange['y'] is not all: newValRange['y'] = [max(0,ValRange['y'][0]-searchRadius[1]),min(img_shape[1], ValRange['y'][1]+searchRadius[1]+1)] new_points[:,1] = points[:,1] - newValRange['y'][0] if ValRange['z'] is not all: newValRange['z'] = [max(0,ValRange['z'][0]-searchRadius[2]),min(img_shape[2], ValRange['z'][1]+searchRadius[2]+1)] new_points[:,2] = points[:,2] - newValRange['z'][0] else: newValRange = ValRange.copy() marker_channel_img = io.readData(DataFile,**newValRange) if thresholdType == 'global': threshold=calcThreshold(marker_channel_img, searchRadius, percent) elif thresholdType == 'adaptive': # Make parallel for faster run time. # threshold=parallel_calcAdaptiveThreshold(marker_channel_img, searchRadius, percent, new_points, localArea, num_workers) threshold=calcAdaptiveThreshold(marker_channel_img, searchRadius, percent, new_points, localArea) # Serial version of code expressionVector = profileCells(new_points, searchRadius, marker_channel_img, option=option,sigma=sigma,threshold=threshold) expressedPoints = points[np.argwhere(np.asarray(expressionVector))] expressedPoints = np.squeeze(expressedPoints, axis=1) #print('Number of positive cells:',expressedPoints.shape[0]) finalPoints = np.concatenate((finalPoints, expressedPoints),axis=0) if save_cells: np.save(bdir('positive_cells.npy'),finalPoints[1:,:]) return finalPoints[1:,:]
facug91/OJ-Solutions
icpcarchive.ecs.baylor.edu/Exploration.cpp
/* By: facug91 From: https://icpcarchive.ecs.baylor.edu/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=4909 Name: Exploration Date: 28/04/2016 */ #include <bits/stdc++.h> #define endl "\n" #define next sbjkdfh329re9fdshfd98fyh #define EPS 1e-9 #define MP make_pair #define F first #define S second #define DB(x) cerr << " #" << (#x) << ": " << (x) #define DBL(x) cerr << " #" << (#x) << ": " << (x) << endl const double PI = acos(-1.0); #define INF 1000000000 //#define MOD 1000000007ll #define MAXN 100000005 using namespace std; typedef long long ll; typedef unsigned long long llu; typedef pair<int, int> ii; typedef pair<ii, ii> iiii; typedef vector<int> vi; typedef vector<ii> vii; typedef vector<iiii> viiii; int n, k, f, degree[2005], u, v, ans; vector<int> adj[2005]; bool vis[2005]; int main () { #ifdef ONLINE_JUDGE ios_base::sync_with_stdio(0); cin.tie(0); #endif //cout<<fixed<<setprecision(2); cerr<<fixed<<setprecision(2); //cin.ignore(INT_MAX, ' '); //cout << setfill('0') << setw(5) int tc = 1, i, j; cin>>tc; while (tc--) { cin>>n>>k>>f; for (i=0; i<n; i++) adj[i].clear(); memset(degree, 0, sizeof degree); while (f--) { cin>>u>>v; u--; v--; adj[u].push_back(v); adj[v].push_back(u); degree[u]++; degree[v]++; } memset(vis, 0, sizeof vis); bool in = true; while (in) { int minId = -1, minD = INT_MAX; for (i=0; i<n; i++) { if (!vis[i] && minD > degree[i]) { minId = i; minD = degree[i]; } } if (minId == -1 || minD >= k) break; for (int v : adj[minId]) { if (!vis[v]) degree[v]--; } degree[minId] = 0; vis[minId] = true; } ans = 0; for (i=0; i<n; i++) if (!vis[i]) ans++; cout<<ans<<endl; } return 0; }
ebridfighter/mrgong-store
app/src/main/java/uk/co/ribot/androidboilerplate/ui/activity/OrderCommitSuccessActivity.java
package uk.co.ribot.androidboilerplate.ui.activity; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.View; import java.util.ArrayList; import java.util.List; import javax.inject.Inject; import butterknife.BindView; import butterknife.ButterKnife; import uk.co.ribot.androidboilerplate.R; import uk.co.ribot.androidboilerplate.data.model.net.response.OrderListResponse; import uk.co.ribot.androidboilerplate.injection.module.ActivityModule; import uk.co.ribot.androidboilerplate.ui.adapter.OrderCommitAdapter; import uk.co.ribot.androidboilerplate.ui.adapter.base.BaseAdapter; import uk.co.ribot.androidboilerplate.ui.base.BaseActivity; import uk.co.ribot.androidboilerplate.ui.base.MvpView; import uk.co.ribot.androidboilerplate.ui.presenter.CommonPresenter; public class OrderCommitSuccessActivity extends BaseActivity implements MvpView { @Inject OrderCommitAdapter mOrderCommitAdapter; @BindView(R.id.rv_order_commit_sucess) RecyclerView mRvOrderCommitSucess; @Inject CommonPresenter mCommonPresenter; public static final String INTENT_KEY_ORDERS = "intent_key_orders"; public static final String INTENT_KEY_TYPE = "intent_key_type"; private static final int REQ_ACT_UPLOAD = 0x1234; private List<OrderListResponse.ListBean> mListOrders; public static Intent getStartIntent(Context context, int type, ArrayList<OrderListResponse.ListBean> listOrders) { Intent intent = new Intent(context, OrderCommitSuccessActivity.class); intent.putExtra(INTENT_KEY_TYPE, type); intent.putExtra(INTENT_KEY_ORDERS, listOrders); return intent; } private int mType; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_order_commit_success); ButterKnife.bind(this); showBackBtn(); configPersistentComponent.orderCommitSuccessActivityComponent(new ActivityModule(this)).inject(this); mType = getIntent().getIntExtra(INTENT_KEY_TYPE, -1); mListOrders = (List<OrderListResponse.ListBean>) getIntent().getSerializableExtra(INTENT_KEY_ORDERS); setTitle(mType == 0 ? getString(R.string.title_modify_order_success) : getString(R.string.title_place_order_success)); mCommonPresenter.attachView(this); mOrderCommitAdapter.setCanSeePrice(mCommonPresenter.canSeePrice()); mOrderCommitAdapter.setType(mType); if (mListOrders.get(0).getOrderSettleName().contains("单次结算")){ mOrderCommitAdapter.setShowUploadButton(true); }else{ mOrderCommitAdapter.setShowUploadButton(false); } if (mListOrders.get(0).getOrderSettleName().contains("先付款后收货")&&mListOrders.get(0).getOrderSettleName().contains("单次结算")){ mOrderCommitAdapter.setShowUploadButton(true); } mOrderCommitAdapter.setData(mListOrders); mOrderCommitAdapter.setOnChildItemClickListener(new BaseAdapter.OnChildItemClickListener() { @Override public void onItemClick(View childView, int position) { // Intent uIntent = new Intent(getActivityContext(), UploadPayedPicActivity.class); // uIntent.putExtra("orderid", bean.getOrderID()); // uIntent.putExtra("ordername", bean.getName()); // uIntent.putExtra("hasattachment", type == 0); // startActivityForResult(uIntent, REQ_ACT_UPLOAD); if (childView.getId() == R.id.tv_order_action){ startActivity(OrderDetailActivity.getStartIntent(getActivityContext(), mListOrders.get(position).getOrderID())); } } }); mRvOrderCommitSucess.setLayoutManager(new LinearLayoutManager(this)); mRvOrderCommitSucess.setAdapter(mOrderCommitAdapter); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if(requestCode==REQ_ACT_UPLOAD && resultCode==200 && data.getBooleanExtra("upload_success",false)){ finish(); } } }
mike-n-jordan/mopub-android-sdk
mopub-sdk/mopub-sdk-base/src/main/java/com/mopub/mobileads/MoPubError.java
<filename>mopub-sdk/mopub-sdk-base/src/main/java/com/mopub/mobileads/MoPubError.java<gh_stars>1-10 // Copyright 2018-2020 Twitter, Inc. // Licensed under the MoPub SDK License Agreement // http://www.mopub.com/legal/sdk-license-agreement/ package com.mopub.mobileads; /** * Temporary solution, this interface will be removed in the next major release */ @Deprecated public interface MoPubError { int ER_SUCCESS = 0; int ER_ADAPTER_NOT_FOUND = 1; int ER_TIMEOUT = 2; int ER_INVALID_DATA = 3; int ER_UNSPECIFIED = 10000; /** * {@link MoPubErrorCode} and NativeErrorCode must implement this function to map * enum value to server error code value * @return ER_* constant value */ int getIntCode(); }
lriki/Lumino
lumino/Graphics/include/LuminoGraphics/Rendering/Kanata/KDrawCommand.hpp
#pragma once #include <LuminoCore/Base/LinearAllocator.hpp> #include "Common.hpp" #include "KPipelineState.hpp" namespace ln { namespace kanata { enum class DrawCommandType { BeginRenderPass, EndRenderPass, DrawPrimitive, }; struct IDrawCommand { DrawCommandType type; }; struct BeginRenderPassCommand final : public IDrawCommand { RenderPass* renderPass; }; struct EndRenderPassCommand final : public IDrawCommand { RenderPass* renderPass; }; // RenderPass 間での使いまわしは無し。 // GeometryPath と ShaderPass では別々の DrawCommand を使う。 struct DrawCommand final : public IDrawCommand { std::array<VertexBuffer*, detail::MaxVertexStreams> vertexBuffers; IndexBuffer* indexBuffer; // Material によるユーザー指定のステートや、RenderPass 固有のステートを統合したもの。 // UE4 では FGraphicsMinimalPipelineStateId として持っていて // ApplyViewOverridesToMeshDrawCommands で ID の発行が行われているようだが、 // その時点ではまだ RenderPass は確定していないため RHIPipelineState を作ることはできない。 // 単にメモリ量削減のためのキャッシュと思われる PipelineState pipelineState; ShaderPass* shaderPass; ShaderDescriptor* shaderDescriptor; int32_t firstIndex; // Indexed only int32_t firstVertex; // No indexed only int32_t primitiveCount; int32_t instanceCount; uint8_t stencilRef; }; class DrawCommandList final : public URefObject { public: DrawCommandList(detail::RenderingManager* manager); void clear(); template<class TBatch, class... TArgs> TBatch* newCommand(TArgs&&... args) { void* buffer = m_dataAllocator->allocate(sizeof(TBatch)); TBatch* data = new (buffer) TBatch(std::forward<TArgs>(args)...); addCommand(data); return data; } void submitMeshDrawCommands(GraphicsCommandList* commandList); private: void addCommand(IDrawCommand* command); void submitMeshDrawCommand(GraphicsCommandList* commandList, const IDrawCommand* command); Ref<detail::LinearAllocator> m_dataAllocator; Array<IDrawCommand*> m_commandList; // TODO: LinkedList のほうがいいか? }; } // namespace kanata } // namespace ln
benhunter/py-stuff
misc/ringzer0-patterniskey.py
""" \x1c\x1e\x1e\x71\x14\x2a\x66\x40\x1c\x1e\x1e\x71\x14\x2a\x66\x40 \x7d\x04\x03\x58\x6a\x53\x52\x59\x7e\x01\x07\x0f\x32\x5c\x19\x06 \x05\x77\x71\x67\x35\x02\x12\x59\x78\x50\x50\x06\x75\x46\x0c\x40 \x77\x7f\x72\x70\x75\x46\x0c\x40 \x1c\x1e\x1e\x71\x14\x2a\x66\x40\x1c\x1e\x1e\x71\x14\x2a\x66\x40\x7d\x04\x03\x58\x6a\x53\x52\x59\x7e\x01\x07\x0f\x32\x5c\x19\x06\x05\x77\x71\x67\x35\x02\x12\x59\x78\x50\x50\x06\x75\x46\x0c\x40\x77\x7f\x72\x70\x75\x46\x0c\x40 0x1c0x1e0x1e0x710x140x2a0x660x400x1c0x1e0x1e0x710x140x2a0x660x400x7d0x040x030x580x6a0x530x520x590x7e0x010x070x0f0x320x5c0x190x060x050x770x710x670x350x020x120x590x780x500x500x060x750x460x0c0x400x770x7f0x720x700x750x460x0c0x40 """ # ciphertext = '0x1c0x1e0x1e0x710x140x2a0x660x400x1c0x1e0x1e0x710x140x2a0x660x400x7d0x040x030x580x6a0x530x520x590x7e0x010x070x0f0x320x5c0x190x060x050x770x710x670x350x020x120x590x780x500x500x060x750x460x0c0x400x770x7f0x720x700x750x460x0c0x40' ciphertext = '\x1c\x1e\x1e\x71\x14\x2a\x66\x40\x1c\x1e\x1e\x71\x14\x2a\x66\x40\x7d\x04\x03\x58\x6a\x53\x52\x59\x7e\x01\x07\x0f\x32\x5c\x19\x06\x05\x77\x71\x67\x35\x02\x12\x59\x78\x50\x50\x06\x75\x46\x0c\x40\x77\x7f\x72\x70\x75\x46\x0c\x40' import binascii print(ciphertext) print(type(ciphertext)) print(len(ciphertext)) print(ciphertext[0]) print(type(ciphertext[0])) print(ciphertext[0] == b'\x1c') # print(len(ciphertext[0])) # for block in range(len(ciphertext)/8): # print(ciphertext[block+:block+8]) print(ciphertext[0:8]) print(ciphertext[8:16]) print(ciphertext[16:24]) print(ciphertext[24:32]) print(ciphertext[32:40]) print(ciphertext[40:48]) print(ciphertext[48:56]) # binascii.unhexlify('\x01\x03') print('#######################') x = b'a' x = binascii.hexlify(x) y = str(x, 'ascii') print(x) print(y) x = binascii.unhexlify(x) print(x) print('#######################') short = b'\x1c\x1e\x1e\x71\x14\x2a\x66\x40' print(short.decode('utf-8')) # binascii.unhexlify(short)
jamhocken/aoc-2020
day18/python/asung/solution.py
#!/usr/bin/env python3 import math import os import re class Puzzle: def __init__(self, filepath: str) -> None: """Read input file at filepath as a list of stripped strings.""" with open(filepath, 'r') as text_file: self.lines = [line.rstrip() for line in text_file.readlines()] @staticmethod def apply(operator: str, operand1: int, operand2: int) -> str: """Return result of operator applied on operand1 and operand2.""" if operator == '+': return str(operand1 + operand2) if operator == '*': return str(operand1 * operand2) raise NotImplementedError("Invalid operator: {operator}") @classmethod def different_math(cls, line: str) -> str: # First recursively resolve terms in parantheses. while ')' in line: right_index = line.index(')') left_index = line.rindex('(', 0, right_index) line = line[:left_index] + cls.different_math(line[left_index+1:right_index]) + line[right_index+1:] # Split remaining sequence and apply operators sequentially. tokens = line.split() while len(tokens) > 1: tokens = [cls.apply(tokens[1], int(tokens[0]), int(tokens[2]))] + tokens[3:] return "".join(tokens) @classmethod def advanced_math(cls, line: str) -> str: # First recursively resolve terms in parantheses. while ')' in line: right_index = line.index(')') left_index = line.rindex('(', 0, right_index) line = line[:left_index] + cls.advanced_math(line[left_index+1:right_index]) + line[right_index+1:] # Then resolve additions. while '+' in line: # Match any * and their left-sided operands, followed by + and its operands, then the rest. match_result = re.match(r'((?:\d+\s*\*\s*)*)(\d+)\s*\+\s*(\d+)([\d\s\+\*]*)', line) if match_result: line = match_result.group(1) + str(int(match_result.group(2)) + int(match_result.group(3))) + match_result.group(4) else: raise ArithmeticError(f"Cannot parse: {line}") # Finally resolve multiplications. tokens = line.split() return str(math.prod(int(token) for index, token in enumerate(tokens) if index % 2 == 0)) def solve_part1(self) -> int: return sum(int(self.different_math(line)) for line in self.lines) def solve_part2(self) -> int: return sum(int(self.advanced_math(line)) for line in self.lines) if __name__ == "__main__": solver = Puzzle(os.path.join(os.path.dirname(__file__), "input.txt")) print(solver.solve_part1()) print(solver.solve_part2())
ut-osa/syncchar
linux-2.6.16-unmod/include/asm-ia64/scatterlist.h
<reponame>ut-osa/syncchar #ifndef _ASM_IA64_SCATTERLIST_H #define _ASM_IA64_SCATTERLIST_H /* * Modified 1998-1999, 2001-2002, 2004 * <NAME> <<EMAIL>>, Hewlett-Packard Co */ struct scatterlist { struct page *page; unsigned int offset; unsigned int length; /* buffer length */ dma_addr_t dma_address; unsigned int dma_length; }; /* * It used to be that ISA_DMA_THRESHOLD had something to do with the * DMA-limits of ISA-devices. Nowadays, its only remaining use (apart * from the aha1542.c driver, which isn't 64-bit clean anyhow) is to * tell the block-layer (via BLK_BOUNCE_ISA) what the max. physical * address of a page is that is allocated with GFP_DMA. On IA-64, * that's 4GB - 1. */ #define ISA_DMA_THRESHOLD 0xffffffff #endif /* _ASM_IA64_SCATTERLIST_H */
balu3083/neotree-android-2018
app/src/main/java/org/neotree/event/RefreshSessionListEvent.java
package org.neotree.event; /** * Created by matteo on 15/11/2016. */ public class RefreshSessionListEvent { }
p-maraver/NeuroMorphoLiterature
Search/src/main/java/org/neuromorpho/literature/search/service/PortalSearchFactory.java
/* * Copyright (c) 2015-2022, <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.neuromorpho.literature.search.service; import org.neuromorpho.literature.search.service.pubmed.PortalSearchPubMedService; import org.neuromorpho.literature.search.service.sciencedirect.PortalSearchScienceDirectService; import org.neuromorpho.literature.search.service.springernature.PortalSearchSpringerNatureService; import org.neuromorpho.literature.search.service.wiley.PortalSearchWileyService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @Component() public class PortalSearchFactory { private final Logger log = LoggerFactory.getLogger(this.getClass()); @Autowired private PortalSearchPubMedService portalSearchPubMedService; @Autowired private PortalSearchSpringerNatureService portalSearchSpringerNatureService; @Autowired private PortalSearchScienceDirectService portalSearchScienceDirectService; @Autowired private PortalSearchWileyService portalSearchWileyService; @Autowired private PortalSearchGoogleScholarService portalSearchGoogleScholarService; public IPortalSearch launchPortalSearch(String portalName) throws Exception { // sets the property for selenium log.debug("Creating the object for portal: " + portalName); if (portalName.equalsIgnoreCase("PubMed") || portalName.equalsIgnoreCase("PubMedCentral")) { return portalSearchPubMedService; } else if (portalName.equalsIgnoreCase("SpringerNature")) { return portalSearchSpringerNatureService; } else if (portalName.equalsIgnoreCase("ScienceDirect")) { return portalSearchScienceDirectService; } else if (portalName.equalsIgnoreCase("Wiley")) { return portalSearchWileyService; } else if (portalName.equalsIgnoreCase("GoogleScholar")) { return portalSearchGoogleScholarService; } else { log.warn("Unsuported Portal: " + portalName); } return null; } }
AntoniosKalattas/Ping_rep
gui/node_modules/core-js/modules/esnext.reflect.metadata.js
<filename>gui/node_modules/core-js/modules/esnext.reflect.metadata.js version https://git-lfs.github.com/spec/v1 oid sha256:8308bf011e29ba64557adde57df7bf20290fff7290425a351344cee060f84c58 size 605
zhangyanwei/wechat-client
src/main/java/com/github/zhangyanwei/wechat/module/respond/impl/WxTextMessageResponder.java
package com.github.zhangyanwei.wechat.module.respond.impl; import com.github.zhangyanwei.wechat.module.respond.MessagePassiveResponder; import com.github.zhangyanwei.wechat.module.respond.RespondException; import com.github.zhangyanwei.wechat.module.respond.model.WxTransferCustomerServiceMessage; import com.github.zhangyanwei.wechat.module.respond.MessageResponderType; import com.github.zhangyanwei.wechat.module.respond.model.WxMessage; import com.github.zhangyanwei.wechat.module.respond.model.WxTextMessage; import org.springframework.stereotype.Component; import java.util.Collections; import java.util.Date; import java.util.List; import static com.github.zhangyanwei.wechat.module.respond.model.WxMessageType.TEXT; import static com.github.zhangyanwei.wechat.module.respond.model.WxMessageType.TRANSFER_CUSTOMER_SERVICE; @Component @MessageResponderType(TEXT) public class WxTextMessageResponder implements MessagePassiveResponder { @Override public WxMessage respond(WxMessage message) throws RespondException { WxTextMessage textMessage = (WxTextMessage) message; List<String> keywords = Collections.emptyList(); boolean matched = keywords.stream().anyMatch(keyword -> textMessage.getContent().contains(keyword)); if (matched) { WxTextMessage responseMessage = new WxTextMessage(); fill(responseMessage, textMessage); responseMessage.setMessageType(TEXT); responseMessage.setContent("如果您有任何的建议或者疑问,欢迎致电 400-876-1369。"); return responseMessage; } // do not specify the customer service account. WxTransferCustomerServiceMessage transferCustomerServiceMessage = new WxTransferCustomerServiceMessage(); fill(transferCustomerServiceMessage, textMessage); transferCustomerServiceMessage.setMessageType(TRANSFER_CUSTOMER_SERVICE); return transferCustomerServiceMessage; } private void fill(WxMessage message, WxMessage receiveMessage) { message.setFromUserName(receiveMessage.getToUserName()); message.setToUserName(receiveMessage.getFromUserName()); message.setCreateTime(new Date()); } }
Hoommus/iscaribot
src/main/java/features/commands/commands/ConfigCommand.java
<gh_stars>1-10 package features.commands.commands; import features.commands.annotations.SubCommand; import features.commands.events.CommandEvent; import model.entities.EnhancedGuild; import model.dbfields.BotFeatures; import model.dbfields.BotMessages; import net.dv8tion.jda.core.EmbedBuilder; import net.dv8tion.jda.core.Permission; import net.dv8tion.jda.core.Region; import net.dv8tion.jda.core.entities.*; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import providers.EnhancedGuildsProvider; import providers.EnhancedUsersProvider; import java.util.*; import java.util.stream.Collectors; import static features.commands.utils.JDACustomUtilities.findRole; import static features.commands.utils.JDACustomUtilities.findTextChannel; import static features.commands.commands.Colors.*; public class ConfigCommand extends AbstractCommand { private static final Logger LOGGER = LogManager.getLogger(ConfigCommand.class); private static final EnhancedGuildsProvider ENHANCED_GUILDS_PROVIDER = EnhancedGuildsProvider.getInstance(); private static final EnhancedUsersProvider ENHANCED_USERS_PROVIDER = EnhancedUsersProvider.getInstance(); public ConfigCommand() { this.name = "config"; this.aliases = new String[]{"cfg", "conf"}; this.description = "command used for simple config"; this.argsCount = -1; this.memberPermissions = new Permission[]{Permission.MANAGE_SERVER}; } public ConfigCommand(String name, String description, String[] aliases, boolean usesTransliteration, int argsCount) { super(name, description, aliases, usesTransliteration, argsCount); } // TODO: Rewrite this shit @Override public void execute(CommandEvent event) { LOGGER.traceEntry(); final Message message = event.getMessage(); final MessageChannel currentChannel = event.getChannel(); final String messageContent = message.getContentRaw().trim().replaceAll("(?: )+", " "); final EnhancedGuild enhancedGuild = event.getEnhancedGuild(); final EmbedBuilder embedResponse = new EmbedBuilder(); embedResponse.setColor(NEUTRAL); final LinkedList<String> args = event.getArgs(); if(args.size() == 0) { printHelp(event); } else if (args.get(0).equals("welcome")) { if(args.get(1).equals("help")) { embedResponse.setTitle("Помощь для команды `config welcome`").setDescription( "`welcome [help]` - вывод данного сообщения" + "\n`welcome status` - вывод текущей конфигурации." + "\n`welcome set channel <канал>` - установка канала для приветствий. " + "В качестве аргумента <канал> может быть название, \"упоминание\" канала или его ID. " + "Если найдено больше 1 канала, установлен будет первый попавшийся." + "\n`welcome set message <сообщение>` - установка сообщения для приветствия. " + "\nДоступны переменные `${usermention}`, `${servername}`. " + "\nВ качестве сообщения принимается всё в точности так, как идёт после \"`message`\", " + "никаких дополнительных скобок и знаков не требуется."); } else if (args.get(1).equalsIgnoreCase("status")) { embedResponse.setDescription("Канал для приветствий: <#" + enhancedGuild.getWelcomeChannel().getId() + ">" + "\nСообщение: \"" + enhancedGuild.getWelcomeMessage() + "\""); } else if (args.get(1).equalsIgnoreCase("message")) { embedResponse.setDescription("Канал для приветствий: <#" + enhancedGuild.getWelcomeChannel().getId() + ">" + "\nСообщение: \"" + enhancedGuild.getWelcomeMessage() + "\""); } else if (args.get(1).equals("set")) { if(args.get(2).equalsIgnoreCase("channel")) { TextChannel old = enhancedGuild.getWelcomeChannel(); enhancedGuild.setWelcomeChannel(findTextChannel(enhancedGuild, args.get(3))); if (enhancedGuild.getWelcomeChannel().getIdLong() != old.getIdLong()) embedResponse.setColor(SUCCESS).addField(":white_check_mark: Установлен канал для приветствий: ", enhancedGuild.getWelcomeChannel().getName(), false); } else if (args.get(2).equalsIgnoreCase("message")) { String finalMessage = messageContent.substring(messageContent.indexOf(args.get(3)), messageContent.length() - 1); enhancedGuild.setWelcomeMessage(finalMessage); embedResponse.setColor(SUCCESS).addField(":white_check_mark: Установлено приветствие", finalMessage, false); } } else { embedResponse.setColor(FAILURE).setDescription(":x: Команда не найдена: " + args.get(1) + " " + args.get(2)); } } else if (args.get(0).equalsIgnoreCase("verify")) { if (args.size() == 1 || args.get(1).equalsIgnoreCase("help")) { embedResponse.setTitle("Помощь для команды `config verify`").setDescription( "`verify [help]` - вывод данного сообщения" + "\n`verify status` - вывод текущей конфигурации." + "\n`verify disable` - отключение верификации. Конфигурация сохранится до следующего подключения." + "\n`verify enable` - подключение верификации. Будет использована старая конфигурация. Чтобы узнать её, напишите `!!cfg verify status`" + "\n`verify set channel <канал>` - установка канала для прослушки ссылок команды `verify`. " + "В качестве аргумента <канал> может быть название, \"упоминание\" канала или его ID. " + "Если найдено больше 1 канала, установлен будет первый попавшийся." + "\n`verify set role <роль1> ...` - установка ролей, которые присваиваются после верификации. " + "Указывать частично или полностью названия или ID через пробел." + "\n`verify set delay <целое число>` - установка времени в секундах, спустя которое фактически присваиваются роли. " + "'0' по-умолчанию." + "\n`verify set timeout <целое число>` - установка времени в часах, дающееся пользователю для предоставления ссылки. " + "Значения 0 и меньше - отключение кика по таймауту." + "\n`verify set message <сообщение>` - установка сообщения после успешной верификации. " + "Доступные переменные ${usermention}, ${servername}."); } else if (args.get(1).equalsIgnoreCase("status")) { embedResponse.setTitle("Текущая конфигурация модуля верификации:").setDescription( "Канал для верификации: <#" + enhancedGuild.getVerificationChannel().getId() + ">" + "\nРоли, выдающиеся при успешной верификации: " + (enhancedGuild.getVerificationRolesString() == null ? "Отсутствуют" : enhancedGuild.getVerificationRolesString()) + "\n"); } else if (args.get(1).equalsIgnoreCase("disable")) { enhancedGuild.setBotFeaturesDisabled(BotFeatures.WikiaVerification, BotFeatures.UserVerificationCleanup, BotFeatures.UserVerificationTimeout, BotFeatures.UserVerificationNotify); embedResponse.setColor(SUCCESS).setDescription(":white_check_mark: Верификация полностью отключена."); } else if (args.get(1).equalsIgnoreCase("enable")) { enhancedGuild.setBotFeaturesEnabled(BotFeatures.WikiaVerification, BotFeatures.UserVerificationCleanup, BotFeatures.UserVerificationTimeout, BotFeatures.UserVerificationNotify); embedResponse.setColor(SUCCESS).setDescription(":white_check_mark: Верификация полностью подключена."); } else if (args.get(1).equals("set")) { if(args.size() == 2) { embedResponse.setColor(FAILURE).setDescription("Укажите параметр для установки.\nПомощь: `!!cfg verify help`"); } else if (args.get(2).equalsIgnoreCase("channel")) { long oldId = enhancedGuild.getVerificationChannel().getIdLong(); enhancedGuild.setVerificationChannel(findTextChannel(enhancedGuild, args.get(3))); if (enhancedGuild.getVerificationChannel().getIdLong() != oldId) embedResponse.setColor(SUCCESS).setDescription(":white_check_mark: Установлен канал для верификации: <#" + enhancedGuild.getVerificationChannel().getId() + ">"); } else if (args.get(2).equalsIgnoreCase("role")) { ArrayList<Role> oldRoles = enhancedGuild.getVerificationRoles(); for (int i = 2; i < args.size(); i++) { Role role = findRole(enhancedGuild, args.get(i)); enhancedGuild.addVerificationRole(role); } if (Collections.disjoint(enhancedGuild.getVerificationRoles(), oldRoles)) embedResponse.setColor(SUCCESS).setDescription(":white_check_mark: Установлены роли для верификации: " + String.join(" ", enhancedGuild.getVerificationRoles().stream().map(Role::getName).toArray(String[]::new))); } else if (args.get(2).equalsIgnoreCase("delay")) { } else if (args.get(2).equalsIgnoreCase("timeout")) { try { int timeout = Integer.parseInt(args.get(3)); enhancedGuild.setVerificationTimeout(timeout); } catch (NumberFormatException e) { } } else { embedResponse.setColor(FAILURE).setDescription(":x: Параметр не найден: " + args.get(1) + " " + args.get(2)); } } else { embedResponse.setColor(FAILURE).setDescription(":x: Команда не найдена: " + args.get(0) + " " + args.get(1)); } } else if (args.get(0).equalsIgnoreCase("locale")) { if (args.size() == 1 || args.get(1).equalsIgnoreCase("help")) { embedResponse.setTitle("Помощь для `config locale`:").setDescription( "`locale list` - вывод списка доступных локалей (языков) стандартных сообщений." + "\n`locale set <locale>` - установка локали (языка) стандартных сообщений бота. Например, русский, ru_RU, uk_UA, en." + "\n`locale reset` - автоматический выбор языка. Если сервер использует регион \"Россия,\" будет выбран русский язык."); } else if (args.get(1).equalsIgnoreCase("list") || args.get(1).equalsIgnoreCase("--list")) { embedResponse.setTitle("Available locales:").setDescription("English - en\nРусский (Russian) - ru_RU\nУкраїнська (Ukrainian) - ua"); } else if (args.get(1).toLowerCase().equals("set")) { String old = enhancedGuild.getLocaleString(); switch (args.get(2).toLowerCase()) { case "ru": case "ru_ru": case "russian": case "русский": enhancedGuild.setLocale(new Locale("ru", "RU")); break; case "ua": case "ukrainian": case "uk_ua": case "українська": enhancedGuild.setLocale(new Locale("uk", "UA")); break; case "en": case "en_en": case "en_us": case "en_uk": case "english": case "default": enhancedGuild.setLocale(Locale.ENGLISH); break; } if(!old.equals(enhancedGuild.getLocaleString())) embedResponse.setColor(SUCCESS).setDescription(":white_check_mark: Установлен язык: " + enhancedGuild.getLocaleReadable()); } else if (args.get(1).equalsIgnoreCase("status")) { embedResponse.setDescription("Текущий язык: " + enhancedGuild.getLocaleReadable()); } else if (args.get(1).equalsIgnoreCase("reset") || args.get(1).equalsIgnoreCase("restore")) { enhancedGuild.setLocale(enhancedGuild.getRegion() == Region.RUSSIA ? new Locale("ru", "RU") : Locale.ENGLISH); } else { embedResponse.setColor(FAILURE).setDescription(":x: Команда не найдена: " + args.get(1)); } } else if (args.get(0).equalsIgnoreCase("prefix")) { if(args.size() == 0) { embedResponse.setColor(NEUTRAL).setDescription("Команда для конфигурации префикса."); } else if (args.get(1).equalsIgnoreCase("reset")) { enhancedGuild.setCommandPrefix("!!"); embedResponse.setColor(SUCCESS).setDescription(":white_check_mark: Установлен префикс: `!!`"); } else if (args.get(1).equalsIgnoreCase("set") && args.get(2).length() <= 3) { enhancedGuild.setCommandPrefix(args.get(2)); embedResponse.setColor(SUCCESS).setDescription(":white_check_mark: Установлен префикс: `" + args.get(2) + "`"); } else if (args.get(1).length() > 3) { embedResponse.setColor(FAILURE).setDescription(":x: Префикс не может быть длиннее трех символов."); } else { embedResponse.setColor(FAILURE).setDescription(":x: Команда не найдена: " + args.get(1) + " " + args.get(2)); } } else { embedResponse.setColor(FAILURE).setDescription(":x: Команда не найдена: " + args.get(0)); } if( ! embedResponse.equals(new EmbedBuilder())) currentChannel.sendMessage(embedResponse.build()).queue(); ENHANCED_GUILDS_PROVIDER.update(enhancedGuild); } @Override @SubCommand(subCommand = "help", aliases = {"-h", "--help"}) public void printHelp(CommandEvent event) { final EmbedBuilder embedResponse = new EmbedBuilder(); embedResponse .setColor(NEUTRAL) .setTitle("Помощь для команды `config`:") .setDescription("Данная команда используется для конфигурации переменных бота для данного сервера. " + "\n`help` - вывод данного сообщения." + "\n\n`welcome [help]` - помощь по конфигурации приветствий. По-умолчанию, приветствия в основном канале." + "\n\n`verify [help]` - конфигурация канала для прослушки верификации. По-умолчанию, канал для приветствий. " + "\n\n`locale [help]` - вывод списка доступных локалей (языков) стандартных сообщений." + "\n\n`prefix set <prefix>` - установка префикса команд для сервера. Не более трех знаков. " + "Возможность использовать префикс по-умолчанию ('!!') остается." + "\n\n`wiki set <wiki url>` - установка вики, к которой принадлежит сервер. " + "Менять этот параметр имеет право только администратор сервера с привязанным Викия аккаунтом " + "с правами 'sysop' на указанной вики и верифицированный с помощью `!!verify [sysop | admin] <url>`." + "\n`wiki set <name>` - установка своего удобочитаемого названия вики. Устанавливается автоматически после привязки к вики."); event.getChannel().sendMessage(embedResponse.build()).queue(); } @SubCommand(subCommand = "status") public void status(CommandEvent event) { final EnhancedGuild enhancedGuild = event.getEnhancedGuild(); final EmbedBuilder embedResponse = new EmbedBuilder(); embedResponse .setColor(NEUTRAL) .setTitle("Текущая конфигурация:", "https://iscaribot.xyz") .addField("Префикс:", "`" + enhancedGuild.getCommandPrefix() + "`", true) .addField("Язык", enhancedGuild.getLocaleReadable(), true) .addField("Канал для приветствий:", enhancedGuild.getWelcomeChannel().getName(), true) .addField("Канал для верификации:", enhancedGuild.getVerificationChannel().getName(), true) .addField("Таймаут верификации:", enhancedGuild.getVerificationTimeout() + " часов", true) .addField("Роли для верификации:", enhancedGuild.getVerificationRolesString() + " ", false) .setFooter("Версия бота: 0.5.0", event.getJDA().getSelfUser().getAvatarUrl()); String messages = String.join(", ", enhancedGuild.getBotMessages() .keySet() .stream().map(BotMessages::name).collect(Collectors.toList())); String features = String.join(", ", enhancedGuild.getBotFeatures().entrySet().stream().filter(Map.Entry::getValue).map(entry -> entry.getKey().name()).collect(Collectors.toList())); embedResponse.addField("Кастомизированные сообщения: ", messages.isEmpty() ? "Отсутствуют" : messages, false) .addField("Подключенные фичи: ", features.isEmpty() ? "Отсутствуют" : features, false); event.getChannel().sendMessage(embedResponse.build()).queue(); } //@SubCommand(subCommand = "verify") public void verify(CommandEvent event) { } //@SubCommand(subCommand = {"verify", "set"}) public void verifySetter(CommandEvent event) { } //@SubCommand(subCommand = "welcome") public void welcome(CommandEvent event) { } //@SubCommand(subCommand = {"welcome", "set"}) public void welcomeSetter(CommandEvent event) { } //@SubCommand(subCommand = "locale") public void locale(CommandEvent event) { } }
erkhabibullina/OnlineShoppingDemo
app/src/main/java/com/example/android/onlineshoppingdemo/store/signup/WelcomeContinueButtonController.java
package com.example.android.onlineshoppingdemo.store.signup; import android.content.Context; import android.content.Intent; import android.view.View; import com.example.android.onlineshoppingdemo.MainActivity; public class WelcomeContinueButtonController implements View.OnClickListener { private Context appContext; private String access; public WelcomeContinueButtonController(Context context, String access) { appContext = context; this.access = access; } @Override public void onClick(View v) { if (access.equals("employeeAccess")) { ((WelcomeActivity) appContext).finish(); } else { Intent intent = new Intent(appContext, MainActivity.class); appContext.startActivity(intent); } } }
basarevych/next-dashboard
api-server/src/Database.js
<filename>api-server/src/Database.js const mongoose = require("mongoose"); const constants = require("../../common/constants"); const shuffle = require("../common/src/shuffle"); class Database { constructor(config, di, fake) { this.config = config; this.di = di; this.fake = fake; this.mongoose = mongoose; this.mongoose.set("useUnifiedTopology", true); this.mongoose.Promise = global.Promise; this.ObjectId = mongoose.Types.ObjectId; } static get $provides() { return "db"; } static get $requires() { return ["config", "di", "fake"]; } static get $lifecycle() { return "singleton"; } async init() { if (this.promise) return this.promise; this.promise = Promise.resolve() .then(async () => { const UserClient = this.di.get("model.user.client"); this.UserClientSchema = UserClient.schema; this.UserClientModel = UserClient.model; const UserProvider = this.di.get("model.user.provider"); this.UserProviderSchema = UserProvider.schema; this.UserProviderModel = UserProvider.model; const User = this.di.get("model.user"); this.UserSchema = User.schema; this.UserModel = User.model; const Employee = this.di.get("model.employee"); this.EmployeeSchema = Employee.schema; this.EmployeeModel = Employee.model; return new Promise((resolve, reject) => { if (process.env.NODE_ENV !== "test") process.stdout.write("> MongoDB... "); this.mongoose.connect( this.config.mongoUrl, { useNewUrlParser: true }, error => { if (error) return reject(error); if (process.env.NODE_ENV !== "test") console.log("online"); resolve(); } ); }); }) .then(async () => { if (this.config.rootLogin && this.config.rootPassword) { let user = await this.UserModel.findOne({ email: this.config.rootLogin }); let msg; if (user) { user.email = this.config.rootLogin; user.password = await this.di .get("auth") .encryptPassword(this.config.rootPassword); user.roles = [constants.roles.ADMIN]; msg = "> Admin user updated"; } else { user = new this.UserModel({ name: "<NAME>", email: this.config.rootLogin, password: await this.di .get("auth") .encryptPassword(this.config.rootPassword), roles: [constants.roles.ADMIN] }); msg = "> Admin user created"; } await user.validate(); await user.save(); console.log(msg); } let count = await this.EmployeeModel.countDocuments(); if (!count) { let employees = []; let usedNames = []; for (let i = 0; i < 100 * Object.keys(constants.depts).length; i++) { employees.push( new this.EmployeeModel(this.fake.createRandomEmployee(usedNames)) ); } shuffle(employees); for (let employee of employees) await employee.save(); console.log("> Employees created"); } }); return this.promise; } } module.exports = Database;
crazyvalse/algorithms
src/14-slidingwindow/m-1456/check/01.js
/* 给你字符串 s 和整数 k 。 请返回字符串 s 中长度为 k 的单个子字符串中可能包含的最大元音字母数。 英文中的 元音字母 为(a, e, i, o, u)。 示例 1: 输入:s = "abciiidef", k = 3 输出:3 解释:子字符串 "iii" 包含 3 个元音字母。 示例 2: 输入:s = "aeiou", k = 2 输出:2 解释:任意长度为 2 的子字符串都包含 2 个元音字母。 示例 3: 输入:s = "leetcode", k = 3 输出:2 解释:"lee"、"eet" 和 "ode" 都包含 2 个元音字母。 示例 4: 输入:s = "rhythms", k = 4 输出:0 解释:字符串 s 中不含任何元音字母。 示例 5: 输入:s = "tryhard", k = 4 输出:1 提示: 1 <= s.length <= 10^5 s 由小写英文字母组成 1 <= k <= s.length */ /** * * @param {string} s * @param {number} k * @return {number} */ var maxVowels = function (s, k) { let max = -Infinity let l = 0 let r = 0 let sum = 0 while (r < s.length) { sum += vowelNum(s[r]) if (r - l + 1 > k) { sum -= vowelNum(s[l++]) } max = Math.max(max, sum) r++ } return max === -Infinity ? 0 : max } function vowelNum(char) { const vowels = { a: true, e: true, i: true, o: true, u: true } return vowels[char] ? 1 : 0 } module.exports = maxVowels
VidersTv/common
streaming/protocol/rtmp/cache/gop.go
package cache import ( "fmt" "github.com/viderstv/common/streaming/av" ) var ( maxGOPCap int = 1024 ErrGopTooBig = fmt.Errorf("gop to big") ) type array struct { index int packets []*av.Packet } func newArray() *array { ret := &array{ index: 0, packets: make([]*av.Packet, 0, maxGOPCap), } return ret } func (a *array) reset() { a.index = 0 a.packets = a.packets[:0] } func (a *array) write(packet *av.Packet) error { if a.index >= maxGOPCap { return ErrGopTooBig } a.packets = append(a.packets, packet) a.index++ return nil } func (a *array) send(w av.WriteCloser) error { for i := 0; i < a.index; i++ { packet := a.packets[i] if err := w.Write(packet); err != nil { return err } } return nil } type GopCache struct { start bool num int count int nextindex int gops []*array } func NewGopCache(num int) *GopCache { if num == 0 { num = 1 } return &GopCache{ count: num, gops: make([]*array, num), } } func (c *GopCache) writeToArray(chunk *av.Packet, startNew bool) error { var ginc *array if startNew { ginc = c.gops[c.nextindex] if ginc == nil { ginc = newArray() c.num++ c.gops[c.nextindex] = ginc } else { ginc.reset() } c.nextindex = (c.nextindex + 1) % c.count } else { ginc = c.gops[(c.nextindex+1)%c.count] } return ginc.write(chunk) } func (c *GopCache) Write(p *av.Packet) error { var ok bool if p.IsVideo { vh := p.Header.(av.VideoPacketHeader) if vh.IsKeyFrame() && !vh.IsSeq() { ok = true } } if ok || c.start { c.start = true return c.writeToArray(p, ok) } return nil } func (c *GopCache) sendTo(w av.WriteCloser) error { var err error pos := (c.nextindex + 1) % c.count for i := 0; i < c.num; i++ { index := (pos - c.num + 1) + i if index < 0 { index += c.count } g := c.gops[index] err = g.send(w) if err != nil { return err } } return nil } func (c *GopCache) Send(w av.WriteCloser) error { return c.sendTo(w) }
nizD/LeetCode-Solutions
C++/239. SlidingWindowMaximum.cpp
/* Problem : You are given an array of integers nums, there is a sliding window of size k which is moving from the very left of the array to the very right. You can only see the k numbers in the window. Each time the sliding window moves right by one position. Return the max sliding window Approach : We scan the array from 0 to n-1, keep favourable elements in the deque. The algorithm is amortized O(n) as each element is put and polled once. At each i, we keep favourable elements, which are potentially max number in window [i-(k-1),i] or any subsequent window. This means if an element in the deque and it is out of i-(k-1), we discard them. We just need to pop from the head, as we are using a deque and elements are ordered as the sequence in the array Now only those elements within [i-(k-1),i] are in the deque. We then discard elements smaller than a[i] from the tail. This is because if a[x] <a[i] and x<i, then a[x] has no chance to be the "max" in [i-(k-1),i], or any other subsequent window: a[i] would always be a better candidate. As a result elements in the deque are ordered in both sequence in array and their value. At each step the head of the deque is the max element in [i-(k-1),i] */ class Solution { public: vector<int> maxSlidingWindow(vector<int>& nums, int k) { deque<int> dq; vector<int> v; int n = nums.size(); for(int i = 0; i < k; i++) { while(!dq.empty() && dq.back() < nums[i]) dq.pop_back(); dq.push_back(nums[i]); } for(int i = k; i < n; i++) { v.push_back(dq.front()); if(dq.front() == nums[i - k]) dq.pop_front(); while(!dq.empty() && dq.back() < nums[i]) dq.pop_back(); dq.push_back(nums[i]); } v.push_back(dq.front()); return v; } };
olavoasantos/jasss
node_modules/collect.js/src/methods/every.js
'use strict'; module.exports = function every(fn) { return this.items .map((item, index) => fn(item, index)) .indexOf(false) === -1; };
zzqqqzzz/WebNES
project/js/db/F62ACF9818E805E234875D11702DCC9E19D83AA2.js
this.NesDb = this.NesDb || {}; NesDb[ 'F62ACF9818E805E234875D11702DCC9E19D83AA2' ] = { "$": { "name": "Barbie", "class": "Licensed", "catalog": "NES-8V-AUS", "publisher": "Hi Tech Expressions", "developer": "Imagineering", "region": "Australia", "players": "1", "date": "1992" }, "cartridge": [ { "$": { "system": "NES-PAL-A", "crc": "D364F816", "sha1": "F62ACF9818E805E234875D11702DCC9E19D83AA2", "dump": "ok", "dumper": "B00daW", "datedumped": "2008-10-13" }, "board": [ { "$": { "type": "NES-SLROM", "pcb": "NES-SLROM-06", "mapper": "1" }, "prg": [ { "$": { "name": "PAL-8V-0 PRG", "size": "128k", "crc": "0538A4E9", "sha1": "E0EEC92796235D23B09CAE00A6D343E87598E59E" } } ], "chr": [ { "$": { "name": "NES-8V-1 CHR", "size": "128k", "crc": "300945A2", "sha1": "82C1C5AC3713648176D84AC8EC253F37858B5932" } } ], "chip": [ { "$": { "type": "MMC1B3" } } ], "cic": [ { "$": { "type": "3197A" } } ] } ] } ], "gameGenieCodes": [ { "name": "Infinite Z's on Dream Meter", "codes": [ [ "SXKSKNVK" ] ] }, { "name": "Start with nine Z's on Dream Meter--1st credit only", "codes": [ [ "PEEZEZIE" ] ] }, { "name": "Start with one Z--1st credit only", "codes": [ [ "PEEZEZIA" ] ] }, { "name": "Can re-enter Barbie's dream an infinite number of times", "codes": [ [ "SZVAAVVK" ] ] }, { "name": "Cannot re-enter Barbie's dream", "codes": [ [ "AEEEYAZA" ] ] } ] };
sergeyreznik/et-engine
include/et/rendering/vulkan/vulkan_renderer.h
/* * This file is part of `et engine` * Copyright 2009-2016 by <NAME> * Please, modify content only if you know what are you doing. * */ #pragma once #include <et/rendering/interface/renderer.h> namespace et { class VulkanRendererPrivate; class VulkanRenderer : public RenderInterface { public: ET_DECLARE_POINTER(VulkanRenderer); public: RenderingAPI api() const override { return RenderingAPI::Vulkan; } VulkanRenderer(); ~VulkanRenderer(); void init(const RenderContextParameters& params) override; void shutdown() override; void destroy() override; void resize(const vec2i&) override; vec2i contextSize() const override; RendererFrame allocateFrame() override; void submitFrame(const RendererFrame&) override; void present() override; RenderPass::Pointer allocateRenderPass(const RenderPass::ConstructionInfo&) override; void beginRenderPass(const RenderPass::Pointer&, const RenderPassBeginInfo&) override; void submitRenderPass(const RenderPass::Pointer&) override; /* * Buffers */ Buffer::Pointer createBuffer(const std::string&, const Buffer::Description&) override; /* * Textures */ Texture::Pointer createTexture(const TextureDescription::Pointer&) override; TextureSet::Pointer createTextureSet(const TextureSet::Description&) override; /* * Samplers */ Sampler::Pointer createSampler(const Sampler::Description&) override; /* * Programs */ Program::Pointer createProgram(uint32_t stages, const std::string& source) override; /* * Pipeline state */ PipelineState::Pointer acquireGraphicsPipeline(const RenderPass::Pointer&, const Material::Pointer&, const VertexStream::Pointer&) override; /* * Compute */ Compute::Pointer createCompute(const Material::Pointer&) override; private: ET_DECLARE_PIMPL(VulkanRenderer, 4096); }; }
Futuremappermydud/Naluluna-Modifier-Quest
include/codegen/include/System/Xml/XmlWellFormedWriter_AttributeValueCache_BufferChunk.hpp
<reponame>Futuremappermydud/Naluluna-Modifier-Quest<gh_stars>1-10 // Autogenerated from CppHeaderCreator on 7/27/2020 3:10:20 PM // Created by Sc2ad // ========================================================================= #pragma once #pragma pack(push, 8) // Begin includes #include "utils/typedefs.h" // Including type: System.Object #include "System/Object.hpp" // Including type: System.Xml.XmlWellFormedWriter/AttributeValueCache #include "System/Xml/XmlWellFormedWriter_AttributeValueCache.hpp" #include "utils/il2cpp-utils.hpp" // Completed includes // Begin forward declares // Completed forward declares // Type namespace: System.Xml namespace System::Xml { // Autogenerated type: System.Xml.XmlWellFormedWriter/AttributeValueCache/BufferChunk class XmlWellFormedWriter::AttributeValueCache::BufferChunk : public ::Il2CppObject { public: // System.Char[] buffer // Offset: 0x10 ::Array<::Il2CppChar>* buffer; // System.Int32 index // Offset: 0x18 int index; // System.Int32 count // Offset: 0x1C int count; // System.Void .ctor(System.Char[] buffer, System.Int32 index, System.Int32 count) // Offset: 0x192A174 static XmlWellFormedWriter::AttributeValueCache::BufferChunk* New_ctor(::Array<::Il2CppChar>* buffer, int index, int count); }; // System.Xml.XmlWellFormedWriter/AttributeValueCache/BufferChunk } DEFINE_IL2CPP_ARG_TYPE(System::Xml::XmlWellFormedWriter::AttributeValueCache::BufferChunk*, "System.Xml", "XmlWellFormedWriter/AttributeValueCache/BufferChunk"); #pragma pack(pop)
aetherinc/cpe-manifest-android-experience
src/com/wb/nextgenlibrary/parser/md/schema/v2_3/DigitalAssetMetadataType.java
<reponame>aetherinc/cpe-manifest-android-experience<gh_stars>1-10 // // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.11 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2016.02.08 at 03:02:05 PM PST // package com.wb.nextgenlibrary.parser.md.schema.v2_3; import com.wb.nextgenlibrary.parser.XmlAccessType; import com.wb.nextgenlibrary.parser.XmlAccessorType; import com.wb.nextgenlibrary.parser.XmlElement; import com.wb.nextgenlibrary.parser.XmlType; /** * <p>Java class for DigitalAssetMetadata-type complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="DigitalAssetMetadata-type"&gt; * &lt;complexContent&gt; * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"&gt; * &lt;choice&gt; * &lt;element name="Audio" type="{http://www.movielabs.com/schema/md/v2.3/md}DigitalAssetAudioData-type"/&gt; * &lt;element name="Video" type="{http://www.movielabs.com/schema/md/v2.3/md}DigitalAssetVideoData-type"/&gt; * &lt;element name="Subtitle" type="{http://www.movielabs.com/schema/md/v2.3/md}DigitalAssetSubtitleData-type"/&gt; * &lt;element name="Image" type="{http://www.movielabs.com/schema/md/v2.3/md}DigitalAssetImageData-type"/&gt; * &lt;element name="Interactive" type="{http://www.movielabs.com/schema/md/v2.3/md}DigitalAssetInteractiveData-type"/&gt; * &lt;element name="Ancillary" type="{http://www.movielabs.com/schema/md/v2.3/md}DigitalAssetAncillaryData-type"/&gt; * &lt;/choice&gt; * &lt;/restriction&gt; * &lt;/complexContent&gt; * &lt;/complexType&gt; * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "DigitalAssetMetadata-type", propOrder = { "audio", "video", "subtitle", "image", "interactive", "ancillary" }) public class DigitalAssetMetadataType { @XmlElement(name = "Audio") protected DigitalAssetAudioDataType audio; @XmlElement(name = "Video") protected DigitalAssetVideoDataType video; @XmlElement(name = "Subtitle") protected DigitalAssetSubtitleDataType subtitle; @XmlElement(name = "Image") protected DigitalAssetImageDataType image; @XmlElement(name = "Interactive") protected DigitalAssetInteractiveDataType interactive; @XmlElement(name = "Ancillary") protected DigitalAssetAncillaryDataType ancillary; /** * Gets the value of the audio property. * * @return * possible object is * {@link DigitalAssetAudioDataType } * */ public DigitalAssetAudioDataType getAudio() { return audio; } /** * Sets the value of the audio property. * * @param value * allowed object is * {@link DigitalAssetAudioDataType } * */ public void setAudio(DigitalAssetAudioDataType value) { this.audio = value; } /** * Gets the value of the video property. * * @return * possible object is * {@link DigitalAssetVideoDataType } * */ public DigitalAssetVideoDataType getVideo() { return video; } /** * Sets the value of the video property. * * @param value * allowed object is * {@link DigitalAssetVideoDataType } * */ public void setVideo(DigitalAssetVideoDataType value) { this.video = value; } /** * Gets the value of the subtitle property. * * @return * possible object is * {@link DigitalAssetSubtitleDataType } * */ public DigitalAssetSubtitleDataType getSubtitle() { return subtitle; } /** * Sets the value of the subtitle property. * * @param value * allowed object is * {@link DigitalAssetSubtitleDataType } * */ public void setSubtitle(DigitalAssetSubtitleDataType value) { this.subtitle = value; } /** * Gets the value of the image property. * * @return * possible object is * {@link DigitalAssetImageDataType } * */ public DigitalAssetImageDataType getImage() { return image; } /** * Sets the value of the image property. * * @param value * allowed object is * {@link DigitalAssetImageDataType } * */ public void setImage(DigitalAssetImageDataType value) { this.image = value; } /** * Gets the value of the interactive property. * * @return * possible object is * {@link DigitalAssetInteractiveDataType } * */ public DigitalAssetInteractiveDataType getInteractive() { return interactive; } /** * Sets the value of the interactive property. * * @param value * allowed object is * {@link DigitalAssetInteractiveDataType } * */ public void setInteractive(DigitalAssetInteractiveDataType value) { this.interactive = value; } /** * Gets the value of the ancillary property. * * @return * possible object is * {@link DigitalAssetAncillaryDataType } * */ public DigitalAssetAncillaryDataType getAncillary() { return ancillary; } /** * Sets the value of the ancillary property. * * @param value * allowed object is * {@link DigitalAssetAncillaryDataType } * */ public void setAncillary(DigitalAssetAncillaryDataType value) { this.ancillary = value; } }
neilrjones/DevOps-Python-tools
hbase_flush_tables.py
#!/usr/bin/env python # vim:ts=4:sts=4:sw=4:et # # Author: <NAME> # Date: 2016-09-12 13:44:24 +0200 (Mon, 12 Sep 2016) # # https://github.com/harisekhon/devops-python-tools # # License: see accompanying Hari Sekhon LICENSE file # # If you're using my code you're welcome to connect with me on LinkedIn # and optionally send me feedback to help steer this or other code I publish # # https://www.linkedin.com/in/harisekhon # # NOTE: 'flush' is not supported in Happybase as it's not in the Thrift API, # only available in the Java API, see HBaseAdmin.flush(table) # I'll write a JVM native alternative to this later as I needed this quickly """ Tool to iterate on and flush all HBase tables Written for flushing bulk imports skipping the WAL, for example OpenTSDB bulk import. The Thrift API doesn't support this action so it uses the HBase shell locally which must be in the $PATH There is also a shell script version of this in the adjacent DevOps-Perl-Tools repo Tested on Hortonworks HDP 2.3 (HBase 1.1.2) and Apache HBase 1.0.3, 1.1.6, 1.2.1, 1.2.2, 1.3.1 """ from __future__ import absolute_import from __future__ import division from __future__ import print_function #from __future__ import unicode_literals import logging import os import re import sys import traceback import subprocess PIPE = subprocess.PIPE libdir = os.path.abspath(os.path.join(os.path.dirname(__file__), 'pylib')) sys.path.append(libdir) try: # pylint: disable=wrong-import-position from harisekhon.utils import log, die, autoflush from harisekhon.utils import validate_regex from harisekhon import CLI except ImportError as _: print(traceback.format_exc(), end='') sys.exit(4) __author__ = '<NAME>' __version__ = '0.1' class HBaseFlushTables(CLI): def __init__(self): # Python 2.x super(HBaseFlushTables, self).__init__() # Python 3.x # super().__init__() self.table_list_header_regex = re.compile('TABLE') self.table_list_end_regex = re.compile(r'row.*\sin\s.*\sseconds') self.table_regex = None self.timeout_default = 6 * 3600 autoflush() def add_options(self): self.add_opt('-r', '--regex', help='Regex of tables to flush') self.add_opt('-l', '--list-tables', action='store_true', help='List tables and exit') def process_args(self): log.setLevel(logging.INFO) self.no_args() regex = self.get_opt('regex') if regex: validate_regex(regex) self.table_regex = re.compile(regex, re.I) log.info('filtering to flush only tables matching regex \'{0}\''.format(regex)) def get_tables(self): log.info('getting table list') try: process = subprocess.Popen(['hbase', 'shell'], stdin=PIPE, stdout=PIPE, stderr=subprocess.STDOUT) (stdout, _) = process.communicate('list') process.wait() if process.returncode != 0: print('ERROR:', end='') die(stdout) lines = stdout.split('\n') lineno = 1 for line in lines: if self.table_list_header_regex.search(line): break lineno += 1 if lineno > len(lines): die("Failed to parse table list output (couldn't find the starting line TABLE)") tables = set() for line in lines[lineno:]: if self.table_list_end_regex.search(line): break line = line.strip() if not line: continue tables.add(line) return tables except OSError as _: die("OSError running hbase shell to list tables: {0}".format(_)) except subprocess.CalledProcessError as _: print('Failed to get tables using HBase shell:\n') print(_.output) sys.exit(_.returncode) def run(self): tables = self.get_tables() if not tables: die('No Tables Found') if self.get_opt('list_tables'): print('Tables:\n\n' + '\n'.join(tables)) sys.exit(3) tables_to_flush = set() if self.table_regex: log.info('filtering tables based on regex') for table in sorted(list(tables)): if self.table_regex.search(table): tables_to_flush.add(table) else: tables_to_flush = sorted(list(tables)) if log.isEnabledFor(logging.INFO): log.info('Flushing tables:\n\n%s\n', '\n'.join(tables_to_flush)) flush_commands = '\n'.join(["flush '{0}'".format(table) for table in tables_to_flush]) try: # by having stdout and stderr go to the same place more likely the output will be in a sane order process = subprocess.Popen(['hbase', 'shell'], stdin=PIPE, stdout=PIPE, stderr=subprocess.STDOUT) (stdout, _) = process.communicate(input=flush_commands) process.wait() if process.returncode != 0: print('ERROR:', end='') die(stdout) print(stdout) except OSError as _: die("OSError running hbase shell to flush tables: {0}".format(_)) except subprocess.CalledProcessError as _: print('Failed to get tables using HBase shell:\n') print(_.output) sys.exit(_.returncode) if __name__ == '__main__': HBaseFlushTables().main()
Portable-EHR/PatientSDK-iOS
ehrPatientSDK-ios/Classes/Models/UserModel.h
// // Created by <NAME> on 2015-10-24. // Copyright (c) 2015-2019 Portable EHR inc. All rights reserved. // #import <Foundation/Foundation.h> #import "EHRInstanceCounterP.h" #import "EHRPersistableP.h" #import "EHRModelSequencerP.h" @class IBUser; @class NotificationsModel; @class UserDeviceSettings; @class MessagesModel; @class ServicesModel; @interface UserModel : NSObject <EHRInstanceCounterP, EHRPersistableP, EHRModelSequencerP> { NSInteger _instanceNumber; NSDate *_lastRefreshed; IBUser *_user; MessagesModel *_messagesModel; NotificationsModel *_notificationsModel; ServicesModel *_servicesModel; NSMutableDictionary *_patientModels; UserDeviceSettings *_deviceSettings; } @property(nonatomic, readonly) IBUser *user; + (UserModel *)guest; + (UserModel *)userModelFor:(IBUser *)user; @property(nonatomic, readonly) MessagesModel *messagesModel; @property(nonatomic, readonly) NotificationsModel *notificationsModel; @property(nonatomic, readonly) ServicesModel *servicesModel; @property(nonatomic, readonly) NSDictionary *patientModels; @property(nonatomic, readonly) BOOL isGuest; @property(nonatomic) UserDeviceSettings *deviceSettings; - (void)updateUserInfo:(IBUser *)newInfo; -(void) updateUserInfo:(IBUser *) newInfo save:(BOOL) saveIt; - (BOOL)isResponderForPatientWithGuid:(NSString *)guid; - (BOOL)hasPatientWithGuid:(NSString *)guid; - (BOOL)isProxyResponderForPatientWithGuid:(NSString *)guid; - (BOOL)hasVisitWithGuid:(NSString *)guid; - (BOOL)isUserForPatientWithGuid:(NSString *)guid; - (BOOL)saveOnDevice; - (BOOL)saveOnDevice:(BOOL)cascade; - (BOOL)eraseFromDevice:(BOOL)cascade; + (UserModel *)readFromDevice:(NSString *)guid cascade:(BOOL)doCascade; - (void)readNotificationsModelFromDevice; @end
ZhouTuo666/xiao
basic/src/main/java/indi/tuo/xiao/base/variable/AbstractVariable.java
package indi.tuo.xiao.base.variable; import java.util.Objects; import lombok.Getter; import lombok.Setter; public abstract class AbstractVariable implements IVariable { @Getter @Setter protected String name; @Getter @Setter protected String id; @Getter protected int scope; @Getter protected long cacheTime; @Getter @Setter protected transient IDataPool dataPool; @Getter private final String _type = this.getClass().getName(); public AbstractVariable(String name, String id, int scope, long cacheTime) { this.name = name; this.id = id; this.scope = scope; this.cacheTime = cacheTime; } protected AbstractVariable() { } @Override public IVariable deepClone() { IVariable variable = this.copy(); variable.setDataPool(getDataPool()); return variable; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } AbstractVariable that = (AbstractVariable) o; return name.equals(that.name) && id.equals(that.id); } @Override public int hashCode() { return Objects.hash(name, id); } protected abstract IVariable copy(); }
rochakchauhan/commcare-hq
custom/icds_reports/migrations/0119_distribute_tables.py
# Generated by Django 1.11.20 on 2019-05-14 12:45 from django.db import migrations from corehq.sql_db.connections import is_citus_db from custom.icds_reports.const import DISTRIBUTED_TABLES, REFERENCE_TABLES from custom.icds_reports.utils.migrations import ( create_citus_distributed_table, create_citus_reference_table, ) def _distribute_citus_tables(apps, schema_editor): with schema_editor.connection.cursor() as cursor: if not is_citus_db(cursor): return for table, col in DISTRIBUTED_TABLES: create_citus_distributed_table(cursor, table, col) for table in REFERENCE_TABLES: create_citus_reference_table(cursor, table) class Migration(migrations.Migration): dependencies = [ ('icds_reports', '0118_monthly_pk'), ] operations = [ migrations.RunPython(_distribute_citus_tables, migrations.RunPython.noop) ]
SoftReaper/Mesa-Renoir-deb
src/gallium/drivers/r600/sfn/sfn_shaderio.cpp
<filename>src/gallium/drivers/r600/sfn/sfn_shaderio.cpp /* -*- mesa-c++ -*- * * Copyright (c) 2018 Collabora LTD * * Author: <NAME> <<EMAIL>> * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * on the rights to use, copy, modify, merge, publish, distribute, sub * license, and/or sell copies of the Software, and to permit persons to whom * the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice (including the next * paragraph) shall be included in all copies or substantial portions of the * Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL * THE AUTHOR(S) AND/OR THEIR SUPPLIERS BE LIABLE FOR ANY CLAIM, * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE * USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "sfn_shaderio.h" #include "sfn_debug.h" #include "tgsi/tgsi_from_mesa.h" #include <queue> namespace r600 { using std::vector; using std::priority_queue; ShaderIO::ShaderIO(): m_two_sided(false), m_lds_pos(0) { } ShaderInput::ShaderInput(tgsi_semantic name): m_name(name), m_gpr(0), m_uses_interpolate_at_centroid(false) { } ShaderInput::~ShaderInput() { } void ShaderInput::set_lds_pos(UNUSED int lds_pos) { } int ShaderInput::ij_index() const { return -1; } bool ShaderInput::interpolate() const { return false; } int ShaderInput::lds_pos() const { return 0; } bool ShaderInput::is_varying() const { return false; } void ShaderInput::set_uses_interpolate_at_centroid() { m_uses_interpolate_at_centroid = true; } void ShaderInput::set_ioinfo(r600_shader_io& io, int translated_ij_index) const { io.name = m_name; io.gpr = m_gpr; io.ij_index = translated_ij_index; io.lds_pos = lds_pos(); io.uses_interpolate_at_centroid = m_uses_interpolate_at_centroid; set_specific_ioinfo(io); } void ShaderInput::set_specific_ioinfo(UNUSED r600_shader_io& io) const { } ShaderInputSystemValue::ShaderInputSystemValue(tgsi_semantic name, int gpr): ShaderInput(name), m_gpr(gpr) { } void ShaderInputSystemValue::set_specific_ioinfo(r600_shader_io& io) const { io.gpr = m_gpr; io.ij_index = 0; } ShaderInputVarying::ShaderInputVarying(tgsi_semantic _name, int sid, unsigned driver_location, unsigned frac, unsigned components, tgsi_interpolate_mode interpolate, tgsi_interpolate_loc interp_loc): ShaderInput(_name), m_driver_location(driver_location), m_location_frac(frac), m_sid(sid), m_interpolate(interpolate), m_interpolate_loc(interp_loc), m_ij_index(-10), m_lds_pos(0), m_mask(((1 << components) - 1) << frac) { evaluate_spi_sid(); m_ij_index = interpolate == TGSI_INTERPOLATE_LINEAR ? 3 : 0; switch (interp_loc) { case TGSI_INTERPOLATE_LOC_CENTROID: m_ij_index += 2; break; case TGSI_INTERPOLATE_LOC_CENTER: m_ij_index += 1; break; default: ; } } ShaderInputVarying::ShaderInputVarying(tgsi_semantic _name, int sid, nir_variable *input): ShaderInput(_name), m_driver_location(input->data.driver_location), m_location_frac(input->data.location_frac), m_sid(sid), m_ij_index(-10), m_lds_pos(0), m_mask(((1 << input->type->components()) - 1) << input->data.location_frac) { sfn_log << SfnLog::io << __func__ << "name:" << _name << " sid: " << sid << " op: " << input->data.interpolation; evaluate_spi_sid(); enum glsl_base_type base_type = glsl_get_base_type(glsl_without_array(input->type)); switch (input->data.interpolation) { case INTERP_MODE_NONE: if (glsl_base_type_is_integer(base_type)) { m_interpolate = TGSI_INTERPOLATE_CONSTANT; break; } if (name() == TGSI_SEMANTIC_COLOR) { m_interpolate = TGSI_INTERPOLATE_COLOR; m_ij_index = 0; break; } FALLTHROUGH; case INTERP_MODE_SMOOTH: assert(!glsl_base_type_is_integer(base_type)); m_interpolate = TGSI_INTERPOLATE_PERSPECTIVE; m_ij_index = 0; break; case INTERP_MODE_NOPERSPECTIVE: assert(!glsl_base_type_is_integer(base_type)); m_interpolate = TGSI_INTERPOLATE_LINEAR; m_ij_index = 3; break; case INTERP_MODE_FLAT: m_interpolate = TGSI_INTERPOLATE_CONSTANT; break; default: m_interpolate = TGSI_INTERPOLATE_CONSTANT; break; } if (input->data.sample) { m_interpolate_loc = TGSI_INTERPOLATE_LOC_SAMPLE; } else if (input->data.centroid) { m_interpolate_loc = TGSI_INTERPOLATE_LOC_CENTROID; m_ij_index += 2; } else { m_interpolate_loc = TGSI_INTERPOLATE_LOC_CENTER; m_ij_index += 1; } sfn_log << SfnLog::io << " -> IP:" << m_interpolate << " IJ:" << m_ij_index << "\n"; } bool ShaderInputVarying::is_varying() const { return true; } void ShaderInputVarying::update_mask(int additional_comps, int frac) { m_mask |= ((1 << additional_comps) - 1) << frac; } void ShaderInputVarying::evaluate_spi_sid() { switch (name()) { case TGSI_SEMANTIC_PSIZE: case TGSI_SEMANTIC_EDGEFLAG: case TGSI_SEMANTIC_FACE: case TGSI_SEMANTIC_SAMPLEMASK: assert(0 && "System value used as varying"); break; case TGSI_SEMANTIC_POSITION: m_spi_sid = 0; break; case TGSI_SEMANTIC_GENERIC: case TGSI_SEMANTIC_TEXCOORD: case TGSI_SEMANTIC_PCOORD: m_spi_sid = m_sid + 1; break; default: /* For non-generic params - pack name and sid into 8 bits */ m_spi_sid = (0x80 | (name() << 3) | m_sid) + 1; } } ShaderInputVarying::ShaderInputVarying(tgsi_semantic name, const ShaderInputVarying& orig, size_t location): ShaderInput(name), m_driver_location(location), m_location_frac(orig.location_frac()), m_sid(orig.m_sid), m_spi_sid(orig.m_spi_sid), m_interpolate(orig.m_interpolate), m_interpolate_loc(orig.m_interpolate_loc), m_ij_index(orig.m_ij_index), m_lds_pos(0), m_mask(0) { evaluate_spi_sid(); } bool ShaderInputVarying::interpolate() const { return m_interpolate > 0; } int ShaderInputVarying::ij_index() const { return m_ij_index; } void ShaderInputVarying::set_lds_pos(int lds_pos) { m_lds_pos = lds_pos; } int ShaderInputVarying::lds_pos() const { return m_lds_pos; } void ShaderInputVarying::set_specific_ioinfo(r600_shader_io& io) const { io.interpolate = m_interpolate; io.interpolate_location = m_interpolate_loc; io.sid = m_sid; io.spi_sid = m_spi_sid; set_color_ioinfo(io); } void ShaderInputVarying::set_color_ioinfo(UNUSED r600_shader_io& io) const { sfn_log << SfnLog::io << __func__ << " Don't set color_ioinfo\n"; } ShaderInputColor::ShaderInputColor(tgsi_semantic name, int sid, nir_variable *input): ShaderInputVarying(name, sid, input), m_back_color_input_idx(0) { sfn_log << SfnLog::io << __func__ << "name << " << name << " sid << " << sid << "\n"; } ShaderInputColor::ShaderInputColor(tgsi_semantic _name, int sid, unsigned driver_location, unsigned frac, unsigned components, tgsi_interpolate_mode interpolate, tgsi_interpolate_loc interp_loc): ShaderInputVarying(_name, sid, driver_location,frac, components, interpolate, interp_loc), m_back_color_input_idx(0) { sfn_log << SfnLog::io << __func__ << "name << " << _name << " sid << " << sid << "\n"; } void ShaderInputColor::set_back_color(unsigned back_color_input_idx) { sfn_log << SfnLog::io << "Set back color index " << back_color_input_idx << "\n"; m_back_color_input_idx = back_color_input_idx; } void ShaderInputColor::set_color_ioinfo(r600_shader_io& io) const { sfn_log << SfnLog::io << __func__ << " set color_ioinfo " << m_back_color_input_idx << "\n"; io.back_color_input = m_back_color_input_idx; } size_t ShaderIO::add_input(ShaderInput *input) { m_inputs.push_back(PShaderInput(input)); return m_inputs.size() - 1; } PShaderInput ShaderIO::find_varying(tgsi_semantic name, int sid) { for (auto& a : m_inputs) { if (a->name() == name) { assert(a->is_varying()); auto& v = static_cast<ShaderInputVarying&>(*a); if (v.sid() == sid) return a; } } return nullptr; } struct VaryingShaderIOLess { bool operator () (PShaderInput lhs, PShaderInput rhs) const { const ShaderInputVarying& l = static_cast<ShaderInputVarying&>(*lhs); const ShaderInputVarying& r = static_cast<ShaderInputVarying&>(*rhs); return l.location() > r.location(); } }; void ShaderIO::sort_varying_inputs() { priority_queue<PShaderInput, vector<PShaderInput>, VaryingShaderIOLess> q; vector<int> idx; for (auto i = 0u; i < m_inputs.size(); ++i) { if (m_inputs[i]->is_varying()) { q.push(m_inputs[i]); idx.push_back(i); } } auto next_index = idx.begin(); while (!q.empty()) { auto si = q.top(); q.pop(); m_inputs[*next_index++] = si; } } void ShaderIO::update_lds_pos() { m_lds_pos = -1; m_ldspos.resize(m_inputs.size()); for (auto& i : m_inputs) { if (!i->is_varying()) continue; auto& v = static_cast<ShaderInputVarying&>(*i); /* There are shaders that miss an input ...*/ if (m_ldspos.size() <= static_cast<unsigned>(v.location())) m_ldspos.resize(v.location() + 1); } std::fill(m_ldspos.begin(), m_ldspos.end(), -1); for (auto& i : m_inputs) { if (!i->is_varying()) continue; auto& v = static_cast<ShaderInputVarying&>(*i); if (v.name() == TGSI_SEMANTIC_POSITION) continue; if (m_ldspos[v.location()] < 0) { ++m_lds_pos; m_ldspos[v.location()] = m_lds_pos; } v.set_lds_pos(m_lds_pos); } ++m_lds_pos; } std::vector<PShaderInput> &ShaderIO::inputs() { return m_inputs; } ShaderInput& ShaderIO::input(size_t k) { assert(k < m_inputs.size()); return *m_inputs[k]; } ShaderInput& ShaderIO::input(size_t driver_loc, int frac) { for (auto& i: m_inputs) { if (!i->is_varying()) continue; auto& v = static_cast<ShaderInputVarying&>(*i); if (v.location() == driver_loc) return v; } return input(driver_loc); } void ShaderIO::set_two_sided() { m_two_sided = true; } std::pair<unsigned, unsigned> r600_get_varying_semantic(unsigned varying_location) { std::pair<unsigned, unsigned> result; tgsi_get_gl_varying_semantic(static_cast<gl_varying_slot>(varying_location), true, &result.first, &result.second); if (result.first == TGSI_SEMANTIC_GENERIC) { result.second += 9; } else if (result.first == TGSI_SEMANTIC_PCOORD) { result.second = 8; } return result; } }
Valzavator/Servlet_Svynarchuk_Periodicals
src/main/java/com/gmail/maxsvynarchuk/presentation/command/impl/user/PostCartRemoveAllItemCommand.java
package com.gmail.maxsvynarchuk.presentation.command.impl.user; import com.gmail.maxsvynarchuk.presentation.command.Command; import com.gmail.maxsvynarchuk.presentation.command.CommandResult; import com.gmail.maxsvynarchuk.presentation.util.Util; import com.gmail.maxsvynarchuk.presentation.util.constants.PagesPaths; import com.gmail.maxsvynarchuk.service.ServiceFactory; import com.gmail.maxsvynarchuk.service.ShoppingCartService; import com.gmail.maxsvynarchuk.service.entity.ShoppingCart; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class PostCartRemoveAllItemCommand implements Command { private final ShoppingCartService shoppingCartService = ServiceFactory.getShoppingCartService(); @Override public CommandResult execute(HttpServletRequest request, HttpServletResponse response) { ShoppingCart shoppingCart = Util.getShoppingCart(request.getSession()); shoppingCartService.removeAllItemFromCart(shoppingCart); return CommandResult.redirect(PagesPaths.CART_PATH); } }
BryceShearn/FinalProject
JPAClusterCafe/src/main/java/com/skilldistillery/clustercafe/entities/GroupMessage.java
<gh_stars>1-10 package com.skilldistillery.clustercafe.entities; import java.time.LocalDateTime; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; import org.hibernate.annotations.CreationTimestamp; import org.hibernate.annotations.UpdateTimestamp; @Entity @Table(name="group_message") public class GroupMessage { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private int id; private String title; private String content; @ManyToOne @JoinColumn(name="creator_id") private User creator; @ManyToOne @JoinColumn(name="cluster_group_id") private ClusterGroup clusterGroup; @Column(name="created_at") @CreationTimestamp private LocalDateTime createdAt; @Column(name="updated_at") @UpdateTimestamp private LocalDateTime updatedAt; private Boolean enabled = true; @ManyToOne @JoinColumn(name="parent_message_id") private GroupMessage parentMessage = null; // Constructor public GroupMessage() {} public int getId() { return id; } public void setId(int id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public User getCreator() { return creator; } public void setCreator(User creator) { this.creator = creator; } public ClusterGroup getClusterGroup() { return clusterGroup; } public void setClusterGroup(ClusterGroup clusterGroup) { this.clusterGroup = clusterGroup; } public LocalDateTime getCreatedAt() { return createdAt; } public void setCreatedAt(LocalDateTime createdAt) { this.createdAt = createdAt; } public LocalDateTime getUpdatedAt() { return updatedAt; } public void setUpdatedAt(LocalDateTime updatedAt) { this.updatedAt = updatedAt; } public Boolean getEnabled() { return enabled; } public void setEnabled(Boolean enabled) { this.enabled = enabled; } public GroupMessage getParentMessage() { return parentMessage; } public void setParentMessage(GroupMessage parentMessage) { this.parentMessage = parentMessage; } @Override public String toString() { return "GroupMessage [id=" + id + ", title=" + title + ", content=" + content + ", creator=" + creator + ", clusterGroup=" + clusterGroup + ", createdAt=" + createdAt + ", updatedAt=" + updatedAt + ", enabled=" + enabled + ", parentMessage=" + parentMessage + "]"; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + id; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; GroupMessage other = (GroupMessage) obj; if (id != other.id) return false; return true; } }
scenaristeur/evejs
lib/transport/Transport.js
'use strict'; /** * Abstract prototype of a transport * @param {Object} [config] * @constructor */ function Transport(config) { this.id = config && config.id || null; this['default'] = config && config['default'] || false; } Transport.prototype.type = null; /** * Connect an agent * @param {String} id * @param {Function} receive Invoked as receive(from, message) * @return {Connection} Returns a connection */ Transport.prototype.connect = function(id, receive) { throw new Error('Cannot invoke abstract function "connect"'); }; /** * Close the transport */ Transport.prototype.close = function() { throw new Error('Cannot invoke abstract function "close"'); }; module.exports = Transport;